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.

61347 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 42
  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. #define JUCE_IOS 1
  75. #else
  76. #define JUCE_MAC 1
  77. #endif
  78. #else
  79. #error "Unknown platform!"
  80. #endif
  81. #if JUCE_WINDOWS
  82. #ifdef _MSC_VER
  83. #ifdef _WIN64
  84. #define JUCE_64BIT 1
  85. #else
  86. #define JUCE_32BIT 1
  87. #endif
  88. #endif
  89. #ifdef _DEBUG
  90. #define JUCE_DEBUG 1
  91. #endif
  92. #ifdef __MINGW32__
  93. #define JUCE_MINGW 1
  94. #endif
  95. /** If defined, this indicates that the processor is little-endian. */
  96. #define JUCE_LITTLE_ENDIAN 1
  97. #define JUCE_INTEL 1
  98. #endif
  99. #if JUCE_MAC
  100. #ifndef NDEBUG
  101. #define JUCE_DEBUG 1
  102. #endif
  103. #ifdef __LITTLE_ENDIAN__
  104. #define JUCE_LITTLE_ENDIAN 1
  105. #else
  106. #define JUCE_BIG_ENDIAN 1
  107. #endif
  108. #if defined (__ppc__) || defined (__ppc64__)
  109. #define JUCE_PPC 1
  110. #else
  111. #define JUCE_INTEL 1
  112. #endif
  113. #ifdef __LP64__
  114. #define JUCE_64BIT 1
  115. #else
  116. #define JUCE_32BIT 1
  117. #endif
  118. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  119. #error "Building for OSX 10.3 is no longer supported!"
  120. #endif
  121. #ifndef MAC_OS_X_VERSION_10_5
  122. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  123. #endif
  124. #endif
  125. #if JUCE_IOS
  126. #ifndef NDEBUG
  127. #define JUCE_DEBUG 1
  128. #endif
  129. #ifdef __LITTLE_ENDIAN__
  130. #define JUCE_LITTLE_ENDIAN 1
  131. #else
  132. #define JUCE_BIG_ENDIAN 1
  133. #endif
  134. #endif
  135. #if JUCE_LINUX
  136. #ifdef _DEBUG
  137. #define JUCE_DEBUG 1
  138. #endif
  139. // Allow override for big-endian Linux platforms
  140. #ifndef JUCE_BIG_ENDIAN
  141. #define JUCE_LITTLE_ENDIAN 1
  142. #endif
  143. #if defined (__LP64__) || defined (_LP64)
  144. #define JUCE_64BIT 1
  145. #else
  146. #define JUCE_32BIT 1
  147. #endif
  148. #define JUCE_INTEL 1
  149. #endif
  150. // Compiler type macros.
  151. #ifdef __GNUC__
  152. #define JUCE_GCC 1
  153. #elif defined (_MSC_VER)
  154. #define JUCE_MSVC 1
  155. #if _MSC_VER >= 1400
  156. #define JUCE_USE_INTRINSICS 1
  157. #endif
  158. #else
  159. #error unknown compiler
  160. #endif
  161. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  162. /*** End of inlined file: juce_TargetPlatform.h ***/
  163. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  164. /*** Start of inlined file: juce_Config.h ***/
  165. #ifndef __JUCE_CONFIG_JUCEHEADER__
  166. #define __JUCE_CONFIG_JUCEHEADER__
  167. /*
  168. This file contains macros that enable/disable various JUCE features.
  169. */
  170. /** The name of the namespace that all Juce classes and functions will be
  171. put inside. If this is not defined, no namespace will be used.
  172. */
  173. #ifndef JUCE_NAMESPACE
  174. #define JUCE_NAMESPACE juce
  175. #endif
  176. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  177. project settings, but if you define this value, you can override this to force
  178. it to be true or false.
  179. */
  180. #ifndef JUCE_FORCE_DEBUG
  181. //#define JUCE_FORCE_DEBUG 0
  182. #endif
  183. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  184. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  185. Enabling it will also leave this turned on in release builds. When it's disabled,
  186. however, the jassert and jassertfalse macros will not be compiled in a
  187. release build.
  188. @see jassert, jassertfalse, Logger
  189. */
  190. #ifndef JUCE_LOG_ASSERTIONS
  191. #define JUCE_LOG_ASSERTIONS 0
  192. #endif
  193. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  194. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  195. on your Windows build machine.
  196. See the comments in the ASIOAudioIODevice class's header file for more
  197. info about this.
  198. */
  199. #ifndef JUCE_ASIO
  200. #define JUCE_ASIO 0
  201. #endif
  202. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  203. */
  204. #ifndef JUCE_WASAPI
  205. #define JUCE_WASAPI 0
  206. #endif
  207. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  208. */
  209. #ifndef JUCE_DIRECTSOUND
  210. #define JUCE_DIRECTSOUND 1
  211. #endif
  212. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  213. #ifndef JUCE_ALSA
  214. #define JUCE_ALSA 1
  215. #endif
  216. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  217. #ifndef JUCE_JACK
  218. #define JUCE_JACK 0
  219. #endif
  220. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  221. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  222. installed, and its header files will need to be on your include path.
  223. */
  224. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  225. #define JUCE_QUICKTIME 0
  226. #endif
  227. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  228. #undef JUCE_QUICKTIME
  229. #endif
  230. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  231. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  232. */
  233. #ifndef JUCE_OPENGL
  234. #define JUCE_OPENGL 1
  235. #endif
  236. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  237. If your app doesn't need to read FLAC files, you might want to disable this to
  238. reduce the size of your codebase and build time.
  239. */
  240. #ifndef JUCE_USE_FLAC
  241. #define JUCE_USE_FLAC 1
  242. #endif
  243. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  244. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  245. reduce the size of your codebase and build time.
  246. */
  247. #ifndef JUCE_USE_OGGVORBIS
  248. #define JUCE_USE_OGGVORBIS 1
  249. #endif
  250. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  251. Unless you're using CD-burning, you should probably turn this flag off to
  252. reduce code size.
  253. */
  254. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  255. #define JUCE_USE_CDBURNER 0
  256. #endif
  257. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  258. Unless you're using CD-reading, you should probably turn this flag off to
  259. reduce code size.
  260. */
  261. #ifndef JUCE_USE_CDREADER
  262. #define JUCE_USE_CDREADER 0
  263. #endif
  264. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  265. */
  266. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  267. #define JUCE_USE_CAMERA 0
  268. #endif
  269. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  270. gets repainted will flash in a random colour, so that you can check exactly how much and how
  271. often your components are being drawn.
  272. */
  273. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  274. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  275. #endif
  276. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  277. Unless you specifically want to disable this, it's best to leave this option turned on.
  278. */
  279. #ifndef JUCE_USE_XINERAMA
  280. #define JUCE_USE_XINERAMA 1
  281. #endif
  282. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  283. turned on unless you have a good reason to disable it.
  284. */
  285. #ifndef JUCE_USE_XSHM
  286. #define JUCE_USE_XSHM 1
  287. #endif
  288. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  289. */
  290. #ifndef JUCE_USE_XRENDER
  291. #define JUCE_USE_XRENDER 0
  292. #endif
  293. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  294. unless you have a good reason to disable it.
  295. */
  296. #ifndef JUCE_USE_XCURSOR
  297. #define JUCE_USE_XCURSOR 1
  298. #endif
  299. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  300. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  301. you're building a plugin hosting app.
  302. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  303. */
  304. #ifndef JUCE_PLUGINHOST_VST
  305. #define JUCE_PLUGINHOST_VST 0
  306. #endif
  307. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  308. of course, and should only be enabled if you're building a plugin hosting app.
  309. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  310. */
  311. #ifndef JUCE_PLUGINHOST_AU
  312. #define JUCE_PLUGINHOST_AU 0
  313. #endif
  314. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  315. This should be enabled if you're writing a console application.
  316. */
  317. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  318. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  319. #endif
  320. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  321. If you're not using any embedded web-pages, turning this off may reduce your code size.
  322. */
  323. #ifndef JUCE_WEB_BROWSER
  324. #define JUCE_WEB_BROWSER 1
  325. #endif
  326. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  327. Carbon isn't required for a normal app, but may be needed by specialised classes like
  328. plugin-hosts, which support older APIs.
  329. */
  330. #ifndef JUCE_SUPPORT_CARBON
  331. #define JUCE_SUPPORT_CARBON 1
  332. #endif
  333. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  334. You might need to tweak this if you're linking to an external zlib library in your app,
  335. but for normal apps, this option should be left alone.
  336. */
  337. #ifndef JUCE_INCLUDE_ZLIB_CODE
  338. #define JUCE_INCLUDE_ZLIB_CODE 1
  339. #endif
  340. #ifndef JUCE_INCLUDE_FLAC_CODE
  341. #define JUCE_INCLUDE_FLAC_CODE 1
  342. #endif
  343. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  344. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  345. #endif
  346. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  347. #define JUCE_INCLUDE_PNGLIB_CODE 1
  348. #endif
  349. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  350. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  351. #endif
  352. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  353. (Currently, this only affects Windows builds in debug mode).
  354. */
  355. #ifndef JUCE_CHECK_MEMORY_LEAKS
  356. #define JUCE_CHECK_MEMORY_LEAKS 1
  357. #endif
  358. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  359. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  360. are passed to the JUCEApplication::unhandledException() callback for logging.
  361. */
  362. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  363. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  364. #endif
  365. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  366. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  367. #undef JUCE_QUICKTIME
  368. #define JUCE_QUICKTIME 0
  369. #undef JUCE_OPENGL
  370. #define JUCE_OPENGL 0
  371. #undef JUCE_USE_CDBURNER
  372. #define JUCE_USE_CDBURNER 0
  373. #undef JUCE_USE_CDREADER
  374. #define JUCE_USE_CDREADER 0
  375. #undef JUCE_WEB_BROWSER
  376. #define JUCE_WEB_BROWSER 0
  377. #undef JUCE_PLUGINHOST_AU
  378. #define JUCE_PLUGINHOST_AU 0
  379. #undef JUCE_PLUGINHOST_VST
  380. #define JUCE_PLUGINHOST_VST 0
  381. #endif
  382. #endif
  383. /*** End of inlined file: juce_Config.h ***/
  384. #ifdef JUCE_NAMESPACE
  385. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  386. #define END_JUCE_NAMESPACE }
  387. #else
  388. #define BEGIN_JUCE_NAMESPACE
  389. #define END_JUCE_NAMESPACE
  390. #endif
  391. /*** Start of inlined file: juce_PlatformDefs.h ***/
  392. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  393. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  394. /* This file defines miscellaneous macros for debugging, assertions, etc.
  395. */
  396. #ifdef JUCE_FORCE_DEBUG
  397. #undef JUCE_DEBUG
  398. #if JUCE_FORCE_DEBUG
  399. #define JUCE_DEBUG 1
  400. #endif
  401. #endif
  402. /** This macro defines the C calling convention used as the standard for Juce calls. */
  403. #if JUCE_MSVC
  404. #define JUCE_CALLTYPE __stdcall
  405. #else
  406. #define JUCE_CALLTYPE
  407. #endif
  408. // Debugging and assertion macros
  409. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  410. #if JUCE_LOG_ASSERTIONS
  411. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  412. #elif JUCE_DEBUG
  413. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  414. #else
  415. #define juce_LogCurrentAssertion
  416. #endif
  417. #if JUCE_DEBUG
  418. // If debugging is enabled..
  419. /** Writes a string to the standard error stream.
  420. This is only compiled in a debug build.
  421. @see Logger::outputDebugString
  422. */
  423. #define DBG(dbgtext) JUCE_NAMESPACE::Logger::outputDebugString (dbgtext);
  424. // Assertions..
  425. #if JUCE_WINDOWS || DOXYGEN
  426. #if JUCE_USE_INTRINSICS
  427. #pragma intrinsic (__debugbreak)
  428. /** This will try to break the debugger if one is currently hosting this app.
  429. @see jassert()
  430. */
  431. #define juce_breakDebugger __debugbreak();
  432. #elif JUCE_GCC
  433. /** This will try to break the debugger if one is currently hosting this app.
  434. @see jassert()
  435. */
  436. #define juce_breakDebugger asm("int $3");
  437. #else
  438. /** This will try to break the debugger if one is currently hosting this app.
  439. @see jassert()
  440. */
  441. #define juce_breakDebugger { __asm int 3 }
  442. #endif
  443. #elif JUCE_MAC
  444. #define juce_breakDebugger Debugger();
  445. #elif JUCE_IOS
  446. #define juce_breakDebugger kill (0, SIGTRAP);
  447. #elif JUCE_LINUX
  448. #define juce_breakDebugger kill (0, SIGTRAP);
  449. #endif
  450. /** This will always cause an assertion failure.
  451. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  452. in juce_Config.h).
  453. @see jassert()
  454. */
  455. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  456. /** Platform-independent assertion macro.
  457. This gets optimised out when not being built with debugging turned on.
  458. Be careful not to call any functions within its arguments that are vital to
  459. the behaviour of the program, because these won't get called in the release
  460. build.
  461. @see jassertfalse
  462. */
  463. #define jassert(expression) { if (! (expression)) jassertfalse; }
  464. #else
  465. // If debugging is disabled, these dummy debug and assertion macros are used..
  466. #define DBG(dbgtext)
  467. #define jassertfalse { juce_LogCurrentAssertion }
  468. #if JUCE_LOG_ASSERTIONS
  469. #define jassert(expression) { if (! (expression)) jassertfalse; }
  470. #else
  471. #define jassert(a) { }
  472. #endif
  473. #endif
  474. #ifndef DOXYGEN
  475. template <bool b> struct JuceStaticAssert;
  476. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  477. #endif
  478. /** A compile-time assertion macro.
  479. If the expression parameter is false, the macro will cause a compile error.
  480. */
  481. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  482. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  483. #define JUCE_TRY try
  484. #define JUCE_CATCH_ALL catch (...) {}
  485. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  486. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  487. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  488. #else
  489. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  490. object so they can be logged by the application if it wants to.
  491. */
  492. #define JUCE_CATCH_EXCEPTION \
  493. catch (const std::exception& e) \
  494. { \
  495. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  496. } \
  497. catch (...) \
  498. { \
  499. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  500. }
  501. #endif
  502. #else
  503. #define JUCE_TRY
  504. #define JUCE_CATCH_EXCEPTION
  505. #define JUCE_CATCH_ALL
  506. #define JUCE_CATCH_ALL_ASSERT
  507. #endif
  508. // Macros for inlining.
  509. #if JUCE_MSVC
  510. /** A platform-independent way of forcing an inline function.
  511. Use the syntax: @code
  512. forcedinline void myfunction (int x)
  513. @endcode
  514. */
  515. #ifndef JUCE_DEBUG
  516. #define forcedinline __forceinline
  517. #else
  518. #define forcedinline inline
  519. #endif
  520. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  521. #else
  522. /** A platform-independent way of forcing an inline function.
  523. Use the syntax: @code
  524. forcedinline void myfunction (int x)
  525. @endcode
  526. */
  527. #ifndef JUCE_DEBUG
  528. #define forcedinline inline __attribute__((always_inline))
  529. #else
  530. #define forcedinline inline
  531. #endif
  532. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  533. #endif
  534. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  535. /*** End of inlined file: juce_PlatformDefs.h ***/
  536. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  537. #if JUCE_MSVC
  538. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  539. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  540. #endif
  541. #pragma warning (push)
  542. #pragma warning (disable: 4514 4245 4100)
  543. #endif
  544. #include <cstdlib>
  545. #include <cstdarg>
  546. #include <climits>
  547. #include <limits>
  548. #include <cmath>
  549. #include <cwchar>
  550. #include <stdexcept>
  551. #include <typeinfo>
  552. #include <cstring>
  553. #include <cstdio>
  554. #include <iostream>
  555. #if JUCE_USE_INTRINSICS
  556. #include <intrin.h>
  557. #endif
  558. #if JUCE_MAC || JUCE_IOS
  559. #include <libkern/OSAtomic.h>
  560. #endif
  561. #if JUCE_LINUX
  562. #include <signal.h>
  563. #if __INTEL_COMPILER
  564. #if __ia64__
  565. #include <ia64intrin.h>
  566. #else
  567. #include <ia32intrin.h>
  568. #endif
  569. #endif
  570. #endif
  571. #if JUCE_MSVC && JUCE_DEBUG
  572. #include <crtdbg.h>
  573. #endif
  574. #if JUCE_MSVC
  575. #include <malloc.h>
  576. #pragma warning (pop)
  577. #if ! JUCE_PUBLIC_INCLUDES
  578. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  579. #endif
  580. #endif
  581. // DLL building settings on Win32
  582. #if JUCE_MSVC
  583. #ifdef JUCE_DLL_BUILD
  584. #define JUCE_API __declspec (dllexport)
  585. #pragma warning (disable: 4251)
  586. #elif defined (JUCE_DLL)
  587. #define JUCE_API __declspec (dllimport)
  588. #pragma warning (disable: 4251)
  589. #endif
  590. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  591. #ifdef JUCE_DLL_BUILD
  592. #define JUCE_API __attribute__ ((visibility("default")))
  593. #endif
  594. #endif
  595. #ifndef JUCE_API
  596. /** This macro is added to all juce public class declarations. */
  597. #define JUCE_API
  598. #endif
  599. /** This macro is added to all juce public function declarations. */
  600. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  601. // Now include some basics that are needed by most of the Juce classes...
  602. BEGIN_JUCE_NAMESPACE
  603. extern bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  604. #if JUCE_LOG_ASSERTIONS
  605. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  606. #endif
  607. /*** Start of inlined file: juce_Memory.h ***/
  608. #ifndef __JUCE_MEMORY_JUCEHEADER__
  609. #define __JUCE_MEMORY_JUCEHEADER__
  610. /*
  611. This file defines the various juce_malloc(), juce_free() macros that should be used in
  612. preference to the standard calls.
  613. */
  614. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  615. #ifndef JUCE_DLL
  616. // Win32 debug non-DLL versions..
  617. /** This should be used instead of calling malloc directly.
  618. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  619. */
  620. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  621. /** This should be used instead of calling calloc directly.
  622. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  623. */
  624. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  625. /** This should be used instead of calling realloc directly.
  626. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  627. */
  628. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  629. /** This should be used instead of calling free directly.
  630. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  631. */
  632. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  633. #else
  634. // Win32 debug DLL versions..
  635. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  636. // way all juce calls in the DLL and in the host API will all use the same allocator.
  637. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  638. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  639. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  640. extern JUCE_API void juce_DebugFree (void* const block);
  641. /** This should be used instead of calling malloc directly.
  642. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  643. */
  644. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  645. /** This should be used instead of calling calloc directly.
  646. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  647. */
  648. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  649. /** This should be used instead of calling realloc directly.
  650. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  651. */
  652. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  653. /** This should be used instead of calling free directly.
  654. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  655. */
  656. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  657. #endif
  658. #if ! defined (_AFXDLL)
  659. /** This macro can be added to classes to add extra debugging information to the memory
  660. allocated for them, so you can see the type of objects involved when there's a dump
  661. of leaked objects at program shutdown. (Only works on win32 at the moment).
  662. */
  663. #define juce_UseDebuggingNewOperator \
  664. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  665. static void* operator new (size_t, void* p) { return p; } \
  666. static void operator delete (void* p) { juce_free (p); } \
  667. static void operator delete (void*, void*) { }
  668. #endif
  669. #elif defined (JUCE_DLL)
  670. // Win32 DLL (release) versions..
  671. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  672. // way all juce calls in the DLL and in the host API will all use the same allocator.
  673. extern JUCE_API void* juce_Malloc (const int size);
  674. extern JUCE_API void* juce_Calloc (const int size);
  675. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  676. extern JUCE_API void juce_Free (void* const block);
  677. /** This should be used instead of calling malloc directly.
  678. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  679. */
  680. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  681. /** This should be used instead of calling calloc directly.
  682. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  683. */
  684. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  685. /** This should be used instead of calling realloc directly.
  686. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  687. */
  688. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  689. /** This should be used instead of calling free directly.
  690. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  691. */
  692. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  693. #define juce_UseDebuggingNewOperator \
  694. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  695. static void* operator new (size_t, void* p) { return p; } \
  696. static void operator delete (void* p) { juce_free (p); } \
  697. static void operator delete (void*, void*) { }
  698. #else
  699. // Mac, Linux and Win32 (release) versions..
  700. /** This should be used instead of calling malloc directly.
  701. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  702. */
  703. #define juce_malloc(numBytes) malloc (numBytes)
  704. /** This should be used instead of calling calloc directly.
  705. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  706. */
  707. #define juce_calloc(numBytes) calloc (1, numBytes)
  708. /** This should be used instead of calling realloc directly.
  709. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  710. */
  711. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  712. /** This should be used instead of calling free directly.
  713. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  714. */
  715. #define juce_free(location) free (location)
  716. #endif
  717. /** This macro can be added to classes to add extra debugging information to the memory
  718. allocated for them, so you can see the type of objects involved when there's a dump
  719. of leaked objects at program shutdown. (Only works on win32 at the moment).
  720. Note that if you create a class that inherits from a class that uses this macro,
  721. your class must also use the macro, otherwise you'll probably get compile errors
  722. because of ambiguous new operators.
  723. Most of the JUCE classes use it, so see these for examples of where it should go.
  724. */
  725. #ifndef juce_UseDebuggingNewOperator
  726. #define juce_UseDebuggingNewOperator
  727. #endif
  728. #if JUCE_MSVC
  729. /** This is a compiler-independent way of declaring a variable as being thread-local.
  730. E.g.
  731. @code
  732. juce_ThreadLocal int myVariable;
  733. @endcode
  734. */
  735. #define juce_ThreadLocal __declspec(thread)
  736. #else
  737. #define juce_ThreadLocal __thread
  738. #endif
  739. #if JUCE_MINGW
  740. /** This allocator is not defined in mingw gcc. */
  741. #define alloca __builtin_alloca
  742. #endif
  743. /** Clears a block of memory. */
  744. inline void zeromem (void* memory, size_t numBytes) { memset (memory, 0, numBytes); }
  745. /** Clears a reference to a local structure. */
  746. template <typename Type>
  747. inline void zerostruct (Type& structure) { memset (&structure, 0, sizeof (structure)); }
  748. /** A handy function that calls delete on a pointer if it's non-zero, and then sets
  749. the pointer to null.
  750. */
  751. template <typename Type>
  752. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  753. #endif // __JUCE_MEMORY_JUCEHEADER__
  754. /*** End of inlined file: juce_Memory.h ***/
  755. /*** Start of inlined file: juce_MathsFunctions.h ***/
  756. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  757. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  758. /*
  759. This file sets up some handy mathematical typdefs and functions.
  760. */
  761. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  762. /** A platform-independent 8-bit signed integer type. */
  763. typedef signed char int8;
  764. /** A platform-independent 8-bit unsigned integer type. */
  765. typedef unsigned char uint8;
  766. /** A platform-independent 16-bit signed integer type. */
  767. typedef signed short int16;
  768. /** A platform-independent 16-bit unsigned integer type. */
  769. typedef unsigned short uint16;
  770. /** A platform-independent 32-bit signed integer type. */
  771. typedef signed int int32;
  772. /** A platform-independent 32-bit unsigned integer type. */
  773. typedef unsigned int uint32;
  774. #if JUCE_MSVC
  775. /** A platform-independent 64-bit integer type. */
  776. typedef __int64 int64;
  777. /** A platform-independent 64-bit unsigned integer type. */
  778. typedef unsigned __int64 uint64;
  779. /** A platform-independent macro for writing 64-bit literals, needed because
  780. different compilers have different syntaxes for this.
  781. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  782. GCC, or 0x1000000000 for MSVC.
  783. */
  784. #define literal64bit(longLiteral) ((__int64) longLiteral)
  785. #else
  786. /** A platform-independent 64-bit integer type. */
  787. typedef long long int64;
  788. /** A platform-independent 64-bit unsigned integer type. */
  789. typedef unsigned long long uint64;
  790. /** A platform-independent macro for writing 64-bit literals, needed because
  791. different compilers have different syntaxes for this.
  792. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  793. GCC, or 0x1000000000 for MSVC.
  794. */
  795. #define literal64bit(longLiteral) (longLiteral##LL)
  796. #endif
  797. #if JUCE_64BIT
  798. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  799. typedef int64 pointer_sized_int;
  800. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  801. typedef uint64 pointer_sized_uint;
  802. #elif _MSC_VER >= 1300
  803. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  804. typedef _W64 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 _W64 unsigned int pointer_sized_uint;
  807. #else
  808. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  809. typedef int pointer_sized_int;
  810. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  811. typedef unsigned int pointer_sized_uint;
  812. #endif
  813. /** A platform-independent unicode character type. */
  814. typedef wchar_t juce_wchar;
  815. // Some indispensible min/max functions
  816. /** Returns the larger of two values. */
  817. template <typename Type>
  818. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  819. /** Returns the larger of three values. */
  820. template <typename Type>
  821. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  822. /** Returns the larger of four values. */
  823. template <typename Type>
  824. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  825. /** Returns the smaller of two values. */
  826. template <typename Type>
  827. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  828. /** Returns the smaller of three values. */
  829. template <typename Type>
  830. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  831. /** Returns the smaller of four values. */
  832. template <typename Type>
  833. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  834. /** Constrains a value to keep it within a given range.
  835. This will check that the specified value lies between the lower and upper bounds
  836. specified, and if not, will return the nearest value that would be in-range. Effectively,
  837. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  838. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  839. the results will be unpredictable.
  840. @param lowerLimit the minimum value to return
  841. @param upperLimit the maximum value to return
  842. @param valueToConstrain the value to try to return
  843. @returns the closest value to valueToConstrain which lies between lowerLimit
  844. and upperLimit (inclusive)
  845. @see jlimit0To, jmin, jmax
  846. */
  847. template <typename Type>
  848. inline Type jlimit (const Type lowerLimit,
  849. const Type upperLimit,
  850. const Type valueToConstrain) throw()
  851. {
  852. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  853. return (valueToConstrain < lowerLimit) ? lowerLimit
  854. : ((upperLimit < valueToConstrain) ? upperLimit
  855. : valueToConstrain);
  856. }
  857. /** Handy function to swap two values over.
  858. */
  859. template <typename Type>
  860. inline void swapVariables (Type& variable1, Type& variable2)
  861. {
  862. const Type tempVal = variable1;
  863. variable1 = variable2;
  864. variable2 = tempVal;
  865. }
  866. /** Handy function for getting the number of elements in a simple const C array.
  867. E.g.
  868. @code
  869. static int myArray[] = { 1, 2, 3 };
  870. int numElements = numElementsInArray (myArray) // returns 3
  871. @endcode
  872. */
  873. template <typename Type>
  874. inline int numElementsInArray (Type& array)
  875. {
  876. (void) array; // (required to avoid a spurious warning in MS compilers)
  877. return static_cast<int> (sizeof (array) / sizeof (array[0]));
  878. }
  879. // Some useful maths functions that aren't always present with all compilers and build settings.
  880. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  881. versions of these functions of various platforms and compilers. */
  882. inline double juce_hypot (double a, double b)
  883. {
  884. #if JUCE_WINDOWS
  885. return _hypot (a, b);
  886. #else
  887. return hypot (a, b);
  888. #endif
  889. }
  890. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  891. versions of these functions of various platforms and compilers. */
  892. inline float juce_hypotf (float a, float b) throw()
  893. {
  894. #if JUCE_WINDOWS
  895. return (float) _hypot (a, b);
  896. #else
  897. return hypotf (a, b);
  898. #endif
  899. }
  900. /** 64-bit abs function. */
  901. inline int64 abs64 (const int64 n) throw()
  902. {
  903. return (n >= 0) ? n : -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 sizeof (Type) == 1 ? (Type) -(char) n
  910. : (sizeof (Type) == 2 ? (Type) -(short) n
  911. : (sizeof (Type) == 4 ? (Type) -(int) n
  912. : ((Type) -(int64) n)));
  913. }
  914. /** This templated negate function will negate pointers as well as integers */
  915. template <typename Type>
  916. inline Type* juce_negate (Type* n) throw()
  917. {
  918. return (Type*) -(pointer_sized_int) n;
  919. }
  920. /** A predefined value for Pi, at double-precision.
  921. @see float_Pi
  922. */
  923. const double double_Pi = 3.1415926535897932384626433832795;
  924. /** A predefined value for Pi, at sngle-precision.
  925. @see double_Pi
  926. */
  927. const float float_Pi = 3.14159265358979323846f;
  928. /** The isfinite() method seems to vary between platforms, so this is a
  929. platform-independent function for it.
  930. */
  931. template <typename FloatingPointType>
  932. inline bool juce_isfinite (FloatingPointType value)
  933. {
  934. #if JUCE_WINDOWS
  935. return _finite (value);
  936. #else
  937. return std::isfinite (value);
  938. #endif
  939. }
  940. /** Fast floating-point-to-integer conversion.
  941. This is faster than using the normal c++ cast to convert a float to an int, and
  942. it will round the value to the nearest integer, rather than rounding it down
  943. like the normal cast does.
  944. Note that this routine gets its speed at the expense of some accuracy, and when
  945. rounding values whose floating point component is exactly 0.5, odd numbers and
  946. even numbers will be rounded up or down differently.
  947. */
  948. template <typename FloatType>
  949. inline int roundToInt (const FloatType value) throw()
  950. {
  951. union { int asInt[2]; double asDouble; } n;
  952. n.asDouble = ((double) value) + 6755399441055744.0;
  953. #if JUCE_BIG_ENDIAN
  954. return n.asInt [1];
  955. #else
  956. return n.asInt [0];
  957. #endif
  958. }
  959. /** Fast floating-point-to-integer conversion.
  960. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  961. fine for values above zero, but negative numbers are rounded the wrong way.
  962. */
  963. inline int roundToIntAccurate (const double value) throw()
  964. {
  965. return roundToInt (value + 1.5e-8);
  966. }
  967. /** Fast floating-point-to-integer conversion.
  968. This is faster than using the normal c++ cast to convert a double to an int, and
  969. it will round the value to the nearest integer, rather than rounding it down
  970. like the normal cast does.
  971. Note that this routine gets its speed at the expense of some accuracy, and when
  972. rounding values whose floating point component is exactly 0.5, odd numbers and
  973. even numbers will be rounded up or down differently. For a more accurate conversion,
  974. see roundDoubleToIntAccurate().
  975. */
  976. inline int roundDoubleToInt (const double value) throw()
  977. {
  978. return roundToInt (value);
  979. }
  980. /** Fast floating-point-to-integer conversion.
  981. This is faster than using the normal c++ cast to convert a float to an int, and
  982. it will round the value to the nearest integer, rather than rounding it down
  983. like the normal cast does.
  984. Note that this routine gets its speed at the expense of some accuracy, and when
  985. rounding values whose floating point component is exactly 0.5, odd numbers and
  986. even numbers will be rounded up or down differently.
  987. */
  988. inline int roundFloatToInt (const float value) throw()
  989. {
  990. return roundToInt (value);
  991. }
  992. /** This namespace contains a few template classes for helping work out class type variations.
  993. */
  994. namespace TypeHelpers
  995. {
  996. #if defined (_MSC_VER) && _MSC_VER <= 1400
  997. #define PARAMETER_TYPE(a) a
  998. #else
  999. /** The ParameterType struct is used to find the best type to use when passing some kind
  1000. of object as a parameter.
  1001. Of course, this is only likely to be useful in certain esoteric template situations.
  1002. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1003. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1004. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1005. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1006. pass-by-value, but passing objects as a const reference, to avoid copying.
  1007. */
  1008. template <typename Type> struct ParameterType { typedef const Type& type; };
  1009. #if ! DOXYGEN
  1010. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1011. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1012. template <> struct ParameterType <char> { typedef char type; };
  1013. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1014. template <> struct ParameterType <short> { typedef short type; };
  1015. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1016. template <> struct ParameterType <int> { typedef int type; };
  1017. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1018. template <> struct ParameterType <long> { typedef long type; };
  1019. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1020. template <> struct ParameterType <int64> { typedef int64 type; };
  1021. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1022. template <> struct ParameterType <bool> { typedef bool type; };
  1023. template <> struct ParameterType <float> { typedef float type; };
  1024. template <> struct ParameterType <double> { typedef double type; };
  1025. #endif
  1026. /** A helpful macro to simplify the use of the ParameterType template.
  1027. @see ParameterType
  1028. */
  1029. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1030. #endif
  1031. }
  1032. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1033. /*** End of inlined file: juce_MathsFunctions.h ***/
  1034. /*** Start of inlined file: juce_ByteOrder.h ***/
  1035. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1036. #define __JUCE_BYTEORDER_JUCEHEADER__
  1037. /** Contains static methods for converting the byte order between different
  1038. endiannesses.
  1039. */
  1040. class JUCE_API ByteOrder
  1041. {
  1042. public:
  1043. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1044. static uint16 swap (uint16 value);
  1045. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1046. static uint32 swap (uint32 value);
  1047. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1048. static uint64 swap (uint64 value);
  1049. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1050. static uint16 swapIfBigEndian (uint16 value);
  1051. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1052. static uint32 swapIfBigEndian (uint32 value);
  1053. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1054. static uint64 swapIfBigEndian (uint64 value);
  1055. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1056. static uint16 swapIfLittleEndian (uint16 value);
  1057. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1058. static uint32 swapIfLittleEndian (uint32 value);
  1059. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1060. static uint64 swapIfLittleEndian (uint64 value);
  1061. /** Turns 4 bytes into a little-endian integer. */
  1062. static uint32 littleEndianInt (const void* bytes);
  1063. /** Turns 2 bytes into a little-endian integer. */
  1064. static uint16 littleEndianShort (const void* bytes);
  1065. /** Turns 4 bytes into a big-endian integer. */
  1066. static uint32 bigEndianInt (const void* bytes);
  1067. /** Turns 2 bytes into a big-endian integer. */
  1068. static uint16 bigEndianShort (const void* bytes);
  1069. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1070. static int littleEndian24Bit (const char* bytes);
  1071. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1072. static int bigEndian24Bit (const char* bytes);
  1073. /** Copies a 24-bit number to 3 little-endian bytes. */
  1074. static void littleEndian24BitToChars (int value, char* destBytes);
  1075. /** Copies a 24-bit number to 3 big-endian bytes. */
  1076. static void bigEndian24BitToChars (int value, char* destBytes);
  1077. /** Returns true if the current CPU is big-endian. */
  1078. static bool isBigEndian();
  1079. private:
  1080. ByteOrder();
  1081. ByteOrder (const ByteOrder&);
  1082. ByteOrder& operator= (const ByteOrder&);
  1083. };
  1084. #if JUCE_USE_INTRINSICS
  1085. #pragma intrinsic (_byteswap_ulong)
  1086. #endif
  1087. inline uint16 ByteOrder::swap (uint16 n)
  1088. {
  1089. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1090. return static_cast <uint16> (_byteswap_ushort (n));
  1091. #else
  1092. return static_cast <uint16> ((n << 8) | (n >> 8));
  1093. #endif
  1094. }
  1095. inline uint32 ByteOrder::swap (uint32 n)
  1096. {
  1097. #if JUCE_MAC || JUCE_IOS
  1098. return OSSwapInt32 (n);
  1099. #elif JUCE_GCC
  1100. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1101. return n;
  1102. #elif JUCE_USE_INTRINSICS
  1103. return _byteswap_ulong (n);
  1104. #else
  1105. __asm {
  1106. mov eax, n
  1107. bswap eax
  1108. mov n, eax
  1109. }
  1110. return n;
  1111. #endif
  1112. }
  1113. inline uint64 ByteOrder::swap (uint64 value)
  1114. {
  1115. #if JUCE_MAC || JUCE_IOS
  1116. return OSSwapInt64 (value);
  1117. #elif JUCE_USE_INTRINSICS
  1118. return _byteswap_uint64 (value);
  1119. #else
  1120. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1121. #endif
  1122. }
  1123. #if JUCE_LITTLE_ENDIAN
  1124. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1125. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1126. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1127. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1128. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1129. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1130. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1131. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1132. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1133. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1134. inline bool ByteOrder::isBigEndian() { return false; }
  1135. #else
  1136. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1137. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1138. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1139. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1140. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1141. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1142. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1143. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1144. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1145. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1146. inline bool ByteOrder::isBigEndian() { return true; }
  1147. #endif
  1148. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1149. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1150. 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); }
  1151. 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); }
  1152. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1153. /*** End of inlined file: juce_ByteOrder.h ***/
  1154. /*** Start of inlined file: juce_Logger.h ***/
  1155. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1156. #define __JUCE_LOGGER_JUCEHEADER__
  1157. /*** Start of inlined file: juce_String.h ***/
  1158. #ifndef __JUCE_STRING_JUCEHEADER__
  1159. #define __JUCE_STRING_JUCEHEADER__
  1160. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1161. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1162. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1163. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1164. typedef juce_wchar tchar;
  1165. #if ! JUCE_DONT_DEFINE_MACROS
  1166. /** The 'T' macro allows a literal string to be compiled as unicode.
  1167. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1168. or "xyz", depending on which representation is best for the String class to work with.
  1169. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1170. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1171. the juce/src directory) to avoid defining this macro. See the comments in
  1172. juce_withoutMacros.h for more info.
  1173. */
  1174. #define T(stringLiteral) JUCE_T(stringLiteral)
  1175. #endif
  1176. /**
  1177. A set of methods for manipulating characters and character strings, with
  1178. duplicate methods to handle 8-bit and unicode characters.
  1179. These are defined as wrappers around the basic C string handlers, to provide
  1180. a clean, cross-platform layer, (because various platforms differ in the
  1181. range of C library calls that they provide).
  1182. @see String
  1183. */
  1184. class JUCE_API CharacterFunctions
  1185. {
  1186. public:
  1187. static int length (const char* const s) throw();
  1188. static int length (const juce_wchar* const s) throw();
  1189. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1190. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1191. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1192. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1193. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1194. static void append (char* dest, const char* src) throw();
  1195. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1196. static int compare (const char* const s1, const char* const s2) throw();
  1197. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1198. static int compare (const juce_wchar* s1, const char* s2) throw();
  1199. static int compare (const char* s1, const juce_wchar* s2) throw();
  1200. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1201. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1202. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1203. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1204. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1205. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1206. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1207. static const char* find (const char* const haystack, const char* const needle) throw();
  1208. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1209. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1210. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1211. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1212. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1213. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1214. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1215. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1216. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1217. static int getIntValue (const char* const s) throw();
  1218. static int getIntValue (const juce_wchar* s) throw();
  1219. static int64 getInt64Value (const char* s) throw();
  1220. static int64 getInt64Value (const juce_wchar* s) throw();
  1221. static double getDoubleValue (const char* const s) throw();
  1222. static double getDoubleValue (const juce_wchar* const s) throw();
  1223. static char toUpperCase (const char character) throw();
  1224. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1225. static void toUpperCase (char* s) throw();
  1226. static void toUpperCase (juce_wchar* s) throw();
  1227. static bool isUpperCase (const char character) throw();
  1228. static bool isUpperCase (const juce_wchar character) throw();
  1229. static char toLowerCase (const char character) throw();
  1230. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1231. static void toLowerCase (char* s) throw();
  1232. static void toLowerCase (juce_wchar* s) throw();
  1233. static bool isLowerCase (const char character) throw();
  1234. static bool isLowerCase (const juce_wchar character) throw();
  1235. static bool isWhitespace (const char character) throw();
  1236. static bool isWhitespace (const juce_wchar character) throw();
  1237. static bool isDigit (const char character) throw();
  1238. static bool isDigit (const juce_wchar character) throw();
  1239. static bool isLetter (const char character) throw();
  1240. static bool isLetter (const juce_wchar character) throw();
  1241. static bool isLetterOrDigit (const char character) throw();
  1242. static bool isLetterOrDigit (const juce_wchar character) throw();
  1243. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1244. hex digit.
  1245. */
  1246. static int getHexDigitValue (const juce_wchar digit) throw();
  1247. };
  1248. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1249. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1250. class OutputStream;
  1251. /**
  1252. The JUCE String class!
  1253. Using a reference-counted internal representation, these strings are fast
  1254. and efficient, and there are methods to do just about any operation you'll ever
  1255. dream of.
  1256. @see StringArray, StringPairArray
  1257. */
  1258. class JUCE_API String
  1259. {
  1260. public:
  1261. /** Creates an empty string.
  1262. @see empty
  1263. */
  1264. String() throw();
  1265. /** Creates a copy of another string. */
  1266. String (const String& other) throw();
  1267. /** Creates a string from a zero-terminated text string.
  1268. The string is assumed to be stored in the default system encoding.
  1269. */
  1270. String (const char* text);
  1271. /** Creates a string from an string of characters.
  1272. This will use up the the first maxChars characters of the string (or
  1273. less if the string is actually shorter)
  1274. */
  1275. String (const char* text, size_t maxChars);
  1276. /** Creates a string from a zero-terminated unicode text string. */
  1277. String (const juce_wchar* unicodeText);
  1278. /** Creates a string from a unicode text string.
  1279. This will use up the the first maxChars characters of the string (or
  1280. less if the string is actually shorter)
  1281. */
  1282. String (const juce_wchar* unicodeText, size_t maxChars);
  1283. /** Creates a string from a single character. */
  1284. static const String charToString (juce_wchar character);
  1285. /** Destructor. */
  1286. ~String() throw();
  1287. /** This is an empty string that can be used whenever one is needed.
  1288. It's better to use this than String() because it explains what's going on
  1289. and is more efficient.
  1290. */
  1291. static const String empty;
  1292. /** Generates a probably-unique 32-bit hashcode from this string. */
  1293. int hashCode() const throw();
  1294. /** Generates a probably-unique 64-bit hashcode from this string. */
  1295. int64 hashCode64() const throw();
  1296. /** Returns the number of characters in the string. */
  1297. int length() const throw();
  1298. // Assignment and concatenation operators..
  1299. /** Replaces this string's contents with another string. */
  1300. String& operator= (const String& other) throw();
  1301. /** Appends another string at the end of this one. */
  1302. String& operator+= (const juce_wchar* textToAppend);
  1303. /** Appends another string at the end of this one. */
  1304. String& operator+= (const String& stringToAppend);
  1305. /** Appends a character at the end of this string. */
  1306. String& operator+= (char characterToAppend);
  1307. /** Appends a character at the end of this string. */
  1308. String& operator+= (juce_wchar characterToAppend);
  1309. /** Appends a decimal number at the end of this string. */
  1310. String& operator+= (int numberToAppend);
  1311. /** Appends a decimal number at the end of this string. */
  1312. String& operator+= (unsigned int numberToAppend);
  1313. /** Appends a string at the end of this one.
  1314. @param textToAppend the string to add
  1315. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1316. */
  1317. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1318. // Comparison methods..
  1319. /** Returns true if the string contains no characters.
  1320. Note that there's also an isNotEmpty() method to help write readable code.
  1321. @see containsNonWhitespaceChars()
  1322. */
  1323. inline bool isEmpty() const throw() { return text[0] == 0; }
  1324. /** Returns true if the string contains at least one character.
  1325. Note that there's also an isEmpty() method to help write readable code.
  1326. @see containsNonWhitespaceChars()
  1327. */
  1328. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1329. /** Case-insensitive comparison with another string. */
  1330. bool equalsIgnoreCase (const String& other) const throw();
  1331. /** Case-insensitive comparison with another string. */
  1332. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1333. /** Case-insensitive comparison with another string. */
  1334. bool equalsIgnoreCase (const char* other) const throw();
  1335. /** Case-sensitive comparison with another string.
  1336. @returns 0 if the two strings are identical; negative if this string
  1337. comes before the other one alphabetically, or positive if it
  1338. comes after it.
  1339. */
  1340. int compare (const String& other) const throw();
  1341. /** Case-sensitive comparison with another string.
  1342. @returns 0 if the two strings are identical; negative if this string
  1343. comes before the other one alphabetically, or positive if it
  1344. comes after it.
  1345. */
  1346. int compare (const char* other) const throw();
  1347. /** Case-sensitive comparison with another string.
  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 compare (const juce_wchar* other) const throw();
  1353. /** Case-insensitive comparison with another string.
  1354. @returns 0 if the two strings are identical; negative if this string
  1355. comes before the other one alphabetically, or positive if it
  1356. comes after it.
  1357. */
  1358. int compareIgnoreCase (const String& other) const throw();
  1359. /** Lexicographic comparison with another string.
  1360. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1361. characters, making it good for sorting human-readable strings.
  1362. @returns 0 if the two strings are identical; negative if this string
  1363. comes before the other one alphabetically, or positive if it
  1364. comes after it.
  1365. */
  1366. int compareLexicographically (const String& other) const throw();
  1367. /** Tests whether the string begins with another string.
  1368. Uses a case-sensitive comparison.
  1369. */
  1370. bool startsWith (const String& text) const throw();
  1371. /** Tests whether the string begins with a particular character.
  1372. Uses a case-sensitive comparison.
  1373. */
  1374. bool startsWithChar (juce_wchar character) const throw();
  1375. /** Tests whether the string begins with another string.
  1376. Uses a case-insensitive comparison.
  1377. */
  1378. bool startsWithIgnoreCase (const String& text) const throw();
  1379. /** Tests whether the string ends with another string.
  1380. Uses a case-sensitive comparison.
  1381. */
  1382. bool endsWith (const String& text) const throw();
  1383. /** Tests whether the string ends with a particular character.
  1384. Uses a case-sensitive comparison.
  1385. */
  1386. bool endsWithChar (juce_wchar character) const throw();
  1387. /** Tests whether the string ends with another string.
  1388. Uses a case-insensitive comparison.
  1389. */
  1390. bool endsWithIgnoreCase (const String& text) const throw();
  1391. /** Tests whether the string contains another substring.
  1392. Uses a case-sensitive comparison.
  1393. */
  1394. bool contains (const String& text) const throw();
  1395. /** Tests whether the string contains a particular character.
  1396. Uses a case-sensitive comparison.
  1397. */
  1398. bool containsChar (juce_wchar character) const throw();
  1399. /** Tests whether the string contains another substring.
  1400. Uses a case-insensitive comparison.
  1401. */
  1402. bool containsIgnoreCase (const String& text) const throw();
  1403. /** Tests whether the string contains another substring as a distict word.
  1404. @returns true if the string contains this word, surrounded by
  1405. non-alphanumeric characters
  1406. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1407. */
  1408. bool containsWholeWord (const String& wordToLookFor) const throw();
  1409. /** Tests whether the string contains another substring as a distict word.
  1410. @returns true if the string contains this word, surrounded by
  1411. non-alphanumeric characters
  1412. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1413. */
  1414. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1415. /** Finds an instance of another substring if it exists as a distict word.
  1416. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1417. then this will return the index of the start of the substring. If it isn't
  1418. found, then it will return -1
  1419. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1420. */
  1421. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1422. /** Finds an instance of another substring if it exists as a distict word.
  1423. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1424. then this will return the index of the start of the substring. If it isn't
  1425. found, then it will return -1
  1426. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1427. */
  1428. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1429. /** Looks for any of a set of characters in the string.
  1430. Uses a case-sensitive comparison.
  1431. @returns true if the string contains any of the characters from
  1432. the string that is passed in.
  1433. */
  1434. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1435. /** Looks for a set of characters in the string.
  1436. Uses a case-sensitive comparison.
  1437. @returns true if the all the characters in the string are also found in the
  1438. string that is passed in.
  1439. */
  1440. bool containsOnly (const String& charactersItMightContain) const throw();
  1441. /** Returns true if this string contains any non-whitespace characters.
  1442. This will return false if the string contains only whitespace characters, or
  1443. if it's empty.
  1444. It is equivalent to calling "myString.trim().isNotEmpty()".
  1445. */
  1446. bool containsNonWhitespaceChars() const throw();
  1447. /** Returns true if the string matches this simple wildcard expression.
  1448. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1449. This isn't a full-blown regex though! The only wildcard characters supported
  1450. are "*" and "?". It's mainly intended for filename pattern matching.
  1451. */
  1452. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1453. // Substring location methods..
  1454. /** Searches for a character inside this string.
  1455. Uses a case-sensitive comparison.
  1456. @returns the index of the first occurrence of the character in this
  1457. string, or -1 if it's not found.
  1458. */
  1459. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1460. /** Searches for a character inside this string.
  1461. Uses a case-sensitive comparison.
  1462. @param startIndex the index from which the search should proceed
  1463. @param characterToLookFor the character to look for
  1464. @returns the index of the first occurrence of the character in this
  1465. string, or -1 if it's not found.
  1466. */
  1467. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  1468. /** Returns the index of the first character that matches one of the characters
  1469. passed-in to this method.
  1470. This scans the string, beginning from the startIndex supplied, and if it finds
  1471. a character that appears in the string charactersToLookFor, it returns its index.
  1472. If none of these characters are found, it returns -1.
  1473. If ignoreCase is true, the comparison will be case-insensitive.
  1474. @see indexOfChar, lastIndexOfAnyOf
  1475. */
  1476. int indexOfAnyOf (const String& charactersToLookFor,
  1477. int startIndex = 0,
  1478. bool ignoreCase = false) const throw();
  1479. /** Searches for a substring within this string.
  1480. Uses a case-sensitive comparison.
  1481. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1482. */
  1483. int indexOf (const String& text) const throw();
  1484. /** Searches for a substring within this string.
  1485. Uses a case-sensitive comparison.
  1486. @param startIndex the index from which the search should proceed
  1487. @param textToLookFor the string to search for
  1488. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1489. */
  1490. int indexOf (int startIndex,
  1491. const String& textToLookFor) const throw();
  1492. /** Searches for a substring within this string.
  1493. Uses a case-insensitive comparison.
  1494. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1495. */
  1496. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1497. /** Searches for a substring within this string.
  1498. Uses a case-insensitive comparison.
  1499. @param startIndex the index from which the search should proceed
  1500. @param textToLookFor the string to search for
  1501. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1502. */
  1503. int indexOfIgnoreCase (int startIndex,
  1504. const String& textToLookFor) const throw();
  1505. /** Searches for a character inside this string (working backwards from the end of the string).
  1506. Uses a case-sensitive comparison.
  1507. @returns the index of the last occurrence of the character in this
  1508. string, or -1 if it's not found.
  1509. */
  1510. int lastIndexOfChar (juce_wchar character) const throw();
  1511. /** Searches for a substring inside this string (working backwards from the end of the string).
  1512. Uses a case-sensitive comparison.
  1513. @returns the index of the start of the last occurrence of the
  1514. substring within this string, or -1 if it's not found.
  1515. */
  1516. int lastIndexOf (const String& textToLookFor) const throw();
  1517. /** Searches for a substring inside this string (working backwards from the end of the string).
  1518. Uses a case-insensitive comparison.
  1519. @returns the index of the start of the last occurrence of the
  1520. substring within this string, or -1 if it's not found.
  1521. */
  1522. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1523. /** Returns the index of the last character in this string that matches one of the
  1524. characters passed-in to this method.
  1525. This scans the string backwards, starting from its end, and if it finds
  1526. a character that appears in the string charactersToLookFor, it returns its index.
  1527. If none of these characters are found, it returns -1.
  1528. If ignoreCase is true, the comparison will be case-insensitive.
  1529. @see lastIndexOf, indexOfAnyOf
  1530. */
  1531. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1532. bool ignoreCase = false) const throw();
  1533. // Substring extraction and manipulation methods..
  1534. /** Returns the character at this index in the string.
  1535. No checks are made to see if the index is within a valid range, so be careful!
  1536. */
  1537. inline const juce_wchar& operator[] (int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text [index]; }
  1538. /** Returns a character from the string such that it can also be altered.
  1539. This can be used as a way of easily changing characters in the string.
  1540. Note that the index passed-in is not checked to see whether it's in-range, so
  1541. be careful when using this.
  1542. */
  1543. juce_wchar& operator[] (int index);
  1544. /** Returns the final character of the string.
  1545. If the string is empty this will return 0.
  1546. */
  1547. juce_wchar getLastCharacter() const throw();
  1548. /** Returns a subsection of the string.
  1549. If the range specified is beyond the limits of the string, as much as
  1550. possible is returned.
  1551. @param startIndex the index of the start of the substring needed
  1552. @param endIndex all characters from startIndex up to (but not including)
  1553. this index are returned
  1554. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1555. */
  1556. const String substring (int startIndex, int endIndex) const;
  1557. /** Returns a section of the string, starting from a given position.
  1558. @param startIndex the first character to include. If this is beyond the end
  1559. of the string, an empty string is returned. If it is zero or
  1560. less, the whole string is returned.
  1561. @returns the substring from startIndex up to the end of the string
  1562. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1563. */
  1564. const String substring (int startIndex) const;
  1565. /** Returns a version of this string with a number of characters removed
  1566. from the end.
  1567. @param numberToDrop the number of characters to drop from the end of the
  1568. string. If this is greater than the length of the string,
  1569. an empty string will be returned. If zero or less, the
  1570. original string will be returned.
  1571. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1572. */
  1573. const String dropLastCharacters (int numberToDrop) const;
  1574. /** Returns a number of characters from the end of the string.
  1575. This returns the last numCharacters characters from the end of the string. If the
  1576. string is shorter than numCharacters, the whole string is returned.
  1577. @see substring, dropLastCharacters, getLastCharacter
  1578. */
  1579. const String getLastCharacters (int numCharacters) const;
  1580. /** Returns a section of the string starting from a given substring.
  1581. This will search for the first occurrence of the given substring, and
  1582. return the section of the string starting from the point where this is
  1583. found (optionally not including the substring itself).
  1584. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1585. fromFirstOccurrenceOf ("34", false) would return "56".
  1586. If the substring isn't found, the method will return an empty string.
  1587. If ignoreCase is true, the comparison will be case-insensitive.
  1588. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1589. */
  1590. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1591. bool includeSubStringInResult,
  1592. bool ignoreCase) const;
  1593. /** Returns a section of the string starting from the last occurrence of a given substring.
  1594. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1595. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1596. return the whole of the original string.
  1597. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1598. */
  1599. const String fromLastOccurrenceOf (const String& substringToFind,
  1600. bool includeSubStringInResult,
  1601. bool ignoreCase) const;
  1602. /** Returns the start of this string, up to the first occurrence of a substring.
  1603. This will search for the first occurrence of a given substring, and then
  1604. return a copy of the string, up to the position of this substring,
  1605. optionally including or excluding the substring itself in the result.
  1606. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1607. upTo ("34", true) would return "1234".
  1608. If the substring isn't found, this will return the whole of the original string.
  1609. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1610. */
  1611. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1612. bool includeSubStringInResult,
  1613. bool ignoreCase) const;
  1614. /** Returns the start of this string, up to the last occurrence of a substring.
  1615. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1616. If the substring isn't found, this will return an empty string.
  1617. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1618. */
  1619. const String upToLastOccurrenceOf (const String& substringToFind,
  1620. bool includeSubStringInResult,
  1621. bool ignoreCase) const;
  1622. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1623. const String trim() const;
  1624. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1625. const String trimStart() const;
  1626. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1627. const String trimEnd() const;
  1628. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1629. Characters are removed from the start of the string until it finds one that is not in the
  1630. specified set, and then it stops.
  1631. @param charactersToTrim the set of characters to remove.
  1632. @see trim, trimStart, trimCharactersAtEnd
  1633. */
  1634. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1635. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1636. Characters are removed from the end of the string until it finds one that is not in the
  1637. specified set, and then it stops.
  1638. @param charactersToTrim the set of characters to remove.
  1639. @see trim, trimEnd, trimCharactersAtStart
  1640. */
  1641. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1642. /** Returns an upper-case version of this string. */
  1643. const String toUpperCase() const;
  1644. /** Returns an lower-case version of this string. */
  1645. const String toLowerCase() const;
  1646. /** Replaces a sub-section of the string with another string.
  1647. This will return a copy of this string, with a set of characters
  1648. from startIndex to startIndex + numCharsToReplace removed, and with
  1649. a new string inserted in their place.
  1650. Note that this is a const method, and won't alter the string itself.
  1651. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1652. it will be constrained to a valid range.
  1653. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1654. characters will be taken out.
  1655. @param stringToInsert the new string to insert at startIndex after the characters have been
  1656. removed.
  1657. */
  1658. const String replaceSection (int startIndex,
  1659. int numCharactersToReplace,
  1660. const String& stringToInsert) const;
  1661. /** Replaces all occurrences of a substring with another string.
  1662. Returns a copy of this string, with any occurrences of stringToReplace
  1663. swapped for stringToInsertInstead.
  1664. Note that this is a const method, and won't alter the string itself.
  1665. */
  1666. const String replace (const String& stringToReplace,
  1667. const String& stringToInsertInstead,
  1668. bool ignoreCase = false) const;
  1669. /** Returns a string with all occurrences of a character replaced with a different one. */
  1670. const String replaceCharacter (juce_wchar characterToReplace,
  1671. juce_wchar characterToInsertInstead) const;
  1672. /** Replaces a set of characters with another set.
  1673. Returns a string in which each character from charactersToReplace has been replaced
  1674. by the character at the equivalent position in newCharacters (so the two strings
  1675. passed in must be the same length).
  1676. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1677. Note that this is a const method, and won't affect the string itself.
  1678. */
  1679. const String replaceCharacters (const String& charactersToReplace,
  1680. const String& charactersToInsertInstead) const;
  1681. /** Returns a version of this string that only retains a fixed set of characters.
  1682. This will return a copy of this string, omitting any characters which are not
  1683. found in the string passed-in.
  1684. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1685. Note that this is a const method, and won't alter the string itself.
  1686. */
  1687. const String retainCharacters (const String& charactersToRetain) const;
  1688. /** Returns a version of this string with a set of characters removed.
  1689. This will return a copy of this string, omitting any characters which are
  1690. found in the string passed-in.
  1691. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1692. Note that this is a const method, and won't alter the string itself.
  1693. */
  1694. const String removeCharacters (const String& charactersToRemove) const;
  1695. /** Returns a section from the start of the string that only contains a certain set of characters.
  1696. This returns the leftmost section of the string, up to (and not including) the
  1697. first character that doesn't appear in the string passed in.
  1698. */
  1699. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1700. /** Returns a section from the start of the string that only contains a certain set of characters.
  1701. This returns the leftmost section of the string, up to (and not including) the
  1702. first character that occurs in the string passed in.
  1703. */
  1704. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1705. /** Checks whether the string might be in quotation marks.
  1706. @returns true if the string begins with a quote character (either a double or single quote).
  1707. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1708. @see unquoted, quoted
  1709. */
  1710. bool isQuotedString() const;
  1711. /** Removes quotation marks from around the string, (if there are any).
  1712. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1713. at the ends of the string are not affected. If there aren't any quotes, the original string
  1714. is returned.
  1715. Note that this is a const method, and won't alter the string itself.
  1716. @see isQuotedString, quoted
  1717. */
  1718. const String unquoted() const;
  1719. /** Adds quotation marks around a string.
  1720. This will return a copy of the string with a quote at the start and end, (but won't
  1721. add the quote if there's already one there, so it's safe to call this on strings that
  1722. may already have quotes around them).
  1723. Note that this is a const method, and won't alter the string itself.
  1724. @param quoteCharacter the character to add at the start and end
  1725. @see isQuotedString, unquoted
  1726. */
  1727. const String quoted (juce_wchar quoteCharacter = '"') const;
  1728. /** Creates a string which is a version of a string repeated and joined together.
  1729. @param stringToRepeat the string to repeat
  1730. @param numberOfTimesToRepeat how many times to repeat it
  1731. */
  1732. static const String repeatedString (const String& stringToRepeat,
  1733. int numberOfTimesToRepeat);
  1734. /** Returns a copy of this string with the specified character repeatedly added to its
  1735. beginning until the total length is at least the minimum length specified.
  1736. */
  1737. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1738. /** Returns a copy of this string with the specified character repeatedly added to its
  1739. end until the total length is at least the minimum length specified.
  1740. */
  1741. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1742. /** Creates a string from data in an unknown format.
  1743. This looks at some binary data and tries to guess whether it's Unicode
  1744. or 8-bit characters, then returns a string that represents it correctly.
  1745. Should be able to handle Unicode endianness correctly, by looking at
  1746. the first two bytes.
  1747. */
  1748. static const String createStringFromData (const void* data, int size);
  1749. /** Creates a String from a printf-style parameter list.
  1750. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1751. using the operator<< methods or pretty much anything else instead. It's only provided
  1752. here because of the popular unrest that was stirred-up when I tried to remove it...
  1753. If you're really determined to use it, at least make sure that you never, ever,
  1754. pass any String objects to it as parameters.
  1755. */
  1756. static const String formatted (const juce_wchar* formatString, ... );
  1757. // Numeric conversions..
  1758. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1759. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1760. */
  1761. explicit String (int decimalInteger);
  1762. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1763. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1764. */
  1765. explicit String (unsigned int decimalInteger);
  1766. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1767. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1768. */
  1769. explicit String (short decimalInteger);
  1770. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1771. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1772. */
  1773. explicit String (unsigned short decimalInteger);
  1774. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1775. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1776. */
  1777. explicit String (int64 largeIntegerValue);
  1778. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1779. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1780. */
  1781. explicit String (uint64 largeIntegerValue);
  1782. /** Creates a string representing this floating-point number.
  1783. @param floatValue the value to convert to a string
  1784. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1785. decimal places, and will not use exponent notation. If 0 or
  1786. less, it will use exponent notation if necessary.
  1787. @see getDoubleValue, getIntValue
  1788. */
  1789. explicit String (float floatValue,
  1790. int numberOfDecimalPlaces = 0);
  1791. /** Creates a string representing this floating-point number.
  1792. @param doubleValue the value to convert to a string
  1793. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1794. decimal places, and will not use exponent notation. If 0 or
  1795. less, it will use exponent notation if necessary.
  1796. @see getFloatValue, getIntValue
  1797. */
  1798. explicit String (double doubleValue,
  1799. int numberOfDecimalPlaces = 0);
  1800. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1801. @returns the value of the string as a 32 bit signed base-10 integer.
  1802. @see getTrailingIntValue, getHexValue32, getHexValue64
  1803. */
  1804. int getIntValue() const throw();
  1805. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1806. @returns the value of the string as a 64 bit signed base-10 integer.
  1807. */
  1808. int64 getLargeIntValue() const throw();
  1809. /** Parses a decimal number from the end of the string.
  1810. This will look for a value at the end of the string.
  1811. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1812. Negative numbers are not handled, so "xyz-5" returns 5.
  1813. @see getIntValue
  1814. */
  1815. int getTrailingIntValue() const throw();
  1816. /** Parses this string as a floating point number.
  1817. @returns the value of the string as a 32-bit floating point value.
  1818. @see getDoubleValue
  1819. */
  1820. float getFloatValue() const throw();
  1821. /** Parses this string as a floating point number.
  1822. @returns the value of the string as a 64-bit floating point value.
  1823. @see getFloatValue
  1824. */
  1825. double getDoubleValue() const throw();
  1826. /** Parses the string as a hexadecimal number.
  1827. Non-hexadecimal characters in the string are ignored.
  1828. If the string contains too many characters, then the lowest significant
  1829. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1830. @returns a 32-bit number which is the value of the string in hex.
  1831. */
  1832. int getHexValue32() const throw();
  1833. /** Parses the string as a hexadecimal number.
  1834. Non-hexadecimal characters in the string are ignored.
  1835. If the string contains too many characters, then the lowest significant
  1836. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1837. @returns a 64-bit number which is the value of the string in hex.
  1838. */
  1839. int64 getHexValue64() const throw();
  1840. /** Creates a string representing this 32-bit value in hexadecimal. */
  1841. static const String toHexString (int number);
  1842. /** Creates a string representing this 64-bit value in hexadecimal. */
  1843. static const String toHexString (int64 number);
  1844. /** Creates a string representing this 16-bit value in hexadecimal. */
  1845. static const String toHexString (short number);
  1846. /** Creates a string containing a hex dump of a block of binary data.
  1847. @param data the binary data to use as input
  1848. @param size how many bytes of data to use
  1849. @param groupSize how many bytes are grouped together before inserting a
  1850. space into the output. e.g. group size 0 has no spaces,
  1851. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1852. like "bea1 c2ff".
  1853. */
  1854. static const String toHexString (const unsigned char* data,
  1855. int size,
  1856. int groupSize = 1);
  1857. /** Returns a unicode version of this string.
  1858. Because it returns a reference to the string's internal data, the pointer
  1859. that is returned must not be stored anywhere, as it can become invalid whenever
  1860. any string methods (even some const ones!) are called.
  1861. */
  1862. inline operator const juce_wchar*() const throw() { return text; }
  1863. /** Returns a unicode version of this string.
  1864. Because it returns a reference to the string's internal data, the pointer
  1865. that is returned must not be stored anywhere, as it can become invalid whenever
  1866. any string methods (even some const ones!) are called.
  1867. */
  1868. inline operator juce_wchar*() throw() { return text; }
  1869. /** Returns a pointer to a UTF-8 version of this string.
  1870. Because it returns a reference to the string's internal data, the pointer
  1871. that is returned must not be stored anywhere, as it can be deleted whenever the
  1872. string changes.
  1873. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  1874. */
  1875. const char* toUTF8() const;
  1876. /** Creates a String from a UTF-8 encoded buffer.
  1877. If the size is < 0, it'll keep reading until it hits a zero.
  1878. */
  1879. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  1880. /** Returns the number of bytes required to represent this string as UTF8.
  1881. The number returned does NOT include the trailing zero.
  1882. @see toUTF8, copyToUTF8
  1883. */
  1884. int getNumBytesAsUTF8() const throw();
  1885. /** Copies the string to a buffer as UTF-8 characters.
  1886. Returns the number of bytes copied to the buffer, including the terminating null
  1887. character.
  1888. @param destBuffer the place to copy it to; if this is a null pointer,
  1889. the method just returns the number of bytes required
  1890. (including the terminating null character).
  1891. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1892. string won't fit, it'll put in as many as it can while
  1893. still allowing for a terminating null char at the end, and
  1894. will return the number of bytes that were actually used.
  1895. */
  1896. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  1897. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  1898. Because it returns a reference to the string's internal data, the pointer
  1899. that is returned must not be stored anywhere, as it can be deleted whenever the
  1900. string changes.
  1901. @see getNumBytesAsCString, copyToCString, toUTF8
  1902. */
  1903. const char* toCString() const;
  1904. /** Returns the number of bytes
  1905. */
  1906. int getNumBytesAsCString() const throw();
  1907. /** Copies the string to a buffer.
  1908. @param destBuffer the place to copy it to; if this is a null pointer,
  1909. the method just returns the number of bytes required
  1910. (including the terminating null character).
  1911. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1912. string won't fit, it'll put in as many as it can while
  1913. still allowing for a terminating null char at the end, and
  1914. will return the number of bytes that were actually used.
  1915. */
  1916. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  1917. /** Copies the string to a unicode buffer.
  1918. @param destBuffer the place to copy it to
  1919. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1920. not including the tailing zero, so this shouldn't be
  1921. larger than the size of your destination buffer - 1
  1922. */
  1923. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  1924. /** Increases the string's internally allocated storage.
  1925. Although the string's contents won't be affected by this call, it will
  1926. increase the amount of memory allocated internally for the string to grow into.
  1927. If you're about to make a large number of calls to methods such
  1928. as += or <<, it's more efficient to preallocate enough extra space
  1929. beforehand, so that these methods won't have to keep resizing the string
  1930. to append the extra characters.
  1931. @param numCharsNeeded the number of characters to allocate storage for. If this
  1932. value is less than the currently allocated size, it will
  1933. have no effect.
  1934. */
  1935. void preallocateStorage (size_t numCharsNeeded);
  1936. /** Swaps the contents of this string with another one.
  1937. This is a very fast operation, as no allocation or copying needs to be done.
  1938. */
  1939. void swapWith (String& other) throw();
  1940. /** A helper class to improve performance when concatenating many large strings
  1941. together.
  1942. Because appending one string to another involves measuring the length of
  1943. both strings, repeatedly doing this for many long strings will become
  1944. an exponentially slow operation. This class uses some internal state to
  1945. avoid that, so that each append operation only needs to measure the length
  1946. of the appended string.
  1947. */
  1948. class JUCE_API Concatenator
  1949. {
  1950. public:
  1951. Concatenator (String& stringToAppendTo);
  1952. ~Concatenator();
  1953. void append (const String& s);
  1954. private:
  1955. String& result;
  1956. int nextIndex;
  1957. Concatenator (const Concatenator&);
  1958. Concatenator& operator= (const Concatenator&);
  1959. };
  1960. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1961. private:
  1962. juce_wchar* text;
  1963. // internal constructor that preallocates a certain amount of memory
  1964. String (size_t numChars, int dummyVariable);
  1965. String (const String& stringToCopy, size_t charsToAllocate);
  1966. void createInternal (const juce_wchar* text, size_t numChars);
  1967. void appendInternal (const juce_wchar* text, int numExtraChars);
  1968. };
  1969. /** Concatenates two strings. */
  1970. const String JUCE_PUBLIC_FUNCTION operator+ (const char* string1, const String& string2);
  1971. /** Concatenates two strings. */
  1972. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* string1, const String& string2);
  1973. /** Concatenates two strings. */
  1974. const String JUCE_PUBLIC_FUNCTION operator+ (char string1, const String& string2);
  1975. /** Concatenates two strings. */
  1976. const String JUCE_PUBLIC_FUNCTION operator+ (juce_wchar string1, const String& string2);
  1977. /** Concatenates two strings. */
  1978. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2);
  1979. /** Concatenates two strings. */
  1980. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* string2);
  1981. /** Concatenates two strings. */
  1982. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* string2);
  1983. /** Concatenates two strings. */
  1984. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, char characterToAppend);
  1985. /** Concatenates two strings. */
  1986. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, juce_wchar characterToAppend);
  1987. /** Appends a character at the end of a string. */
  1988. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, char characterToAppend);
  1989. /** Appends a character at the end of a string. */
  1990. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, juce_wchar characterToAppend);
  1991. /** Appends a string to the end of the first one. */
  1992. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* string2);
  1993. /** Appends a string to the end of the first one. */
  1994. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* string2);
  1995. /** Appends a string to the end of the first one. */
  1996. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2);
  1997. /** Appends a decimal number at the end of a string. */
  1998. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, short number);
  1999. /** Appends a decimal number at the end of a string. */
  2000. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, int number);
  2001. /** Appends a decimal number at the end of a string. */
  2002. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, unsigned int number);
  2003. /** Appends a decimal number at the end of a string. */
  2004. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, long number);
  2005. /** Appends a decimal number at the end of a string. */
  2006. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, unsigned long number);
  2007. /** Appends a decimal number at the end of a string. */
  2008. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, float number);
  2009. /** Appends a decimal number at the end of a string. */
  2010. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, double number);
  2011. /** Case-sensitive comparison of two strings. */
  2012. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw();
  2013. /** Case-sensitive comparison of two strings. */
  2014. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw();
  2015. /** Case-sensitive comparison of two strings. */
  2016. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw();
  2017. /** Case-sensitive comparison of two strings. */
  2018. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw();
  2019. /** Case-sensitive comparison of two strings. */
  2020. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw();
  2021. /** Case-sensitive comparison of two strings. */
  2022. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw();
  2023. /** Case-sensitive comparison of two strings. */
  2024. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw();
  2025. /** Case-sensitive comparison of two strings. */
  2026. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw();
  2027. /** Case-sensitive comparison of two strings. */
  2028. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw();
  2029. /** Case-sensitive comparison of two strings. */
  2030. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw();
  2031. /** This streaming override allows you to pass a juce String directly into std output streams.
  2032. This is very handy for writing strings to std::cout, std::cerr, etc.
  2033. */
  2034. template <class charT, class traits>
  2035. std::basic_ostream <charT, traits>& JUCE_PUBLIC_FUNCTION operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2036. {
  2037. return stream << stringToWrite.toUTF8();
  2038. }
  2039. /** Writes a string to an OutputStream as UTF8. */
  2040. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text);
  2041. #endif // __JUCE_STRING_JUCEHEADER__
  2042. /*** End of inlined file: juce_String.h ***/
  2043. /**
  2044. Acts as an application-wide logging class.
  2045. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2046. method and this will then be used by all calls to writeToLog.
  2047. The logger class also contains methods for writing messages to the debugger's
  2048. output stream.
  2049. @see FileLogger
  2050. */
  2051. class JUCE_API Logger
  2052. {
  2053. public:
  2054. /** Destructor. */
  2055. virtual ~Logger();
  2056. /** Sets the current logging class to use.
  2057. Note that the object passed in won't be deleted when no longer needed.
  2058. A null pointer can be passed-in to disable any logging.
  2059. If deleteOldLogger is set to true, the existing logger will be
  2060. deleted (if there is one).
  2061. */
  2062. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2063. const bool deleteOldLogger = false);
  2064. /** Writes a string to the current logger.
  2065. This will pass the string to the logger's logMessage() method if a logger
  2066. has been set.
  2067. @see logMessage
  2068. */
  2069. static void JUCE_CALLTYPE writeToLog (const String& message);
  2070. /** Writes a message to the standard error stream.
  2071. This can be called directly, or by using the DBG() macro in
  2072. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2073. */
  2074. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2075. protected:
  2076. Logger();
  2077. /** This is overloaded by subclasses to implement custom logging behaviour.
  2078. @see setCurrentLogger
  2079. */
  2080. virtual void logMessage (const String& message) = 0;
  2081. private:
  2082. static Logger* currentLogger;
  2083. };
  2084. #endif // __JUCE_LOGGER_JUCEHEADER__
  2085. /*** End of inlined file: juce_Logger.h ***/
  2086. END_JUCE_NAMESPACE
  2087. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2088. /*** End of inlined file: juce_StandardHeader.h ***/
  2089. BEGIN_JUCE_NAMESPACE
  2090. #if JUCE_MSVC
  2091. // this is set explicitly in case the app is using a different packing size.
  2092. #pragma pack (push, 8)
  2093. #pragma warning (push)
  2094. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2095. #endif
  2096. // this is where all the class header files get brought in..
  2097. /*** Start of inlined file: juce_core_includes.h ***/
  2098. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2099. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2100. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2101. /*** Start of inlined file: juce_Array.h ***/
  2102. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2103. #define __JUCE_ARRAY_JUCEHEADER__
  2104. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2105. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2106. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2107. /*** Start of inlined file: juce_HeapBlock.h ***/
  2108. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2109. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2110. /**
  2111. Very simple container class to hold a pointer to some data on the heap.
  2112. When you need to allocate some heap storage for something, always try to use
  2113. this class instead of allocating the memory directly using malloc/free.
  2114. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2115. as an char*, but as long as you allocate it on the stack or as a class member,
  2116. it's almost impossible for it to leak memory.
  2117. It also makes your code much more concise and readable than doing the same thing
  2118. using direct allocations,
  2119. E.g. instead of this:
  2120. @code
  2121. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  2122. memcpy (temp, xyz, 1024 * sizeof (int));
  2123. juce_free (temp);
  2124. temp = (int*) juce_calloc (2048 * sizeof (int));
  2125. temp[0] = 1234;
  2126. memcpy (foobar, temp, 2048 * sizeof (int));
  2127. juce_free (temp);
  2128. @endcode
  2129. ..you could just write this:
  2130. @code
  2131. HeapBlock <int> temp (1024);
  2132. memcpy (temp, xyz, 1024 * sizeof (int));
  2133. temp.calloc (2048);
  2134. temp[0] = 1234;
  2135. memcpy (foobar, temp, 2048 * sizeof (int));
  2136. @endcode
  2137. The class is extremely lightweight, containing only a pointer to the
  2138. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2139. as their less object-oriented counterparts. Despite adding safety, you probably
  2140. won't sacrifice any performance by using this in place of normal pointers.
  2141. @see Array, OwnedArray, MemoryBlock
  2142. */
  2143. template <class ElementType>
  2144. class HeapBlock
  2145. {
  2146. public:
  2147. /** Creates a HeapBlock which is initially just a null pointer.
  2148. After creation, you can resize the array using the malloc(), calloc(),
  2149. or realloc() methods.
  2150. */
  2151. HeapBlock() throw() : data (0)
  2152. {
  2153. }
  2154. /** Creates a HeapBlock containing a number of elements.
  2155. The contents of the block are undefined, as it will have been created by a
  2156. malloc call.
  2157. If you want an array of zero values, you can use the calloc() method instead.
  2158. */
  2159. explicit HeapBlock (const size_t numElements)
  2160. : data (static_cast <ElementType*> (::juce_malloc (numElements * sizeof (ElementType))))
  2161. {
  2162. }
  2163. /** Destructor.
  2164. This will free the data, if any has been allocated.
  2165. */
  2166. ~HeapBlock()
  2167. {
  2168. ::juce_free (data);
  2169. }
  2170. /** Returns a raw pointer to the allocated data.
  2171. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2172. freed by calling the free() method.
  2173. */
  2174. inline operator ElementType*() const throw() { return data; }
  2175. /** Returns a raw pointer to the allocated data.
  2176. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2177. freed by calling the free() method.
  2178. */
  2179. inline ElementType* getData() const throw() { return data; }
  2180. /** Returns a void pointer to the allocated data.
  2181. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2182. freed by calling the free() method.
  2183. */
  2184. inline operator void*() const throw() { return static_cast <void*> (data); }
  2185. /** Lets you use indirect calls to the first element in the array.
  2186. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2187. be referencing a null pointer.
  2188. */
  2189. inline ElementType* operator->() const throw() { return data; }
  2190. /** Returns a reference to one of the data elements.
  2191. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2192. has no idea of the size it currently has allocated.
  2193. */
  2194. template <typename IndexType>
  2195. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2196. /** Returns a pointer to a data element at an offset from the start of the array.
  2197. This is the same as doing pointer arithmetic on the raw pointer itself.
  2198. */
  2199. template <typename IndexType>
  2200. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2201. /** Returns a reference to the raw data pointer.
  2202. Beware that the pointer returned here will become invalid as soon as you call
  2203. any of the allocator methods on this object!
  2204. */
  2205. inline ElementType* const* operator&() const throw() { return static_cast <ElementType* const*> (&data); }
  2206. /** Returns a reference to the raw data pointer.
  2207. Beware that the pointer returned here will become invalid as soon as you call
  2208. any of the allocator methods on this object!
  2209. */
  2210. inline ElementType** operator&() throw() { return static_cast <ElementType**> (&data); }
  2211. /** Compares the pointer with another pointer.
  2212. This can be handy for checking whether this is a null pointer.
  2213. */
  2214. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2215. /** Compares the pointer with another pointer.
  2216. This can be handy for checking whether this is a null pointer.
  2217. */
  2218. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2219. /** Allocates a specified amount of memory.
  2220. This uses the normal malloc to allocate an amount of memory for this object.
  2221. Any previously allocated memory will be freed by this method.
  2222. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2223. you wouldn't need to specify the second parameter, but it can be handy if you need
  2224. to allocate a size in bytes rather than in terms of the number of elements.
  2225. The data that is allocated will be freed when this object is deleted, or when you
  2226. call free() or any of the allocation methods.
  2227. */
  2228. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2229. {
  2230. ::juce_free (data);
  2231. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2232. }
  2233. /** Allocates a specified amount of memory and clears it.
  2234. This does the same job as the malloc() method, but clears the memory that it allocates.
  2235. */
  2236. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2237. {
  2238. ::juce_free (data);
  2239. data = static_cast <ElementType*> (::juce_calloc (newNumElements * elementSize));
  2240. }
  2241. /** Allocates a specified amount of memory and optionally clears it.
  2242. This does the same job as either malloc() or calloc(), depending on the
  2243. initialiseToZero parameter.
  2244. */
  2245. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2246. {
  2247. ::juce_free (data);
  2248. if (initialiseToZero)
  2249. data = static_cast <ElementType*> (::juce_calloc (newNumElements * sizeof (ElementType)));
  2250. else
  2251. data = static_cast <ElementType*> (::juce_malloc (newNumElements * sizeof (ElementType)));
  2252. }
  2253. /** Re-allocates a specified amount of memory.
  2254. The semantics of this method are the same as malloc() and calloc(), but it
  2255. uses realloc() to keep as much of the existing data as possible.
  2256. */
  2257. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2258. {
  2259. if (data == 0)
  2260. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2261. else
  2262. data = static_cast <ElementType*> (::juce_realloc (data, newNumElements * elementSize));
  2263. }
  2264. /** Frees any currently-allocated data.
  2265. This will free the data and reset this object to be a null pointer.
  2266. */
  2267. void free()
  2268. {
  2269. ::juce_free (data);
  2270. data = 0;
  2271. }
  2272. /** Swaps this object's data with the data of another HeapBlock.
  2273. The two objects simply exchange their data pointers.
  2274. */
  2275. void swapWith (HeapBlock <ElementType>& other) throw()
  2276. {
  2277. swapVariables (data, other.data);
  2278. }
  2279. private:
  2280. ElementType* data;
  2281. HeapBlock (const HeapBlock&);
  2282. HeapBlock& operator= (const HeapBlock&);
  2283. };
  2284. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2285. /*** End of inlined file: juce_HeapBlock.h ***/
  2286. /**
  2287. Implements some basic array storage allocation functions.
  2288. This class isn't really for public use - it's used by the other
  2289. array classes, but might come in handy for some purposes.
  2290. It inherits from a critical section class to allow the arrays to use
  2291. the "empty base class optimisation" pattern to reduce their footprint.
  2292. @see Array, OwnedArray, ReferenceCountedArray
  2293. */
  2294. template <class ElementType, class TypeOfCriticalSectionToUse>
  2295. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2296. {
  2297. public:
  2298. /** Creates an empty array. */
  2299. ArrayAllocationBase() throw()
  2300. : numAllocated (0)
  2301. {
  2302. }
  2303. /** Destructor. */
  2304. ~ArrayAllocationBase()
  2305. {
  2306. }
  2307. /** Changes the amount of storage allocated.
  2308. This will retain any data currently held in the array, and either add or
  2309. remove extra space at the end.
  2310. @param numElements the number of elements that are needed
  2311. */
  2312. void setAllocatedSize (const int numElements)
  2313. {
  2314. if (numAllocated != numElements)
  2315. {
  2316. if (numElements > 0)
  2317. elements.realloc (numElements);
  2318. else
  2319. elements.free();
  2320. numAllocated = numElements;
  2321. }
  2322. }
  2323. /** Increases the amount of storage allocated if it is less than a given amount.
  2324. This will retain any data currently held in the array, but will add
  2325. extra space at the end to make sure there it's at least as big as the size
  2326. passed in. If it's already bigger, no action is taken.
  2327. @param minNumElements the minimum number of elements that are needed
  2328. */
  2329. void ensureAllocatedSize (const int minNumElements)
  2330. {
  2331. if (minNumElements > numAllocated)
  2332. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2333. }
  2334. /** Minimises the amount of storage allocated so that it's no more than
  2335. the given number of elements.
  2336. */
  2337. void shrinkToNoMoreThan (const int maxNumElements)
  2338. {
  2339. if (maxNumElements < numAllocated)
  2340. setAllocatedSize (maxNumElements);
  2341. }
  2342. /** Swap the contents of two objects. */
  2343. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2344. {
  2345. elements.swapWith (other.elements);
  2346. swapVariables (numAllocated, other.numAllocated);
  2347. }
  2348. HeapBlock <ElementType> elements;
  2349. int numAllocated;
  2350. private:
  2351. ArrayAllocationBase (const ArrayAllocationBase&);
  2352. ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2353. };
  2354. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2355. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  2356. /*** Start of inlined file: juce_ElementComparator.h ***/
  2357. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2358. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2359. /**
  2360. Sorts a range of elements in an array.
  2361. The comparator object that is passed-in must define a public method with the following
  2362. signature:
  2363. @code
  2364. int compareElements (ElementType first, ElementType second);
  2365. @endcode
  2366. ..and this method must return:
  2367. - a value of < 0 if the first comes before the second
  2368. - a value of 0 if the two objects are equivalent
  2369. - a value of > 0 if the second comes before the first
  2370. To improve performance, the compareElements() method can be declared as static or const.
  2371. @param comparator an object which defines a compareElements() method
  2372. @param array the array to sort
  2373. @param firstElement the index of the first element of the range to be sorted
  2374. @param lastElement the index of the last element in the range that needs
  2375. sorting (this is inclusive)
  2376. @param retainOrderOfEquivalentItems if true, the order of items that the
  2377. comparator deems the same will be maintained - this will be
  2378. a slower algorithm than if they are allowed to be moved around.
  2379. @see sortArrayRetainingOrder
  2380. */
  2381. template <class ElementType, class ElementComparator>
  2382. static void sortArray (ElementComparator& comparator,
  2383. ElementType* const array,
  2384. int firstElement,
  2385. int lastElement,
  2386. const bool retainOrderOfEquivalentItems)
  2387. {
  2388. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2389. // avoids getting warning messages about the parameter being unused
  2390. if (lastElement > firstElement)
  2391. {
  2392. if (retainOrderOfEquivalentItems)
  2393. {
  2394. for (int i = firstElement; i < lastElement; ++i)
  2395. {
  2396. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2397. {
  2398. const ElementType temp = array [i];
  2399. array [i] = array[i + 1];
  2400. array [i + 1] = temp;
  2401. if (i > firstElement)
  2402. i -= 2;
  2403. }
  2404. }
  2405. }
  2406. else
  2407. {
  2408. int fromStack[30], toStack[30];
  2409. int stackIndex = 0;
  2410. for (;;)
  2411. {
  2412. const int size = (lastElement - firstElement) + 1;
  2413. if (size <= 8)
  2414. {
  2415. int j = lastElement;
  2416. int maxIndex;
  2417. while (j > firstElement)
  2418. {
  2419. maxIndex = firstElement;
  2420. for (int k = firstElement + 1; k <= j; ++k)
  2421. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2422. maxIndex = k;
  2423. const ElementType temp = array [maxIndex];
  2424. array [maxIndex] = array[j];
  2425. array [j] = temp;
  2426. --j;
  2427. }
  2428. }
  2429. else
  2430. {
  2431. const int mid = firstElement + (size >> 1);
  2432. ElementType temp = array [mid];
  2433. array [mid] = array [firstElement];
  2434. array [firstElement] = temp;
  2435. int i = firstElement;
  2436. int j = lastElement + 1;
  2437. for (;;)
  2438. {
  2439. while (++i <= lastElement
  2440. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2441. {}
  2442. while (--j > firstElement
  2443. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2444. {}
  2445. if (j < i)
  2446. break;
  2447. temp = array[i];
  2448. array[i] = array[j];
  2449. array[j] = temp;
  2450. }
  2451. temp = array [firstElement];
  2452. array [firstElement] = array[j];
  2453. array [j] = temp;
  2454. if (j - 1 - firstElement >= lastElement - i)
  2455. {
  2456. if (firstElement + 1 < j)
  2457. {
  2458. fromStack [stackIndex] = firstElement;
  2459. toStack [stackIndex] = j - 1;
  2460. ++stackIndex;
  2461. }
  2462. if (i < lastElement)
  2463. {
  2464. firstElement = i;
  2465. continue;
  2466. }
  2467. }
  2468. else
  2469. {
  2470. if (i < lastElement)
  2471. {
  2472. fromStack [stackIndex] = i;
  2473. toStack [stackIndex] = lastElement;
  2474. ++stackIndex;
  2475. }
  2476. if (firstElement + 1 < j)
  2477. {
  2478. lastElement = j - 1;
  2479. continue;
  2480. }
  2481. }
  2482. }
  2483. if (--stackIndex < 0)
  2484. break;
  2485. jassert (stackIndex < numElementsInArray (fromStack));
  2486. firstElement = fromStack [stackIndex];
  2487. lastElement = toStack [stackIndex];
  2488. }
  2489. }
  2490. }
  2491. }
  2492. /**
  2493. Searches a sorted array of elements, looking for the index at which a specified value
  2494. should be inserted for it to be in the correct order.
  2495. The comparator object that is passed-in must define a public method with the following
  2496. signature:
  2497. @code
  2498. int compareElements (ElementType first, ElementType second);
  2499. @endcode
  2500. ..and this method must return:
  2501. - a value of < 0 if the first comes before the second
  2502. - a value of 0 if the two objects are equivalent
  2503. - a value of > 0 if the second comes before the first
  2504. To improve performance, the compareElements() method can be declared as static or const.
  2505. @param comparator an object which defines a compareElements() method
  2506. @param array the array to search
  2507. @param newElement the value that is going to be inserted
  2508. @param firstElement the index of the first element to search
  2509. @param lastElement the index of the last element in the range (this is non-inclusive)
  2510. */
  2511. template <class ElementType, class ElementComparator>
  2512. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2513. ElementType* const array,
  2514. const ElementType newElement,
  2515. int firstElement,
  2516. int lastElement)
  2517. {
  2518. jassert (firstElement <= lastElement);
  2519. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2520. // avoids getting warning messages about the parameter being unused
  2521. while (firstElement < lastElement)
  2522. {
  2523. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2524. {
  2525. ++firstElement;
  2526. break;
  2527. }
  2528. else
  2529. {
  2530. const int halfway = (firstElement + lastElement) >> 1;
  2531. if (halfway == firstElement)
  2532. {
  2533. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2534. ++firstElement;
  2535. break;
  2536. }
  2537. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2538. {
  2539. firstElement = halfway;
  2540. }
  2541. else
  2542. {
  2543. lastElement = halfway;
  2544. }
  2545. }
  2546. }
  2547. return firstElement;
  2548. }
  2549. /**
  2550. A simple ElementComparator class that can be used to sort an array of
  2551. objects that support the '<' operator.
  2552. This will work for primitive types and objects that implement operator<().
  2553. Example: @code
  2554. Array <int> myArray;
  2555. DefaultElementComparator<int> sorter;
  2556. myArray.sort (sorter);
  2557. @endcode
  2558. @see ElementComparator
  2559. */
  2560. template <class ElementType>
  2561. class DefaultElementComparator
  2562. {
  2563. private:
  2564. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2565. public:
  2566. static int compareElements (ParameterType first, ParameterType second)
  2567. {
  2568. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  2569. }
  2570. };
  2571. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2572. /*** End of inlined file: juce_ElementComparator.h ***/
  2573. /*** Start of inlined file: juce_CriticalSection.h ***/
  2574. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2575. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2576. class JUCE_API ScopedLock;
  2577. class JUCE_API ScopedUnlock;
  2578. /**
  2579. Prevents multiple threads from accessing shared objects at the same time.
  2580. @see ScopedLock, Thread, InterProcessLock
  2581. */
  2582. class JUCE_API CriticalSection
  2583. {
  2584. public:
  2585. /**
  2586. Creates a CriticalSection object
  2587. */
  2588. CriticalSection() throw();
  2589. /** Destroys a CriticalSection object.
  2590. If the critical section is deleted whilst locked, its subsequent behaviour
  2591. is unpredictable.
  2592. */
  2593. ~CriticalSection() throw();
  2594. /** Locks this critical section.
  2595. If the lock is currently held by another thread, this will wait until it
  2596. becomes free.
  2597. If the lock is already held by the caller thread, the method returns immediately.
  2598. @see exit, ScopedLock
  2599. */
  2600. void enter() const throw();
  2601. /** Attempts to lock this critical section without blocking.
  2602. This method behaves identically to CriticalSection::enter, except that the caller thread
  2603. does not wait if the lock is currently held by another thread but returns false immediately.
  2604. @returns false if the lock is currently held by another thread, true otherwise.
  2605. @see enter
  2606. */
  2607. bool tryEnter() const throw();
  2608. /** Releases the lock.
  2609. If the caller thread hasn't got the lock, this can have unpredictable results.
  2610. If the enter() method has been called multiple times by the thread, each
  2611. call must be matched by a call to exit() before other threads will be allowed
  2612. to take over the lock.
  2613. @see enter, ScopedLock
  2614. */
  2615. void exit() const throw();
  2616. /** Provides the type of scoped lock to use with this type of critical section object. */
  2617. typedef ScopedLock ScopedLockType;
  2618. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  2619. typedef ScopedUnlock ScopedUnlockType;
  2620. juce_UseDebuggingNewOperator
  2621. private:
  2622. #if JUCE_WINDOWS
  2623. #if JUCE_64BIT
  2624. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2625. // block of memory here that's big enough to be used internally as a windows critical
  2626. // section object.
  2627. uint8 internal [44];
  2628. #else
  2629. uint8 internal [24];
  2630. #endif
  2631. #else
  2632. mutable pthread_mutex_t internal;
  2633. #endif
  2634. CriticalSection (const CriticalSection&);
  2635. CriticalSection& operator= (const CriticalSection&);
  2636. };
  2637. /**
  2638. A class that can be used in place of a real CriticalSection object.
  2639. This is currently used by some templated classes, and should get
  2640. optimised out by the compiler.
  2641. @see Array, OwnedArray, ReferenceCountedArray
  2642. */
  2643. class JUCE_API DummyCriticalSection
  2644. {
  2645. public:
  2646. inline DummyCriticalSection() throw() {}
  2647. inline ~DummyCriticalSection() throw() {}
  2648. inline void enter() const throw() {}
  2649. inline void exit() const throw() {}
  2650. /** A dummy scoped-lock type to use with a dummy critical section. */
  2651. struct ScopedLockType
  2652. {
  2653. ScopedLockType (const DummyCriticalSection&) throw() {}
  2654. };
  2655. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  2656. typedef ScopedLockType ScopedUnlockType;
  2657. private:
  2658. DummyCriticalSection (const DummyCriticalSection&);
  2659. DummyCriticalSection& operator= (const DummyCriticalSection&);
  2660. };
  2661. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2662. /*** End of inlined file: juce_CriticalSection.h ***/
  2663. /**
  2664. Holds a list of simple objects, such as ints, doubles, or pointers.
  2665. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  2666. The array can be used to hold simple, non-polymorphic objects as well as primitive types - to
  2667. do so, the class must fulfil these requirements:
  2668. - it must have a copy constructor and operator=
  2669. - it must be able to be relocated in memory by a memcpy without this causing a problem - so no
  2670. objects whose functionality relies on pointers or references to themselves can be used.
  2671. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  2672. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  2673. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  2674. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  2675. specialised class StringArray, which provides more useful functions.
  2676. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2677. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2678. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2679. */
  2680. template <typename ElementType,
  2681. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  2682. class Array
  2683. {
  2684. private:
  2685. #if defined (_MSC_VER) && _MSC_VER <= 1400
  2686. typedef const ElementType& ParameterType;
  2687. #else
  2688. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2689. #endif
  2690. public:
  2691. /** Creates an empty array. */
  2692. Array() throw()
  2693. : numUsed (0)
  2694. {
  2695. }
  2696. /** Creates a copy of another array.
  2697. @param other the array to copy
  2698. */
  2699. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  2700. {
  2701. const ScopedLockType lock (other.getLock());
  2702. numUsed = other.numUsed;
  2703. data.setAllocatedSize (other.numUsed);
  2704. for (int i = 0; i < numUsed; ++i)
  2705. new (data.elements + i) ElementType (other.data.elements[i]);
  2706. }
  2707. /** Initalises from a null-terminated C array of values.
  2708. @param values the array to copy from
  2709. */
  2710. template <typename TypeToCreateFrom>
  2711. explicit Array (const TypeToCreateFrom* values)
  2712. : numUsed (0)
  2713. {
  2714. while (*values != TypeToCreateFrom())
  2715. add (*values++);
  2716. }
  2717. /** Initalises from a C array of values.
  2718. @param values the array to copy from
  2719. @param numValues the number of values in the array
  2720. */
  2721. template <typename TypeToCreateFrom>
  2722. Array (const TypeToCreateFrom* values, int numValues)
  2723. : numUsed (numValues)
  2724. {
  2725. data.setAllocatedSize (numValues);
  2726. for (int i = 0; i < numValues; ++i)
  2727. new (data.elements + i) ElementType (values[i]);
  2728. }
  2729. /** Destructor. */
  2730. ~Array()
  2731. {
  2732. for (int i = 0; i < numUsed; ++i)
  2733. data.elements[i].~ElementType();
  2734. }
  2735. /** Copies another array.
  2736. @param other the array to copy
  2737. */
  2738. Array& operator= (const Array& other)
  2739. {
  2740. if (this != &other)
  2741. {
  2742. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  2743. swapWithArray (otherCopy);
  2744. }
  2745. return *this;
  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. const ScopedLockType lock (getLock());
  2756. if (numUsed != other.numUsed)
  2757. return false;
  2758. for (int i = numUsed; --i >= 0;)
  2759. if (! (data.elements [i] == other.data.elements [i]))
  2760. return false;
  2761. return true;
  2762. }
  2763. /** Compares this array to another one.
  2764. Two arrays are considered equal if they both contain the same set of
  2765. elements, in the same order.
  2766. @param other the other array to compare with
  2767. */
  2768. template <class OtherArrayType>
  2769. bool operator!= (const OtherArrayType& other) const
  2770. {
  2771. return ! operator== (other);
  2772. }
  2773. /** Removes all elements from the array.
  2774. This will remove all the elements, and free any storage that the array is
  2775. using. To clear the array without freeing the storage, use the clearQuick()
  2776. method instead.
  2777. @see clearQuick
  2778. */
  2779. void clear()
  2780. {
  2781. const ScopedLockType lock (getLock());
  2782. for (int i = 0; i < numUsed; ++i)
  2783. data.elements[i].~ElementType();
  2784. data.setAllocatedSize (0);
  2785. numUsed = 0;
  2786. }
  2787. /** Removes all elements from the array without freeing the array's allocated storage.
  2788. @see clear
  2789. */
  2790. void clearQuick()
  2791. {
  2792. const ScopedLockType lock (getLock());
  2793. for (int i = 0; i < numUsed; ++i)
  2794. data.elements[i].~ElementType();
  2795. numUsed = 0;
  2796. }
  2797. /** Returns the current number of elements in the array.
  2798. */
  2799. inline int size() const throw()
  2800. {
  2801. return numUsed;
  2802. }
  2803. /** Returns one of the elements in the array.
  2804. If the index passed in is beyond the range of valid elements, this
  2805. will return zero.
  2806. If you're certain that the index will always be a valid element, you
  2807. can call getUnchecked() instead, which is faster.
  2808. @param index the index of the element being requested (0 is the first element in the array)
  2809. @see getUnchecked, getFirst, getLast
  2810. */
  2811. inline ElementType operator[] (const int index) const
  2812. {
  2813. const ScopedLockType lock (getLock());
  2814. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  2815. : ElementType();
  2816. }
  2817. /** Returns one of the elements in the array, without checking the index passed in.
  2818. Unlike the operator[] method, this will try to return an element without
  2819. checking that the index is within the bounds of the array, so should only
  2820. be used when you're confident that it will always be a valid index.
  2821. @param index the index of the element being requested (0 is the first element in the array)
  2822. @see operator[], getFirst, getLast
  2823. */
  2824. inline const ElementType getUnchecked (const int index) const
  2825. {
  2826. const ScopedLockType lock (getLock());
  2827. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2828. return data.elements [index];
  2829. }
  2830. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2831. This is like getUnchecked, but returns a direct reference to the element, so that
  2832. you can alter it directly. Obviously this can be dangerous, so only use it when
  2833. absolutely necessary.
  2834. @param index the index of the element being requested (0 is the first element in the array)
  2835. @see operator[], getFirst, getLast
  2836. */
  2837. inline ElementType& getReference (const int index) const throw()
  2838. {
  2839. const ScopedLockType lock (getLock());
  2840. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2841. return data.elements [index];
  2842. }
  2843. /** Returns the first element in the array, or 0 if the array is empty.
  2844. @see operator[], getUnchecked, getLast
  2845. */
  2846. inline ElementType getFirst() const
  2847. {
  2848. const ScopedLockType lock (getLock());
  2849. return (numUsed > 0) ? data.elements [0]
  2850. : ElementType();
  2851. }
  2852. /** Returns the last element in the array, or 0 if the array is empty.
  2853. @see operator[], getUnchecked, getFirst
  2854. */
  2855. inline ElementType getLast() const
  2856. {
  2857. const ScopedLockType lock (getLock());
  2858. return (numUsed > 0) ? data.elements [numUsed - 1]
  2859. : ElementType();
  2860. }
  2861. /** Returns a pointer to the actual array data.
  2862. This pointer will only be valid until the next time a non-const method
  2863. is called on the array.
  2864. */
  2865. inline ElementType* getRawDataPointer() throw()
  2866. {
  2867. return data.elements;
  2868. }
  2869. /** Finds the index of the first element which matches the value passed in.
  2870. This will search the array for the given object, and return the index
  2871. of its first occurrence. If the object isn't found, the method will return -1.
  2872. @param elementToLookFor the value or object to look for
  2873. @returns the index of the object, or -1 if it's not found
  2874. */
  2875. int indexOf (ParameterType elementToLookFor) const
  2876. {
  2877. const ScopedLockType lock (getLock());
  2878. const ElementType* e = data.elements.getData();
  2879. const ElementType* const end = e + numUsed;
  2880. while (e != end)
  2881. {
  2882. if (elementToLookFor == *e)
  2883. return static_cast <int> (e - data.elements.getData());
  2884. ++e;
  2885. }
  2886. return -1;
  2887. }
  2888. /** Returns true if the array contains at least one occurrence of an object.
  2889. @param elementToLookFor the value or object to look for
  2890. @returns true if the item is found
  2891. */
  2892. bool contains (ParameterType elementToLookFor) const
  2893. {
  2894. const ScopedLockType lock (getLock());
  2895. const ElementType* e = data.elements.getData();
  2896. const ElementType* const end = e + numUsed;
  2897. while (e != end)
  2898. {
  2899. if (elementToLookFor == *e)
  2900. return true;
  2901. ++e;
  2902. }
  2903. return false;
  2904. }
  2905. /** Appends a new element at the end of the array.
  2906. @param newElement the new object to add to the array
  2907. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  2908. */
  2909. void add (ParameterType newElement)
  2910. {
  2911. const ScopedLockType lock (getLock());
  2912. data.ensureAllocatedSize (numUsed + 1);
  2913. new (data.elements + numUsed++) ElementType (newElement);
  2914. }
  2915. /** Inserts a new element into the array at a given position.
  2916. If the index is less than 0 or greater than the size of the array, the
  2917. element will be added to the end of the array.
  2918. Otherwise, it will be inserted into the array, moving all the later elements
  2919. along to make room.
  2920. @param indexToInsertAt the index at which the new element should be
  2921. inserted (pass in -1 to add it to the end)
  2922. @param newElement the new object to add to the array
  2923. @see add, addSorted, addUsingDefaultSort, set
  2924. */
  2925. void insert (int indexToInsertAt, ParameterType newElement)
  2926. {
  2927. const ScopedLockType lock (getLock());
  2928. data.ensureAllocatedSize (numUsed + 1);
  2929. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2930. {
  2931. ElementType* const insertPos = data.elements + indexToInsertAt;
  2932. const int numberToMove = numUsed - indexToInsertAt;
  2933. if (numberToMove > 0)
  2934. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2935. new (insertPos) ElementType (newElement);
  2936. ++numUsed;
  2937. }
  2938. else
  2939. {
  2940. new (data.elements + numUsed++) ElementType (newElement);
  2941. }
  2942. }
  2943. /** Inserts multiple copies of an element into the array at a given position.
  2944. If the index is less than 0 or greater than the size of the array, the
  2945. element will be added to the end of the array.
  2946. Otherwise, it will be inserted into the array, moving all the later elements
  2947. along to make room.
  2948. @param indexToInsertAt the index at which the new element should be inserted
  2949. @param newElement the new object to add to the array
  2950. @param numberOfTimesToInsertIt how many copies of the value to insert
  2951. @see insert, add, addSorted, set
  2952. */
  2953. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  2954. int numberOfTimesToInsertIt)
  2955. {
  2956. if (numberOfTimesToInsertIt > 0)
  2957. {
  2958. const ScopedLockType lock (getLock());
  2959. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2960. ElementType* insertPos;
  2961. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2962. {
  2963. insertPos = data.elements + indexToInsertAt;
  2964. const int numberToMove = numUsed - indexToInsertAt;
  2965. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2966. }
  2967. else
  2968. {
  2969. insertPos = data.elements + numUsed;
  2970. }
  2971. numUsed += numberOfTimesToInsertIt;
  2972. while (--numberOfTimesToInsertIt >= 0)
  2973. new (insertPos++) ElementType (newElement);
  2974. }
  2975. }
  2976. /** Inserts an array of values into this array at a given position.
  2977. If the index is less than 0 or greater than the size of the array, the
  2978. new elements will be added to the end of the array.
  2979. Otherwise, they will be inserted into the array, moving all the later elements
  2980. along to make room.
  2981. @param indexToInsertAt the index at which the first new element should be inserted
  2982. @param newElements the new values to add to the array
  2983. @param numberOfElements how many items are in the array
  2984. @see insert, add, addSorted, set
  2985. */
  2986. void insertArray (int indexToInsertAt,
  2987. const ElementType* newElements,
  2988. int numberOfElements)
  2989. {
  2990. if (numberOfElements > 0)
  2991. {
  2992. const ScopedLockType lock (getLock());
  2993. data.ensureAllocatedSize (numUsed + numberOfElements);
  2994. ElementType* insertPos;
  2995. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2996. {
  2997. insertPos = data.elements + indexToInsertAt;
  2998. const int numberToMove = numUsed - indexToInsertAt;
  2999. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3000. }
  3001. else
  3002. {
  3003. insertPos = data.elements + numUsed;
  3004. }
  3005. numUsed += numberOfElements;
  3006. while (--numberOfElements >= 0)
  3007. new (insertPos++) ElementType (*newElements++);
  3008. }
  3009. }
  3010. /** Appends a new element at the end of the array as long as the array doesn't
  3011. already contain it.
  3012. If the array already contains an element that matches the one passed in, nothing
  3013. will be done.
  3014. @param newElement the new object to add to the array
  3015. */
  3016. void addIfNotAlreadyThere (ParameterType newElement)
  3017. {
  3018. const ScopedLockType lock (getLock());
  3019. if (! contains (newElement))
  3020. add (newElement);
  3021. }
  3022. /** Replaces an element with a new value.
  3023. If the index is less than zero, this method does nothing.
  3024. If the index is beyond the end of the array, the item is added to the end of the array.
  3025. @param indexToChange the index whose value you want to change
  3026. @param newValue the new value to set for this index.
  3027. @see add, insert
  3028. */
  3029. void set (const int indexToChange, ParameterType newValue)
  3030. {
  3031. jassert (indexToChange >= 0);
  3032. const ScopedLockType lock (getLock());
  3033. if (((unsigned int) indexToChange) < (unsigned int) numUsed)
  3034. {
  3035. data.elements [indexToChange] = newValue;
  3036. }
  3037. else if (indexToChange >= 0)
  3038. {
  3039. data.ensureAllocatedSize (numUsed + 1);
  3040. new (data.elements + numUsed++) ElementType (newValue);
  3041. }
  3042. }
  3043. /** Replaces an element with a new value without doing any bounds-checking.
  3044. This just sets a value directly in the array's internal storage, so you'd
  3045. better make sure it's in range!
  3046. @param indexToChange the index whose value you want to change
  3047. @param newValue the new value to set for this index.
  3048. @see set, getUnchecked
  3049. */
  3050. void setUnchecked (const int indexToChange, ParameterType newValue)
  3051. {
  3052. const ScopedLockType lock (getLock());
  3053. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3054. data.elements [indexToChange] = newValue;
  3055. }
  3056. /** Adds elements from an array to the end of this array.
  3057. @param elementsToAdd the array of elements to add
  3058. @param numElementsToAdd how many elements are in this other array
  3059. @see add
  3060. */
  3061. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3062. {
  3063. const ScopedLockType lock (getLock());
  3064. if (numElementsToAdd > 0)
  3065. {
  3066. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3067. while (--numElementsToAdd >= 0)
  3068. {
  3069. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  3070. ++numUsed;
  3071. }
  3072. }
  3073. }
  3074. /** This swaps the contents of this array with those of another array.
  3075. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3076. because it just swaps their internal pointers.
  3077. */
  3078. void swapWithArray (Array& otherArray) throw()
  3079. {
  3080. const ScopedLockType lock1 (getLock());
  3081. const ScopedLockType lock2 (otherArray.getLock());
  3082. data.swapWith (otherArray.data);
  3083. swapVariables (numUsed, otherArray.numUsed);
  3084. }
  3085. /** Adds elements from another array to the end of this array.
  3086. @param arrayToAddFrom the array from which to copy the elements
  3087. @param startIndex the first element of the other array to start copying from
  3088. @param numElementsToAdd how many elements to add from the other array. If this
  3089. value is negative or greater than the number of available elements,
  3090. all available elements will be copied.
  3091. @see add
  3092. */
  3093. template <class OtherArrayType>
  3094. void addArray (const OtherArrayType& arrayToAddFrom,
  3095. int startIndex = 0,
  3096. int numElementsToAdd = -1)
  3097. {
  3098. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3099. const ScopedLockType lock2 (getLock());
  3100. if (startIndex < 0)
  3101. {
  3102. jassertfalse;
  3103. startIndex = 0;
  3104. }
  3105. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3106. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3107. while (--numElementsToAdd >= 0)
  3108. add (arrayToAddFrom.getUnchecked (startIndex++));
  3109. }
  3110. /** Inserts a new element into the array, assuming that the array is sorted.
  3111. This will use a comparator to find the position at which the new element
  3112. should go. If the array isn't sorted, the behaviour of this
  3113. method will be unpredictable.
  3114. @param comparator the comparator to use to compare the elements - see the sort()
  3115. method for details about the form this object should take
  3116. @param newElement the new element to insert to the array
  3117. @see addUsingDefaultSort, add, sort
  3118. */
  3119. template <class ElementComparator>
  3120. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3121. {
  3122. const ScopedLockType lock (getLock());
  3123. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3124. }
  3125. /** Inserts a new element into the array, assuming that the array is sorted.
  3126. This will use the DefaultElementComparator class for sorting, so your ElementType
  3127. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3128. method will be unpredictable.
  3129. @param newElement the new element to insert to the array
  3130. @see addSorted, sort
  3131. */
  3132. void addUsingDefaultSort (ParameterType newElement)
  3133. {
  3134. DefaultElementComparator <ElementType> comparator;
  3135. addSorted (comparator, newElement);
  3136. }
  3137. /** Finds the index of an element in the array, assuming that the array is sorted.
  3138. This will use a comparator to do a binary-chop to find the index of the given
  3139. element, if it exists. If the array isn't sorted, the behaviour of this
  3140. method will be unpredictable.
  3141. @param comparator the comparator to use to compare the elements - see the sort()
  3142. method for details about the form this object should take
  3143. @param elementToLookFor the element to search for
  3144. @returns the index of the element, or -1 if it's not found
  3145. @see addSorted, sort
  3146. */
  3147. template <class ElementComparator>
  3148. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3149. {
  3150. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3151. // avoids getting warning messages about the parameter being unused
  3152. const ScopedLockType lock (getLock());
  3153. int start = 0;
  3154. int end = numUsed;
  3155. for (;;)
  3156. {
  3157. if (start >= end)
  3158. {
  3159. return -1;
  3160. }
  3161. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3162. {
  3163. return start;
  3164. }
  3165. else
  3166. {
  3167. const int halfway = (start + end) >> 1;
  3168. if (halfway == start)
  3169. return -1;
  3170. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3171. start = halfway;
  3172. else
  3173. end = halfway;
  3174. }
  3175. }
  3176. }
  3177. /** Removes an element from the array.
  3178. This will remove the element at a given index, and move back
  3179. all the subsequent elements to close the gap.
  3180. If the index passed in is out-of-range, nothing will happen.
  3181. @param indexToRemove the index of the element to remove
  3182. @returns the element that has been removed
  3183. @see removeValue, removeRange
  3184. */
  3185. ElementType remove (const int indexToRemove)
  3186. {
  3187. const ScopedLockType lock (getLock());
  3188. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3189. {
  3190. --numUsed;
  3191. ElementType* const e = data.elements + indexToRemove;
  3192. ElementType removed (*e);
  3193. e->~ElementType();
  3194. const int numberToShift = numUsed - indexToRemove;
  3195. if (numberToShift > 0)
  3196. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3197. if ((numUsed << 1) < data.numAllocated)
  3198. minimiseStorageOverheads();
  3199. return removed;
  3200. }
  3201. else
  3202. {
  3203. return ElementType();
  3204. }
  3205. }
  3206. /** Removes an item from the array.
  3207. This will remove the first occurrence of the given element from the array.
  3208. If the item isn't found, no action is taken.
  3209. @param valueToRemove the object to try to remove
  3210. @see remove, removeRange
  3211. */
  3212. void removeValue (ParameterType valueToRemove)
  3213. {
  3214. const ScopedLockType lock (getLock());
  3215. ElementType* e = data.elements;
  3216. for (int i = numUsed; --i >= 0;)
  3217. {
  3218. if (valueToRemove == *e)
  3219. {
  3220. remove (static_cast <int> (e - data.elements.getData()));
  3221. break;
  3222. }
  3223. ++e;
  3224. }
  3225. }
  3226. /** Removes a range of elements from the array.
  3227. This will remove a set of elements, starting from the given index,
  3228. and move subsequent elements down to close the gap.
  3229. If the range extends beyond the bounds of the array, it will
  3230. be safely clipped to the size of the array.
  3231. @param startIndex the index of the first element to remove
  3232. @param numberToRemove how many elements should be removed
  3233. @see remove, removeValue
  3234. */
  3235. void removeRange (int startIndex, int numberToRemove)
  3236. {
  3237. const ScopedLockType lock (getLock());
  3238. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3239. startIndex = jlimit (0, numUsed, startIndex);
  3240. if (endIndex > startIndex)
  3241. {
  3242. ElementType* const e = data.elements + startIndex;
  3243. numberToRemove = endIndex - startIndex;
  3244. for (int i = 0; i < numberToRemove; ++i)
  3245. e[i].~ElementType();
  3246. const int numToShift = numUsed - endIndex;
  3247. if (numToShift > 0)
  3248. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3249. numUsed -= numberToRemove;
  3250. if ((numUsed << 1) < data.numAllocated)
  3251. minimiseStorageOverheads();
  3252. }
  3253. }
  3254. /** Removes the last n elements from the array.
  3255. @param howManyToRemove how many elements to remove from the end of the array
  3256. @see remove, removeValue, removeRange
  3257. */
  3258. void removeLast (int howManyToRemove = 1)
  3259. {
  3260. const ScopedLockType lock (getLock());
  3261. if (howManyToRemove > numUsed)
  3262. howManyToRemove = numUsed;
  3263. for (int i = 0; i < howManyToRemove; ++i)
  3264. data.elements [numUsed - i].~ElementType();
  3265. numUsed -= howManyToRemove;
  3266. if ((numUsed << 1) < data.numAllocated)
  3267. minimiseStorageOverheads();
  3268. }
  3269. /** Removes any elements which are also in another array.
  3270. @param otherArray the other array in which to look for elements to remove
  3271. @see removeValuesNotIn, remove, removeValue, removeRange
  3272. */
  3273. template <class OtherArrayType>
  3274. void removeValuesIn (const OtherArrayType& otherArray)
  3275. {
  3276. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3277. const ScopedLockType lock2 (getLock());
  3278. if (this == &otherArray)
  3279. {
  3280. clear();
  3281. }
  3282. else
  3283. {
  3284. if (otherArray.size() > 0)
  3285. {
  3286. for (int i = numUsed; --i >= 0;)
  3287. if (otherArray.contains (data.elements [i]))
  3288. remove (i);
  3289. }
  3290. }
  3291. }
  3292. /** Removes any elements which are not found in another array.
  3293. Only elements which occur in this other array will be retained.
  3294. @param otherArray the array in which to look for elements NOT to remove
  3295. @see removeValuesIn, remove, removeValue, removeRange
  3296. */
  3297. template <class OtherArrayType>
  3298. void removeValuesNotIn (const OtherArrayType& otherArray)
  3299. {
  3300. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3301. const ScopedLockType lock2 (getLock());
  3302. if (this != &otherArray)
  3303. {
  3304. if (otherArray.size() <= 0)
  3305. {
  3306. clear();
  3307. }
  3308. else
  3309. {
  3310. for (int i = numUsed; --i >= 0;)
  3311. if (! otherArray.contains (data.elements [i]))
  3312. remove (i);
  3313. }
  3314. }
  3315. }
  3316. /** Swaps over two elements in the array.
  3317. This swaps over the elements found at the two indexes passed in.
  3318. If either index is out-of-range, this method will do nothing.
  3319. @param index1 index of one of the elements to swap
  3320. @param index2 index of the other element to swap
  3321. */
  3322. void swap (const int index1,
  3323. const int index2)
  3324. {
  3325. const ScopedLockType lock (getLock());
  3326. if (((unsigned int) index1) < (unsigned int) numUsed
  3327. && ((unsigned int) index2) < (unsigned int) numUsed)
  3328. {
  3329. swapVariables (data.elements [index1],
  3330. data.elements [index2]);
  3331. }
  3332. }
  3333. /** Moves one of the values to a different position.
  3334. This will move the value to a specified index, shuffling along
  3335. any intervening elements as required.
  3336. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3337. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3338. @param currentIndex the index of the value to be moved. If this isn't a
  3339. valid index, then nothing will be done
  3340. @param newIndex the index at which you'd like this value to end up. If this
  3341. is less than zero, the value will be moved to the end
  3342. of the array
  3343. */
  3344. void move (const int currentIndex, int newIndex) throw()
  3345. {
  3346. if (currentIndex != newIndex)
  3347. {
  3348. const ScopedLockType lock (getLock());
  3349. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3350. {
  3351. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3352. newIndex = numUsed - 1;
  3353. char tempCopy [sizeof (ElementType)];
  3354. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  3355. if (newIndex > currentIndex)
  3356. {
  3357. memmove (data.elements + currentIndex,
  3358. data.elements + currentIndex + 1,
  3359. (newIndex - currentIndex) * sizeof (ElementType));
  3360. }
  3361. else
  3362. {
  3363. memmove (data.elements + newIndex + 1,
  3364. data.elements + newIndex,
  3365. (currentIndex - newIndex) * sizeof (ElementType));
  3366. }
  3367. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  3368. }
  3369. }
  3370. }
  3371. /** Reduces the amount of storage being used by the array.
  3372. Arrays typically allocate slightly more storage than they need, and after
  3373. removing elements, they may have quite a lot of unused space allocated.
  3374. This method will reduce the amount of allocated storage to a minimum.
  3375. */
  3376. void minimiseStorageOverheads()
  3377. {
  3378. const ScopedLockType lock (getLock());
  3379. data.shrinkToNoMoreThan (numUsed);
  3380. }
  3381. /** Increases the array's internal storage to hold a minimum number of elements.
  3382. Calling this before adding a large known number of elements means that
  3383. the array won't have to keep dynamically resizing itself as the elements
  3384. are added, and it'll therefore be more efficient.
  3385. */
  3386. void ensureStorageAllocated (const int minNumElements)
  3387. {
  3388. const ScopedLockType lock (getLock());
  3389. data.ensureAllocatedSize (minNumElements);
  3390. }
  3391. /** Sorts the elements in the array.
  3392. This will use a comparator object to sort the elements into order. The object
  3393. passed must have a method of the form:
  3394. @code
  3395. int compareElements (ElementType first, ElementType second);
  3396. @endcode
  3397. ..and this method must return:
  3398. - a value of < 0 if the first comes before the second
  3399. - a value of 0 if the two objects are equivalent
  3400. - a value of > 0 if the second comes before the first
  3401. To improve performance, the compareElements() method can be declared as static or const.
  3402. @param comparator the comparator to use for comparing elements.
  3403. @param retainOrderOfEquivalentItems if this is true, then items
  3404. which the comparator says are equivalent will be
  3405. kept in the order in which they currently appear
  3406. in the array. This is slower to perform, but may
  3407. be important in some cases. If it's false, a faster
  3408. algorithm is used, but equivalent elements may be
  3409. rearranged.
  3410. @see addSorted, indexOfSorted, sortArray
  3411. */
  3412. template <class ElementComparator>
  3413. void sort (ElementComparator& comparator,
  3414. const bool retainOrderOfEquivalentItems = false) const
  3415. {
  3416. const ScopedLockType lock (getLock());
  3417. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3418. // avoids getting warning messages about the parameter being unused
  3419. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  3420. }
  3421. /** Returns the CriticalSection that locks this array.
  3422. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  3423. an object of ScopedLockType as an RAII lock for it.
  3424. */
  3425. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  3426. /** Returns the type of scoped lock to use for locking this array */
  3427. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  3428. juce_UseDebuggingNewOperator
  3429. private:
  3430. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  3431. int numUsed;
  3432. };
  3433. #endif // __JUCE_ARRAY_JUCEHEADER__
  3434. /*** End of inlined file: juce_Array.h ***/
  3435. #endif
  3436. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3437. #endif
  3438. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3439. /*** Start of inlined file: juce_BigInteger.h ***/
  3440. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3441. #define __JUCE_BIGINTEGER_JUCEHEADER__
  3442. class MemoryBlock;
  3443. /**
  3444. An arbitrarily large integer class.
  3445. A BigInteger can be used in a similar way to a normal integer, but has no size
  3446. limit (except for memory and performance constraints).
  3447. Negative values are possible, but the value isn't stored as 2s-complement, so
  3448. be careful if you use negative values and look at the values of individual bits.
  3449. */
  3450. class JUCE_API BigInteger
  3451. {
  3452. public:
  3453. /** Creates an empty BigInteger */
  3454. BigInteger();
  3455. /** Creates a BigInteger containing an integer value in its low bits.
  3456. The low 32 bits of the number are initialised with this value.
  3457. */
  3458. BigInteger (unsigned int value);
  3459. /** Creates a BigInteger containing an integer value in its low bits.
  3460. The low 32 bits of the number are initialised with the absolute value
  3461. passed in, and its sign is set to reflect the sign of the number.
  3462. */
  3463. BigInteger (int value);
  3464. /** Creates a BigInteger containing an integer value in its low bits.
  3465. The low 64 bits of the number are initialised with the absolute value
  3466. passed in, and its sign is set to reflect the sign of the number.
  3467. */
  3468. BigInteger (int64 value);
  3469. /** Creates a copy of another BigInteger. */
  3470. BigInteger (const BigInteger& other);
  3471. /** Destructor. */
  3472. ~BigInteger();
  3473. /** Copies another BigInteger onto this one. */
  3474. BigInteger& operator= (const BigInteger& other);
  3475. /** Swaps the internal contents of this with another object. */
  3476. void swapWith (BigInteger& other) throw();
  3477. /** Returns the value of a specified bit in the number.
  3478. If the index is out-of-range, the result will be false.
  3479. */
  3480. bool operator[] (int bit) const throw();
  3481. /** Returns true if no bits are set. */
  3482. bool isZero() const throw();
  3483. /** Returns true if the value is 1. */
  3484. bool isOne() const throw();
  3485. /** Attempts to get the lowest bits of the value as an integer.
  3486. If the value is bigger than the integer limits, this will return only the lower bits.
  3487. */
  3488. int toInteger() const throw();
  3489. /** Resets the value to 0. */
  3490. void clear();
  3491. /** Clears a particular bit in the number. */
  3492. void clearBit (int bitNumber) throw();
  3493. /** Sets a specified bit to 1. */
  3494. void setBit (int bitNumber);
  3495. /** Sets or clears a specified bit. */
  3496. void setBit (int bitNumber, bool shouldBeSet);
  3497. /** Sets a range of bits to be either on or off.
  3498. @param startBit the first bit to change
  3499. @param numBits the number of bits to change
  3500. @param shouldBeSet whether to turn these bits on or off
  3501. */
  3502. void setRange (int startBit, int numBits, bool shouldBeSet);
  3503. /** Inserts a bit an a given position, shifting up any bits above it. */
  3504. void insertBit (int bitNumber, bool shouldBeSet);
  3505. /** Returns a range of bits as a new BigInteger.
  3506. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3507. @see getBitRangeAsInt
  3508. */
  3509. const BigInteger getBitRange (int startBit, int numBits) const;
  3510. /** Returns a range of bits as an integer value.
  3511. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3512. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3513. getBitRange().
  3514. */
  3515. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3516. /** Sets a range of bits to an integer value.
  3517. Copies the given integer onto a range of bits, starting at startBit,
  3518. and using up to numBits of the available bits.
  3519. */
  3520. void setBitRangeAsInt (int startBit, int numBits, unsigned int valueToSet);
  3521. /** Shifts a section of bits left or right.
  3522. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3523. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3524. */
  3525. void shiftBits (int howManyBitsLeft, int startBit);
  3526. /** Returns the total number of set bits in the value. */
  3527. int countNumberOfSetBits() const throw();
  3528. /** Looks for the index of the next set bit after a given starting point.
  3529. This searches from startIndex (inclusive) upwards for the first set bit,
  3530. and returns its index. If no set bits are found, it returns -1.
  3531. */
  3532. int findNextSetBit (int startIndex = 0) const throw();
  3533. /** Looks for the index of the next clear bit after a given starting point.
  3534. This searches from startIndex (inclusive) upwards for the first clear bit,
  3535. and returns its index.
  3536. */
  3537. int findNextClearBit (int startIndex = 0) const throw();
  3538. /** Returns the index of the highest set bit in the number.
  3539. If the value is zero, this will return -1.
  3540. */
  3541. int getHighestBit() const throw();
  3542. // All the standard arithmetic ops...
  3543. BigInteger& operator+= (const BigInteger& other);
  3544. BigInteger& operator-= (const BigInteger& other);
  3545. BigInteger& operator*= (const BigInteger& other);
  3546. BigInteger& operator/= (const BigInteger& other);
  3547. BigInteger& operator|= (const BigInteger& other);
  3548. BigInteger& operator&= (const BigInteger& other);
  3549. BigInteger& operator^= (const BigInteger& other);
  3550. BigInteger& operator%= (const BigInteger& other);
  3551. BigInteger& operator<<= (int numBitsToShift);
  3552. BigInteger& operator>>= (int numBitsToShift);
  3553. BigInteger& operator++();
  3554. BigInteger& operator--();
  3555. const BigInteger operator++ (int);
  3556. const BigInteger operator-- (int);
  3557. const BigInteger operator-() const;
  3558. const BigInteger operator+ (const BigInteger& other) const;
  3559. const BigInteger operator- (const BigInteger& other) const;
  3560. const BigInteger operator* (const BigInteger& other) const;
  3561. const BigInteger operator/ (const BigInteger& other) const;
  3562. const BigInteger operator| (const BigInteger& other) const;
  3563. const BigInteger operator& (const BigInteger& other) const;
  3564. const BigInteger operator^ (const BigInteger& other) const;
  3565. const BigInteger operator% (const BigInteger& other) const;
  3566. const BigInteger operator<< (int numBitsToShift) const;
  3567. const BigInteger operator>> (int numBitsToShift) const;
  3568. bool operator== (const BigInteger& other) const throw();
  3569. bool operator!= (const BigInteger& other) const throw();
  3570. bool operator< (const BigInteger& other) const throw();
  3571. bool operator<= (const BigInteger& other) const throw();
  3572. bool operator> (const BigInteger& other) const throw();
  3573. bool operator>= (const BigInteger& other) const throw();
  3574. /** Does a signed comparison of two BigIntegers.
  3575. Return values are:
  3576. - 0 if the numbers are the same
  3577. - < 0 if this number is smaller than the other
  3578. - > 0 if this number is bigger than the other
  3579. */
  3580. int compare (const BigInteger& other) const throw();
  3581. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  3582. Return values are:
  3583. - 0 if the numbers are the same
  3584. - < 0 if this number is smaller than the other
  3585. - > 0 if this number is bigger than the other
  3586. */
  3587. int compareAbsolute (const BigInteger& other) const throw();
  3588. /** Divides this value by another one and returns the remainder.
  3589. This number is divided by other, leaving the quotient in this number,
  3590. with the remainder being copied to the other BigInteger passed in.
  3591. */
  3592. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  3593. /** Returns the largest value that will divide both this value and the one passed-in.
  3594. */
  3595. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  3596. /** Performs a combined exponent and modulo operation.
  3597. This BigInteger's value becomes (this ^ exponent) % modulus.
  3598. */
  3599. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  3600. /** Performs an inverse modulo on the value.
  3601. i.e. the result is (this ^ -1) mod (modulus).
  3602. */
  3603. void inverseModulo (const BigInteger& modulus);
  3604. /** Returns true if the value is less than zero.
  3605. @see setNegative, negate
  3606. */
  3607. bool isNegative() const throw();
  3608. /** Changes the sign of the number to be positive or negative.
  3609. @see isNegative, negate
  3610. */
  3611. void setNegative (const bool shouldBeNegative) throw();
  3612. /** Inverts the sign of the number.
  3613. @see isNegative, setNegative
  3614. */
  3615. void negate() throw();
  3616. /** Converts the number to a string.
  3617. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3618. If minimumNumCharacters is greater than 0, the returned string will be
  3619. padded with leading zeros to reach at least that length.
  3620. */
  3621. const String toString (int base, int minimumNumCharacters = 1) const;
  3622. /** Reads the numeric value from a string.
  3623. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3624. Any invalid characters will be ignored.
  3625. */
  3626. void parseString (const String& text, int base);
  3627. /** Turns the number into a block of binary data.
  3628. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3629. of the number, and so on.
  3630. @see loadFromMemoryBlock
  3631. */
  3632. const MemoryBlock toMemoryBlock() const;
  3633. /** Converts a block of raw data into a number.
  3634. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3635. of the number, and so on.
  3636. @see toMemoryBlock
  3637. */
  3638. void loadFromMemoryBlock (const MemoryBlock& data);
  3639. juce_UseDebuggingNewOperator
  3640. private:
  3641. HeapBlock <unsigned int> values;
  3642. int numValues, highestBit;
  3643. bool negative;
  3644. void ensureSize (int numVals);
  3645. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  3646. };
  3647. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  3648. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  3649. /** For backwards compatibility, BitArray is defined to be an alias for BigInteger.
  3650. */
  3651. typedef BigInteger BitArray;
  3652. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  3653. /*** End of inlined file: juce_BigInteger.h ***/
  3654. #endif
  3655. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3656. /*** Start of inlined file: juce_DynamicObject.h ***/
  3657. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3658. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3659. /*** Start of inlined file: juce_NamedValueSet.h ***/
  3660. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  3661. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  3662. /*** Start of inlined file: juce_Variant.h ***/
  3663. #ifndef __JUCE_VARIANT_JUCEHEADER__
  3664. #define __JUCE_VARIANT_JUCEHEADER__
  3665. /*** Start of inlined file: juce_Identifier.h ***/
  3666. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  3667. #define __JUCE_IDENTIFIER_JUCEHEADER__
  3668. /*** Start of inlined file: juce_StringPool.h ***/
  3669. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  3670. #define __JUCE_STRINGPOOL_JUCEHEADER__
  3671. /**
  3672. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  3673. comparison speed when dealing with many duplicate strings.
  3674. When you add a string to a pool using getPooledString, it'll return a character
  3675. array containing the same string. This array is owned by the pool, and the same array
  3676. is returned every time a matching string is asked for. This means that it's trivial to
  3677. compare two pooled strings for equality, as you can simply compare their pointers. It
  3678. also cuts down on storage if you're using many copies of the same string.
  3679. */
  3680. class JUCE_API StringPool
  3681. {
  3682. public:
  3683. /** Creates an empty pool. */
  3684. StringPool() throw();
  3685. /** Destructor */
  3686. ~StringPool();
  3687. /** Returns a pointer to a copy of the string that is passed in.
  3688. The pool will always return the same pointer when asked for a string that matches it.
  3689. The pool will own all the pointers that it returns, deleting them when the pool itself
  3690. is deleted.
  3691. */
  3692. const juce_wchar* getPooledString (const String& original);
  3693. /** Returns a pointer to a copy of the string that is passed in.
  3694. The pool will always return the same pointer when asked for a string that matches it.
  3695. The pool will own all the pointers that it returns, deleting them when the pool itself
  3696. is deleted.
  3697. */
  3698. const juce_wchar* getPooledString (const char* original);
  3699. /** Returns a pointer to a copy of the string that is passed in.
  3700. The pool will always return the same pointer when asked for a string that matches it.
  3701. The pool will own all the pointers that it returns, deleting them when the pool itself
  3702. is deleted.
  3703. */
  3704. const juce_wchar* getPooledString (const juce_wchar* original);
  3705. /** Returns the number of strings in the pool. */
  3706. int size() const throw();
  3707. /** Returns one of the strings in the pool, by index. */
  3708. const juce_wchar* operator[] (int index) const throw();
  3709. private:
  3710. Array <String> strings;
  3711. };
  3712. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  3713. /*** End of inlined file: juce_StringPool.h ***/
  3714. /**
  3715. Represents a string identifier, designed for accessing properties by name.
  3716. Identifier objects are very light and fast to copy, but slower to initialise
  3717. from a string, so it's much faster to keep a static identifier object to refer
  3718. to frequently-used names, rather than constructing them each time you need it.
  3719. @see NamedPropertySet, ValueTree
  3720. */
  3721. class JUCE_API Identifier
  3722. {
  3723. public:
  3724. /** Creates a null identifier. */
  3725. Identifier() throw();
  3726. /** Creates an identifier with a specified name.
  3727. Because this name may need to be used in contexts such as script variables or XML
  3728. tags, it must only contain ascii letters and digits, or the underscore character.
  3729. */
  3730. Identifier (const char* name);
  3731. /** Creates an identifier with a specified name.
  3732. Because this name may need to be used in contexts such as script variables or XML
  3733. tags, it must only contain ascii letters and digits, or the underscore character.
  3734. */
  3735. Identifier (const String& name);
  3736. /** Creates a copy of another identifier. */
  3737. Identifier (const Identifier& other) throw();
  3738. /** Creates a copy of another identifier. */
  3739. Identifier& operator= (const Identifier& other) throw();
  3740. /** Destructor */
  3741. ~Identifier();
  3742. /** Compares two identifiers. This is a very fast operation. */
  3743. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  3744. /** Compares two identifiers. This is a very fast operation. */
  3745. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  3746. /** Returns this identifier as a string. */
  3747. const String toString() const { return name; }
  3748. /** Returns this identifier's raw string pointer. */
  3749. operator const juce_wchar*() const throw() { return name; }
  3750. private:
  3751. const juce_wchar* name;
  3752. static StringPool& getPool();
  3753. };
  3754. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  3755. /*** End of inlined file: juce_Identifier.h ***/
  3756. /*** Start of inlined file: juce_OutputStream.h ***/
  3757. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3758. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3759. /*** Start of inlined file: juce_InputStream.h ***/
  3760. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  3761. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  3762. /*** Start of inlined file: juce_MemoryBlock.h ***/
  3763. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3764. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3765. /**
  3766. A class to hold a resizable block of raw data.
  3767. */
  3768. class JUCE_API MemoryBlock
  3769. {
  3770. public:
  3771. /** Create an uninitialised block with 0 size. */
  3772. MemoryBlock() throw();
  3773. /** Creates a memory block with a given initial size.
  3774. @param initialSize the size of block to create
  3775. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3776. */
  3777. MemoryBlock (const size_t initialSize,
  3778. const bool initialiseToZero = false) throw();
  3779. /** Creates a copy of another memory block. */
  3780. MemoryBlock (const MemoryBlock& other) throw();
  3781. /** Creates a memory block using a copy of a block of data.
  3782. @param dataToInitialiseFrom some data to copy into this block
  3783. @param sizeInBytes how much space to use
  3784. */
  3785. MemoryBlock (const void* const dataToInitialiseFrom,
  3786. const size_t sizeInBytes) throw();
  3787. /** Destructor. */
  3788. ~MemoryBlock() throw();
  3789. /** Copies another memory block onto this one.
  3790. This block will be resized and copied to exactly match the other one.
  3791. */
  3792. MemoryBlock& operator= (const MemoryBlock& other) throw();
  3793. /** Compares two memory blocks.
  3794. @returns true only if the two blocks are the same size and have identical contents.
  3795. */
  3796. bool operator== (const MemoryBlock& other) const throw();
  3797. /** Compares two memory blocks.
  3798. @returns true if the two blocks are different sizes or have different contents.
  3799. */
  3800. bool operator!= (const MemoryBlock& other) const throw();
  3801. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  3802. */
  3803. bool matches (const void* data, size_t dataSize) const throw();
  3804. /** Returns a void pointer to the data.
  3805. Note that the pointer returned will probably become invalid when the
  3806. block is resized.
  3807. */
  3808. void* getData() const throw() { return data; }
  3809. /** Returns a byte from the memory block.
  3810. This returns a reference, so you can also use it to set a byte.
  3811. */
  3812. template <typename Type>
  3813. char& operator[] (const Type offset) const throw() { return data [offset]; }
  3814. /** Returns the block's current allocated size, in bytes. */
  3815. size_t getSize() const throw() { return size; }
  3816. /** Resizes the memory block.
  3817. This will try to keep as much of the block's current content as it can,
  3818. and can optionally be made to clear any new space that gets allocated at
  3819. the end of the block.
  3820. @param newSize the new desired size for the block
  3821. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3822. whether to clear the new section or just leave it
  3823. uninitialised
  3824. @see ensureSize
  3825. */
  3826. void setSize (const size_t newSize,
  3827. const bool initialiseNewSpaceToZero = false) throw();
  3828. /** Increases the block's size only if it's smaller than a given size.
  3829. @param minimumSize if the block is already bigger than this size, no action
  3830. will be taken; otherwise it will be increased to this size
  3831. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3832. whether to clear the new section or just leave it
  3833. uninitialised
  3834. @see setSize
  3835. */
  3836. void ensureSize (const size_t minimumSize,
  3837. const bool initialiseNewSpaceToZero = false) throw();
  3838. /** Fills the entire memory block with a repeated byte value.
  3839. This is handy for clearing a block of memory to zero.
  3840. */
  3841. void fillWith (const uint8 valueToUse) throw();
  3842. /** Adds another block of data to the end of this one.
  3843. This block's size will be increased accordingly.
  3844. */
  3845. void append (const void* const data,
  3846. const size_t numBytes) throw();
  3847. /** Exchanges the contents of this and another memory block.
  3848. No actual copying is required for this, so it's very fast.
  3849. */
  3850. void swapWith (MemoryBlock& other) throw();
  3851. /** Copies data into this MemoryBlock from a memory address.
  3852. @param srcData the memory location of the data to copy into this block
  3853. @param destinationOffset the offset in this block at which the data being copied should begin
  3854. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3855. it will be clipped so not to do anything nasty)
  3856. */
  3857. void copyFrom (const void* srcData,
  3858. int destinationOffset,
  3859. size_t numBytes) throw();
  3860. /** Copies data from this MemoryBlock to a memory address.
  3861. @param destData the memory location to write to
  3862. @param sourceOffset the offset within this block from which the copied data will be read
  3863. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3864. zeros will be used for that portion of the data)
  3865. */
  3866. void copyTo (void* destData,
  3867. int sourceOffset,
  3868. size_t numBytes) const throw();
  3869. /** Chops out a section of the block.
  3870. This will remove a section of the memory block and close the gap around it,
  3871. shifting any subsequent data downwards and reducing the size of the block.
  3872. If the range specified goes beyond the size of the block, it will be clipped.
  3873. */
  3874. void removeSection (size_t startByte, size_t numBytesToRemove) throw();
  3875. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3876. characters in the system's default encoding. */
  3877. const String toString() const throw();
  3878. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3879. The block will be resized to the number of valid bytes read from the string.
  3880. Non-hex characters in the string will be ignored.
  3881. @see String::toHexString()
  3882. */
  3883. void loadFromHexString (const String& sourceHexString) throw();
  3884. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3885. void setBitRange (size_t bitRangeStart,
  3886. size_t numBits,
  3887. int binaryNumberToApply) throw();
  3888. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3889. int getBitRange (size_t bitRangeStart,
  3890. size_t numBitsToRead) const throw();
  3891. /** Returns a string of characters that represent the binary contents of this block.
  3892. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3893. of simple non-extended characters, e.g. for storage in XML.
  3894. @see fromBase64Encoding
  3895. */
  3896. const String toBase64Encoding() const throw();
  3897. /** Takes a string of encoded characters and turns it into binary data.
  3898. The string passed in must have been created by to64BitEncoding(), and this
  3899. block will be resized to recreate the original data block.
  3900. @see toBase64Encoding
  3901. */
  3902. bool fromBase64Encoding (const String& encodedString) throw();
  3903. juce_UseDebuggingNewOperator
  3904. private:
  3905. HeapBlock <char> data;
  3906. size_t size;
  3907. static const char* const encodingTable;
  3908. };
  3909. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3910. /*** End of inlined file: juce_MemoryBlock.h ***/
  3911. /** The base class for streams that read data.
  3912. Input and output streams are used throughout the library - subclasses can override
  3913. some or all of the virtual functions to implement their behaviour.
  3914. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  3915. */
  3916. class JUCE_API InputStream
  3917. {
  3918. public:
  3919. /** Destructor. */
  3920. virtual ~InputStream() {}
  3921. /** Returns the total number of bytes available for reading in this stream.
  3922. Note that this is the number of bytes available from the start of the
  3923. stream, not from the current position.
  3924. If the size of the stream isn't actually known, this may return -1.
  3925. */
  3926. virtual int64 getTotalLength() = 0;
  3927. /** Returns true if the stream has no more data to read. */
  3928. virtual bool isExhausted() = 0;
  3929. /** Reads a set of bytes from the stream into a memory buffer.
  3930. This is the only read method that subclasses actually need to implement, as the
  3931. InputStream base class implements the other read methods in terms of this one (although
  3932. it's often more efficient for subclasses to implement them directly).
  3933. @param destBuffer the destination buffer for the data
  3934. @param maxBytesToRead the maximum number of bytes to read - make sure the
  3935. memory block passed in is big enough to contain this
  3936. many bytes.
  3937. @returns the actual number of bytes that were read, which may be less than
  3938. maxBytesToRead if the stream is exhausted before it gets that far
  3939. */
  3940. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  3941. /** Reads a byte from the stream.
  3942. If the stream is exhausted, this will return zero.
  3943. @see OutputStream::writeByte
  3944. */
  3945. virtual char readByte();
  3946. /** Reads a boolean from the stream.
  3947. The bool is encoded as a single byte - 1 for true, 0 for false.
  3948. If the stream is exhausted, this will return false.
  3949. @see OutputStream::writeBool
  3950. */
  3951. virtual bool readBool();
  3952. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3953. If the next two bytes read are byte1 and byte2, this returns
  3954. (byte1 | (byte2 << 8)).
  3955. If the stream is exhausted partway through reading the bytes, this will return zero.
  3956. @see OutputStream::writeShort, readShortBigEndian
  3957. */
  3958. virtual short readShort();
  3959. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3960. If the next two bytes read are byte1 and byte2, this returns
  3961. (byte2 | (byte1 << 8)).
  3962. If the stream is exhausted partway through reading the bytes, this will return zero.
  3963. @see OutputStream::writeShortBigEndian, readShort
  3964. */
  3965. virtual short readShortBigEndian();
  3966. /** Reads four bytes from the stream as a little-endian 32-bit value.
  3967. If the next four bytes are byte1 to byte4, this returns
  3968. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  3969. If the stream is exhausted partway through reading the bytes, this will return zero.
  3970. @see OutputStream::writeInt, readIntBigEndian
  3971. */
  3972. virtual int readInt();
  3973. /** Reads four bytes from the stream as a big-endian 32-bit value.
  3974. If the next four bytes are byte1 to byte4, this returns
  3975. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  3976. If the stream is exhausted partway through reading the bytes, this will return zero.
  3977. @see OutputStream::writeIntBigEndian, readInt
  3978. */
  3979. virtual int readIntBigEndian();
  3980. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  3981. If the next eight bytes are byte1 to byte8, this returns
  3982. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  3983. If the stream is exhausted partway through reading the bytes, this will return zero.
  3984. @see OutputStream::writeInt64, readInt64BigEndian
  3985. */
  3986. virtual int64 readInt64();
  3987. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  3988. If the next eight bytes are byte1 to byte8, this returns
  3989. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  3990. If the stream is exhausted partway through reading the bytes, this will return zero.
  3991. @see OutputStream::writeInt64BigEndian, readInt64
  3992. */
  3993. virtual int64 readInt64BigEndian();
  3994. /** Reads four bytes as a 32-bit floating point value.
  3995. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  3996. If the stream is exhausted partway through reading the bytes, this will return zero.
  3997. @see OutputStream::writeFloat, readDouble
  3998. */
  3999. virtual float readFloat();
  4000. /** Reads four bytes as a 32-bit floating point value.
  4001. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  4002. If the stream is exhausted partway through reading the bytes, this will return zero.
  4003. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  4004. */
  4005. virtual float readFloatBigEndian();
  4006. /** Reads eight bytes as a 64-bit floating point value.
  4007. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  4008. If the stream is exhausted partway through reading the bytes, this will return zero.
  4009. @see OutputStream::writeDouble, readFloat
  4010. */
  4011. virtual double readDouble();
  4012. /** Reads eight bytes as a 64-bit floating point value.
  4013. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4014. If the stream is exhausted partway through reading the bytes, this will return zero.
  4015. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4016. */
  4017. virtual double readDoubleBigEndian();
  4018. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4019. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4020. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4021. @see OutputStream::writeCompressedInt()
  4022. */
  4023. virtual int readCompressedInt();
  4024. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4025. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4026. After this call, the stream's position will be left pointing to the next character
  4027. following the line-feed, but the linefeeds aren't included in the string that
  4028. is returned.
  4029. */
  4030. virtual const String readNextLine();
  4031. /** Reads a zero-terminated UTF8 string from the stream.
  4032. This will read characters from the stream until it hits a zero character or
  4033. end-of-stream.
  4034. @see OutputStream::writeString, readEntireStreamAsString
  4035. */
  4036. virtual const String readString();
  4037. /** Tries to read the whole stream and turn it into a string.
  4038. This will read from the stream's current position until the end-of-stream, and
  4039. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4040. */
  4041. virtual const String readEntireStreamAsString();
  4042. /** Reads from the stream and appends the data to a MemoryBlock.
  4043. @param destBlock the block to append the data onto
  4044. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4045. of bytes that will be read - if it's negative, data
  4046. will be read until the stream is exhausted.
  4047. @returns the number of bytes that were added to the memory block
  4048. */
  4049. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4050. int maxNumBytesToRead = -1);
  4051. /** Returns the offset of the next byte that will be read from the stream.
  4052. @see setPosition
  4053. */
  4054. virtual int64 getPosition() = 0;
  4055. /** Tries to move the current read position of the stream.
  4056. The position is an absolute number of bytes from the stream's start.
  4057. Some streams might not be able to do this, in which case they should do
  4058. nothing and return false. Others might be able to manage it by resetting
  4059. themselves and skipping to the correct position, although this is
  4060. obviously a bit slow.
  4061. @returns true if the stream manages to reposition itself correctly
  4062. @see getPosition
  4063. */
  4064. virtual bool setPosition (int64 newPosition) = 0;
  4065. /** Reads and discards a number of bytes from the stream.
  4066. Some input streams might implement this efficiently, but the base
  4067. class will just keep reading data until the requisite number of bytes
  4068. have been done.
  4069. */
  4070. virtual void skipNextBytes (int64 numBytesToSkip);
  4071. juce_UseDebuggingNewOperator
  4072. protected:
  4073. InputStream() throw() {}
  4074. };
  4075. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4076. /*** End of inlined file: juce_InputStream.h ***/
  4077. class File;
  4078. /**
  4079. The base class for streams that write data to some kind of destination.
  4080. Input and output streams are used throughout the library - subclasses can override
  4081. some or all of the virtual functions to implement their behaviour.
  4082. @see InputStream, MemoryOutputStream, FileOutputStream
  4083. */
  4084. class JUCE_API OutputStream
  4085. {
  4086. protected:
  4087. OutputStream();
  4088. public:
  4089. /** Destructor.
  4090. Some subclasses might want to do things like call flush() during their
  4091. destructors.
  4092. */
  4093. virtual ~OutputStream();
  4094. /** If the stream is using a buffer, this will ensure it gets written
  4095. out to the destination. */
  4096. virtual void flush() = 0;
  4097. /** Tries to move the stream's output position.
  4098. Not all streams will be able to seek to a new position - this will return
  4099. false if it fails to work.
  4100. @see getPosition
  4101. */
  4102. virtual bool setPosition (int64 newPosition) = 0;
  4103. /** Returns the stream's current position.
  4104. @see setPosition
  4105. */
  4106. virtual int64 getPosition() = 0;
  4107. /** Writes a block of data to the stream.
  4108. When creating a subclass of OutputStream, this is the only write method
  4109. that needs to be overloaded - the base class has methods for writing other
  4110. types of data which use this to do the work.
  4111. @returns false if the write operation fails for some reason
  4112. */
  4113. virtual bool write (const void* dataToWrite,
  4114. int howManyBytes) = 0;
  4115. /** Writes a single byte to the stream.
  4116. @see InputStream::readByte
  4117. */
  4118. virtual void writeByte (char byte);
  4119. /** Writes a boolean to the stream as a single byte.
  4120. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4121. @see InputStream::readBool
  4122. */
  4123. virtual void writeBool (bool boolValue);
  4124. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4125. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4126. @see InputStream::readShort
  4127. */
  4128. virtual void writeShort (short value);
  4129. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4130. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4131. @see InputStream::readShortBigEndian
  4132. */
  4133. virtual void writeShortBigEndian (short value);
  4134. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4135. @see InputStream::readInt
  4136. */
  4137. virtual void writeInt (int value);
  4138. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4139. @see InputStream::readIntBigEndian
  4140. */
  4141. virtual void writeIntBigEndian (int value);
  4142. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4143. @see InputStream::readInt64
  4144. */
  4145. virtual void writeInt64 (int64 value);
  4146. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4147. @see InputStream::readInt64BigEndian
  4148. */
  4149. virtual void writeInt64BigEndian (int64 value);
  4150. /** Writes a 32-bit floating point value to the stream in a binary format.
  4151. The binary 32-bit encoding of the float is written as a little-endian int.
  4152. @see InputStream::readFloat
  4153. */
  4154. virtual void writeFloat (float value);
  4155. /** Writes a 32-bit floating point value to the stream in a binary format.
  4156. The binary 32-bit encoding of the float is written as a big-endian int.
  4157. @see InputStream::readFloatBigEndian
  4158. */
  4159. virtual void writeFloatBigEndian (float value);
  4160. /** Writes a 64-bit floating point value to the stream in a binary format.
  4161. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4162. @see InputStream::readDouble
  4163. */
  4164. virtual void writeDouble (double value);
  4165. /** Writes a 64-bit floating point value to the stream in a binary format.
  4166. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  4167. @see InputStream::readDoubleBigEndian
  4168. */
  4169. virtual void writeDoubleBigEndian (double value);
  4170. /** Writes a condensed binary encoding of a 32-bit integer.
  4171. If you're storing a lot of integers which are unlikely to have very large values,
  4172. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4173. under 0xffff only 3 bytes, etc.
  4174. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4175. @see InputStream::readCompressedInt
  4176. */
  4177. virtual void writeCompressedInt (int value);
  4178. /** Stores a string in the stream in a binary format.
  4179. This isn't the method to use if you're trying to append text to the end of a
  4180. text-file! It's intended for storing a string so that it can be retrieved later
  4181. by InputStream::readString().
  4182. It writes the string to the stream as UTF8, including the null termination character.
  4183. For appending text to a file, instead use writeText, or operator<<
  4184. @see InputStream::readString, writeText, operator<<
  4185. */
  4186. virtual void writeString (const String& text);
  4187. /** Writes a string of text to the stream.
  4188. It can either write it as UTF8 characters or as unicode, and
  4189. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4190. should only be done at the start of a file).
  4191. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4192. */
  4193. virtual void writeText (const String& text,
  4194. bool asUnicode,
  4195. bool writeUnicodeHeaderBytes);
  4196. /** Reads data from an input stream and writes it to this stream.
  4197. @param source the stream to read from
  4198. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4199. less than zero, it will keep reading until the input
  4200. is exhausted)
  4201. */
  4202. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4203. juce_UseDebuggingNewOperator
  4204. };
  4205. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4206. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4207. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4208. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4209. /** Writes a character to a stream. */
  4210. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4211. /** Writes a null-terminated text string to a stream. */
  4212. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4213. /** Writes a block of data from a MemoryBlock to a stream. */
  4214. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4215. /** Writes the contents of a file to a stream. */
  4216. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4217. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4218. /*** End of inlined file: juce_OutputStream.h ***/
  4219. class JUCE_API DynamicObject;
  4220. /**
  4221. A variant class, that can be used to hold a range of primitive values.
  4222. A var object can hold a range of simple primitive values, strings, or
  4223. a reference-counted pointer to a DynamicObject. The var class is intended
  4224. to act like the values used in dynamic scripting languages.
  4225. @see DynamicObject
  4226. */
  4227. class JUCE_API var
  4228. {
  4229. public:
  4230. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4231. typedef Identifier identifier;
  4232. /** Creates a void variant. */
  4233. var() throw();
  4234. /** Destructor. */
  4235. ~var() throw();
  4236. /** A static var object that can be used where you need an empty variant object. */
  4237. static const var null;
  4238. var (const var& valueToCopy);
  4239. var (int value) throw();
  4240. var (bool value) throw();
  4241. var (double value) throw();
  4242. var (const char* value);
  4243. var (const juce_wchar* value);
  4244. var (const String& value);
  4245. var (DynamicObject* object);
  4246. var (MethodFunction method) throw();
  4247. var& operator= (const var& valueToCopy);
  4248. var& operator= (int value);
  4249. var& operator= (bool value);
  4250. var& operator= (double value);
  4251. var& operator= (const char* value);
  4252. var& operator= (const juce_wchar* value);
  4253. var& operator= (const String& value);
  4254. var& operator= (DynamicObject* object);
  4255. var& operator= (MethodFunction method);
  4256. void swapWith (var& other) throw();
  4257. operator int() const;
  4258. operator bool() const;
  4259. operator float() const;
  4260. operator double() const;
  4261. operator const String() const;
  4262. const String toString() const;
  4263. DynamicObject* getObject() const;
  4264. bool isVoid() const throw();
  4265. bool isInt() const throw();
  4266. bool isBool() const throw();
  4267. bool isDouble() const throw();
  4268. bool isString() const throw();
  4269. bool isObject() const throw();
  4270. bool isMethod() const throw();
  4271. /** Writes a binary representation of this value to a stream.
  4272. The data can be read back later using readFromStream().
  4273. */
  4274. void writeToStream (OutputStream& output) const;
  4275. /** Reads back a stored binary representation of a value.
  4276. The data in the stream must have been written using writeToStream(), or this
  4277. will have unpredictable results.
  4278. */
  4279. static const var readFromStream (InputStream& input);
  4280. /** If this variant is an object, this returns one of its properties. */
  4281. const var operator[] (const Identifier& propertyName) const;
  4282. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4283. const var call (const Identifier& method) const;
  4284. /** If this variant is an object, this invokes one of its methods with one argument. */
  4285. const var call (const Identifier& method, const var& arg1) const;
  4286. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4287. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4288. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4289. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4290. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4291. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4292. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4293. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4294. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4295. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4296. /** If this variant is a method pointer, this invokes it on a target object. */
  4297. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4298. juce_UseDebuggingNewOperator
  4299. /** Returns true if this var has the same value as the one supplied. */
  4300. bool equals (const var& other) const throw();
  4301. private:
  4302. class VariantType;
  4303. friend class VariantType;
  4304. class VariantType_Void;
  4305. friend class VariantType_Void;
  4306. class VariantType_Int;
  4307. friend class VariantType_Int;
  4308. class VariantType_Double;
  4309. friend class VariantType_Double;
  4310. class VariantType_Float;
  4311. friend class VariantType_Float;
  4312. class VariantType_Bool;
  4313. friend class VariantType_Bool;
  4314. class VariantType_String;
  4315. friend class VariantType_String;
  4316. class VariantType_Object;
  4317. friend class VariantType_Object;
  4318. class VariantType_Method;
  4319. friend class VariantType_Method;
  4320. union ValueUnion
  4321. {
  4322. int intValue;
  4323. bool boolValue;
  4324. double doubleValue;
  4325. String* stringValue;
  4326. DynamicObject* objectValue;
  4327. MethodFunction methodValue;
  4328. };
  4329. const VariantType* type;
  4330. ValueUnion value;
  4331. };
  4332. bool operator== (const var& v1, const var& v2) throw();
  4333. bool operator!= (const var& v1, const var& v2) throw();
  4334. bool operator== (const var& v1, const String& v2) throw();
  4335. bool operator!= (const var& v1, const String& v2) throw();
  4336. #endif // __JUCE_VARIANT_JUCEHEADER__
  4337. /*** End of inlined file: juce_Variant.h ***/
  4338. /** Holds a set of named var objects.
  4339. This can be used as a basic structure to hold a set of var object, which can
  4340. be retrieved by using their identifier.
  4341. */
  4342. class JUCE_API NamedValueSet
  4343. {
  4344. public:
  4345. /** Creates an empty set. */
  4346. NamedValueSet() throw();
  4347. /** Creates a copy of another set. */
  4348. NamedValueSet (const NamedValueSet& other);
  4349. /** Replaces this set with a copy of another set. */
  4350. NamedValueSet& operator= (const NamedValueSet& other);
  4351. /** Destructor. */
  4352. ~NamedValueSet();
  4353. bool operator== (const NamedValueSet& other) const;
  4354. bool operator!= (const NamedValueSet& other) const;
  4355. /** Returns the total number of values that the set contains. */
  4356. int size() const throw();
  4357. /** Returns the value of a named item.
  4358. If the name isn't found, this will return a void variant.
  4359. @see getProperty
  4360. */
  4361. const var& operator[] (const Identifier& name) const;
  4362. /** Tries to return the named value, but if no such value is found, this will
  4363. instead return the supplied default value.
  4364. */
  4365. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  4366. /** Returns a pointer to the object holding a named value, or
  4367. null if there is no value with this name. */
  4368. var* getItem (const Identifier& name) const;
  4369. /** Changes or adds a named value.
  4370. @returns true if a value was changed or added; false if the
  4371. value was already set the the value passed-in.
  4372. */
  4373. bool set (const Identifier& name, const var& newValue);
  4374. /** Returns true if the set contains an item with the specified name. */
  4375. bool contains (const Identifier& name) const;
  4376. /** Removes a value from the set.
  4377. @returns true if a value was removed; false if there was no value
  4378. with the name that was given.
  4379. */
  4380. bool remove (const Identifier& name);
  4381. /** Returns the name of the value at a given index.
  4382. The index must be between 0 and size() - 1. Out-of-range indexes will
  4383. return an empty identifier.
  4384. */
  4385. const Identifier getName (int index) const;
  4386. /** Returns the value of the item at a given index.
  4387. The index must be between 0 and size() - 1. Out-of-range indexes will
  4388. return an empty identifier.
  4389. */
  4390. const var getValueAt (int index) const;
  4391. /** Removes all values. */
  4392. void clear();
  4393. juce_UseDebuggingNewOperator
  4394. private:
  4395. struct NamedValue
  4396. {
  4397. NamedValue() throw();
  4398. NamedValue (const Identifier& name, const var& value);
  4399. bool operator== (const NamedValue& other) const throw();
  4400. Identifier name;
  4401. var value;
  4402. };
  4403. Array <NamedValue> values;
  4404. };
  4405. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  4406. /*** End of inlined file: juce_NamedValueSet.h ***/
  4407. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  4408. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4409. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4410. /*** Start of inlined file: juce_Atomic.h ***/
  4411. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4412. #define __JUCE_ATOMIC_JUCEHEADER__
  4413. /**
  4414. Simple class to hold a primitive value and perform atomic operations on it.
  4415. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  4416. There are methods to perform most of the basic atomic operations.
  4417. */
  4418. template <typename Type>
  4419. class Atomic
  4420. {
  4421. public:
  4422. /** Creates a new value, initialised to zero. */
  4423. inline Atomic() throw()
  4424. : value (0)
  4425. {
  4426. }
  4427. /** Creates a new value, with a given initial value. */
  4428. inline Atomic (const Type initialValue) throw()
  4429. : value (initialValue)
  4430. {
  4431. }
  4432. /** Copies another value (atomically). */
  4433. inline Atomic (const Atomic& other) throw()
  4434. : value (other.get())
  4435. {
  4436. }
  4437. /** Destructor. */
  4438. inline ~Atomic() throw()
  4439. {
  4440. // This class can only be used for types which are 32 or 64 bits in size.
  4441. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  4442. }
  4443. /** Atomically reads and returns the current value. */
  4444. Type get() const throw();
  4445. /** Copies another value onto this one (atomically). */
  4446. inline Atomic& operator= (const Atomic& other) throw() { exchange (other.get()); return *this; }
  4447. /** Copies another value onto this one (atomically). */
  4448. inline Atomic& operator= (const Type newValue) throw() { exchange (newValue); return *this; }
  4449. /** Atomically sets the current value. */
  4450. void set (Type newValue) throw() { exchange (newValue); }
  4451. /** Atomically sets the current value, returning the value that was replaced. */
  4452. Type exchange (Type value) throw();
  4453. /** Atomically adds a number to this value, returning the new value. */
  4454. Type operator+= (Type amountToAdd) throw();
  4455. /** Atomically subtracts a number from this value, returning the new value. */
  4456. Type operator-= (Type amountToSubtract) throw();
  4457. /** Atomically increments this value, returning the new value. */
  4458. Type operator++() throw();
  4459. /** Atomically decrements this value, returning the new value. */
  4460. Type operator--() throw();
  4461. /** Atomically compares this value with a target value, and if it is equal, sets
  4462. this to be equal to a new value.
  4463. This operation is the atomic equivalent of doing this:
  4464. @code
  4465. bool compareAndSetBool (Type newValue, Type valueToCompare)
  4466. {
  4467. if (get() == valueToCompare)
  4468. {
  4469. set (newValue);
  4470. return true;
  4471. }
  4472. return false;
  4473. }
  4474. @endcode
  4475. @returns true if the comparison was true and the value was replaced; false if
  4476. the comparison failed and the value was left unchanged.
  4477. @see compareAndSetValue
  4478. */
  4479. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  4480. /** Atomically compares this value with a target value, and if it is equal, sets
  4481. this to be equal to a new value.
  4482. This operation is the atomic equivalent of doing this:
  4483. @code
  4484. Type compareAndSetValue (Type newValue, Type valueToCompare)
  4485. {
  4486. Type oldValue = get();
  4487. if (oldValue == valueToCompare)
  4488. set (newValue);
  4489. return oldValue;
  4490. }
  4491. @endcode
  4492. @returns the old value before it was changed.
  4493. @see compareAndSetBool
  4494. */
  4495. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  4496. /** Implements a memory read/write barrier. */
  4497. static void memoryBarrier() throw();
  4498. JUCE_ALIGN(8)
  4499. /** The raw value that this class operates on.
  4500. This is exposed publically in case you need to manipulate it directly
  4501. for performance reasons.
  4502. */
  4503. volatile Type value;
  4504. private:
  4505. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  4506. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  4507. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  4508. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  4509. };
  4510. /*
  4511. The following code is in the header so that the atomics can be inlined where possible...
  4512. */
  4513. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  4514. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  4515. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  4516. #if JUCE_PPC || JUCE_IOS
  4517. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  4518. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, volatile Type* a) throw() { jassertfalse; return *a += b; }
  4519. template <typename Type> static Type OSAtomicIncrement64Barrier (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4520. template <typename Type> static Type OSAtomicDecrement64Barrier (volatile Type* a) throw() { jassertfalse; return --*a; }
  4521. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, volatile Type* value) throw()
  4522. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  4523. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4524. #endif
  4525. #elif JUCE_GCC
  4526. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  4527. #if JUCE_IOS
  4528. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  4529. #endif
  4530. #else
  4531. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  4532. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  4533. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  4534. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  4535. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  4536. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  4537. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  4538. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  4539. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  4540. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  4541. #define juce_MemoryBarrier _ReadWriteBarrier
  4542. #else
  4543. // (these are defined in juce_win32_Threads.cpp)
  4544. long juce_InterlockedExchange (volatile long* a, long b) throw();
  4545. long juce_InterlockedIncrement (volatile long* a) throw();
  4546. long juce_InterlockedDecrement (volatile long* a) throw();
  4547. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  4548. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  4549. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  4550. static void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  4551. #endif
  4552. #if JUCE_64BIT
  4553. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  4554. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  4555. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  4556. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  4557. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  4558. #else
  4559. // None of these atomics are available in a 32-bit Windows build!!
  4560. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  4561. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  4562. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4563. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4564. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4565. #endif
  4566. #endif
  4567. #if JUCE_MSVC
  4568. #pragma warning (push)
  4569. #pragma warning (disable: 4311) // (truncation warning)
  4570. #endif
  4571. template <typename Type>
  4572. inline Type Atomic<Type>::get() const throw()
  4573. {
  4574. #if JUCE_ATOMICS_MAC
  4575. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier (0, (int32_t*) &value))
  4576. : castFrom64Bit ((int64) OSAtomicAdd64Barrier (0, (int64_t*) &value));
  4577. #elif JUCE_ATOMICS_WINDOWS
  4578. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  4579. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  4580. #elif JUCE_ATOMICS_GCC
  4581. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  4582. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  4583. #endif
  4584. }
  4585. template <typename Type>
  4586. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  4587. {
  4588. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  4589. Type currentVal = value;
  4590. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  4591. return currentVal;
  4592. #elif JUCE_ATOMICS_WINDOWS
  4593. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  4594. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  4595. #endif
  4596. }
  4597. template <typename Type>
  4598. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  4599. {
  4600. #if JUCE_ATOMICS_MAC
  4601. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) amountToAdd, (int32_t*) &value)
  4602. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (int64_t*) &value);
  4603. #elif JUCE_ATOMICS_WINDOWS
  4604. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  4605. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  4606. #elif JUCE_ATOMICS_GCC
  4607. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  4608. #endif
  4609. }
  4610. template <typename Type>
  4611. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  4612. {
  4613. return operator+= (juce_negate (amountToSubtract));
  4614. }
  4615. template <typename Type>
  4616. inline Type Atomic<Type>::operator++() throw()
  4617. {
  4618. #if JUCE_ATOMICS_MAC
  4619. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((int32_t*) &value)
  4620. : (Type) OSAtomicIncrement64Barrier ((int64_t*) &value);
  4621. #elif JUCE_ATOMICS_WINDOWS
  4622. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  4623. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  4624. #elif JUCE_ATOMICS_GCC
  4625. return (Type) __sync_add_and_fetch (&value, 1);
  4626. #endif
  4627. }
  4628. template <typename Type>
  4629. inline Type Atomic<Type>::operator--() throw()
  4630. {
  4631. #if JUCE_ATOMICS_MAC
  4632. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((int32_t*) &value)
  4633. : (Type) OSAtomicDecrement64Barrier ((int64_t*) &value);
  4634. #elif JUCE_ATOMICS_WINDOWS
  4635. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  4636. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  4637. #elif JUCE_ATOMICS_GCC
  4638. return (Type) __sync_add_and_fetch (&value, -1);
  4639. #endif
  4640. }
  4641. template <typename Type>
  4642. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  4643. {
  4644. #if JUCE_ATOMICS_MAC
  4645. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (int32_t*) &value)
  4646. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (int64_t*) &value);
  4647. #elif JUCE_ATOMICS_WINDOWS
  4648. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  4649. #elif JUCE_ATOMICS_GCC
  4650. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  4651. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  4652. #endif
  4653. }
  4654. template <typename Type>
  4655. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  4656. {
  4657. #if JUCE_ATOMICS_MAC
  4658. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  4659. {
  4660. if (compareAndSetBool (newValue, valueToCompare))
  4661. return valueToCompare;
  4662. const Type result = value;
  4663. if (result != valueToCompare)
  4664. return result;
  4665. }
  4666. #elif JUCE_ATOMICS_WINDOWS
  4667. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  4668. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  4669. #elif JUCE_ATOMICS_GCC
  4670. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  4671. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  4672. #endif
  4673. }
  4674. template <typename Type>
  4675. inline void Atomic<Type>::memoryBarrier() throw()
  4676. {
  4677. #if JUCE_ATOMICS_MAC
  4678. OSMemoryBarrier();
  4679. #elif JUCE_ATOMICS_GCC
  4680. __sync_synchronize();
  4681. #elif JUCE_ATOMICS_WINDOWS
  4682. juce_MemoryBarrier();
  4683. #endif
  4684. }
  4685. #if JUCE_MSVC
  4686. #pragma warning (pop)
  4687. #endif
  4688. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4689. /*** End of inlined file: juce_Atomic.h ***/
  4690. /**
  4691. Adds reference-counting to an object.
  4692. To add reference-counting to a class, derive it from this class, and
  4693. use the ReferenceCountedObjectPtr class to point to it.
  4694. e.g. @code
  4695. class MyClass : public ReferenceCountedObject
  4696. {
  4697. void foo();
  4698. // This is a neat way of declaring a typedef for a pointer class,
  4699. // rather than typing out the full templated name each time..
  4700. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  4701. };
  4702. MyClass::Ptr p = new MyClass();
  4703. MyClass::Ptr p2 = p;
  4704. p = 0;
  4705. p2->foo();
  4706. @endcode
  4707. Once a new ReferenceCountedObject has been assigned to a pointer, be
  4708. careful not to delete the object manually.
  4709. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  4710. */
  4711. class JUCE_API ReferenceCountedObject
  4712. {
  4713. public:
  4714. /** Increments the object's reference count.
  4715. This is done automatically by the smart pointer, but is public just
  4716. in case it's needed for nefarious purposes.
  4717. */
  4718. inline void incReferenceCount() throw()
  4719. {
  4720. ++refCount;
  4721. }
  4722. /** Decreases the object's reference count.
  4723. If the count gets to zero, the object will be deleted.
  4724. */
  4725. inline void decReferenceCount() throw()
  4726. {
  4727. jassert (getReferenceCount() > 0);
  4728. if (--refCount == 0)
  4729. delete this;
  4730. }
  4731. /** Returns the object's current reference count. */
  4732. inline int getReferenceCount() const throw()
  4733. {
  4734. return refCount.get();
  4735. }
  4736. protected:
  4737. /** Creates the reference-counted object (with an initial ref count of zero). */
  4738. ReferenceCountedObject()
  4739. {
  4740. }
  4741. /** Destructor. */
  4742. virtual ~ReferenceCountedObject()
  4743. {
  4744. // it's dangerous to delete an object that's still referenced by something else!
  4745. jassert (getReferenceCount() == 0);
  4746. }
  4747. private:
  4748. Atomic <int> refCount;
  4749. };
  4750. /**
  4751. Used to point to an object of type ReferenceCountedObject.
  4752. It's wise to use a typedef instead of typing out the templated name
  4753. each time - e.g.
  4754. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  4755. @see ReferenceCountedObject, ReferenceCountedObjectArray
  4756. */
  4757. template <class ReferenceCountedObjectClass>
  4758. class ReferenceCountedObjectPtr
  4759. {
  4760. public:
  4761. /** Creates a pointer to a null object. */
  4762. inline ReferenceCountedObjectPtr() throw()
  4763. : referencedObject (0)
  4764. {
  4765. }
  4766. /** Creates a pointer to an object.
  4767. This will increment the object's reference-count if it is non-null.
  4768. */
  4769. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  4770. : referencedObject (refCountedObject)
  4771. {
  4772. if (refCountedObject != 0)
  4773. refCountedObject->incReferenceCount();
  4774. }
  4775. /** Copies another pointer.
  4776. This will increment the object's reference-count (if it is non-null).
  4777. */
  4778. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  4779. : referencedObject (other.referencedObject)
  4780. {
  4781. if (referencedObject != 0)
  4782. referencedObject->incReferenceCount();
  4783. }
  4784. /** Changes this pointer to point at a different object.
  4785. The reference count of the old object is decremented, and it might be
  4786. deleted if it hits zero. The new object's count is incremented.
  4787. */
  4788. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  4789. {
  4790. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  4791. if (newObject != referencedObject)
  4792. {
  4793. if (newObject != 0)
  4794. newObject->incReferenceCount();
  4795. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4796. referencedObject = newObject;
  4797. if (oldObject != 0)
  4798. oldObject->decReferenceCount();
  4799. }
  4800. return *this;
  4801. }
  4802. /** Changes this pointer to point at a different object.
  4803. The reference count of the old object is decremented, and it might be
  4804. deleted if it hits zero. The new object's count is incremented.
  4805. */
  4806. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  4807. {
  4808. if (referencedObject != newObject)
  4809. {
  4810. if (newObject != 0)
  4811. newObject->incReferenceCount();
  4812. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4813. referencedObject = newObject;
  4814. if (oldObject != 0)
  4815. oldObject->decReferenceCount();
  4816. }
  4817. return *this;
  4818. }
  4819. /** Destructor.
  4820. This will decrement the object's reference-count, and may delete it if it
  4821. gets to zero.
  4822. */
  4823. inline ~ReferenceCountedObjectPtr()
  4824. {
  4825. if (referencedObject != 0)
  4826. referencedObject->decReferenceCount();
  4827. }
  4828. /** Returns the object that this pointer references.
  4829. The pointer returned may be zero, of course.
  4830. */
  4831. inline operator ReferenceCountedObjectClass*() const throw()
  4832. {
  4833. return referencedObject;
  4834. }
  4835. /** Returns true if this pointer refers to the given object. */
  4836. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  4837. {
  4838. return referencedObject == object;
  4839. }
  4840. /** Returns true if this pointer doesn't refer to the given object. */
  4841. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  4842. {
  4843. return referencedObject != object;
  4844. }
  4845. // the -> operator is called on the referenced object
  4846. inline ReferenceCountedObjectClass* operator->() const throw()
  4847. {
  4848. return referencedObject;
  4849. }
  4850. /** Returns the object that this pointer references.
  4851. The pointer returned may be zero, of course.
  4852. */
  4853. inline ReferenceCountedObjectClass* getObject() const throw()
  4854. {
  4855. return referencedObject;
  4856. }
  4857. private:
  4858. ReferenceCountedObjectClass* referencedObject;
  4859. };
  4860. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4861. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  4862. /**
  4863. Represents a dynamically implemented object.
  4864. This class is primarily intended for wrapping scripting language objects,
  4865. but could be used for other purposes.
  4866. An instance of a DynamicObject can be used to store named properties, and
  4867. by subclassing hasMethod() and invokeMethod(), you can give your object
  4868. methods.
  4869. */
  4870. class JUCE_API DynamicObject : public ReferenceCountedObject
  4871. {
  4872. public:
  4873. DynamicObject();
  4874. /** Destructor. */
  4875. virtual ~DynamicObject();
  4876. /** Returns true if the object has a property with this name.
  4877. Note that if the property is actually a method, this will return false.
  4878. */
  4879. virtual bool hasProperty (const Identifier& propertyName) const;
  4880. /** Returns a named property.
  4881. This returns a void if no such property exists.
  4882. */
  4883. virtual const var getProperty (const Identifier& propertyName) const;
  4884. /** Sets a named property. */
  4885. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  4886. /** Removes a named property. */
  4887. virtual void removeProperty (const Identifier& propertyName);
  4888. /** Checks whether this object has the specified method.
  4889. The default implementation of this just checks whether there's a property
  4890. with this name that's actually a method, but this can be overridden for
  4891. building objects with dynamic invocation.
  4892. */
  4893. virtual bool hasMethod (const Identifier& methodName) const;
  4894. /** Invokes a named method on this object.
  4895. The default implementation looks up the named property, and if it's a method
  4896. call, then it invokes it.
  4897. This method is virtual to allow more dynamic invocation to used for objects
  4898. where the methods may not already be set as properies.
  4899. */
  4900. virtual const var invokeMethod (const Identifier& methodName,
  4901. const var* parameters,
  4902. int numParameters);
  4903. /** Sets up a method.
  4904. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  4905. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  4906. the code easier to read,
  4907. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  4908. @code
  4909. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  4910. @endcode
  4911. */
  4912. void setMethod (const Identifier& methodName,
  4913. var::MethodFunction methodFunction);
  4914. /** Removes all properties and methods from the object. */
  4915. void clear();
  4916. juce_UseDebuggingNewOperator
  4917. private:
  4918. NamedValueSet properties;
  4919. };
  4920. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4921. /*** End of inlined file: juce_DynamicObject.h ***/
  4922. #endif
  4923. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4924. #endif
  4925. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4926. #endif
  4927. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4928. #endif
  4929. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4930. #endif
  4931. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4932. #endif
  4933. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4934. /*** Start of inlined file: juce_OwnedArray.h ***/
  4935. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4936. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4937. /*** Start of inlined file: juce_ScopedPointer.h ***/
  4938. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4939. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4940. /**
  4941. This class holds a pointer which is automatically deleted when this object goes
  4942. out of scope.
  4943. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  4944. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  4945. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  4946. created objects.
  4947. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  4948. to an object. If you use the assignment operator to assign a different object to a
  4949. ScopedPointer, the old one will be automatically deleted.
  4950. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  4951. object to which it points during its lifetime. This means that making a copy of a const
  4952. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  4953. old one.
  4954. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  4955. can use the release() method.
  4956. */
  4957. template <class ObjectType>
  4958. class ScopedPointer
  4959. {
  4960. public:
  4961. /** Creates a ScopedPointer containing a null pointer. */
  4962. inline ScopedPointer() throw() : object (0)
  4963. {
  4964. }
  4965. /** Creates a ScopedPointer that owns the specified object. */
  4966. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  4967. : object (objectToTakePossessionOf)
  4968. {
  4969. }
  4970. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  4971. Because a pointer can only belong to one ScopedPointer, this transfers
  4972. the pointer from the other object to this one, and the other object is reset to
  4973. be a null pointer.
  4974. */
  4975. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  4976. : object (objectToTransferFrom.object)
  4977. {
  4978. objectToTransferFrom.object = 0;
  4979. }
  4980. /** Destructor.
  4981. This will delete the object that this ScopedPointer currently refers to.
  4982. */
  4983. inline ~ScopedPointer() { delete object; }
  4984. /** Changes this ScopedPointer to point to a new object.
  4985. Because a pointer can only belong to one ScopedPointer, this transfers
  4986. the pointer from the other object to this one, and the other object is reset to
  4987. be a null pointer.
  4988. If this ScopedPointer already points to an object, that object
  4989. will first be deleted.
  4990. */
  4991. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  4992. {
  4993. if (this != objectToTransferFrom.getAddress())
  4994. {
  4995. // Two ScopedPointers should never be able to refer to the same object - if
  4996. // this happens, you must have done something dodgy!
  4997. jassert (object == 0 || object != objectToTransferFrom.object);
  4998. ObjectType* const oldObject = object;
  4999. object = objectToTransferFrom.object;
  5000. objectToTransferFrom.object = 0;
  5001. delete oldObject;
  5002. }
  5003. return *this;
  5004. }
  5005. /** Changes this ScopedPointer to point to a new object.
  5006. If this ScopedPointer already points to an object, that object
  5007. will first be deleted.
  5008. The pointer that you pass is may be null.
  5009. */
  5010. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  5011. {
  5012. if (object != newObjectToTakePossessionOf)
  5013. {
  5014. ObjectType* const oldObject = object;
  5015. object = newObjectToTakePossessionOf;
  5016. delete oldObject;
  5017. }
  5018. return *this;
  5019. }
  5020. /** Returns the object that this ScopedPointer refers to.
  5021. */
  5022. inline operator ObjectType*() const throw() { return object; }
  5023. /** Returns the object that this ScopedPointer refers to.
  5024. */
  5025. inline ObjectType& operator*() const throw() { return *object; }
  5026. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  5027. inline ObjectType* operator->() const throw() { return object; }
  5028. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  5029. inline ObjectType* const* operator&() const throw() { return static_cast <ObjectType* const*> (&object); }
  5030. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  5031. inline ObjectType** operator&() throw() { return static_cast <ObjectType**> (&object); }
  5032. /** Removes the current object from this ScopedPointer without deleting it.
  5033. This will return the current object, and set the ScopedPointer to a null pointer.
  5034. */
  5035. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  5036. /** Swaps this object with that of another ScopedPointer.
  5037. The two objects simply exchange their pointers.
  5038. */
  5039. void swapWith (ScopedPointer <ObjectType>& other) throw()
  5040. {
  5041. // Two ScopedPointers should never be able to refer to the same object - if
  5042. // this happens, you must have done something dodgy!
  5043. jassert (object != other.object);
  5044. swapVariables (object, other.object);
  5045. }
  5046. private:
  5047. ObjectType* object;
  5048. // (Required as an alternative to the overloaded & operator).
  5049. const ScopedPointer* getAddress() const throw() { return this; }
  5050. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  5051. // This is private to stop people accidentally copying a const ScopedPointer (the compiler
  5052. // will let you do so by implicitly casting the source to its raw object pointer).
  5053. ScopedPointer (const ScopedPointer&);
  5054. #endif
  5055. };
  5056. /** Compares a ScopedPointer with another pointer.
  5057. This can be handy for checking whether this is a null pointer.
  5058. */
  5059. template <class ObjectType>
  5060. inline bool operator== (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5061. {
  5062. return static_cast <ObjectType*> (pointer1) == pointer2;
  5063. }
  5064. /** Compares a ScopedPointer with another pointer.
  5065. This can be handy for checking whether this is a null pointer.
  5066. */
  5067. template <class ObjectType>
  5068. inline bool operator!= (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5069. {
  5070. return static_cast <ObjectType*> (pointer1) != pointer2;
  5071. }
  5072. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  5073. /*** End of inlined file: juce_ScopedPointer.h ***/
  5074. /** An array designed for holding objects.
  5075. This holds a list of pointers to objects, and will automatically
  5076. delete the objects when they are removed from the array, or when the
  5077. array is itself deleted.
  5078. Declare it in the form: OwnedArray<MyObjectClass>
  5079. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  5080. After adding objects, they are 'owned' by the array and will be deleted when
  5081. removed or replaced.
  5082. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5083. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5084. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  5085. */
  5086. template <class ObjectClass,
  5087. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5088. class OwnedArray
  5089. {
  5090. public:
  5091. /** Creates an empty array. */
  5092. OwnedArray() throw()
  5093. : numUsed (0)
  5094. {
  5095. }
  5096. /** Deletes the array and also deletes any objects inside it.
  5097. To get rid of the array without deleting its objects, use its
  5098. clear (false) method before deleting it.
  5099. */
  5100. ~OwnedArray()
  5101. {
  5102. clear (true);
  5103. }
  5104. /** Clears the array, optionally deleting the objects inside it first. */
  5105. void clear (const bool deleteObjects = true)
  5106. {
  5107. const ScopedLockType lock (getLock());
  5108. if (deleteObjects)
  5109. {
  5110. while (numUsed > 0)
  5111. delete data.elements [--numUsed];
  5112. }
  5113. data.setAllocatedSize (0);
  5114. numUsed = 0;
  5115. }
  5116. /** Returns the number of items currently in the array.
  5117. @see operator[]
  5118. */
  5119. inline int size() const throw()
  5120. {
  5121. return numUsed;
  5122. }
  5123. /** Returns a pointer to the object at this index in the array.
  5124. If the index is out-of-range, this will return a null pointer, (and
  5125. it could be null anyway, because it's ok for the array to hold null
  5126. pointers as well as objects).
  5127. @see getUnchecked
  5128. */
  5129. inline ObjectClass* operator[] (const int index) const throw()
  5130. {
  5131. const ScopedLockType lock (getLock());
  5132. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  5133. : static_cast <ObjectClass*> (0);
  5134. }
  5135. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5136. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5137. it can be used when you're sure the index if always going to be legal.
  5138. */
  5139. inline ObjectClass* getUnchecked (const int index) const throw()
  5140. {
  5141. const ScopedLockType lock (getLock());
  5142. jassert (((unsigned int) index) < (unsigned int) numUsed);
  5143. return data.elements [index];
  5144. }
  5145. /** Returns a pointer to the first object in the array.
  5146. This will return a null pointer if the array's empty.
  5147. @see getLast
  5148. */
  5149. inline ObjectClass* getFirst() const throw()
  5150. {
  5151. const ScopedLockType lock (getLock());
  5152. return numUsed > 0 ? data.elements [0]
  5153. : static_cast <ObjectClass*> (0);
  5154. }
  5155. /** Returns a pointer to the last object in the array.
  5156. This will return a null pointer if the array's empty.
  5157. @see getFirst
  5158. */
  5159. inline ObjectClass* getLast() const throw()
  5160. {
  5161. const ScopedLockType lock (getLock());
  5162. return numUsed > 0 ? data.elements [numUsed - 1]
  5163. : static_cast <ObjectClass*> (0);
  5164. }
  5165. /** Returns a pointer to the actual array data.
  5166. This pointer will only be valid until the next time a non-const method
  5167. is called on the array.
  5168. */
  5169. inline ObjectClass** getRawDataPointer() throw()
  5170. {
  5171. return data.elements;
  5172. }
  5173. /** Finds the index of an object which might be in the array.
  5174. @param objectToLookFor the object to look for
  5175. @returns the index at which the object was found, or -1 if it's not found
  5176. */
  5177. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5178. {
  5179. const ScopedLockType lock (getLock());
  5180. ObjectClass* const* e = data.elements.getData();
  5181. ObjectClass* const* const end = e + numUsed;
  5182. while (e != end)
  5183. {
  5184. if (objectToLookFor == *e)
  5185. return static_cast <int> (e - data.elements.getData());
  5186. ++e;
  5187. }
  5188. return -1;
  5189. }
  5190. /** Returns true if the array contains a specified object.
  5191. @param objectToLookFor the object to look for
  5192. @returns true if the object is in the array
  5193. */
  5194. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5195. {
  5196. const ScopedLockType lock (getLock());
  5197. ObjectClass* const* e = data.elements.getData();
  5198. ObjectClass* const* const end = e + numUsed;
  5199. while (e != end)
  5200. {
  5201. if (objectToLookFor == *e)
  5202. return true;
  5203. ++e;
  5204. }
  5205. return false;
  5206. }
  5207. /** Appends a new object to the end of the array.
  5208. Note that the this object will be deleted by the OwnedArray when it
  5209. is removed, so be careful not to delete it somewhere else.
  5210. Also be careful not to add the same object to the array more than once,
  5211. as this will obviously cause deletion of dangling pointers.
  5212. @param newObject the new object to add to the array
  5213. @see set, insert, addIfNotAlreadyThere, addSorted
  5214. */
  5215. void add (const ObjectClass* const newObject) throw()
  5216. {
  5217. const ScopedLockType lock (getLock());
  5218. data.ensureAllocatedSize (numUsed + 1);
  5219. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5220. }
  5221. /** Inserts a new object into the array at the given index.
  5222. Note that the this object will be deleted by the OwnedArray when it
  5223. is removed, so be careful not to delete it somewhere else.
  5224. If the index is less than 0 or greater than the size of the array, the
  5225. element will be added to the end of the array.
  5226. Otherwise, it will be inserted into the array, moving all the later elements
  5227. along to make room.
  5228. Be careful not to add the same object to the array more than once,
  5229. as this will obviously cause deletion of dangling pointers.
  5230. @param indexToInsertAt the index at which the new element should be inserted
  5231. @param newObject the new object to add to the array
  5232. @see add, addSorted, addIfNotAlreadyThere, set
  5233. */
  5234. void insert (int indexToInsertAt,
  5235. const ObjectClass* const newObject) throw()
  5236. {
  5237. if (indexToInsertAt >= 0)
  5238. {
  5239. const ScopedLockType lock (getLock());
  5240. if (indexToInsertAt > numUsed)
  5241. indexToInsertAt = numUsed;
  5242. data.ensureAllocatedSize (numUsed + 1);
  5243. ObjectClass** const e = data.elements + indexToInsertAt;
  5244. const int numToMove = numUsed - indexToInsertAt;
  5245. if (numToMove > 0)
  5246. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5247. *e = const_cast <ObjectClass*> (newObject);
  5248. ++numUsed;
  5249. }
  5250. else
  5251. {
  5252. add (newObject);
  5253. }
  5254. }
  5255. /** Appends a new object at the end of the array as long as the array doesn't
  5256. already contain it.
  5257. If the array already contains a matching object, nothing will be done.
  5258. @param newObject the new object to add to the array
  5259. */
  5260. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5261. {
  5262. const ScopedLockType lock (getLock());
  5263. if (! contains (newObject))
  5264. add (newObject);
  5265. }
  5266. /** Replaces an object in the array with a different one.
  5267. If the index is less than zero, this method does nothing.
  5268. If the index is beyond the end of the array, the new object is added to the end of the array.
  5269. Be careful not to add the same object to the array more than once,
  5270. as this will obviously cause deletion of dangling pointers.
  5271. @param indexToChange the index whose value you want to change
  5272. @param newObject the new value to set for this index.
  5273. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5274. @see add, insert, remove
  5275. */
  5276. void set (const int indexToChange,
  5277. const ObjectClass* const newObject,
  5278. const bool deleteOldElement = true)
  5279. {
  5280. if (indexToChange >= 0)
  5281. {
  5282. ScopedPointer <ObjectClass> toDelete;
  5283. const ScopedLockType lock (getLock());
  5284. if (indexToChange < numUsed)
  5285. {
  5286. if (deleteOldElement)
  5287. {
  5288. toDelete = data.elements [indexToChange];
  5289. if (toDelete == newObject)
  5290. toDelete = 0;
  5291. }
  5292. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5293. }
  5294. else
  5295. {
  5296. data.ensureAllocatedSize (numUsed + 1);
  5297. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5298. }
  5299. }
  5300. }
  5301. /** Adds elements from another array to the end of this array.
  5302. @param arrayToAddFrom the array from which to copy the elements
  5303. @param startIndex the first element of the other array to start copying from
  5304. @param numElementsToAdd how many elements to add from the other array. If this
  5305. value is negative or greater than the number of available elements,
  5306. all available elements will be copied.
  5307. @see add
  5308. */
  5309. template <class OtherArrayType>
  5310. void addArray (const OtherArrayType& arrayToAddFrom,
  5311. int startIndex = 0,
  5312. int numElementsToAdd = -1)
  5313. {
  5314. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5315. const ScopedLockType lock2 (getLock());
  5316. if (startIndex < 0)
  5317. {
  5318. jassertfalse;
  5319. startIndex = 0;
  5320. }
  5321. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5322. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5323. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5324. while (--numElementsToAdd >= 0)
  5325. {
  5326. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  5327. ++numUsed;
  5328. }
  5329. }
  5330. /** Adds copies of the elements in another array to the end of this array.
  5331. The other array must be either an OwnedArray of a compatible type of object, or an Array
  5332. containing pointers to the same kind of object. The objects involved must provide
  5333. a copy constructor, and this will be used to create new copies of each element, and
  5334. add them to this array.
  5335. @param arrayToAddFrom the array from which to copy the elements
  5336. @param startIndex the first element of the other array to start copying from
  5337. @param numElementsToAdd how many elements to add from the other array. If this
  5338. value is negative or greater than the number of available elements,
  5339. all available elements will be copied.
  5340. @see add
  5341. */
  5342. template <class OtherArrayType>
  5343. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  5344. int startIndex = 0,
  5345. int numElementsToAdd = -1)
  5346. {
  5347. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5348. const ScopedLockType lock2 (getLock());
  5349. if (startIndex < 0)
  5350. {
  5351. jassertfalse;
  5352. startIndex = 0;
  5353. }
  5354. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5355. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5356. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5357. while (--numElementsToAdd >= 0)
  5358. {
  5359. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  5360. ++numUsed;
  5361. }
  5362. }
  5363. /** Inserts a new object into the array assuming that the array is sorted.
  5364. This will use a comparator to find the position at which the new object
  5365. should go. If the array isn't sorted, the behaviour of this
  5366. method will be unpredictable.
  5367. @param comparator the comparator to use to compare the elements - see the sort method
  5368. for details about this object's structure
  5369. @param newObject the new object to insert to the array
  5370. @see add, sort, indexOfSorted
  5371. */
  5372. template <class ElementComparator>
  5373. void addSorted (ElementComparator& comparator,
  5374. ObjectClass* const newObject) throw()
  5375. {
  5376. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5377. // avoids getting warning messages about the parameter being unused
  5378. const ScopedLockType lock (getLock());
  5379. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5380. }
  5381. /** Finds the index of an object in the array, assuming that the array is sorted.
  5382. This will use a comparator to do a binary-chop to find the index of the given
  5383. element, if it exists. If the array isn't sorted, the behaviour of this
  5384. method will be unpredictable.
  5385. @param comparator the comparator to use to compare the elements - see the sort()
  5386. method for details about the form this object should take
  5387. @param objectToLookFor the object to search for
  5388. @returns the index of the element, or -1 if it's not found
  5389. @see addSorted, sort
  5390. */
  5391. template <class ElementComparator>
  5392. int indexOfSorted (ElementComparator& comparator,
  5393. const ObjectClass* const objectToLookFor) const throw()
  5394. {
  5395. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5396. // avoids getting warning messages about the parameter being unused
  5397. const ScopedLockType lock (getLock());
  5398. int start = 0;
  5399. int end = numUsed;
  5400. for (;;)
  5401. {
  5402. if (start >= end)
  5403. {
  5404. return -1;
  5405. }
  5406. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5407. {
  5408. return start;
  5409. }
  5410. else
  5411. {
  5412. const int halfway = (start + end) >> 1;
  5413. if (halfway == start)
  5414. return -1;
  5415. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5416. start = halfway;
  5417. else
  5418. end = halfway;
  5419. }
  5420. }
  5421. }
  5422. /** Removes an object from the array.
  5423. This will remove the object at a given index (optionally also
  5424. deleting it) and move back all the subsequent objects to close the gap.
  5425. If the index passed in is out-of-range, nothing will happen.
  5426. @param indexToRemove the index of the element to remove
  5427. @param deleteObject whether to delete the object that is removed
  5428. @see removeObject, removeRange
  5429. */
  5430. void remove (const int indexToRemove,
  5431. const bool deleteObject = true)
  5432. {
  5433. ScopedPointer <ObjectClass> toDelete;
  5434. const ScopedLockType lock (getLock());
  5435. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5436. {
  5437. ObjectClass** const e = data.elements + indexToRemove;
  5438. if (deleteObject)
  5439. toDelete = *e;
  5440. --numUsed;
  5441. const int numToShift = numUsed - indexToRemove;
  5442. if (numToShift > 0)
  5443. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5444. if ((numUsed << 1) < data.numAllocated)
  5445. minimiseStorageOverheads();
  5446. }
  5447. }
  5448. /** Removes and returns an object from the array without deleting it.
  5449. This will remove the object at a given index and return it, moving back all
  5450. the subsequent objects to close the gap. If the index passed in is out-of-range,
  5451. nothing will happen.
  5452. @param indexToRemove the index of the element to remove
  5453. @see remove, removeObject, removeRange
  5454. */
  5455. ObjectClass* removeAndReturn (const int indexToRemove)
  5456. {
  5457. ObjectClass* removedItem = 0;
  5458. const ScopedLockType lock (getLock());
  5459. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5460. {
  5461. ObjectClass** const e = data.elements + indexToRemove;
  5462. removedItem = *e;
  5463. --numUsed;
  5464. const int numToShift = numUsed - indexToRemove;
  5465. if (numToShift > 0)
  5466. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5467. if ((numUsed << 1) < data.numAllocated)
  5468. minimiseStorageOverheads();
  5469. }
  5470. return removedItem;
  5471. }
  5472. /** Removes a specified object from the array.
  5473. If the item isn't found, no action is taken.
  5474. @param objectToRemove the object to try to remove
  5475. @param deleteObject whether to delete the object (if it's found)
  5476. @see remove, removeRange
  5477. */
  5478. void removeObject (const ObjectClass* const objectToRemove,
  5479. const bool deleteObject = true)
  5480. {
  5481. const ScopedLockType lock (getLock());
  5482. ObjectClass** e = data.elements.getData();
  5483. for (int i = numUsed; --i >= 0;)
  5484. {
  5485. if (objectToRemove == *e)
  5486. {
  5487. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5488. break;
  5489. }
  5490. ++e;
  5491. }
  5492. }
  5493. /** Removes a range of objects from the array.
  5494. This will remove a set of objects, starting from the given index,
  5495. and move any subsequent elements down to close the gap.
  5496. If the range extends beyond the bounds of the array, it will
  5497. be safely clipped to the size of the array.
  5498. @param startIndex the index of the first object to remove
  5499. @param numberToRemove how many objects should be removed
  5500. @param deleteObjects whether to delete the objects that get removed
  5501. @see remove, removeObject
  5502. */
  5503. void removeRange (int startIndex,
  5504. const int numberToRemove,
  5505. const bool deleteObjects = true)
  5506. {
  5507. const ScopedLockType lock (getLock());
  5508. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5509. startIndex = jlimit (0, numUsed, startIndex);
  5510. if (endIndex > startIndex)
  5511. {
  5512. if (deleteObjects)
  5513. {
  5514. for (int i = startIndex; i < endIndex; ++i)
  5515. {
  5516. delete data.elements [i];
  5517. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5518. }
  5519. }
  5520. const int rangeSize = endIndex - startIndex;
  5521. ObjectClass** e = data.elements + startIndex;
  5522. int numToShift = numUsed - endIndex;
  5523. numUsed -= rangeSize;
  5524. while (--numToShift >= 0)
  5525. {
  5526. *e = e [rangeSize];
  5527. ++e;
  5528. }
  5529. if ((numUsed << 1) < data.numAllocated)
  5530. minimiseStorageOverheads();
  5531. }
  5532. }
  5533. /** Removes the last n objects from the array.
  5534. @param howManyToRemove how many objects to remove from the end of the array
  5535. @param deleteObjects whether to also delete the objects that are removed
  5536. @see remove, removeObject, removeRange
  5537. */
  5538. void removeLast (int howManyToRemove = 1,
  5539. const bool deleteObjects = true)
  5540. {
  5541. const ScopedLockType lock (getLock());
  5542. if (howManyToRemove >= numUsed)
  5543. clear (deleteObjects);
  5544. else
  5545. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  5546. }
  5547. /** Swaps a pair of objects in the array.
  5548. If either of the indexes passed in is out-of-range, nothing will happen,
  5549. otherwise the two objects at these positions will be exchanged.
  5550. */
  5551. void swap (const int index1,
  5552. const int index2) throw()
  5553. {
  5554. const ScopedLockType lock (getLock());
  5555. if (((unsigned int) index1) < (unsigned int) numUsed
  5556. && ((unsigned int) index2) < (unsigned int) numUsed)
  5557. {
  5558. swapVariables (data.elements [index1],
  5559. data.elements [index2]);
  5560. }
  5561. }
  5562. /** Moves one of the objects to a different position.
  5563. This will move the object to a specified index, shuffling along
  5564. any intervening elements as required.
  5565. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5566. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5567. @param currentIndex the index of the object to be moved. If this isn't a
  5568. valid index, then nothing will be done
  5569. @param newIndex the index at which you'd like this object to end up. If this
  5570. is less than zero, it will be moved to the end of the array
  5571. */
  5572. void move (const int currentIndex,
  5573. int newIndex) throw()
  5574. {
  5575. if (currentIndex != newIndex)
  5576. {
  5577. const ScopedLockType lock (getLock());
  5578. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  5579. {
  5580. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  5581. newIndex = numUsed - 1;
  5582. ObjectClass* const value = data.elements [currentIndex];
  5583. if (newIndex > currentIndex)
  5584. {
  5585. memmove (data.elements + currentIndex,
  5586. data.elements + currentIndex + 1,
  5587. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5588. }
  5589. else
  5590. {
  5591. memmove (data.elements + newIndex + 1,
  5592. data.elements + newIndex,
  5593. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5594. }
  5595. data.elements [newIndex] = value;
  5596. }
  5597. }
  5598. }
  5599. /** This swaps the contents of this array with those of another array.
  5600. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5601. because it just swaps their internal pointers.
  5602. */
  5603. void swapWithArray (OwnedArray& otherArray) throw()
  5604. {
  5605. const ScopedLockType lock1 (getLock());
  5606. const ScopedLockType lock2 (otherArray.getLock());
  5607. data.swapWith (otherArray.data);
  5608. swapVariables (numUsed, otherArray.numUsed);
  5609. }
  5610. /** Reduces the amount of storage being used by the array.
  5611. Arrays typically allocate slightly more storage than they need, and after
  5612. removing elements, they may have quite a lot of unused space allocated.
  5613. This method will reduce the amount of allocated storage to a minimum.
  5614. */
  5615. void minimiseStorageOverheads() throw()
  5616. {
  5617. const ScopedLockType lock (getLock());
  5618. data.shrinkToNoMoreThan (numUsed);
  5619. }
  5620. /** Increases the array's internal storage to hold a minimum number of elements.
  5621. Calling this before adding a large known number of elements means that
  5622. the array won't have to keep dynamically resizing itself as the elements
  5623. are added, and it'll therefore be more efficient.
  5624. */
  5625. void ensureStorageAllocated (const int minNumElements) throw()
  5626. {
  5627. const ScopedLockType lock (getLock());
  5628. data.ensureAllocatedSize (minNumElements);
  5629. }
  5630. /** Sorts the elements in the array.
  5631. This will use a comparator object to sort the elements into order. The object
  5632. passed must have a method of the form:
  5633. @code
  5634. int compareElements (ElementType first, ElementType second);
  5635. @endcode
  5636. ..and this method must return:
  5637. - a value of < 0 if the first comes before the second
  5638. - a value of 0 if the two objects are equivalent
  5639. - a value of > 0 if the second comes before the first
  5640. To improve performance, the compareElements() method can be declared as static or const.
  5641. @param comparator the comparator to use for comparing elements.
  5642. @param retainOrderOfEquivalentItems if this is true, then items
  5643. which the comparator says are equivalent will be
  5644. kept in the order in which they currently appear
  5645. in the array. This is slower to perform, but may
  5646. be important in some cases. If it's false, a faster
  5647. algorithm is used, but equivalent elements may be
  5648. rearranged.
  5649. @see sortArray, indexOfSorted
  5650. */
  5651. template <class ElementComparator>
  5652. void sort (ElementComparator& comparator,
  5653. const bool retainOrderOfEquivalentItems = false) const throw()
  5654. {
  5655. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5656. // avoids getting warning messages about the parameter being unused
  5657. const ScopedLockType lock (getLock());
  5658. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5659. }
  5660. /** Returns the CriticalSection that locks this array.
  5661. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5662. an object of ScopedLockType as an RAII lock for it.
  5663. */
  5664. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5665. /** Returns the type of scoped lock to use for locking this array */
  5666. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5667. juce_UseDebuggingNewOperator
  5668. private:
  5669. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  5670. int numUsed;
  5671. // disallow copy constructor and assignment
  5672. OwnedArray (const OwnedArray&);
  5673. OwnedArray& operator= (const OwnedArray&);
  5674. };
  5675. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5676. /*** End of inlined file: juce_OwnedArray.h ***/
  5677. #endif
  5678. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5679. /*** Start of inlined file: juce_PropertySet.h ***/
  5680. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5681. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5682. /*** Start of inlined file: juce_StringPairArray.h ***/
  5683. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5684. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5685. /*** Start of inlined file: juce_StringArray.h ***/
  5686. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5687. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5688. /**
  5689. A special array for holding a list of strings.
  5690. @see String, StringPairArray
  5691. */
  5692. class JUCE_API StringArray
  5693. {
  5694. public:
  5695. /** Creates an empty string array */
  5696. StringArray() throw();
  5697. /** Creates a copy of another string array */
  5698. StringArray (const StringArray& other);
  5699. /** Creates an array containing a single string. */
  5700. explicit StringArray (const String& firstValue);
  5701. /** Creates a copy of an array of string literals.
  5702. @param strings an array of strings to add. Null pointers in the array will be
  5703. treated as empty strings
  5704. @param numberOfStrings how many items there are in the array
  5705. */
  5706. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  5707. /** Creates a copy of an array of string literals.
  5708. @param strings an array of strings to add. Null pointers in the array will be
  5709. treated as empty strings
  5710. @param numberOfStrings how many items there are in the array
  5711. */
  5712. StringArray (const char* const* strings, int numberOfStrings);
  5713. /** Creates a copy of a null-terminated array of string literals.
  5714. Each item from the array passed-in is added, until it encounters a null pointer,
  5715. at which point it stops.
  5716. */
  5717. explicit StringArray (const juce_wchar* const* strings);
  5718. /** Creates a copy of a null-terminated array of string literals.
  5719. Each item from the array passed-in is added, until it encounters a null pointer,
  5720. at which point it stops.
  5721. */
  5722. explicit StringArray (const char* const* strings);
  5723. /** Destructor. */
  5724. ~StringArray();
  5725. /** Copies the contents of another string array into this one */
  5726. StringArray& operator= (const StringArray& other);
  5727. /** Compares two arrays.
  5728. Comparisons are case-sensitive.
  5729. @returns true only if the other array contains exactly the same strings in the same order
  5730. */
  5731. bool operator== (const StringArray& other) const throw();
  5732. /** Compares two arrays.
  5733. Comparisons are case-sensitive.
  5734. @returns false if the other array contains exactly the same strings in the same order
  5735. */
  5736. bool operator!= (const StringArray& other) const throw();
  5737. /** Returns the number of strings in the array */
  5738. inline int size() const throw() { return strings.size(); };
  5739. /** Returns one of the strings from the array.
  5740. If the index is out-of-range, an empty string is returned.
  5741. Obviously the reference returned shouldn't be stored for later use, as the
  5742. string it refers to may disappear when the array changes.
  5743. */
  5744. const String& operator[] (int index) const throw();
  5745. /** Returns a reference to one of the strings in the array.
  5746. This lets you modify a string in-place in the array, but you must be sure that
  5747. the index is in-range.
  5748. */
  5749. String& getReference (int index) throw();
  5750. /** Searches for a string in the array.
  5751. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5752. @returns true if the string is found inside the array
  5753. */
  5754. bool contains (const String& stringToLookFor,
  5755. bool ignoreCase = false) const;
  5756. /** Searches for a string in the array.
  5757. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5758. @param stringToLookFor the string to try to find
  5759. @param ignoreCase whether the comparison should be case-insensitive
  5760. @param startIndex the first index to start searching from
  5761. @returns the index of the first occurrence of the string in this array,
  5762. or -1 if it isn't found.
  5763. */
  5764. int indexOf (const String& stringToLookFor,
  5765. bool ignoreCase = false,
  5766. int startIndex = 0) const;
  5767. /** Appends a string at the end of the array. */
  5768. void add (const String& stringToAdd);
  5769. /** Inserts a string into the array.
  5770. This will insert a string into the array at the given index, moving
  5771. up the other elements to make room for it.
  5772. If the index is less than zero or greater than the size of the array,
  5773. the new string will be added to the end of the array.
  5774. */
  5775. void insert (int index, const String& stringToAdd);
  5776. /** Adds a string to the array as long as it's not already in there.
  5777. The search can optionally be case-insensitive.
  5778. */
  5779. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  5780. /** Replaces one of the strings in the array with another one.
  5781. If the index is higher than the array's size, the new string will be
  5782. added to the end of the array; if it's less than zero nothing happens.
  5783. */
  5784. void set (int index, const String& newString);
  5785. /** Appends some strings from another array to the end of this one.
  5786. @param other the array to add
  5787. @param startIndex the first element of the other array to add
  5788. @param numElementsToAdd the maximum number of elements to add (if this is
  5789. less than zero, they are all added)
  5790. */
  5791. void addArray (const StringArray& other,
  5792. int startIndex = 0,
  5793. int numElementsToAdd = -1);
  5794. /** Breaks up a string into tokens and adds them to this array.
  5795. This will tokenise the given string using whitespace characters as the
  5796. token delimiters, and will add these tokens to the end of the array.
  5797. @returns the number of tokens added
  5798. */
  5799. int addTokens (const String& stringToTokenise,
  5800. bool preserveQuotedStrings);
  5801. /** Breaks up a string into tokens and adds them to this array.
  5802. This will tokenise the given string (using the string passed in to define the
  5803. token delimiters), and will add these tokens to the end of the array.
  5804. @param stringToTokenise the string to tokenise
  5805. @param breakCharacters a string of characters, any of which will be considered
  5806. to be a token delimiter.
  5807. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5808. which are treated as quotes. Any text occurring
  5809. between quotes is not broken up into tokens.
  5810. @returns the number of tokens added
  5811. */
  5812. int addTokens (const String& stringToTokenise,
  5813. const String& breakCharacters,
  5814. const String& quoteCharacters);
  5815. /** Breaks up a string into lines and adds them to this array.
  5816. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5817. to the array. Line-break characters are omitted from the strings that are added to
  5818. the array.
  5819. */
  5820. int addLines (const String& stringToBreakUp);
  5821. /** Removes all elements from the array. */
  5822. void clear();
  5823. /** Removes a string from the array.
  5824. If the index is out-of-range, no action will be taken.
  5825. */
  5826. void remove (int index);
  5827. /** Finds a string in the array and removes it.
  5828. This will remove the first occurrence of the given string from the array. The
  5829. comparison may be case-insensitive depending on the ignoreCase parameter.
  5830. */
  5831. void removeString (const String& stringToRemove,
  5832. bool ignoreCase = false);
  5833. /** Removes a range of elements from the array.
  5834. This will remove a set of elements, starting from the given index,
  5835. and move subsequent elements down to close the gap.
  5836. If the range extends beyond the bounds of the array, it will
  5837. be safely clipped to the size of the array.
  5838. @param startIndex the index of the first element to remove
  5839. @param numberToRemove how many elements should be removed
  5840. */
  5841. void removeRange (int startIndex, int numberToRemove);
  5842. /** Removes any duplicated elements from the array.
  5843. If any string appears in the array more than once, only the first occurrence of
  5844. it will be retained.
  5845. @param ignoreCase whether to use a case-insensitive comparison
  5846. */
  5847. void removeDuplicates (bool ignoreCase);
  5848. /** Removes empty strings from the array.
  5849. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5850. characters will also be removed
  5851. */
  5852. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  5853. /** Moves one of the strings to a different position.
  5854. This will move the string to a specified index, shuffling along
  5855. any intervening elements as required.
  5856. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5857. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5858. @param currentIndex the index of the value to be moved. If this isn't a
  5859. valid index, then nothing will be done
  5860. @param newIndex the index at which you'd like this value to end up. If this
  5861. is less than zero, the value will be moved to the end
  5862. of the array
  5863. */
  5864. void move (int currentIndex, int newIndex) throw();
  5865. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5866. void trim();
  5867. /** Adds numbers to the strings in the array, to make each string unique.
  5868. This will add numbers to the ends of groups of similar strings.
  5869. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5870. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5871. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5872. also has a number appended to it.
  5873. @param preNumberString when adding a number, this string is added before the number.
  5874. If you pass 0, a default string will be used, which adds
  5875. brackets around the number.
  5876. @param postNumberString this string is appended after any numbers that are added.
  5877. If you pass 0, a default string will be used, which adds
  5878. brackets around the number.
  5879. */
  5880. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  5881. bool appendNumberToFirstInstance,
  5882. const juce_wchar* preNumberString = 0,
  5883. const juce_wchar* postNumberString = 0);
  5884. /** Joins the strings in the array together into one string.
  5885. This will join a range of elements from the array into a string, separating
  5886. them with a given string.
  5887. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5888. @param separatorString the string to insert between all the strings
  5889. @param startIndex the first element to join
  5890. @param numberOfElements how many elements to join together. If this is less
  5891. than zero, all available elements will be used.
  5892. */
  5893. const String joinIntoString (const String& separatorString,
  5894. int startIndex = 0,
  5895. int numberOfElements = -1) const;
  5896. /** Sorts the array into alphabetical order.
  5897. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5898. */
  5899. void sort (bool ignoreCase);
  5900. /** Reduces the amount of storage being used by the array.
  5901. Arrays typically allocate slightly more storage than they need, and after
  5902. removing elements, they may have quite a lot of unused space allocated.
  5903. This method will reduce the amount of allocated storage to a minimum.
  5904. */
  5905. void minimiseStorageOverheads();
  5906. juce_UseDebuggingNewOperator
  5907. private:
  5908. Array <String> strings;
  5909. };
  5910. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5911. /*** End of inlined file: juce_StringArray.h ***/
  5912. /**
  5913. A container for holding a set of strings which are keyed by another string.
  5914. @see StringArray
  5915. */
  5916. class JUCE_API StringPairArray
  5917. {
  5918. public:
  5919. /** Creates an empty array */
  5920. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  5921. /** Creates a copy of another array */
  5922. StringPairArray (const StringPairArray& other);
  5923. /** Destructor. */
  5924. ~StringPairArray();
  5925. /** Copies the contents of another string array into this one */
  5926. StringPairArray& operator= (const StringPairArray& other);
  5927. /** Compares two arrays.
  5928. Comparisons are case-sensitive.
  5929. @returns true only if the other array contains exactly the same strings with the same keys
  5930. */
  5931. bool operator== (const StringPairArray& other) const;
  5932. /** Compares two arrays.
  5933. Comparisons are case-sensitive.
  5934. @returns false if the other array contains exactly the same strings with the same keys
  5935. */
  5936. bool operator!= (const StringPairArray& other) const;
  5937. /** Finds the value corresponding to a key string.
  5938. If no such key is found, this will just return an empty string. To check whether
  5939. a given key actually exists (because it might actually be paired with an empty string), use
  5940. the getAllKeys() method to obtain a list.
  5941. Obviously the reference returned shouldn't be stored for later use, as the
  5942. string it refers to may disappear when the array changes.
  5943. @see getValue
  5944. */
  5945. const String& operator[] (const String& key) const;
  5946. /** Finds the value corresponding to a key string.
  5947. If no such key is found, this will just return the value provided as a default.
  5948. @see operator[]
  5949. */
  5950. const String getValue (const String& key, const String& defaultReturnValue) const;
  5951. /** Returns a list of all keys in the array. */
  5952. const StringArray& getAllKeys() const throw() { return keys; }
  5953. /** Returns a list of all values in the array. */
  5954. const StringArray& getAllValues() const throw() { return values; }
  5955. /** Returns the number of strings in the array */
  5956. inline int size() const throw() { return keys.size(); };
  5957. /** Adds or amends a key/value pair.
  5958. If a value already exists with this key, its value will be overwritten,
  5959. otherwise the key/value pair will be added to the array.
  5960. */
  5961. void set (const String& key, const String& value);
  5962. /** Adds the items from another array to this one.
  5963. This is equivalent to using set() to add each of the pairs from the other array.
  5964. */
  5965. void addArray (const StringPairArray& other);
  5966. /** Removes all elements from the array. */
  5967. void clear();
  5968. /** Removes a string from the array based on its key.
  5969. If the key isn't found, nothing will happen.
  5970. */
  5971. void remove (const String& key);
  5972. /** Removes a string from the array based on its index.
  5973. If the index is out-of-range, no action will be taken.
  5974. */
  5975. void remove (int index);
  5976. /** Indicates whether to use a case-insensitive search when looking up a key string.
  5977. */
  5978. void setIgnoresCase (bool shouldIgnoreCase);
  5979. /** Returns a descriptive string containing the items.
  5980. This is handy for dumping the contents of an array.
  5981. */
  5982. const String getDescription() const;
  5983. /** Reduces the amount of storage being used by the array.
  5984. Arrays typically allocate slightly more storage than they need, and after
  5985. removing elements, they may have quite a lot of unused space allocated.
  5986. This method will reduce the amount of allocated storage to a minimum.
  5987. */
  5988. void minimiseStorageOverheads();
  5989. juce_UseDebuggingNewOperator
  5990. private:
  5991. StringArray keys, values;
  5992. bool ignoreCase;
  5993. };
  5994. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5995. /*** End of inlined file: juce_StringPairArray.h ***/
  5996. /*** Start of inlined file: juce_XmlElement.h ***/
  5997. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5998. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5999. /*** Start of inlined file: juce_File.h ***/
  6000. #ifndef __JUCE_FILE_JUCEHEADER__
  6001. #define __JUCE_FILE_JUCEHEADER__
  6002. /*** Start of inlined file: juce_Time.h ***/
  6003. #ifndef __JUCE_TIME_JUCEHEADER__
  6004. #define __JUCE_TIME_JUCEHEADER__
  6005. /*** Start of inlined file: juce_RelativeTime.h ***/
  6006. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  6007. #define __JUCE_RELATIVETIME_JUCEHEADER__
  6008. /** A relative measure of time.
  6009. The time is stored as a number of seconds, at double-precision floating
  6010. point accuracy, and may be positive or negative.
  6011. If you need an absolute time, (i.e. a date + time), see the Time class.
  6012. */
  6013. class JUCE_API RelativeTime
  6014. {
  6015. public:
  6016. /** Creates a RelativeTime.
  6017. @param seconds the number of seconds, which may be +ve or -ve.
  6018. @see milliseconds, minutes, hours, days, weeks
  6019. */
  6020. explicit RelativeTime (double seconds = 0.0) throw();
  6021. /** Copies another relative time. */
  6022. RelativeTime (const RelativeTime& other) throw();
  6023. /** Copies another relative time. */
  6024. RelativeTime& operator= (const RelativeTime& other) throw();
  6025. /** Destructor. */
  6026. ~RelativeTime() throw();
  6027. /** Creates a new RelativeTime object representing a number of milliseconds.
  6028. @see minutes, hours, days, weeks
  6029. */
  6030. static const RelativeTime milliseconds (int milliseconds) throw();
  6031. /** Creates a new RelativeTime object representing a number of milliseconds.
  6032. @see minutes, hours, days, weeks
  6033. */
  6034. static const RelativeTime milliseconds (int64 milliseconds) throw();
  6035. /** Creates a new RelativeTime object representing a number of minutes.
  6036. @see milliseconds, hours, days, weeks
  6037. */
  6038. static const RelativeTime minutes (double numberOfMinutes) throw();
  6039. /** Creates a new RelativeTime object representing a number of hours.
  6040. @see milliseconds, minutes, days, weeks
  6041. */
  6042. static const RelativeTime hours (double numberOfHours) throw();
  6043. /** Creates a new RelativeTime object representing a number of days.
  6044. @see milliseconds, minutes, hours, weeks
  6045. */
  6046. static const RelativeTime days (double numberOfDays) throw();
  6047. /** Creates a new RelativeTime object representing a number of weeks.
  6048. @see milliseconds, minutes, hours, days
  6049. */
  6050. static const RelativeTime weeks (double numberOfWeeks) throw();
  6051. /** Returns the number of milliseconds this time represents.
  6052. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6053. */
  6054. int64 inMilliseconds() const throw();
  6055. /** Returns the number of seconds this time represents.
  6056. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  6057. */
  6058. double inSeconds() const throw() { return seconds; }
  6059. /** Returns the number of minutes this time represents.
  6060. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  6061. */
  6062. double inMinutes() const throw();
  6063. /** Returns the number of hours this time represents.
  6064. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  6065. */
  6066. double inHours() const throw();
  6067. /** Returns the number of days this time represents.
  6068. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  6069. */
  6070. double inDays() const throw();
  6071. /** Returns the number of weeks this time represents.
  6072. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  6073. */
  6074. double inWeeks() const throw();
  6075. /** Returns a readable textual description of the time.
  6076. The exact format of the string returned will depend on
  6077. the magnitude of the time - e.g.
  6078. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  6079. so that only the two most significant units are printed.
  6080. The returnValueForZeroTime value is the result that is returned if the
  6081. length is zero. Depending on your application you might want to use this
  6082. to return something more relevant like "empty" or "0 secs", etc.
  6083. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6084. */
  6085. const String getDescription (const String& returnValueForZeroTime = "0") const throw();
  6086. /** Compares two RelativeTimes. */
  6087. bool operator== (const RelativeTime& other) const throw();
  6088. /** Compares two RelativeTimes. */
  6089. bool operator!= (const RelativeTime& other) const throw();
  6090. /** Compares two RelativeTimes. */
  6091. bool operator> (const RelativeTime& other) const throw();
  6092. /** Compares two RelativeTimes. */
  6093. bool operator< (const RelativeTime& other) const throw();
  6094. /** Compares two RelativeTimes. */
  6095. bool operator>= (const RelativeTime& other) const throw();
  6096. /** Compares two RelativeTimes. */
  6097. bool operator<= (const RelativeTime& other) const throw();
  6098. /** Adds another RelativeTime to this one and returns the result. */
  6099. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  6100. /** Subtracts another RelativeTime from this one and returns the result. */
  6101. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  6102. /** Adds a number of seconds to this RelativeTime and returns the result. */
  6103. const RelativeTime operator+ (double secondsToAdd) const throw();
  6104. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  6105. const RelativeTime operator- (double secondsToSubtract) const throw();
  6106. /** Adds another RelativeTime to this one. */
  6107. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  6108. /** Subtracts another RelativeTime from this one. */
  6109. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  6110. /** Adds a number of seconds to this time. */
  6111. const RelativeTime& operator+= (double secondsToAdd) throw();
  6112. /** Subtracts a number of seconds from this time. */
  6113. const RelativeTime& operator-= (double secondsToSubtract) throw();
  6114. juce_UseDebuggingNewOperator
  6115. private:
  6116. double seconds;
  6117. };
  6118. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  6119. /*** End of inlined file: juce_RelativeTime.h ***/
  6120. /**
  6121. Holds an absolute date and time.
  6122. Internally, the time is stored at millisecond precision.
  6123. @see RelativeTime
  6124. */
  6125. class JUCE_API Time
  6126. {
  6127. public:
  6128. /** Creates a Time object.
  6129. This default constructor creates a time of 1st January 1970, (which is
  6130. represented internally as 0ms).
  6131. To create a time object representing the current time, use getCurrentTime().
  6132. @see getCurrentTime
  6133. */
  6134. Time() throw();
  6135. /** Creates a copy of another Time object. */
  6136. Time (const Time& other) throw();
  6137. /** Creates a time based on a number of milliseconds.
  6138. The internal millisecond count is set to 0 (1st January 1970). To create a
  6139. time object set to the current time, use getCurrentTime().
  6140. @param millisecondsSinceEpoch the number of milliseconds since the unix
  6141. 'epoch' (midnight Jan 1st 1970).
  6142. @see getCurrentTime, currentTimeMillis
  6143. */
  6144. Time (int64 millisecondsSinceEpoch) throw();
  6145. /** Creates a time from a set of date components.
  6146. The timezone is assumed to be whatever the system is using as its locale.
  6147. @param year the year, in 4-digit format, e.g. 2004
  6148. @param month the month, in the range 0 to 11
  6149. @param day the day of the month, in the range 1 to 31
  6150. @param hours hours in 24-hour clock format, 0 to 23
  6151. @param minutes minutes 0 to 59
  6152. @param seconds seconds 0 to 59
  6153. @param milliseconds milliseconds 0 to 999
  6154. @param useLocalTime if true, encode using the current machine's local time; if
  6155. false, it will always work in GMT.
  6156. */
  6157. Time (int year,
  6158. int month,
  6159. int day,
  6160. int hours,
  6161. int minutes,
  6162. int seconds = 0,
  6163. int milliseconds = 0,
  6164. bool useLocalTime = true) throw();
  6165. /** Destructor. */
  6166. ~Time() throw();
  6167. /** Copies this time from another one. */
  6168. Time& operator= (const Time& other) throw();
  6169. /** Returns a Time object that is set to the current system time.
  6170. @see currentTimeMillis
  6171. */
  6172. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6173. /** Returns the time as a number of milliseconds.
  6174. @returns the number of milliseconds this Time object represents, since
  6175. midnight jan 1st 1970.
  6176. @see getMilliseconds
  6177. */
  6178. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6179. /** Returns the year.
  6180. A 4-digit format is used, e.g. 2004.
  6181. */
  6182. int getYear() const throw();
  6183. /** Returns the number of the month.
  6184. The value returned is in the range 0 to 11.
  6185. @see getMonthName
  6186. */
  6187. int getMonth() const throw();
  6188. /** Returns the name of the month.
  6189. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6190. it'll return the long form, e.g. "January"
  6191. @see getMonth
  6192. */
  6193. const String getMonthName (bool threeLetterVersion) const throw();
  6194. /** Returns the day of the month.
  6195. The value returned is in the range 1 to 31.
  6196. */
  6197. int getDayOfMonth() const throw();
  6198. /** Returns the number of the day of the week.
  6199. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6200. */
  6201. int getDayOfWeek() const throw();
  6202. /** Returns the name of the weekday.
  6203. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6204. false, it'll return the full version, e.g. "Tuesday".
  6205. */
  6206. const String getWeekdayName (bool threeLetterVersion) const throw();
  6207. /** Returns the number of hours since midnight.
  6208. This is in 24-hour clock format, in the range 0 to 23.
  6209. @see getHoursInAmPmFormat, isAfternoon
  6210. */
  6211. int getHours() const throw();
  6212. /** Returns true if the time is in the afternoon.
  6213. So it returns true for "PM", false for "AM".
  6214. @see getHoursInAmPmFormat, getHours
  6215. */
  6216. bool isAfternoon() const throw();
  6217. /** Returns the hours in 12-hour clock format.
  6218. This will return a value 1 to 12 - use isAfternoon() to find out
  6219. whether this is in the afternoon or morning.
  6220. @see getHours, isAfternoon
  6221. */
  6222. int getHoursInAmPmFormat() const throw();
  6223. /** Returns the number of minutes, 0 to 59. */
  6224. int getMinutes() const throw();
  6225. /** Returns the number of seconds, 0 to 59. */
  6226. int getSeconds() const throw();
  6227. /** Returns the number of milliseconds, 0 to 999.
  6228. Unlike toMilliseconds(), this just returns the position within the
  6229. current second rather than the total number since the epoch.
  6230. @see toMilliseconds
  6231. */
  6232. int getMilliseconds() const throw();
  6233. /** Returns true if the local timezone uses a daylight saving correction. */
  6234. bool isDaylightSavingTime() const throw();
  6235. /** Returns a 3-character string to indicate the local timezone. */
  6236. const String getTimeZone() const throw();
  6237. /** Quick way of getting a string version of a date and time.
  6238. For a more powerful way of formatting the date and time, see the formatted() method.
  6239. @param includeDate whether to include the date in the string
  6240. @param includeTime whether to include the time in the string
  6241. @param includeSeconds if the time is being included, this provides an option not to include
  6242. the seconds in it
  6243. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6244. hour notation.
  6245. @see formatted
  6246. */
  6247. const String toString (bool includeDate,
  6248. bool includeTime,
  6249. bool includeSeconds = true,
  6250. bool use24HourClock = false) const throw();
  6251. /** Converts this date/time to a string with a user-defined format.
  6252. This uses the C strftime() function to format this time as a string. To save you
  6253. looking it up, these are the escape codes that strftime uses (other codes might
  6254. work on some platforms and not others, but these are the common ones):
  6255. %a is replaced by the locale's abbreviated weekday name.
  6256. %A is replaced by the locale's full weekday name.
  6257. %b is replaced by the locale's abbreviated month name.
  6258. %B is replaced by the locale's full month name.
  6259. %c is replaced by the locale's appropriate date and time representation.
  6260. %d is replaced by the day of the month as a decimal number [01,31].
  6261. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6262. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6263. %j is replaced by the day of the year as a decimal number [001,366].
  6264. %m is replaced by the month as a decimal number [01,12].
  6265. %M is replaced by the minute as a decimal number [00,59].
  6266. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6267. %S is replaced by the second as a decimal number [00,61].
  6268. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6269. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6270. %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.
  6271. %x is replaced by the locale's appropriate date representation.
  6272. %X is replaced by the locale's appropriate time representation.
  6273. %y is replaced by the year without century as a decimal number [00,99].
  6274. %Y is replaced by the year with century as a decimal number.
  6275. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6276. %% is replaced by %.
  6277. @see toString
  6278. */
  6279. const String formatted (const String& format) const throw();
  6280. /** Adds a RelativeTime to this time and returns the result. */
  6281. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  6282. /** Subtracts a RelativeTime from this time and returns the result. */
  6283. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  6284. /** Returns the relative time difference between this time and another one. */
  6285. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  6286. /** Compares two Time objects. */
  6287. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  6288. /** Compares two Time objects. */
  6289. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  6290. /** Compares two Time objects. */
  6291. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  6292. /** Compares two Time objects. */
  6293. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  6294. /** Compares two Time objects. */
  6295. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  6296. /** Compares two Time objects. */
  6297. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  6298. /** Tries to set the computer's clock.
  6299. @returns true if this succeeds, although depending on the system, the
  6300. application might not have sufficient privileges to do this.
  6301. */
  6302. bool setSystemTimeToThisTime() const;
  6303. /** Returns the name of a day of the week.
  6304. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6305. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6306. false, it'll return the full version, e.g. "Tuesday".
  6307. */
  6308. static const String getWeekdayName (int dayNumber,
  6309. bool threeLetterVersion) throw();
  6310. /** Returns the name of one of the months.
  6311. @param monthNumber the month, 0 to 11
  6312. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6313. it'll return the long form, e.g. "January"
  6314. */
  6315. static const String getMonthName (int monthNumber,
  6316. bool threeLetterVersion) throw();
  6317. // Static methods for getting system timers directly..
  6318. /** Returns the current system time.
  6319. Returns the number of milliseconds since midnight jan 1st 1970.
  6320. Should be accurate to within a few millisecs, depending on platform,
  6321. hardware, etc.
  6322. */
  6323. static int64 currentTimeMillis() throw();
  6324. /** Returns the number of millisecs since system startup.
  6325. Should be accurate to within a few millisecs, depending on platform,
  6326. hardware, etc.
  6327. @see getApproximateMillisecondCounter
  6328. */
  6329. static uint32 getMillisecondCounter() throw();
  6330. /** Returns the number of millisecs since system startup.
  6331. Same as getMillisecondCounter(), but returns a more accurate value, using
  6332. the high-res timer.
  6333. @see getMillisecondCounter
  6334. */
  6335. static double getMillisecondCounterHiRes() throw();
  6336. /** Waits until the getMillisecondCounter() reaches a given value.
  6337. This will make the thread sleep as efficiently as it can while it's waiting.
  6338. */
  6339. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6340. /** Less-accurate but faster version of getMillisecondCounter().
  6341. This will return the last value that getMillisecondCounter() returned, so doesn't
  6342. need to make a system call, but is less accurate - it shouldn't be more than
  6343. 100ms away from the correct time, though, so is still accurate enough for a
  6344. lot of purposes.
  6345. @see getMillisecondCounter
  6346. */
  6347. static uint32 getApproximateMillisecondCounter() throw();
  6348. // High-resolution timers..
  6349. /** Returns the current high-resolution counter's tick-count.
  6350. This is a similar idea to getMillisecondCounter(), but with a higher
  6351. resolution.
  6352. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6353. secondsToHighResolutionTicks
  6354. */
  6355. static int64 getHighResolutionTicks() throw();
  6356. /** Returns the resolution of the high-resolution counter in ticks per second.
  6357. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6358. secondsToHighResolutionTicks
  6359. */
  6360. static int64 getHighResolutionTicksPerSecond() throw();
  6361. /** Converts a number of high-resolution ticks into seconds.
  6362. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6363. secondsToHighResolutionTicks
  6364. */
  6365. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6366. /** Converts a number seconds into high-resolution ticks.
  6367. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6368. highResolutionTicksToSeconds
  6369. */
  6370. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6371. private:
  6372. int64 millisSinceEpoch;
  6373. };
  6374. #endif // __JUCE_TIME_JUCEHEADER__
  6375. /*** End of inlined file: juce_Time.h ***/
  6376. class FileInputStream;
  6377. class FileOutputStream;
  6378. /**
  6379. Represents a local file or directory.
  6380. This class encapsulates the absolute pathname of a file or directory, and
  6381. has methods for finding out about the file and changing its properties.
  6382. To read or write to the file, there are methods for returning an input or
  6383. output stream.
  6384. @see FileInputStream, FileOutputStream
  6385. */
  6386. class JUCE_API File
  6387. {
  6388. public:
  6389. /** Creates an (invalid) file object.
  6390. The file is initially set to an empty path, so getFullPath() will return
  6391. an empty string, and comparing the file to File::nonexistent will return
  6392. true.
  6393. You can use its operator= method to point it at a proper file.
  6394. */
  6395. File() {}
  6396. /** Creates a file from an absolute path.
  6397. If the path supplied is a relative path, it is taken to be relative
  6398. to the current working directory (see File::getCurrentWorkingDirectory()),
  6399. but this isn't a recommended way of creating a file, because you
  6400. never know what the CWD is going to be.
  6401. On the Mac/Linux, the path can include "~" notation for referring to
  6402. user home directories.
  6403. */
  6404. File (const String& path);
  6405. /** Creates a copy of another file object. */
  6406. File (const File& other);
  6407. /** Destructor. */
  6408. ~File() {}
  6409. /** Sets the file based on an absolute pathname.
  6410. If the path supplied is a relative path, it is taken to be relative
  6411. to the current working directory (see File::getCurrentWorkingDirectory()),
  6412. but this isn't a recommended way of creating a file, because you
  6413. never know what the CWD is going to be.
  6414. On the Mac/Linux, the path can include "~" notation for referring to
  6415. user home directories.
  6416. */
  6417. File& operator= (const String& newFilePath);
  6418. /** Copies from another file object. */
  6419. File& operator= (const File& otherFile);
  6420. /** This static constant is used for referring to an 'invalid' file. */
  6421. static const File nonexistent;
  6422. /** Checks whether the file actually exists.
  6423. @returns true if the file exists, either as a file or a directory.
  6424. @see existsAsFile, isDirectory
  6425. */
  6426. bool exists() const;
  6427. /** Checks whether the file exists and is a file rather than a directory.
  6428. @returns true only if this is a real file, false if it's a directory
  6429. or doesn't exist
  6430. @see exists, isDirectory
  6431. */
  6432. bool existsAsFile() const;
  6433. /** Checks whether the file is a directory that exists.
  6434. @returns true only if the file is a directory which actually exists, so
  6435. false if it's a file or doesn't exist at all
  6436. @see exists, existsAsFile
  6437. */
  6438. bool isDirectory() const;
  6439. /** Returns the size of the file in bytes.
  6440. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6441. */
  6442. int64 getSize() const;
  6443. /** Utility function to convert a file size in bytes to a neat string description.
  6444. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6445. 2000000 would produce "2 MB", etc.
  6446. */
  6447. static const String descriptionOfSizeInBytes (int64 bytes);
  6448. /** Returns the complete, absolute path of this file.
  6449. This includes the filename and all its parent folders. On Windows it'll
  6450. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6451. path starting from the root folder.
  6452. If you just want the file's name, you should use getFileName() or
  6453. getFileNameWithoutExtension().
  6454. @see getFileName, getRelativePathFrom
  6455. */
  6456. const String& getFullPathName() const throw() { return fullPath; }
  6457. /** Returns the last section of the pathname.
  6458. Returns just the final part of the path - e.g. if the whole path
  6459. is "/moose/fish/foo.txt" this will return "foo.txt".
  6460. For a directory, it returns the final part of the path - e.g. for the
  6461. directory "/moose/fish" it'll return "fish".
  6462. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6463. "/moose/.fish", it'll return ".fish"
  6464. @see getFullPathName, getFileNameWithoutExtension
  6465. */
  6466. const String getFileName() const;
  6467. /** Creates a relative path that refers to a file relatively to a given directory.
  6468. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6469. would return "../../foo.txt".
  6470. If it's not possible to navigate from one file to the other, an absolute
  6471. path is returned. If the paths are invalid, an empty string may also be
  6472. returned.
  6473. @param directoryToBeRelativeTo the directory which the resultant string will
  6474. be relative to. If this is actually a file rather than
  6475. a directory, its parent directory will be used instead.
  6476. If it doesn't exist, it's assumed to be a directory.
  6477. @see getChildFile, isAbsolutePath
  6478. */
  6479. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  6480. /** Returns the file's extension.
  6481. Returns the file extension of this file, also including the dot.
  6482. e.g. "/moose/fish/foo.txt" would return ".txt"
  6483. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  6484. */
  6485. const String getFileExtension() const;
  6486. /** Checks whether the file has a given extension.
  6487. @param extensionToTest the extension to look for - it doesn't matter whether or
  6488. not this string has a dot at the start, so ".wav" and "wav"
  6489. will have the same effect. The comparison used is
  6490. case-insensitve. To compare with multiple extensions, this
  6491. parameter can contain multiple strings, separated by semi-colons -
  6492. so, for example: hasFileExtension (".jpeg;png;gif") would return
  6493. true if the file has any of those three extensions.
  6494. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  6495. */
  6496. bool hasFileExtension (const String& extensionToTest) const;
  6497. /** Returns a version of this file with a different file extension.
  6498. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  6499. @param newExtension the new extension, either with or without a dot at the start (this
  6500. doesn't make any difference). To get remove a file's extension altogether,
  6501. pass an empty string into this function.
  6502. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  6503. */
  6504. const File withFileExtension (const String& newExtension) const;
  6505. /** Returns the last part of the filename, without its file extension.
  6506. e.g. for "/moose/fish/foo.txt" this will return "foo".
  6507. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  6508. */
  6509. const String getFileNameWithoutExtension() const;
  6510. /** Returns a 32-bit hash-code that identifies this file.
  6511. This is based on the filename. Obviously it's possible, although unlikely, that
  6512. two files will have the same hash-code.
  6513. */
  6514. int hashCode() const;
  6515. /** Returns a 64-bit hash-code that identifies this file.
  6516. This is based on the filename. Obviously it's possible, although unlikely, that
  6517. two files will have the same hash-code.
  6518. */
  6519. int64 hashCode64() const;
  6520. /** Returns a file based on a relative path.
  6521. This will find a child file or directory of the current object.
  6522. e.g.
  6523. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  6524. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  6525. If the string is actually an absolute path, it will be treated as such, e.g.
  6526. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  6527. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  6528. */
  6529. const File getChildFile (String relativePath) const;
  6530. /** Returns a file which is in the same directory as this one.
  6531. This is equivalent to getParentDirectory().getChildFile (name).
  6532. @see getChildFile, getParentDirectory
  6533. */
  6534. const File getSiblingFile (const String& siblingFileName) const;
  6535. /** Returns the directory that contains this file or directory.
  6536. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  6537. */
  6538. const File getParentDirectory() const;
  6539. /** Checks whether a file is somewhere inside a directory.
  6540. Returns true if this file is somewhere inside a subdirectory of the directory
  6541. that is passed in. Neither file actually has to exist, because the function
  6542. just checks the paths for similarities.
  6543. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  6544. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  6545. */
  6546. bool isAChildOf (const File& potentialParentDirectory) const;
  6547. /** Chooses a filename relative to this one that doesn't already exist.
  6548. If this file is a directory, this will return a child file of this
  6549. directory that doesn't exist, by adding numbers to a prefix and suffix until
  6550. it finds one that isn't already there.
  6551. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  6552. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  6553. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  6554. @param prefix the string to use for the filename before the number
  6555. @param suffix the string to add to the filename after the number
  6556. @param putNumbersInBrackets if true, this will create filenames in the
  6557. format "prefix(number)suffix", if false, it will leave the
  6558. brackets out.
  6559. */
  6560. const File getNonexistentChildFile (const String& prefix,
  6561. const String& suffix,
  6562. bool putNumbersInBrackets = true) const;
  6563. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  6564. If this file doesn't exist, this will just return itself, otherwise it
  6565. will return an appropriate sibling that doesn't exist, e.g. if a file
  6566. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  6567. @param putNumbersInBrackets whether to add brackets around the numbers that
  6568. get appended to the new filename.
  6569. */
  6570. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  6571. /** Compares the pathnames for two files. */
  6572. bool operator== (const File& otherFile) const;
  6573. /** Compares the pathnames for two files. */
  6574. bool operator!= (const File& otherFile) const;
  6575. /** Compares the pathnames for two files. */
  6576. bool operator< (const File& otherFile) const;
  6577. /** Compares the pathnames for two files. */
  6578. bool operator> (const File& otherFile) const;
  6579. /** Checks whether a file can be created or written to.
  6580. @returns true if it's possible to create and write to this file. If the file
  6581. doesn't already exist, this will check its parent directory to
  6582. see if writing is allowed.
  6583. @see setReadOnly
  6584. */
  6585. bool hasWriteAccess() const;
  6586. /** Changes the write-permission of a file or directory.
  6587. @param shouldBeReadOnly whether to add or remove write-permission
  6588. @param applyRecursively if the file is a directory and this is true, it will
  6589. recurse through all the subfolders changing the permissions
  6590. of all files
  6591. @returns true if it manages to change the file's permissions.
  6592. @see hasWriteAccess
  6593. */
  6594. bool setReadOnly (bool shouldBeReadOnly,
  6595. bool applyRecursively = false) const;
  6596. /** Returns true if this file is a hidden or system file.
  6597. The criteria for deciding whether a file is hidden are platform-dependent.
  6598. */
  6599. bool isHidden() const;
  6600. /** If this file is a link, this returns the file that it points to.
  6601. If this file isn't actually link, it'll just return itself.
  6602. */
  6603. const File getLinkedTarget() const;
  6604. /** Returns the last modification time of this file.
  6605. @returns the time, or an invalid time if the file doesn't exist.
  6606. @see setLastModificationTime, getLastAccessTime, getCreationTime
  6607. */
  6608. const Time getLastModificationTime() const;
  6609. /** Returns the last time this file was accessed.
  6610. @returns the time, or an invalid time if the file doesn't exist.
  6611. @see setLastAccessTime, getLastModificationTime, getCreationTime
  6612. */
  6613. const Time getLastAccessTime() const;
  6614. /** Returns the time that this file was created.
  6615. @returns the time, or an invalid time if the file doesn't exist.
  6616. @see getLastModificationTime, getLastAccessTime
  6617. */
  6618. const Time getCreationTime() const;
  6619. /** Changes the modification time for this file.
  6620. @param newTime the time to apply to the file
  6621. @returns true if it manages to change the file's time.
  6622. @see getLastModificationTime, setLastAccessTime, setCreationTime
  6623. */
  6624. bool setLastModificationTime (const Time& newTime) const;
  6625. /** Changes the last-access time for this file.
  6626. @param newTime the time to apply to the file
  6627. @returns true if it manages to change the file's time.
  6628. @see getLastAccessTime, setLastModificationTime, setCreationTime
  6629. */
  6630. bool setLastAccessTime (const Time& newTime) const;
  6631. /** Changes the creation date for this file.
  6632. @param newTime the time to apply to the file
  6633. @returns true if it manages to change the file's time.
  6634. @see getCreationTime, setLastModificationTime, setLastAccessTime
  6635. */
  6636. bool setCreationTime (const Time& newTime) const;
  6637. /** If possible, this will try to create a version string for the given file.
  6638. The OS may be able to look at the file and give a version for it - e.g. with
  6639. executables, bundles, dlls, etc. If no version is available, this will
  6640. return an empty string.
  6641. */
  6642. const String getVersion() const;
  6643. /** Creates an empty file if it doesn't already exist.
  6644. If the file that this object refers to doesn't exist, this will create a file
  6645. of zero size.
  6646. If it already exists or is a directory, this method will do nothing.
  6647. @returns true if the file has been created (or if it already existed).
  6648. @see createDirectory
  6649. */
  6650. bool create() const;
  6651. /** Creates a new directory for this filename.
  6652. This will try to create the file as a directory, and fill also create
  6653. any parent directories it needs in order to complete the operation.
  6654. @returns true if the directory has been created successfully, (or if it
  6655. already existed beforehand).
  6656. @see create
  6657. */
  6658. bool createDirectory() const;
  6659. /** Deletes a file.
  6660. If this file is actually a directory, it may not be deleted correctly if it
  6661. contains files. See deleteRecursively() as a better way of deleting directories.
  6662. @returns true if the file has been successfully deleted (or if it didn't exist to
  6663. begin with).
  6664. @see deleteRecursively
  6665. */
  6666. bool deleteFile() const;
  6667. /** Deletes a file or directory and all its subdirectories.
  6668. If this file is a directory, this will try to delete it and all its subfolders. If
  6669. it's just a file, it will just try to delete the file.
  6670. @returns true if the file and all its subfolders have been successfully deleted
  6671. (or if it didn't exist to begin with).
  6672. @see deleteFile
  6673. */
  6674. bool deleteRecursively() const;
  6675. /** Moves this file or folder to the trash.
  6676. @returns true if the operation succeeded. It could fail if the trash is full, or
  6677. if the file is write-protected, so you should check the return value
  6678. and act appropriately.
  6679. */
  6680. bool moveToTrash() const;
  6681. /** Moves or renames a file.
  6682. Tries to move a file to a different location.
  6683. If the target file already exists, this will attempt to delete it first, and
  6684. will fail if this can't be done.
  6685. Note that the destination file isn't the directory to put it in, it's the actual
  6686. filename that you want the new file to have.
  6687. @returns true if the operation succeeds
  6688. */
  6689. bool moveFileTo (const File& targetLocation) const;
  6690. /** Copies a file.
  6691. Tries to copy a file to a different location.
  6692. If the target file already exists, this will attempt to delete it first, and
  6693. will fail if this can't be done.
  6694. @returns true if the operation succeeds
  6695. */
  6696. bool copyFileTo (const File& targetLocation) const;
  6697. /** Copies a directory.
  6698. Tries to copy an entire directory, recursively.
  6699. If this file isn't a directory or if any target files can't be created, this
  6700. will return false.
  6701. @param newDirectory the directory that this one should be copied to. Note that this
  6702. is the name of the actual directory to create, not the directory
  6703. into which the new one should be placed, so there must be enough
  6704. write privileges to create it if it doesn't exist. Any files inside
  6705. it will be overwritten by similarly named ones that are copied.
  6706. */
  6707. bool copyDirectoryTo (const File& newDirectory) const;
  6708. /** Used in file searching, to specify whether to return files, directories, or both.
  6709. */
  6710. enum TypesOfFileToFind
  6711. {
  6712. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  6713. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  6714. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  6715. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  6716. };
  6717. /** Searches inside a directory for files matching a wildcard pattern.
  6718. Assuming that this file is a directory, this method will search it
  6719. for either files or subdirectories whose names match a filename pattern.
  6720. @param results an array to which File objects will be added for the
  6721. files that the search comes up with
  6722. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6723. return files, directories, or both. If the ignoreHiddenFiles flag
  6724. is also added to this value, hidden files won't be returned
  6725. @param searchRecursively if true, all subdirectories will be recursed into to do
  6726. an exhaustive search
  6727. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6728. @returns the number of results that have been found
  6729. @see getNumberOfChildFiles, DirectoryIterator
  6730. */
  6731. int findChildFiles (Array<File>& results,
  6732. int whatToLookFor,
  6733. bool searchRecursively,
  6734. const String& wildCardPattern = "*") const;
  6735. /** Searches inside a directory and counts how many files match a wildcard pattern.
  6736. Assuming that this file is a directory, this method will search it
  6737. for either files or subdirectories whose names match a filename pattern,
  6738. and will return the number of matches found.
  6739. This isn't a recursive call, and will only search this directory, not
  6740. its children.
  6741. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6742. count files, directories, or both. If the ignoreHiddenFiles flag
  6743. is also added to this value, hidden files won't be counted
  6744. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6745. @returns the number of matches found
  6746. @see findChildFiles, DirectoryIterator
  6747. */
  6748. int getNumberOfChildFiles (int whatToLookFor,
  6749. const String& wildCardPattern = "*") const;
  6750. /** Returns true if this file is a directory that contains one or more subdirectories.
  6751. @see isDirectory, findChildFiles
  6752. */
  6753. bool containsSubDirectories() const;
  6754. /** Creates a stream to read from this file.
  6755. @returns a stream that will read from this file (initially positioned at the
  6756. start of the file), or 0 if the file can't be opened for some reason
  6757. @see createOutputStream, loadFileAsData
  6758. */
  6759. FileInputStream* createInputStream() const;
  6760. /** Creates a stream to write to this file.
  6761. If the file exists, the stream that is returned will be positioned ready for
  6762. writing at the end of the file, so you might want to use deleteFile() first
  6763. to write to an empty file.
  6764. @returns a stream that will write to this file (initially positioned at the
  6765. end of the file), or 0 if the file can't be opened for some reason
  6766. @see createInputStream, appendData, appendText
  6767. */
  6768. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  6769. /** Loads a file's contents into memory as a block of binary data.
  6770. Of course, trying to load a very large file into memory will blow up, so
  6771. it's better to check first.
  6772. @param result the data block to which the file's contents should be appended - note
  6773. that if the memory block might already contain some data, you
  6774. might want to clear it first
  6775. @returns true if the file could all be read into memory
  6776. */
  6777. bool loadFileAsData (MemoryBlock& result) const;
  6778. /** Reads a file into memory as a string.
  6779. Attempts to load the entire file as a zero-terminated string.
  6780. This makes use of InputStream::readEntireStreamAsString, which should
  6781. automatically cope with unicode/acsii file formats.
  6782. */
  6783. const String loadFileAsString() const;
  6784. /** Appends a block of binary data to the end of the file.
  6785. This will try to write the given buffer to the end of the file.
  6786. @returns false if it can't write to the file for some reason
  6787. */
  6788. bool appendData (const void* dataToAppend,
  6789. int numberOfBytes) const;
  6790. /** Replaces this file's contents with a given block of data.
  6791. This will delete the file and replace it with the given data.
  6792. A nice feature of this method is that it's safe - instead of deleting
  6793. the file first and then re-writing it, it creates a new temporary file,
  6794. writes the data to that, and then moves the new file to replace the existing
  6795. file. This means that if the power gets pulled out or something crashes,
  6796. you're a lot less likely to end up with an empty file..
  6797. Returns true if the operation succeeds, or false if it fails.
  6798. @see appendText
  6799. */
  6800. bool replaceWithData (const void* dataToWrite,
  6801. int numberOfBytes) const;
  6802. /** Appends a string to the end of the file.
  6803. This will try to append a text string to the file, as either 16-bit unicode
  6804. or 8-bit characters in the default system encoding.
  6805. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6806. the endianness of the file.
  6807. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6808. @see replaceWithText
  6809. */
  6810. bool appendText (const String& textToAppend,
  6811. bool asUnicode = false,
  6812. bool writeUnicodeHeaderBytes = false) const;
  6813. /** Replaces this file's contents with a given text string.
  6814. This will delete the file and replace it with the given text.
  6815. A nice feature of this method is that it's safe - instead of deleting
  6816. the file first and then re-writing it, it creates a new temporary file,
  6817. writes the text to that, and then moves the new file to replace the existing
  6818. file. This means that if the power gets pulled out or something crashes,
  6819. you're a lot less likely to end up with an empty file..
  6820. For an explanation of the parameters here, see the appendText() method.
  6821. Returns true if the operation succeeds, or false if it fails.
  6822. @see appendText
  6823. */
  6824. bool replaceWithText (const String& textToWrite,
  6825. bool asUnicode = false,
  6826. bool writeUnicodeHeaderBytes = false) const;
  6827. /** Attempts to scan the contents of this file and compare it to another file, returning
  6828. true if this is possible and they match byte-for-byte.
  6829. */
  6830. bool hasIdenticalContentTo (const File& other) const;
  6831. /** Creates a set of files to represent each file root.
  6832. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6833. to which ones are available. On the Mac/Linux, this will probably
  6834. just add a single entry for "/".
  6835. */
  6836. static void findFileSystemRoots (Array<File>& results);
  6837. /** Finds the name of the drive on which this file lives.
  6838. @returns the volume label of the drive, or an empty string if this isn't possible
  6839. */
  6840. const String getVolumeLabel() const;
  6841. /** Returns the serial number of the volume on which this file lives.
  6842. @returns the serial number, or zero if there's a problem doing this
  6843. */
  6844. int getVolumeSerialNumber() const;
  6845. /** Returns the number of bytes free on the drive that this file lives on.
  6846. @returns the number of bytes free, or 0 if there's a problem finding this out
  6847. @see getVolumeTotalSize
  6848. */
  6849. int64 getBytesFreeOnVolume() const;
  6850. /** Returns the total size of the drive that contains this file.
  6851. @returns the total number of bytes that the volume can hold
  6852. @see getBytesFreeOnVolume
  6853. */
  6854. int64 getVolumeTotalSize() const;
  6855. /** Returns true if this file is on a CD or DVD drive. */
  6856. bool isOnCDRomDrive() const;
  6857. /** Returns true if this file is on a hard disk.
  6858. This will fail if it's a network drive, but will still be true for
  6859. removable hard-disks.
  6860. */
  6861. bool isOnHardDisk() const;
  6862. /** Returns true if this file is on a removable disk drive.
  6863. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6864. */
  6865. bool isOnRemovableDrive() const;
  6866. /** Launches the file as a process.
  6867. - if the file is executable, this will run it.
  6868. - if it's a document of some kind, it will launch the document with its
  6869. default viewer application.
  6870. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6871. @see revealToUser
  6872. */
  6873. bool startAsProcess (const String& parameters = String::empty) const;
  6874. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6875. @see startAsProcess
  6876. */
  6877. void revealToUser() const;
  6878. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6879. */
  6880. enum SpecialLocationType
  6881. {
  6882. /** The user's home folder. This is the same as using File ("~"). */
  6883. userHomeDirectory,
  6884. /** The user's default documents folder. On Windows, this might be the user's
  6885. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6886. doesn't tend to have one of these, so it might just return their home folder.
  6887. */
  6888. userDocumentsDirectory,
  6889. /** The folder that contains the user's desktop objects. */
  6890. userDesktopDirectory,
  6891. /** The folder in which applications store their persistent user-specific settings.
  6892. On Windows, this might be "\Documents and Settings\username\Application Data".
  6893. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6894. always create your own sub-folder to put them in, to avoid making a mess.
  6895. */
  6896. userApplicationDataDirectory,
  6897. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6898. of the computer, rather than just the current user.
  6899. On the Mac it'll be "/Library", on Windows, it could be something like
  6900. "\Documents and Settings\All Users\Application Data".
  6901. Depending on the setup, this folder may be read-only.
  6902. */
  6903. commonApplicationDataDirectory,
  6904. /** The folder that should be used for temporary files.
  6905. Always delete them when you're finished, to keep the user's computer tidy!
  6906. */
  6907. tempDirectory,
  6908. /** Returns this application's executable file.
  6909. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6910. host app.
  6911. On the mac this will return the unix binary, not the package folder - see
  6912. currentApplicationFile for that.
  6913. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6914. file link, invokedExecutableFile will return the name of the link.
  6915. */
  6916. currentExecutableFile,
  6917. /** Returns this application's location.
  6918. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6919. host app.
  6920. On the mac this will return the package folder (if it's in one), not the unix binary
  6921. that's inside it - compare with currentExecutableFile.
  6922. */
  6923. currentApplicationFile,
  6924. /** Returns the file that was invoked to launch this executable.
  6925. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6926. will return the name of the link that was used, whereas currentExecutableFile will return
  6927. the actual location of the target executable.
  6928. */
  6929. invokedExecutableFile,
  6930. /** The directory in which applications normally get installed.
  6931. So on windows, this would be something like "c:\program files", on the
  6932. Mac "/Applications", or "/usr" on linux.
  6933. */
  6934. globalApplicationsDirectory,
  6935. /** The most likely place where a user might store their music files.
  6936. */
  6937. userMusicDirectory,
  6938. /** The most likely place where a user might store their movie files.
  6939. */
  6940. userMoviesDirectory,
  6941. };
  6942. /** Finds the location of a special type of file or directory, such as a home folder or
  6943. documents folder.
  6944. @see SpecialLocationType
  6945. */
  6946. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6947. /** Returns a temporary file in the system's temp directory.
  6948. This will try to return the name of a non-existent temp file.
  6949. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6950. */
  6951. static const File createTempFile (const String& fileNameEnding);
  6952. /** Returns the current working directory.
  6953. @see setAsCurrentWorkingDirectory
  6954. */
  6955. static const File getCurrentWorkingDirectory();
  6956. /** Sets the current working directory to be this file.
  6957. For this to work the file must point to a valid directory.
  6958. @returns true if the current directory has been changed.
  6959. @see getCurrentWorkingDirectory
  6960. */
  6961. bool setAsCurrentWorkingDirectory() const;
  6962. /** The system-specific file separator character.
  6963. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6964. */
  6965. static const juce_wchar separator;
  6966. /** The system-specific file separator character, as a string.
  6967. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6968. */
  6969. static const String separatorString;
  6970. /** Removes illegal characters from a filename.
  6971. This will return a copy of the given string after removing characters
  6972. that are not allowed in a legal filename, and possibly shortening the
  6973. string if it's too long.
  6974. Because this will remove slashes, don't use it on an absolute pathname.
  6975. @see createLegalPathName
  6976. */
  6977. static const String createLegalFileName (const String& fileNameToFix);
  6978. /** Removes illegal characters from a pathname.
  6979. Similar to createLegalFileName(), but this won't remove slashes, so can
  6980. be used on a complete pathname.
  6981. @see createLegalFileName
  6982. */
  6983. static const String createLegalPathName (const String& pathNameToFix);
  6984. /** Indicates whether filenames are case-sensitive on the current operating system.
  6985. */
  6986. static bool areFileNamesCaseSensitive();
  6987. /** Returns true if the string seems to be a fully-specified absolute path.
  6988. */
  6989. static bool isAbsolutePath (const String& path);
  6990. /** Creates a file that simply contains this string, without doing the sanity-checking
  6991. that the normal constructors do.
  6992. Best to avoid this unless you really know what you're doing.
  6993. */
  6994. static const File createFileWithoutCheckingPath (const String& path);
  6995. /** Adds a separator character to the end of a path if it doesn't already have one. */
  6996. static const String addTrailingSeparator (const String& path);
  6997. juce_UseDebuggingNewOperator
  6998. private:
  6999. String fullPath;
  7000. // internal way of contructing a file without checking the path
  7001. friend class DirectoryIterator;
  7002. File (const String&, int);
  7003. const String getPathUpToLastSlash() const;
  7004. void createDirectoryInternal (const String& fileName) const;
  7005. bool copyInternal (const File& dest) const;
  7006. bool moveInternal (const File& dest) const;
  7007. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  7008. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  7009. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  7010. static const String parseAbsolutePath (const String& path);
  7011. static bool fileTypeMatches (int whatToLookFor, bool isDir, bool isHidden);
  7012. };
  7013. #endif // __JUCE_FILE_JUCEHEADER__
  7014. /*** End of inlined file: juce_File.h ***/
  7015. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  7016. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7017. will be the name of a pointer to each child element.
  7018. E.g. @code
  7019. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7020. forEachXmlChildElement (*myParentXml, child)
  7021. {
  7022. if (child->hasTagName ("FOO"))
  7023. doSomethingWithXmlElement (child);
  7024. }
  7025. @endcode
  7026. @see forEachXmlChildElementWithTagName
  7027. */
  7028. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  7029. \
  7030. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  7031. childElementVariableName != 0; \
  7032. childElementVariableName = childElementVariableName->getNextElement())
  7033. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  7034. which have a specified tag.
  7035. This does the same job as the forEachXmlChildElement macro, but only for those
  7036. elements that have a particular tag name.
  7037. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7038. will be the name of a pointer to each child element. The requiredTagName is the
  7039. tag name to match.
  7040. E.g. @code
  7041. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7042. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  7043. {
  7044. // the child object is now guaranteed to be a <MYTAG> element..
  7045. doSomethingWithMYTAGElement (child);
  7046. }
  7047. @endcode
  7048. @see forEachXmlChildElement
  7049. */
  7050. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7051. \
  7052. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7053. childElementVariableName != 0; \
  7054. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7055. /** Used to build a tree of elements representing an XML document.
  7056. An XML document can be parsed into a tree of XmlElements, each of which
  7057. represents an XML tag structure, and which may itself contain other
  7058. nested elements.
  7059. An XmlElement can also be converted back into a text document, and has
  7060. lots of useful methods for manipulating its attributes and sub-elements,
  7061. so XmlElements can actually be used as a handy general-purpose data
  7062. structure.
  7063. Here's an example of parsing some elements: @code
  7064. // check we're looking at the right kind of document..
  7065. if (myElement->hasTagName ("ANIMALS"))
  7066. {
  7067. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7068. forEachXmlChildElement (*myElement, e)
  7069. {
  7070. if (e->hasTagName ("GIRAFFE"))
  7071. {
  7072. // found a giraffe, so use some of its attributes..
  7073. String giraffeName = e->getStringAttribute ("name");
  7074. int giraffeAge = e->getIntAttribute ("age");
  7075. bool isFriendly = e->getBoolAttribute ("friendly");
  7076. }
  7077. }
  7078. }
  7079. @endcode
  7080. And here's an example of how to create an XML document from scratch: @code
  7081. // create an outer node called "ANIMALS"
  7082. XmlElement animalsList ("ANIMALS");
  7083. for (int i = 0; i < numAnimals; ++i)
  7084. {
  7085. // create an inner element..
  7086. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7087. giraffe->setAttribute ("name", "nigel");
  7088. giraffe->setAttribute ("age", 10);
  7089. giraffe->setAttribute ("friendly", true);
  7090. // ..and add our new element to the parent node
  7091. animalsList.addChildElement (giraffe);
  7092. }
  7093. // now we can turn the whole thing into a text document..
  7094. String myXmlDoc = animalsList.createDocument (String::empty);
  7095. @endcode
  7096. @see XmlDocument
  7097. */
  7098. class JUCE_API XmlElement
  7099. {
  7100. public:
  7101. /** Creates an XmlElement with this tag name. */
  7102. explicit XmlElement (const String& tagName) throw();
  7103. /** Creates a (deep) copy of another element. */
  7104. XmlElement (const XmlElement& other);
  7105. /** Creates a (deep) copy of another element. */
  7106. XmlElement& operator= (const XmlElement& other);
  7107. /** Deleting an XmlElement will also delete all its child elements. */
  7108. ~XmlElement() throw();
  7109. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7110. The elements are only considered equivalent if they contain the same attiributes
  7111. with the same values, and have the same sub-nodes.
  7112. @param other the other element to compare to
  7113. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7114. same attributes in a different order will be
  7115. considered the same; if false, the attributes must
  7116. be in the same order as well
  7117. */
  7118. bool isEquivalentTo (const XmlElement* other,
  7119. bool ignoreOrderOfAttributes) const throw();
  7120. /** Returns an XML text document that represents this element.
  7121. The string returned can be parsed to recreate the same XmlElement that
  7122. was used to create it.
  7123. @param dtdToUse the DTD to add to the document
  7124. @param allOnOneLine if true, this means that the document will not contain any
  7125. linefeeds, so it'll be smaller but not very easy to read.
  7126. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7127. document
  7128. @param encodingType the character encoding format string to put into the xml
  7129. header
  7130. @param lineWrapLength the line length that will be used before items get placed on
  7131. a new line. This isn't an absolute maximum length, it just
  7132. determines how lists of attributes get broken up
  7133. @see writeToStream, writeToFile
  7134. */
  7135. const String createDocument (const String& dtdToUse,
  7136. bool allOnOneLine = false,
  7137. bool includeXmlHeader = true,
  7138. const String& encodingType = "UTF-8",
  7139. int lineWrapLength = 60) const;
  7140. /** Writes the document to a stream as UTF-8.
  7141. @param output the stream to write to
  7142. @param dtdToUse the DTD to add to the document
  7143. @param allOnOneLine if true, this means that the document will not contain any
  7144. linefeeds, so it'll be smaller but not very easy to read.
  7145. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7146. document
  7147. @param encodingType the character encoding format string to put into the xml
  7148. header
  7149. @param lineWrapLength the line length that will be used before items get placed on
  7150. a new line. This isn't an absolute maximum length, it just
  7151. determines how lists of attributes get broken up
  7152. @see writeToFile, createDocument
  7153. */
  7154. void writeToStream (OutputStream& output,
  7155. const String& dtdToUse,
  7156. bool allOnOneLine = false,
  7157. bool includeXmlHeader = true,
  7158. const String& encodingType = "UTF-8",
  7159. int lineWrapLength = 60) const;
  7160. /** Writes the element to a file as an XML document.
  7161. To improve safety in case something goes wrong while writing the file, this
  7162. will actually write the document to a new temporary file in the same
  7163. directory as the destination file, and if this succeeds, it will rename this
  7164. new file as the destination file (overwriting any existing file that was there).
  7165. @param destinationFile the file to write to. If this already exists, it will be
  7166. overwritten.
  7167. @param dtdToUse the DTD to add to the document
  7168. @param encodingType the character encoding format string to put into the xml
  7169. header
  7170. @param lineWrapLength the line length that will be used before items get placed on
  7171. a new line. This isn't an absolute maximum length, it just
  7172. determines how lists of attributes get broken up
  7173. @returns true if the file is written successfully; false if something goes wrong
  7174. in the process
  7175. @see createDocument
  7176. */
  7177. bool writeToFile (const File& destinationFile,
  7178. const String& dtdToUse,
  7179. const String& encodingType = "UTF-8",
  7180. int lineWrapLength = 60) const;
  7181. /** Returns this element's tag type name.
  7182. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7183. "MOOSE".
  7184. @see hasTagName
  7185. */
  7186. inline const String& getTagName() const throw() { return tagName; }
  7187. /** Tests whether this element has a particular tag name.
  7188. @param possibleTagName the tag name you're comparing it with
  7189. @see getTagName
  7190. */
  7191. bool hasTagName (const String& possibleTagName) const throw();
  7192. /** Returns the number of XML attributes this element contains.
  7193. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7194. return 2.
  7195. */
  7196. int getNumAttributes() const throw();
  7197. /** Returns the name of one of the elements attributes.
  7198. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7199. getAttributeName(1) would return "antlers".
  7200. @see getAttributeValue, getStringAttribute
  7201. */
  7202. const String& getAttributeName (int attributeIndex) const throw();
  7203. /** Returns the value of one of the elements attributes.
  7204. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7205. getAttributeName(1) would return "2".
  7206. @see getAttributeName, getStringAttribute
  7207. */
  7208. const String& getAttributeValue (int attributeIndex) const throw();
  7209. // Attribute-handling methods..
  7210. /** Checks whether the element contains an attribute with a certain name. */
  7211. bool hasAttribute (const String& attributeName) const throw();
  7212. /** Returns the value of a named attribute.
  7213. @param attributeName the name of the attribute to look up
  7214. */
  7215. const String& getStringAttribute (const String& attributeName) const throw();
  7216. /** Returns the value of a named attribute.
  7217. @param attributeName the name of the attribute to look up
  7218. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7219. with this name
  7220. */
  7221. const String getStringAttribute (const String& attributeName,
  7222. const String& defaultReturnValue) const;
  7223. /** Compares the value of a named attribute with a value passed-in.
  7224. @param attributeName the name of the attribute to look up
  7225. @param stringToCompareAgainst the value to compare it with
  7226. @param ignoreCase whether the comparison should be case-insensitive
  7227. @returns true if the value of the attribute is the same as the string passed-in;
  7228. false if it's different (or if no such attribute exists)
  7229. */
  7230. bool compareAttribute (const String& attributeName,
  7231. const String& stringToCompareAgainst,
  7232. bool ignoreCase = false) const throw();
  7233. /** Returns the value of a named attribute as an integer.
  7234. This will try to find the attribute and convert it to an integer (using
  7235. the String::getIntValue() method).
  7236. @param attributeName the name of the attribute to look up
  7237. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7238. with this name
  7239. @see setAttribute
  7240. */
  7241. int getIntAttribute (const String& attributeName,
  7242. int defaultReturnValue = 0) const;
  7243. /** Returns the value of a named attribute as floating-point.
  7244. This will try to find the attribute and convert it to an integer (using
  7245. the String::getDoubleValue() method).
  7246. @param attributeName the name of the attribute to look up
  7247. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7248. with this name
  7249. @see setAttribute
  7250. */
  7251. double getDoubleAttribute (const String& attributeName,
  7252. double defaultReturnValue = 0.0) const;
  7253. /** Returns the value of a named attribute as a boolean.
  7254. This will try to find the attribute and interpret it as a boolean. To do this,
  7255. it'll return true if the value is "1", "true", "y", etc, or false for other
  7256. values.
  7257. @param attributeName the name of the attribute to look up
  7258. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7259. with this name
  7260. */
  7261. bool getBoolAttribute (const String& attributeName,
  7262. bool defaultReturnValue = false) const;
  7263. /** Adds a named attribute to the element.
  7264. If the element already contains an attribute with this name, it's value will
  7265. be updated to the new value. If there's no such attribute yet, a new one will
  7266. be added.
  7267. Note that there are other setAttribute() methods that take integers,
  7268. doubles, etc. to make it easy to store numbers.
  7269. @param attributeName the name of the attribute to set
  7270. @param newValue the value to set it to
  7271. @see removeAttribute
  7272. */
  7273. void setAttribute (const String& attributeName,
  7274. const String& newValue);
  7275. /** Adds a named attribute to the element, setting it to an integer value.
  7276. If the element already contains an attribute with this name, it's value will
  7277. be updated to the new value. If there's no such attribute yet, a new one will
  7278. be added.
  7279. Note that there are other setAttribute() methods that take integers,
  7280. doubles, etc. to make it easy to store numbers.
  7281. @param attributeName the name of the attribute to set
  7282. @param newValue the value to set it to
  7283. */
  7284. void setAttribute (const String& attributeName,
  7285. int newValue);
  7286. /** Adds a named attribute to the element, setting it to a floating-point value.
  7287. If the element already contains an attribute with this name, it's value will
  7288. be updated to the new value. If there's no such attribute yet, a new one will
  7289. be added.
  7290. Note that there are other setAttribute() methods that take integers,
  7291. doubles, etc. to make it easy to store numbers.
  7292. @param attributeName the name of the attribute to set
  7293. @param newValue the value to set it to
  7294. */
  7295. void setAttribute (const String& attributeName,
  7296. double newValue);
  7297. /** Removes a named attribute from the element.
  7298. @param attributeName the name of the attribute to remove
  7299. @see removeAllAttributes
  7300. */
  7301. void removeAttribute (const String& attributeName) throw();
  7302. /** Removes all attributes from this element.
  7303. */
  7304. void removeAllAttributes() throw();
  7305. // Child element methods..
  7306. /** Returns the first of this element's sub-elements.
  7307. see getNextElement() for an example of how to iterate the sub-elements.
  7308. @see forEachXmlChildElement
  7309. */
  7310. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7311. /** Returns the next of this element's siblings.
  7312. This can be used for iterating an element's sub-elements, e.g.
  7313. @code
  7314. XmlElement* child = myXmlDocument->getFirstChildElement();
  7315. while (child != 0)
  7316. {
  7317. ...do stuff with this child..
  7318. child = child->getNextElement();
  7319. }
  7320. @endcode
  7321. Note that when iterating the child elements, some of them might be
  7322. text elements as well as XML tags - use isTextElement() to work this
  7323. out.
  7324. Also, it's much easier and neater to use this method indirectly via the
  7325. forEachXmlChildElement macro.
  7326. @returns the sibling element that follows this one, or zero if this is the last
  7327. element in its parent
  7328. @see getNextElement, isTextElement, forEachXmlChildElement
  7329. */
  7330. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7331. /** Returns the next of this element's siblings which has the specified tag
  7332. name.
  7333. This is like getNextElement(), but will scan through the list until it
  7334. finds an element with the given tag name.
  7335. @see getNextElement, forEachXmlChildElementWithTagName
  7336. */
  7337. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7338. /** Returns the number of sub-elements in this element.
  7339. @see getChildElement
  7340. */
  7341. int getNumChildElements() const throw();
  7342. /** Returns the sub-element at a certain index.
  7343. It's not very efficient to iterate the sub-elements by index - see
  7344. getNextElement() for an example of how best to iterate.
  7345. @returns the n'th child of this element, or 0 if the index is out-of-range
  7346. @see getNextElement, isTextElement, getChildByName
  7347. */
  7348. XmlElement* getChildElement (int index) const throw();
  7349. /** Returns the first sub-element with a given tag-name.
  7350. @param tagNameToLookFor the tag name of the element you want to find
  7351. @returns the first element with this tag name, or 0 if none is found
  7352. @see getNextElement, isTextElement, getChildElement
  7353. */
  7354. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7355. /** Appends an element to this element's list of children.
  7356. Child elements are deleted automatically when their parent is deleted, so
  7357. make sure the object that you pass in will not be deleted by anything else,
  7358. and make sure it's not already the child of another element.
  7359. @see getFirstChildElement, getNextElement, getNumChildElements,
  7360. getChildElement, removeChildElement
  7361. */
  7362. void addChildElement (XmlElement* const newChildElement) throw();
  7363. /** Inserts an element into this element's list of children.
  7364. Child elements are deleted automatically when their parent is deleted, so
  7365. make sure the object that you pass in will not be deleted by anything else,
  7366. and make sure it's not already the child of another element.
  7367. @param newChildNode the element to add
  7368. @param indexToInsertAt the index at which to insert the new element - if this is
  7369. below zero, it will be added to the end of the list
  7370. @see addChildElement, insertChildElement
  7371. */
  7372. void insertChildElement (XmlElement* newChildNode,
  7373. int indexToInsertAt) throw();
  7374. /** Creates a new element with the given name and returns it, after adding it
  7375. as a child element.
  7376. This is a handy method that means that instead of writing this:
  7377. @code
  7378. XmlElement* newElement = new XmlElement ("foobar");
  7379. myParentElement->addChildElement (newElement);
  7380. @endcode
  7381. ..you could just write this:
  7382. @code
  7383. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7384. @endcode
  7385. */
  7386. XmlElement* createNewChildElement (const String& tagName);
  7387. /** Replaces one of this element's children with another node.
  7388. If the current element passed-in isn't actually a child of this element,
  7389. this will return false and the new one won't be added. Otherwise, the
  7390. existing element will be deleted, replaced with the new one, and it
  7391. will return true.
  7392. */
  7393. bool replaceChildElement (XmlElement* currentChildElement,
  7394. XmlElement* newChildNode) throw();
  7395. /** Removes a child element.
  7396. @param childToRemove the child to look for and remove
  7397. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7398. just remove it
  7399. */
  7400. void removeChildElement (XmlElement* childToRemove,
  7401. bool shouldDeleteTheChild) throw();
  7402. /** Deletes all the child elements in the element.
  7403. @see removeChildElement, deleteAllChildElementsWithTagName
  7404. */
  7405. void deleteAllChildElements() throw();
  7406. /** Deletes all the child elements with a given tag name.
  7407. @see removeChildElement
  7408. */
  7409. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7410. /** Returns true if the given element is a child of this one. */
  7411. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7412. /** Recursively searches all sub-elements to find one that contains the specified
  7413. child element.
  7414. */
  7415. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7416. /** Sorts the child elements using a comparator.
  7417. This will use a comparator object to sort the elements into order. The object
  7418. passed must have a method of the form:
  7419. @code
  7420. int compareElements (const XmlElement* first, const XmlElement* second);
  7421. @endcode
  7422. ..and this method must return:
  7423. - a value of < 0 if the first comes before the second
  7424. - a value of 0 if the two objects are equivalent
  7425. - a value of > 0 if the second comes before the first
  7426. To improve performance, the compareElements() method can be declared as static or const.
  7427. @param comparator the comparator to use for comparing elements.
  7428. @param retainOrderOfEquivalentItems if this is true, then items
  7429. which the comparator says are equivalent will be
  7430. kept in the order in which they currently appear
  7431. in the array. This is slower to perform, but may
  7432. be important in some cases. If it's false, a faster
  7433. algorithm is used, but equivalent elements may be
  7434. rearranged.
  7435. */
  7436. template <class ElementComparator>
  7437. void sortChildElements (ElementComparator& comparator,
  7438. bool retainOrderOfEquivalentItems = false)
  7439. {
  7440. const int num = getNumChildElements();
  7441. if (num > 1)
  7442. {
  7443. HeapBlock <XmlElement*> elems (num);
  7444. getChildElementsAsArray (elems);
  7445. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7446. reorderChildElements (elems, num);
  7447. }
  7448. }
  7449. /** Returns true if this element is a section of text.
  7450. Elements can either be an XML tag element or a secton of text, so this
  7451. is used to find out what kind of element this one is.
  7452. @see getAllText, addTextElement, deleteAllTextElements
  7453. */
  7454. bool isTextElement() const throw();
  7455. /** Returns the text for a text element.
  7456. Note that if you have an element like this:
  7457. @code<xyz>hello</xyz>@endcode
  7458. then calling getText on the "xyz" element won't return "hello", because that is
  7459. actually stored in a special text sub-element inside the xyz element. To get the
  7460. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7461. use getAllSubText() to do this automatically.
  7462. @see isTextElement, getAllSubText, getChildElementAllSubText
  7463. */
  7464. const String& getText() const throw();
  7465. /** Sets the text in a text element.
  7466. Note that this is only a valid call if this element is a text element. If it's
  7467. not, then no action will be performed.
  7468. */
  7469. void setText (const String& newText);
  7470. /** Returns all the text from this element's child nodes.
  7471. This iterates all the child elements and when it finds text elements,
  7472. it concatenates their text into a big string which it returns.
  7473. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7474. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7475. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7476. */
  7477. const String getAllSubText() const;
  7478. /** Returns all the sub-text of a named child element.
  7479. If there is a child element with the given tag name, this will return
  7480. all of its sub-text (by calling getAllSubText() on it). If there is
  7481. no such child element, this will return the default string passed-in.
  7482. @see getAllSubText
  7483. */
  7484. const String getChildElementAllSubText (const String& childTagName,
  7485. const String& defaultReturnValue) const;
  7486. /** Appends a section of text to this element.
  7487. @see isTextElement, getText, getAllSubText
  7488. */
  7489. void addTextElement (const String& text);
  7490. /** Removes all the text elements from this element.
  7491. @see isTextElement, getText, getAllSubText, addTextElement
  7492. */
  7493. void deleteAllTextElements() throw();
  7494. /** Creates a text element that can be added to a parent element.
  7495. */
  7496. static XmlElement* createTextElement (const String& text);
  7497. juce_UseDebuggingNewOperator
  7498. private:
  7499. friend class XmlDocument;
  7500. String tagName;
  7501. XmlElement* firstChildElement;
  7502. XmlElement* nextElement;
  7503. struct XmlAttributeNode
  7504. {
  7505. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7506. XmlAttributeNode (const String& name, const String& value) throw();
  7507. String name, value;
  7508. XmlAttributeNode* next;
  7509. private:
  7510. XmlAttributeNode& operator= (const XmlAttributeNode&);
  7511. };
  7512. XmlAttributeNode* attributes;
  7513. XmlElement (int) throw();
  7514. void copyChildrenAndAttributesFrom (const XmlElement& other);
  7515. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  7516. void getChildElementsAsArray (XmlElement**) const throw();
  7517. void reorderChildElements (XmlElement** const, const int) throw();
  7518. };
  7519. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7520. /*** End of inlined file: juce_XmlElement.h ***/
  7521. /**
  7522. A set of named property values, which can be strings, integers, floating point, etc.
  7523. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7524. to load and save types other than strings.
  7525. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7526. messages and saves/loads the list from a file.
  7527. */
  7528. class JUCE_API PropertySet
  7529. {
  7530. public:
  7531. /** Creates an empty PropertySet.
  7532. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7533. case-insensitive way
  7534. */
  7535. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7536. /** Creates a copy of another PropertySet.
  7537. */
  7538. PropertySet (const PropertySet& other) throw();
  7539. /** Copies another PropertySet over this one.
  7540. */
  7541. PropertySet& operator= (const PropertySet& other) throw();
  7542. /** Destructor. */
  7543. virtual ~PropertySet();
  7544. /** Returns one of the properties as a string.
  7545. If the value isn't found in this set, then this will look for it in a fallback
  7546. property set (if you've specified one with the setFallbackPropertySet() method),
  7547. and if it can't find one there, it'll return the default value passed-in.
  7548. @param keyName the name of the property to retrieve
  7549. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7550. */
  7551. const String getValue (const String& keyName,
  7552. const String& defaultReturnValue = String::empty) const throw();
  7553. /** Returns one of the properties as an integer.
  7554. If the value isn't found in this set, then this will look for it in a fallback
  7555. property set (if you've specified one with the setFallbackPropertySet() method),
  7556. and if it can't find one there, it'll return the default value passed-in.
  7557. @param keyName the name of the property to retrieve
  7558. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7559. */
  7560. int getIntValue (const String& keyName,
  7561. const int defaultReturnValue = 0) const throw();
  7562. /** Returns one of the properties as an double.
  7563. If the value isn't found in this set, then this will look for it in a fallback
  7564. property set (if you've specified one with the setFallbackPropertySet() method),
  7565. and if it can't find one there, it'll return the default value passed-in.
  7566. @param keyName the name of the property to retrieve
  7567. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7568. */
  7569. double getDoubleValue (const String& keyName,
  7570. const double defaultReturnValue = 0.0) const throw();
  7571. /** Returns one of the properties as an boolean.
  7572. The result will be true if the string found for this key name can be parsed as a non-zero
  7573. integer.
  7574. If the value isn't found in this set, then this will look for it in a fallback
  7575. property set (if you've specified one with the setFallbackPropertySet() method),
  7576. and if it can't find one there, it'll return the default value passed-in.
  7577. @param keyName the name of the property to retrieve
  7578. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7579. */
  7580. bool getBoolValue (const String& keyName,
  7581. const bool defaultReturnValue = false) const throw();
  7582. /** Returns one of the properties as an XML element.
  7583. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7584. key isn't found, or if the entry contains an string that isn't valid XML.
  7585. If the value isn't found in this set, then this will look for it in a fallback
  7586. property set (if you've specified one with the setFallbackPropertySet() method),
  7587. and if it can't find one there, it'll return the default value passed-in.
  7588. @param keyName the name of the property to retrieve
  7589. */
  7590. XmlElement* getXmlValue (const String& keyName) const;
  7591. /** Sets a named property as a string.
  7592. @param keyName the name of the property to set. (This mustn't be an empty string)
  7593. @param value the new value to set it to
  7594. */
  7595. void setValue (const String& keyName, const String& value) throw();
  7596. /** Sets a named property to an integer.
  7597. @param keyName the name of the property to set. (This mustn't be an empty string)
  7598. @param value the new value to set it to
  7599. */
  7600. void setValue (const String& keyName, const int value) throw();
  7601. /** Sets a named property to a double.
  7602. @param keyName the name of the property to set. (This mustn't be an empty string)
  7603. @param value the new value to set it to
  7604. */
  7605. void setValue (const String& keyName, const double value) throw();
  7606. /** Sets a named property to a boolean.
  7607. @param keyName the name of the property to set. (This mustn't be an empty string)
  7608. @param value the new value to set it to
  7609. */
  7610. void setValue (const String& keyName, const bool value) throw();
  7611. /** Sets a named property to an XML element.
  7612. @param keyName the name of the property to set. (This mustn't be an empty string)
  7613. @param xml the new element to set it to. If this is zero, the value will be set to
  7614. an empty string
  7615. @see getXmlValue
  7616. */
  7617. void setValue (const String& keyName, const XmlElement* const xml);
  7618. /** Deletes a property.
  7619. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7620. */
  7621. void removeValue (const String& keyName) throw();
  7622. /** Returns true if the properies include the given key. */
  7623. bool containsKey (const String& keyName) const throw();
  7624. /** Removes all values. */
  7625. void clear();
  7626. /** Returns the keys/value pair array containing all the properties. */
  7627. StringPairArray& getAllProperties() throw() { return properties; }
  7628. /** Returns the lock used when reading or writing to this set */
  7629. const CriticalSection& getLock() const throw() { return lock; }
  7630. /** Returns an XML element which encapsulates all the items in this property set.
  7631. The string parameter is the tag name that should be used for the node.
  7632. @see restoreFromXml
  7633. */
  7634. XmlElement* createXml (const String& nodeName) const throw();
  7635. /** Reloads a set of properties that were previously stored as XML.
  7636. The node passed in must have been created by the createXml() method.
  7637. @see createXml
  7638. */
  7639. void restoreFromXml (const XmlElement& xml) throw();
  7640. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7641. set in this one.
  7642. If you set this up to be a pointer to a second property set, then whenever one
  7643. of the getValue() methods fails to find an entry in this set, it will look up that
  7644. value in the fallback set, and if it finds it, it will return that.
  7645. Make sure that you don't delete the fallback set while it's still being used by
  7646. another set! To remove the fallback set, just call this method with a null pointer.
  7647. @see getFallbackPropertySet
  7648. */
  7649. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7650. /** Returns the fallback property set.
  7651. @see setFallbackPropertySet
  7652. */
  7653. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7654. juce_UseDebuggingNewOperator
  7655. protected:
  7656. /** Subclasses can override this to be told when one of the properies has been changed.
  7657. */
  7658. virtual void propertyChanged();
  7659. private:
  7660. StringPairArray properties;
  7661. PropertySet* fallbackProperties;
  7662. CriticalSection lock;
  7663. bool ignoreCaseOfKeys;
  7664. };
  7665. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7666. /*** End of inlined file: juce_PropertySet.h ***/
  7667. #endif
  7668. #ifndef __JUCE_RANGE_JUCEHEADER__
  7669. /*** Start of inlined file: juce_Range.h ***/
  7670. #ifndef __JUCE_RANGE_JUCEHEADER__
  7671. #define __JUCE_RANGE_JUCEHEADER__
  7672. /** A general-purpose range object, that simply represents any linear range with
  7673. a start and end point.
  7674. The templated parameter is expected to be a primitive integer or floating point
  7675. type, though class types could also be used if they behave in a number-like way.
  7676. */
  7677. template <typename ValueType>
  7678. class Range
  7679. {
  7680. public:
  7681. /** Constructs an empty range. */
  7682. Range() throw()
  7683. : start (ValueType()), end (ValueType())
  7684. {
  7685. }
  7686. /** Constructs a range with given start and end values. */
  7687. Range (const ValueType start_, const ValueType end_) throw()
  7688. : start (start_), end (jmax (start_, end_))
  7689. {
  7690. }
  7691. /** Constructs a copy of another range. */
  7692. Range (const Range& other) throw()
  7693. : start (other.start), end (other.end)
  7694. {
  7695. }
  7696. /** Copies another range object. */
  7697. Range& operator= (const Range& other) throw()
  7698. {
  7699. start = other.start;
  7700. end = other.end;
  7701. return *this;
  7702. }
  7703. /** Destructor. */
  7704. ~Range() throw()
  7705. {
  7706. }
  7707. /** Returns the range that lies between two positions (in either order). */
  7708. static const Range between (const ValueType position1, const ValueType position2) throw()
  7709. {
  7710. return (position1 < position2) ? Range (position1, position2)
  7711. : Range (position2, position1);
  7712. }
  7713. /** Returns a range with the specified start position and a length of zero. */
  7714. static const Range emptyRange (const ValueType start) throw()
  7715. {
  7716. return Range (start, start);
  7717. }
  7718. /** Returns the start of the range. */
  7719. inline ValueType getStart() const throw() { return start; }
  7720. /** Returns the length of the range. */
  7721. inline ValueType getLength() const throw() { return end - start; }
  7722. /** Returns the end of the range. */
  7723. inline ValueType getEnd() const throw() { return end; }
  7724. /** Returns true if the range has a length of zero. */
  7725. inline bool isEmpty() const throw() { return start == end; }
  7726. /** Changes the start position of the range, leaving the end position unchanged.
  7727. If the new start position is higher than the current end of the range, the end point
  7728. will be pushed along to equal it, leaving an empty range at the new position.
  7729. */
  7730. void setStart (const ValueType newStart) throw()
  7731. {
  7732. start = newStart;
  7733. if (end < newStart)
  7734. end = newStart;
  7735. }
  7736. /** Returns a range with the same end as this one, but a different start.
  7737. If the new start position is higher than the current end of the range, the end point
  7738. will be pushed along to equal it, returning an empty range at the new position.
  7739. */
  7740. const Range withStart (const ValueType newStart) const throw()
  7741. {
  7742. return Range (newStart, jmax (newStart, end));
  7743. }
  7744. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7745. const Range movedToStartAt (const ValueType newStart) const throw()
  7746. {
  7747. return Range (newStart, newStart + getLength());
  7748. }
  7749. /** Changes the end position of the range, leaving the start unchanged.
  7750. If the new end position is below the current start of the range, the start point
  7751. will be pushed back to equal the new end point.
  7752. */
  7753. void setEnd (const ValueType newEnd) throw()
  7754. {
  7755. end = newEnd;
  7756. if (newEnd < start)
  7757. start = newEnd;
  7758. }
  7759. /** Returns a range with the same start position as this one, but a different end.
  7760. If the new end position is below the current start of the range, the start point
  7761. will be pushed back to equal the new end point.
  7762. */
  7763. const Range withEnd (const ValueType newEnd) const throw()
  7764. {
  7765. return Range (jmin (start, newEnd), newEnd);
  7766. }
  7767. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7768. const Range movedToEndAt (const ValueType newEnd) const throw()
  7769. {
  7770. return Range (newEnd - getLength(), newEnd);
  7771. }
  7772. /** Changes the length of the range.
  7773. Lengths less than zero are treated as zero.
  7774. */
  7775. void setLength (const ValueType newLength) throw()
  7776. {
  7777. end = start + jmax (ValueType(), newLength);
  7778. }
  7779. /** Returns a range with the same start as this one, but a different length.
  7780. Lengths less than zero are treated as zero.
  7781. */
  7782. const Range withLength (const ValueType newLength) const throw()
  7783. {
  7784. return Range (start, start + newLength);
  7785. }
  7786. /** Adds an amount to the start and end of the range. */
  7787. inline const Range& operator+= (const ValueType amountToAdd) throw()
  7788. {
  7789. start += amountToAdd;
  7790. end += amountToAdd;
  7791. return *this;
  7792. }
  7793. /** Subtracts an amount from the start and end of the range. */
  7794. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  7795. {
  7796. start -= amountToSubtract;
  7797. end -= amountToSubtract;
  7798. return *this;
  7799. }
  7800. /** Returns a range that is equal to this one with an amount added to its
  7801. start and end.
  7802. */
  7803. const Range operator+ (const ValueType amountToAdd) const throw()
  7804. {
  7805. return Range (start + amountToAdd, end + amountToAdd);
  7806. }
  7807. /** Returns a range that is equal to this one with the specified amount
  7808. subtracted from its start and end. */
  7809. const Range operator- (const ValueType amountToSubtract) const throw()
  7810. {
  7811. return Range (start - amountToSubtract, end - amountToSubtract);
  7812. }
  7813. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  7814. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  7815. /** Returns true if the given position lies inside this range. */
  7816. bool contains (const ValueType position) const throw()
  7817. {
  7818. return start <= position && position < end;
  7819. }
  7820. /** Returns the nearest value to the one supplied, which lies within the range. */
  7821. ValueType clipValue (const ValueType value) const throw()
  7822. {
  7823. return jlimit (start, end, value);
  7824. }
  7825. /** Returns true if the given range lies entirely inside this range. */
  7826. bool contains (const Range& other) const throw()
  7827. {
  7828. return start <= other.start && end >= other.end;
  7829. }
  7830. /** Returns true if the given range intersects this one. */
  7831. bool intersects (const Range& other) const throw()
  7832. {
  7833. return other.start < end && start < other.end;
  7834. }
  7835. /** Returns the range that is the intersection of the two ranges, or an empty range
  7836. with an undefined start position if they don't overlap. */
  7837. const Range getIntersectionWith (const Range& other) const throw()
  7838. {
  7839. return Range (jmax (start, other.start),
  7840. jmin (end, other.end));
  7841. }
  7842. /** Returns the smallest range that contains both this one and the other one. */
  7843. const Range getUnionWith (const Range& other) const throw()
  7844. {
  7845. return Range (jmin (start, other.start),
  7846. jmax (end, other.end));
  7847. }
  7848. /** Returns a given range, after moving it forwards or backwards to fit it
  7849. within this range.
  7850. If the supplied range has a greater length than this one, the return value
  7851. will be this range.
  7852. Otherwise, if the supplied range is smaller than this one, the return value
  7853. will be the new range, shifted forwards or backwards so that it doesn't extend
  7854. beyond this one, but keeping its original length.
  7855. */
  7856. const Range constrainRange (const Range& rangeToConstrain) const throw()
  7857. {
  7858. const ValueType otherLen = rangeToConstrain.getLength();
  7859. return getLength() <= otherLen
  7860. ? *this
  7861. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  7862. }
  7863. juce_UseDebuggingNewOperator
  7864. private:
  7865. ValueType start, end;
  7866. };
  7867. #endif // __JUCE_RANGE_JUCEHEADER__
  7868. /*** End of inlined file: juce_Range.h ***/
  7869. #endif
  7870. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7871. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  7872. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7873. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7874. /**
  7875. Holds a list of objects derived from ReferenceCountedObject.
  7876. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7877. and takes care of incrementing and decrementing their ref counts when they
  7878. are added and removed from the array.
  7879. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7880. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7881. @see Array, OwnedArray, StringArray
  7882. */
  7883. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7884. class ReferenceCountedArray
  7885. {
  7886. public:
  7887. /** Creates an empty array.
  7888. @see ReferenceCountedObject, Array, OwnedArray
  7889. */
  7890. ReferenceCountedArray() throw()
  7891. : numUsed (0)
  7892. {
  7893. }
  7894. /** Creates a copy of another array */
  7895. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7896. {
  7897. const ScopedLockType lock (other.getLock());
  7898. numUsed = other.numUsed;
  7899. data.setAllocatedSize (numUsed);
  7900. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7901. for (int i = numUsed; --i >= 0;)
  7902. if (data.elements[i] != 0)
  7903. data.elements[i]->incReferenceCount();
  7904. }
  7905. /** Copies another array into this one.
  7906. Any existing objects in this array will first be released.
  7907. */
  7908. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7909. {
  7910. if (this != &other)
  7911. {
  7912. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  7913. swapWithArray (otherCopy);
  7914. }
  7915. return *this;
  7916. }
  7917. /** Destructor.
  7918. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7919. */
  7920. ~ReferenceCountedArray()
  7921. {
  7922. clear();
  7923. }
  7924. /** Removes all objects from the array.
  7925. Any objects in the array that are not referenced from elsewhere will be deleted.
  7926. */
  7927. void clear()
  7928. {
  7929. const ScopedLockType lock (getLock());
  7930. while (numUsed > 0)
  7931. if (data.elements [--numUsed] != 0)
  7932. data.elements [numUsed]->decReferenceCount();
  7933. jassert (numUsed == 0);
  7934. data.setAllocatedSize (0);
  7935. }
  7936. /** Returns the current number of objects in the array. */
  7937. inline int size() const throw()
  7938. {
  7939. return numUsed;
  7940. }
  7941. /** Returns a pointer to the object at this index in the array.
  7942. If the index is out-of-range, this will return a null pointer, (and
  7943. it could be null anyway, because it's ok for the array to hold null
  7944. pointers as well as objects).
  7945. @see getUnchecked
  7946. */
  7947. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7948. {
  7949. const ScopedLockType lock (getLock());
  7950. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  7951. : static_cast <ObjectClass*> (0);
  7952. }
  7953. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7954. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7955. it can be used when you're sure the index if always going to be legal.
  7956. */
  7957. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7958. {
  7959. const ScopedLockType lock (getLock());
  7960. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7961. return data.elements [index];
  7962. }
  7963. /** Returns a pointer to the first object in the array.
  7964. This will return a null pointer if the array's empty.
  7965. @see getLast
  7966. */
  7967. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7968. {
  7969. const ScopedLockType lock (getLock());
  7970. return numUsed > 0 ? data.elements [0]
  7971. : static_cast <ObjectClass*> (0);
  7972. }
  7973. /** Returns a pointer to the last object in the array.
  7974. This will return a null pointer if the array's empty.
  7975. @see getFirst
  7976. */
  7977. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7978. {
  7979. const ScopedLockType lock (getLock());
  7980. return numUsed > 0 ? data.elements [numUsed - 1]
  7981. : static_cast <ObjectClass*> (0);
  7982. }
  7983. /** Finds the index of the first occurrence of an object in the array.
  7984. @param objectToLookFor the object to look for
  7985. @returns the index at which the object was found, or -1 if it's not found
  7986. */
  7987. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7988. {
  7989. const ScopedLockType lock (getLock());
  7990. ObjectClass** e = data.elements.getData();
  7991. ObjectClass** const end = e + numUsed;
  7992. while (e != end)
  7993. {
  7994. if (objectToLookFor == *e)
  7995. return static_cast <int> (e - data.elements.getData());
  7996. ++e;
  7997. }
  7998. return -1;
  7999. }
  8000. /** Returns true if the array contains a specified object.
  8001. @param objectToLookFor the object to look for
  8002. @returns true if the object is in the array
  8003. */
  8004. bool contains (const ObjectClass* const objectToLookFor) const throw()
  8005. {
  8006. const ScopedLockType lock (getLock());
  8007. ObjectClass** e = data.elements.getData();
  8008. ObjectClass** const end = e + numUsed;
  8009. while (e != end)
  8010. {
  8011. if (objectToLookFor == *e)
  8012. return true;
  8013. ++e;
  8014. }
  8015. return false;
  8016. }
  8017. /** Appends a new object to the end of the array.
  8018. This will increase the new object's reference count.
  8019. @param newObject the new object to add to the array
  8020. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  8021. */
  8022. void add (ObjectClass* const newObject) throw()
  8023. {
  8024. const ScopedLockType lock (getLock());
  8025. data.ensureAllocatedSize (numUsed + 1);
  8026. data.elements [numUsed++] = newObject;
  8027. if (newObject != 0)
  8028. newObject->incReferenceCount();
  8029. }
  8030. /** Inserts a new object into the array at the given index.
  8031. If the index is less than 0 or greater than the size of the array, the
  8032. element will be added to the end of the array.
  8033. Otherwise, it will be inserted into the array, moving all the later elements
  8034. along to make room.
  8035. This will increase the new object's reference count.
  8036. @param indexToInsertAt the index at which the new element should be inserted
  8037. @param newObject the new object to add to the array
  8038. @see add, addSorted, addIfNotAlreadyThere, set
  8039. */
  8040. void insert (int indexToInsertAt,
  8041. ObjectClass* const newObject) throw()
  8042. {
  8043. if (indexToInsertAt >= 0)
  8044. {
  8045. const ScopedLockType lock (getLock());
  8046. if (indexToInsertAt > numUsed)
  8047. indexToInsertAt = numUsed;
  8048. data.ensureAllocatedSize (numUsed + 1);
  8049. ObjectClass** const e = data.elements + indexToInsertAt;
  8050. const int numToMove = numUsed - indexToInsertAt;
  8051. if (numToMove > 0)
  8052. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8053. *e = newObject;
  8054. if (newObject != 0)
  8055. newObject->incReferenceCount();
  8056. ++numUsed;
  8057. }
  8058. else
  8059. {
  8060. add (newObject);
  8061. }
  8062. }
  8063. /** Appends a new object at the end of the array as long as the array doesn't
  8064. already contain it.
  8065. If the array already contains a matching object, nothing will be done.
  8066. @param newObject the new object to add to the array
  8067. */
  8068. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8069. {
  8070. const ScopedLockType lock (getLock());
  8071. if (! contains (newObject))
  8072. add (newObject);
  8073. }
  8074. /** Replaces an object in the array with a different one.
  8075. If the index is less than zero, this method does nothing.
  8076. If the index is beyond the end of the array, the new object is added to the end of the array.
  8077. The object being added has its reference count increased, and if it's replacing
  8078. another object, then that one has its reference count decreased, and may be deleted.
  8079. @param indexToChange the index whose value you want to change
  8080. @param newObject the new value to set for this index.
  8081. @see add, insert, remove
  8082. */
  8083. void set (const int indexToChange,
  8084. ObjectClass* const newObject)
  8085. {
  8086. if (indexToChange >= 0)
  8087. {
  8088. const ScopedLockType lock (getLock());
  8089. if (newObject != 0)
  8090. newObject->incReferenceCount();
  8091. if (indexToChange < numUsed)
  8092. {
  8093. if (data.elements [indexToChange] != 0)
  8094. data.elements [indexToChange]->decReferenceCount();
  8095. data.elements [indexToChange] = newObject;
  8096. }
  8097. else
  8098. {
  8099. data.ensureAllocatedSize (numUsed + 1);
  8100. data.elements [numUsed++] = newObject;
  8101. }
  8102. }
  8103. }
  8104. /** Adds elements from another array to the end of this array.
  8105. @param arrayToAddFrom the array from which to copy the elements
  8106. @param startIndex the first element of the other array to start copying from
  8107. @param numElementsToAdd how many elements to add from the other array. If this
  8108. value is negative or greater than the number of available elements,
  8109. all available elements will be copied.
  8110. @see add
  8111. */
  8112. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8113. int startIndex = 0,
  8114. int numElementsToAdd = -1) throw()
  8115. {
  8116. arrayToAddFrom.lockArray();
  8117. const ScopedLockType lock (getLock());
  8118. if (startIndex < 0)
  8119. {
  8120. jassertfalse;
  8121. startIndex = 0;
  8122. }
  8123. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8124. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8125. if (numElementsToAdd > 0)
  8126. {
  8127. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8128. while (--numElementsToAdd >= 0)
  8129. add (arrayToAddFrom.getUnchecked (startIndex++));
  8130. }
  8131. arrayToAddFrom.unlockArray();
  8132. }
  8133. /** Inserts a new object into the array assuming that the array is sorted.
  8134. This will use a comparator to find the position at which the new object
  8135. should go. If the array isn't sorted, the behaviour of this
  8136. method will be unpredictable.
  8137. @param comparator the comparator object to use to compare the elements - see the
  8138. sort() method for details about this object's form
  8139. @param newObject the new object to insert to the array
  8140. @see add, sort
  8141. */
  8142. template <class ElementComparator>
  8143. void addSorted (ElementComparator& comparator,
  8144. ObjectClass* newObject) throw()
  8145. {
  8146. const ScopedLockType lock (getLock());
  8147. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8148. }
  8149. /** Inserts or replaces an object in the array, assuming it is sorted.
  8150. This is similar to addSorted, but if a matching element already exists, then it will be
  8151. replaced by the new one, rather than the new one being added as well.
  8152. */
  8153. template <class ElementComparator>
  8154. void addOrReplaceSorted (ElementComparator& comparator,
  8155. ObjectClass* newObject) throw()
  8156. {
  8157. const ScopedLockType lock (getLock());
  8158. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8159. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8160. set (index - 1, newObject); // replace an existing object that matches
  8161. else
  8162. insert (index, newObject); // no match, so insert the new one
  8163. }
  8164. /** Removes an object from the array.
  8165. This will remove the object at a given index and move back all the
  8166. subsequent objects to close the gap.
  8167. If the index passed in is out-of-range, nothing will happen.
  8168. The object that is removed will have its reference count decreased,
  8169. and may be deleted if not referenced from elsewhere.
  8170. @param indexToRemove the index of the element to remove
  8171. @see removeObject, removeRange
  8172. */
  8173. void remove (const int indexToRemove)
  8174. {
  8175. const ScopedLockType lock (getLock());
  8176. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8177. {
  8178. ObjectClass** const e = data.elements + indexToRemove;
  8179. if (*e != 0)
  8180. (*e)->decReferenceCount();
  8181. --numUsed;
  8182. const int numberToShift = numUsed - indexToRemove;
  8183. if (numberToShift > 0)
  8184. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8185. if ((numUsed << 1) < data.numAllocated)
  8186. minimiseStorageOverheads();
  8187. }
  8188. }
  8189. /** Removes the first occurrence of a specified object from the array.
  8190. If the item isn't found, no action is taken. If it is found, it is
  8191. removed and has its reference count decreased.
  8192. @param objectToRemove the object to try to remove
  8193. @see remove, removeRange
  8194. */
  8195. void removeObject (ObjectClass* const objectToRemove)
  8196. {
  8197. const ScopedLockType lock (getLock());
  8198. remove (indexOf (objectToRemove));
  8199. }
  8200. /** Removes a range of objects from the array.
  8201. This will remove a set of objects, starting from the given index,
  8202. and move any subsequent elements down to close the gap.
  8203. If the range extends beyond the bounds of the array, it will
  8204. be safely clipped to the size of the array.
  8205. The objects that are removed will have their reference counts decreased,
  8206. and may be deleted if not referenced from elsewhere.
  8207. @param startIndex the index of the first object to remove
  8208. @param numberToRemove how many objects should be removed
  8209. @see remove, removeObject
  8210. */
  8211. void removeRange (const int startIndex,
  8212. const int numberToRemove)
  8213. {
  8214. const ScopedLockType lock (getLock());
  8215. const int start = jlimit (0, numUsed, startIndex);
  8216. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8217. if (end > start)
  8218. {
  8219. int i;
  8220. for (i = start; i < end; ++i)
  8221. {
  8222. if (data.elements[i] != 0)
  8223. {
  8224. data.elements[i]->decReferenceCount();
  8225. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8226. }
  8227. }
  8228. const int rangeSize = end - start;
  8229. ObjectClass** e = data.elements + start;
  8230. i = numUsed - end;
  8231. numUsed -= rangeSize;
  8232. while (--i >= 0)
  8233. {
  8234. *e = e [rangeSize];
  8235. ++e;
  8236. }
  8237. if ((numUsed << 1) < data.numAllocated)
  8238. minimiseStorageOverheads();
  8239. }
  8240. }
  8241. /** Removes the last n objects from the array.
  8242. The objects that are removed will have their reference counts decreased,
  8243. and may be deleted if not referenced from elsewhere.
  8244. @param howManyToRemove how many objects to remove from the end of the array
  8245. @see remove, removeObject, removeRange
  8246. */
  8247. void removeLast (int howManyToRemove = 1)
  8248. {
  8249. const ScopedLockType lock (getLock());
  8250. if (howManyToRemove > numUsed)
  8251. howManyToRemove = numUsed;
  8252. while (--howManyToRemove >= 0)
  8253. remove (numUsed - 1);
  8254. }
  8255. /** Swaps a pair of objects in the array.
  8256. If either of the indexes passed in is out-of-range, nothing will happen,
  8257. otherwise the two objects at these positions will be exchanged.
  8258. */
  8259. void swap (const int index1,
  8260. const int index2) throw()
  8261. {
  8262. const ScopedLockType lock (getLock());
  8263. if (((unsigned int) index1) < (unsigned int) numUsed
  8264. && ((unsigned int) index2) < (unsigned int) numUsed)
  8265. {
  8266. swapVariables (data.elements [index1],
  8267. data.elements [index2]);
  8268. }
  8269. }
  8270. /** Moves one of the objects to a different position.
  8271. This will move the object to a specified index, shuffling along
  8272. any intervening elements as required.
  8273. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8274. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8275. @param currentIndex the index of the object to be moved. If this isn't a
  8276. valid index, then nothing will be done
  8277. @param newIndex the index at which you'd like this object to end up. If this
  8278. is less than zero, it will be moved to the end of the array
  8279. */
  8280. void move (const int currentIndex,
  8281. int newIndex) throw()
  8282. {
  8283. if (currentIndex != newIndex)
  8284. {
  8285. const ScopedLockType lock (getLock());
  8286. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8287. {
  8288. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8289. newIndex = numUsed - 1;
  8290. ObjectClass* const value = data.elements [currentIndex];
  8291. if (newIndex > currentIndex)
  8292. {
  8293. memmove (data.elements + currentIndex,
  8294. data.elements + currentIndex + 1,
  8295. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8296. }
  8297. else
  8298. {
  8299. memmove (data.elements + newIndex + 1,
  8300. data.elements + newIndex,
  8301. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8302. }
  8303. data.elements [newIndex] = value;
  8304. }
  8305. }
  8306. }
  8307. /** This swaps the contents of this array with those of another array.
  8308. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8309. because it just swaps their internal pointers.
  8310. */
  8311. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8312. {
  8313. const ScopedLockType lock1 (getLock());
  8314. const ScopedLockType lock2 (otherArray.getLock());
  8315. data.swapWith (otherArray.data);
  8316. swapVariables (numUsed, otherArray.numUsed);
  8317. }
  8318. /** Compares this array to another one.
  8319. @returns true only if the other array contains the same objects in the same order
  8320. */
  8321. bool operator== (const ReferenceCountedArray& other) const throw()
  8322. {
  8323. const ScopedLockType lock2 (other.getLock());
  8324. const ScopedLockType lock1 (getLock());
  8325. if (numUsed != other.numUsed)
  8326. return false;
  8327. for (int i = numUsed; --i >= 0;)
  8328. if (data.elements [i] != other.data.elements [i])
  8329. return false;
  8330. return true;
  8331. }
  8332. /** Compares this array to another one.
  8333. @see operator==
  8334. */
  8335. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8336. {
  8337. return ! operator== (other);
  8338. }
  8339. /** Sorts the elements in the array.
  8340. This will use a comparator object to sort the elements into order. The object
  8341. passed must have a method of the form:
  8342. @code
  8343. int compareElements (ElementType first, ElementType second);
  8344. @endcode
  8345. ..and this method must return:
  8346. - a value of < 0 if the first comes before the second
  8347. - a value of 0 if the two objects are equivalent
  8348. - a value of > 0 if the second comes before the first
  8349. To improve performance, the compareElements() method can be declared as static or const.
  8350. @param comparator the comparator to use for comparing elements.
  8351. @param retainOrderOfEquivalentItems if this is true, then items
  8352. which the comparator says are equivalent will be
  8353. kept in the order in which they currently appear
  8354. in the array. This is slower to perform, but may
  8355. be important in some cases. If it's false, a faster
  8356. algorithm is used, but equivalent elements may be
  8357. rearranged.
  8358. @see sortArray
  8359. */
  8360. template <class ElementComparator>
  8361. void sort (ElementComparator& comparator,
  8362. const bool retainOrderOfEquivalentItems = false) const throw()
  8363. {
  8364. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8365. // avoids getting warning messages about the parameter being unused
  8366. const ScopedLockType lock (getLock());
  8367. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8368. }
  8369. /** Reduces the amount of storage being used by the array.
  8370. Arrays typically allocate slightly more storage than they need, and after
  8371. removing elements, they may have quite a lot of unused space allocated.
  8372. This method will reduce the amount of allocated storage to a minimum.
  8373. */
  8374. void minimiseStorageOverheads() throw()
  8375. {
  8376. const ScopedLockType lock (getLock());
  8377. data.shrinkToNoMoreThan (numUsed);
  8378. }
  8379. /** Returns the CriticalSection that locks this array.
  8380. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8381. an object of ScopedLockType as an RAII lock for it.
  8382. */
  8383. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8384. /** Returns the type of scoped lock to use for locking this array */
  8385. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8386. juce_UseDebuggingNewOperator
  8387. private:
  8388. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8389. int numUsed;
  8390. };
  8391. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8392. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8393. #endif
  8394. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8395. #endif
  8396. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8397. #endif
  8398. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8399. /*** Start of inlined file: juce_SortedSet.h ***/
  8400. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8401. #define __JUCE_SORTEDSET_JUCEHEADER__
  8402. #if JUCE_MSVC
  8403. #pragma warning (push)
  8404. #pragma warning (disable: 4512)
  8405. #endif
  8406. /**
  8407. Holds a set of unique primitive objects, such as ints or doubles.
  8408. A set can only hold one item with a given value, so if for example it's a
  8409. set of integers, attempting to add the same integer twice will do nothing
  8410. the second time.
  8411. Internally, the list of items is kept sorted (which means that whatever
  8412. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8413. to determine the order), and searching the set for known values is very fast
  8414. because it uses a binary-chop method.
  8415. Note that if you're using a class or struct as the element type, it must be
  8416. capable of being copied or moved with a straightforward memcpy, rather than
  8417. needing construction and destruction code.
  8418. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8419. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8420. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8421. */
  8422. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8423. class SortedSet
  8424. {
  8425. public:
  8426. /** Creates an empty set. */
  8427. SortedSet() throw()
  8428. : numUsed (0)
  8429. {
  8430. }
  8431. /** Creates a copy of another set.
  8432. @param other the set to copy
  8433. */
  8434. SortedSet (const SortedSet& other) throw()
  8435. {
  8436. const ScopedLockType lock (other.getLock());
  8437. numUsed = other.numUsed;
  8438. data.setAllocatedSize (other.numUsed);
  8439. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8440. }
  8441. /** Destructor. */
  8442. ~SortedSet() throw()
  8443. {
  8444. }
  8445. /** Copies another set over this one.
  8446. @param other the set to copy
  8447. */
  8448. SortedSet& operator= (const SortedSet& other) throw()
  8449. {
  8450. if (this != &other)
  8451. {
  8452. const ScopedLockType lock1 (other.getLock());
  8453. const ScopedLockType lock2 (getLock());
  8454. data.ensureAllocatedSize (other.size());
  8455. numUsed = other.numUsed;
  8456. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8457. minimiseStorageOverheads();
  8458. }
  8459. return *this;
  8460. }
  8461. /** Compares this set to another one.
  8462. Two sets are considered equal if they both contain the same set of
  8463. elements.
  8464. @param other the other set to compare with
  8465. */
  8466. bool operator== (const SortedSet<ElementType>& other) const throw()
  8467. {
  8468. const ScopedLockType lock (getLock());
  8469. if (numUsed != other.numUsed)
  8470. return false;
  8471. for (int i = numUsed; --i >= 0;)
  8472. if (data.elements[i] != other.data.elements[i])
  8473. return false;
  8474. return true;
  8475. }
  8476. /** Compares this set to another one.
  8477. Two sets are considered equal if they both contain the same set of
  8478. elements.
  8479. @param other the other set to compare with
  8480. */
  8481. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8482. {
  8483. return ! operator== (other);
  8484. }
  8485. /** Removes all elements from the set.
  8486. This will remove all the elements, and free any storage that the set is
  8487. using. To clear it without freeing the storage, use the clearQuick()
  8488. method instead.
  8489. @see clearQuick
  8490. */
  8491. void clear() throw()
  8492. {
  8493. const ScopedLockType lock (getLock());
  8494. data.setAllocatedSize (0);
  8495. numUsed = 0;
  8496. }
  8497. /** Removes all elements from the set without freeing the array's allocated storage.
  8498. @see clear
  8499. */
  8500. void clearQuick() throw()
  8501. {
  8502. const ScopedLockType lock (getLock());
  8503. numUsed = 0;
  8504. }
  8505. /** Returns the current number of elements in the set.
  8506. */
  8507. inline int size() const throw()
  8508. {
  8509. return numUsed;
  8510. }
  8511. /** Returns one of the elements in the set.
  8512. If the index passed in is beyond the range of valid elements, this
  8513. will return zero.
  8514. If you're certain that the index will always be a valid element, you
  8515. can call getUnchecked() instead, which is faster.
  8516. @param index the index of the element being requested (0 is the first element in the set)
  8517. @see getUnchecked, getFirst, getLast
  8518. */
  8519. inline ElementType operator[] (const int index) const throw()
  8520. {
  8521. const ScopedLockType lock (getLock());
  8522. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  8523. : ElementType();
  8524. }
  8525. /** Returns one of the elements in the set, without checking the index passed in.
  8526. Unlike the operator[] method, this will try to return an element without
  8527. checking that the index is within the bounds of the set, so should only
  8528. be used when you're confident that it will always be a valid index.
  8529. @param index the index of the element being requested (0 is the first element in the set)
  8530. @see operator[], getFirst, getLast
  8531. */
  8532. inline ElementType getUnchecked (const int index) const throw()
  8533. {
  8534. const ScopedLockType lock (getLock());
  8535. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8536. return data.elements [index];
  8537. }
  8538. /** Returns the first element in the set, or 0 if the set is empty.
  8539. @see operator[], getUnchecked, getLast
  8540. */
  8541. inline ElementType getFirst() const throw()
  8542. {
  8543. const ScopedLockType lock (getLock());
  8544. return numUsed > 0 ? data.elements [0] : ElementType();
  8545. }
  8546. /** Returns the last element in the set, or 0 if the set is empty.
  8547. @see operator[], getUnchecked, getFirst
  8548. */
  8549. inline ElementType getLast() const throw()
  8550. {
  8551. const ScopedLockType lock (getLock());
  8552. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8553. }
  8554. /** Finds the index of the first element which matches the value passed in.
  8555. This will search the set for the given object, and return the index
  8556. of its first occurrence. If the object isn't found, the method will return -1.
  8557. @param elementToLookFor the value or object to look for
  8558. @returns the index of the object, or -1 if it's not found
  8559. */
  8560. int indexOf (const ElementType elementToLookFor) const throw()
  8561. {
  8562. const ScopedLockType lock (getLock());
  8563. int start = 0;
  8564. int end = numUsed;
  8565. for (;;)
  8566. {
  8567. if (start >= end)
  8568. {
  8569. return -1;
  8570. }
  8571. else if (elementToLookFor == data.elements [start])
  8572. {
  8573. return start;
  8574. }
  8575. else
  8576. {
  8577. const int halfway = (start + end) >> 1;
  8578. if (halfway == start)
  8579. return -1;
  8580. else if (elementToLookFor >= data.elements [halfway])
  8581. start = halfway;
  8582. else
  8583. end = halfway;
  8584. }
  8585. }
  8586. }
  8587. /** Returns true if the set contains at least one occurrence of an object.
  8588. @param elementToLookFor the value or object to look for
  8589. @returns true if the item is found
  8590. */
  8591. bool contains (const ElementType elementToLookFor) const throw()
  8592. {
  8593. const ScopedLockType lock (getLock());
  8594. int start = 0;
  8595. int end = numUsed;
  8596. for (;;)
  8597. {
  8598. if (start >= end)
  8599. {
  8600. return false;
  8601. }
  8602. else if (elementToLookFor == data.elements [start])
  8603. {
  8604. return true;
  8605. }
  8606. else
  8607. {
  8608. const int halfway = (start + end) >> 1;
  8609. if (halfway == start)
  8610. return false;
  8611. else if (elementToLookFor >= data.elements [halfway])
  8612. start = halfway;
  8613. else
  8614. end = halfway;
  8615. }
  8616. }
  8617. }
  8618. /** Adds a new element to the set, (as long as it's not already in there).
  8619. @param newElement the new object to add to the set
  8620. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8621. */
  8622. void add (const ElementType newElement) throw()
  8623. {
  8624. const ScopedLockType lock (getLock());
  8625. int start = 0;
  8626. int end = numUsed;
  8627. for (;;)
  8628. {
  8629. if (start >= end)
  8630. {
  8631. jassert (start <= end);
  8632. insertInternal (start, newElement);
  8633. break;
  8634. }
  8635. else if (newElement == data.elements [start])
  8636. {
  8637. break;
  8638. }
  8639. else
  8640. {
  8641. const int halfway = (start + end) >> 1;
  8642. if (halfway == start)
  8643. {
  8644. if (newElement >= data.elements [halfway])
  8645. insertInternal (start + 1, newElement);
  8646. else
  8647. insertInternal (start, newElement);
  8648. break;
  8649. }
  8650. else if (newElement >= data.elements [halfway])
  8651. start = halfway;
  8652. else
  8653. end = halfway;
  8654. }
  8655. }
  8656. }
  8657. /** Adds elements from an array to this set.
  8658. @param elementsToAdd the array of elements to add
  8659. @param numElementsToAdd how many elements are in this other array
  8660. @see add
  8661. */
  8662. void addArray (const ElementType* elementsToAdd,
  8663. int numElementsToAdd) throw()
  8664. {
  8665. const ScopedLockType lock (getLock());
  8666. while (--numElementsToAdd >= 0)
  8667. add (*elementsToAdd++);
  8668. }
  8669. /** Adds elements from another set to this one.
  8670. @param setToAddFrom the set from which to copy the elements
  8671. @param startIndex the first element of the other set to start copying from
  8672. @param numElementsToAdd how many elements to add from the other set. If this
  8673. value is negative or greater than the number of available elements,
  8674. all available elements will be copied.
  8675. @see add
  8676. */
  8677. template <class OtherSetType>
  8678. void addSet (const OtherSetType& setToAddFrom,
  8679. int startIndex = 0,
  8680. int numElementsToAdd = -1) throw()
  8681. {
  8682. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  8683. const ScopedLockType lock2 (getLock());
  8684. jassert (this != &setToAddFrom);
  8685. if (this != &setToAddFrom)
  8686. {
  8687. if (startIndex < 0)
  8688. {
  8689. jassertfalse;
  8690. startIndex = 0;
  8691. }
  8692. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8693. numElementsToAdd = setToAddFrom.size() - startIndex;
  8694. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8695. }
  8696. }
  8697. /** Removes an element from the set.
  8698. This will remove the element at a given index.
  8699. If the index passed in is out-of-range, nothing will happen.
  8700. @param indexToRemove the index of the element to remove
  8701. @returns the element that has been removed
  8702. @see removeValue, removeRange
  8703. */
  8704. ElementType remove (const int indexToRemove) throw()
  8705. {
  8706. const ScopedLockType lock (getLock());
  8707. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8708. {
  8709. --numUsed;
  8710. ElementType* const e = data.elements + indexToRemove;
  8711. ElementType const removed = *e;
  8712. const int numberToShift = numUsed - indexToRemove;
  8713. if (numberToShift > 0)
  8714. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8715. if ((numUsed << 1) < data.numAllocated)
  8716. minimiseStorageOverheads();
  8717. return removed;
  8718. }
  8719. return 0;
  8720. }
  8721. /** Removes an item from the set.
  8722. This will remove the given element from the set, if it's there.
  8723. @param valueToRemove the object to try to remove
  8724. @see remove, removeRange
  8725. */
  8726. void removeValue (const ElementType valueToRemove) throw()
  8727. {
  8728. const ScopedLockType lock (getLock());
  8729. remove (indexOf (valueToRemove));
  8730. }
  8731. /** Removes any elements which are also in another set.
  8732. @param otherSet the other set in which to look for elements to remove
  8733. @see removeValuesNotIn, remove, removeValue, removeRange
  8734. */
  8735. template <class OtherSetType>
  8736. void removeValuesIn (const OtherSetType& otherSet) throw()
  8737. {
  8738. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8739. const ScopedLockType lock2 (getLock());
  8740. if (this == &otherSet)
  8741. {
  8742. clear();
  8743. }
  8744. else
  8745. {
  8746. if (otherSet.size() > 0)
  8747. {
  8748. for (int i = numUsed; --i >= 0;)
  8749. if (otherSet.contains (data.elements [i]))
  8750. remove (i);
  8751. }
  8752. }
  8753. }
  8754. /** Removes any elements which are not found in another set.
  8755. Only elements which occur in this other set will be retained.
  8756. @param otherSet the set in which to look for elements NOT to remove
  8757. @see removeValuesIn, remove, removeValue, removeRange
  8758. */
  8759. template <class OtherSetType>
  8760. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8761. {
  8762. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8763. const ScopedLockType lock2 (getLock());
  8764. if (this != &otherSet)
  8765. {
  8766. if (otherSet.size() <= 0)
  8767. {
  8768. clear();
  8769. }
  8770. else
  8771. {
  8772. for (int i = numUsed; --i >= 0;)
  8773. if (! otherSet.contains (data.elements [i]))
  8774. remove (i);
  8775. }
  8776. }
  8777. }
  8778. /** Reduces the amount of storage being used by the set.
  8779. Sets typically allocate slightly more storage than they need, and after
  8780. removing elements, they may have quite a lot of unused space allocated.
  8781. This method will reduce the amount of allocated storage to a minimum.
  8782. */
  8783. void minimiseStorageOverheads() throw()
  8784. {
  8785. const ScopedLockType lock (getLock());
  8786. data.shrinkToNoMoreThan (numUsed);
  8787. }
  8788. /** Returns the CriticalSection that locks this array.
  8789. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8790. an object of ScopedLockType as an RAII lock for it.
  8791. */
  8792. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8793. /** Returns the type of scoped lock to use for locking this array */
  8794. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8795. juce_UseDebuggingNewOperator
  8796. private:
  8797. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  8798. int numUsed;
  8799. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8800. {
  8801. data.ensureAllocatedSize (numUsed + 1);
  8802. ElementType* const insertPos = data.elements + indexToInsertAt;
  8803. const int numberToMove = numUsed - indexToInsertAt;
  8804. if (numberToMove > 0)
  8805. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8806. *insertPos = newElement;
  8807. ++numUsed;
  8808. }
  8809. };
  8810. #if JUCE_MSVC
  8811. #pragma warning (pop)
  8812. #endif
  8813. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8814. /*** End of inlined file: juce_SortedSet.h ***/
  8815. #endif
  8816. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8817. /*** Start of inlined file: juce_SparseSet.h ***/
  8818. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8819. #define __JUCE_SPARSESET_JUCEHEADER__
  8820. /**
  8821. Holds a set of primitive values, storing them as a set of ranges.
  8822. This container acts like an array, but can efficiently hold large continguous
  8823. ranges of values. It's quite a specialised class, mostly useful for things
  8824. like keeping the set of selected rows in a listbox.
  8825. The type used as a template paramter must be an integer type, such as int, short,
  8826. int64, etc.
  8827. */
  8828. template <class Type>
  8829. class SparseSet
  8830. {
  8831. public:
  8832. /** Creates a new empty set. */
  8833. SparseSet()
  8834. {
  8835. }
  8836. /** Creates a copy of another SparseSet. */
  8837. SparseSet (const SparseSet<Type>& other)
  8838. : values (other.values)
  8839. {
  8840. }
  8841. /** Destructor. */
  8842. ~SparseSet()
  8843. {
  8844. }
  8845. /** Clears the set. */
  8846. void clear()
  8847. {
  8848. values.clear();
  8849. }
  8850. /** Checks whether the set is empty.
  8851. This is much quicker than using (size() == 0).
  8852. */
  8853. bool isEmpty() const throw()
  8854. {
  8855. return values.size() == 0;
  8856. }
  8857. /** Returns the number of values in the set.
  8858. Because of the way the data is stored, this method can take longer if there
  8859. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8860. are any items.
  8861. */
  8862. Type size() const
  8863. {
  8864. Type total (0);
  8865. for (int i = 0; i < values.size(); i += 2)
  8866. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  8867. return total;
  8868. }
  8869. /** Returns one of the values in the set.
  8870. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8871. @returns the value at this index, or 0 if it's out-of-range
  8872. */
  8873. Type operator[] (Type index) const
  8874. {
  8875. for (int i = 0; i < values.size(); i += 2)
  8876. {
  8877. const Type start (values.getUnchecked (i));
  8878. const Type len (values.getUnchecked (i + 1) - start);
  8879. if (index < len)
  8880. return start + index;
  8881. index -= len;
  8882. }
  8883. return Type (0);
  8884. }
  8885. /** Checks whether a particular value is in the set. */
  8886. bool contains (const Type valueToLookFor) const
  8887. {
  8888. for (int i = 0; i < values.size(); ++i)
  8889. if (valueToLookFor < values.getUnchecked(i))
  8890. return (i & 1) != 0;
  8891. return false;
  8892. }
  8893. /** Returns the number of contiguous blocks of values.
  8894. @see getRange
  8895. */
  8896. int getNumRanges() const throw()
  8897. {
  8898. return values.size() >> 1;
  8899. }
  8900. /** Returns one of the contiguous ranges of values stored.
  8901. @param rangeIndex the index of the range to look up, between 0
  8902. and (getNumRanges() - 1)
  8903. @see getTotalRange
  8904. */
  8905. const Range<Type> getRange (const int rangeIndex) const
  8906. {
  8907. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8908. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  8909. values.getUnchecked ((rangeIndex << 1) + 1));
  8910. else
  8911. return Range<Type>();
  8912. }
  8913. /** Returns the range between the lowest and highest values in the set.
  8914. @see getRange
  8915. */
  8916. const Range<Type> getTotalRange() const
  8917. {
  8918. if (values.size() > 0)
  8919. {
  8920. jassert ((values.size() & 1) == 0);
  8921. return Range<Type> (values.getUnchecked (0),
  8922. values.getUnchecked (values.size() - 1));
  8923. }
  8924. return Range<Type>();
  8925. }
  8926. /** Adds a range of contiguous values to the set.
  8927. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  8928. */
  8929. void addRange (const Range<Type>& range)
  8930. {
  8931. jassert (range.getLength() >= 0);
  8932. if (range.getLength() > 0)
  8933. {
  8934. removeRange (range);
  8935. values.addUsingDefaultSort (range.getStart());
  8936. values.addUsingDefaultSort (range.getEnd());
  8937. simplify();
  8938. }
  8939. }
  8940. /** Removes a range of values from the set.
  8941. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  8942. */
  8943. void removeRange (const Range<Type>& rangeToRemove)
  8944. {
  8945. jassert (rangeToRemove.getLength() >= 0);
  8946. if (rangeToRemove.getLength() > 0
  8947. && values.size() > 0
  8948. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  8949. && values.getUnchecked(0) < rangeToRemove.getEnd())
  8950. {
  8951. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  8952. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  8953. const bool onAtEnd = contains (lastValue);
  8954. for (int i = values.size(); --i >= 0;)
  8955. {
  8956. if (values.getUnchecked(i) <= lastValue)
  8957. {
  8958. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  8959. {
  8960. values.remove (i);
  8961. if (--i < 0)
  8962. break;
  8963. }
  8964. break;
  8965. }
  8966. }
  8967. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  8968. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  8969. simplify();
  8970. }
  8971. }
  8972. /** Does an XOR of the values in a given range. */
  8973. void invertRange (const Range<Type>& range)
  8974. {
  8975. SparseSet newItems;
  8976. newItems.addRange (range);
  8977. int i;
  8978. for (i = getNumRanges(); --i >= 0;)
  8979. newItems.removeRange (getRange (i));
  8980. removeRange (range);
  8981. for (i = newItems.getNumRanges(); --i >= 0;)
  8982. addRange (newItems.getRange(i));
  8983. }
  8984. /** Checks whether any part of a given range overlaps any part of this set. */
  8985. bool overlapsRange (const Range<Type>& range)
  8986. {
  8987. if (range.getLength() > 0)
  8988. {
  8989. for (int i = getNumRanges(); --i >= 0;)
  8990. {
  8991. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8992. return false;
  8993. if (values.getUnchecked (i << 1) < range.getEnd())
  8994. return true;
  8995. }
  8996. }
  8997. return false;
  8998. }
  8999. /** Checks whether the whole of a given range is contained within this one. */
  9000. bool containsRange (const Range<Type>& range)
  9001. {
  9002. if (range.getLength() > 0)
  9003. {
  9004. for (int i = getNumRanges(); --i >= 0;)
  9005. {
  9006. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  9007. return false;
  9008. if (values.getUnchecked (i << 1) <= range.getStart()
  9009. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  9010. return true;
  9011. }
  9012. }
  9013. return false;
  9014. }
  9015. bool operator== (const SparseSet<Type>& other) throw()
  9016. {
  9017. return values == other.values;
  9018. }
  9019. bool operator!= (const SparseSet<Type>& other) throw()
  9020. {
  9021. return values != other.values;
  9022. }
  9023. juce_UseDebuggingNewOperator
  9024. private:
  9025. // alternating start/end values of ranges of values that are present.
  9026. Array<Type, DummyCriticalSection> values;
  9027. void simplify()
  9028. {
  9029. jassert ((values.size() & 1) == 0);
  9030. for (int i = values.size(); --i > 0;)
  9031. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  9032. values.removeRange (--i, 2);
  9033. }
  9034. };
  9035. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9036. /*** End of inlined file: juce_SparseSet.h ***/
  9037. #endif
  9038. #ifndef __JUCE_VALUE_JUCEHEADER__
  9039. /*** Start of inlined file: juce_Value.h ***/
  9040. #ifndef __JUCE_VALUE_JUCEHEADER__
  9041. #define __JUCE_VALUE_JUCEHEADER__
  9042. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  9043. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  9044. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  9045. /*** Start of inlined file: juce_MessageListener.h ***/
  9046. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  9047. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  9048. /*** Start of inlined file: juce_Message.h ***/
  9049. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  9050. #define __JUCE_MESSAGE_JUCEHEADER__
  9051. class MessageListener;
  9052. class MessageManager;
  9053. /** The base class for objects that can be delivered to a MessageListener.
  9054. The simplest Message object contains a few integer and pointer parameters
  9055. that the user can set, and this is enough for a lot of purposes. For passing more
  9056. complex data, subclasses of Message can also be used.
  9057. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9058. */
  9059. class JUCE_API Message
  9060. {
  9061. public:
  9062. /** Creates an uninitialised message.
  9063. The class's variables will also be left uninitialised.
  9064. */
  9065. Message() throw();
  9066. /** Creates a message object, filling in the member variables.
  9067. The corresponding public member variables will be set from the parameters
  9068. passed in.
  9069. */
  9070. Message (int intParameter1,
  9071. int intParameter2,
  9072. int intParameter3,
  9073. void* pointerParameter) throw();
  9074. /** Destructor. */
  9075. virtual ~Message() throw();
  9076. // These values can be used for carrying simple data that the application needs to
  9077. // pass around. For more complex messages, just create a subclass.
  9078. int intParameter1; /**< user-defined integer value. */
  9079. int intParameter2; /**< user-defined integer value. */
  9080. int intParameter3; /**< user-defined integer value. */
  9081. void* pointerParameter; /**< user-defined pointer value. */
  9082. juce_UseDebuggingNewOperator
  9083. private:
  9084. friend class MessageListener;
  9085. friend class MessageManager;
  9086. MessageListener* messageRecipient;
  9087. Message (const Message&);
  9088. Message& operator= (const Message&);
  9089. };
  9090. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9091. /*** End of inlined file: juce_Message.h ***/
  9092. /**
  9093. MessageListener subclasses can post and receive Message objects.
  9094. @see Message, MessageManager, ActionListener, ChangeListener
  9095. */
  9096. class JUCE_API MessageListener
  9097. {
  9098. protected:
  9099. /** Creates a MessageListener. */
  9100. MessageListener() throw();
  9101. public:
  9102. /** Destructor.
  9103. When a MessageListener is deleted, it removes itself from a global list
  9104. of registered listeners, so that the isValidMessageListener() method
  9105. will no longer return true.
  9106. */
  9107. virtual ~MessageListener();
  9108. /** This is the callback method that receives incoming messages.
  9109. This is called by the MessageManager from its dispatch loop.
  9110. @see postMessage
  9111. */
  9112. virtual void handleMessage (const Message& message) = 0;
  9113. /** Sends a message to the message queue, for asynchronous delivery to this listener
  9114. later on.
  9115. This method can be called safely by any thread.
  9116. @param message the message object to send - this will be deleted
  9117. automatically by the message queue, so don't keep any
  9118. references to it after calling this method.
  9119. @see handleMessage
  9120. */
  9121. void postMessage (Message* message) const throw();
  9122. /** Checks whether this MessageListener has been deleted.
  9123. Although not foolproof, this method is safe to call on dangling or null
  9124. pointers. A list of active MessageListeners is kept internally, so this
  9125. checks whether the object is on this list or not.
  9126. Note that it's possible to get a false-positive here, if an object is
  9127. deleted and another is subsequently created that happens to be at the
  9128. exact same memory location, but I can't think of a good way of avoiding
  9129. this.
  9130. */
  9131. bool isValidMessageListener() const throw();
  9132. };
  9133. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  9134. /*** End of inlined file: juce_MessageListener.h ***/
  9135. /**
  9136. Has a callback method that is triggered asynchronously.
  9137. This object allows an asynchronous callback function to be triggered, for
  9138. tasks such as coalescing multiple updates into a single callback later on.
  9139. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  9140. message thread calling handleAsyncUpdate() as soon as it can.
  9141. */
  9142. class JUCE_API AsyncUpdater
  9143. {
  9144. public:
  9145. /** Creates an AsyncUpdater object. */
  9146. AsyncUpdater() throw();
  9147. /** Destructor.
  9148. If there are any pending callbacks when the object is deleted, these are lost.
  9149. */
  9150. virtual ~AsyncUpdater();
  9151. /** Causes the callback to be triggered at a later time.
  9152. This method returns immediately, having made sure that a callback
  9153. to the handleAsyncUpdate() method will occur as soon as possible.
  9154. If an update callback is already pending but hasn't happened yet, calls
  9155. to this method will be ignored.
  9156. It's thread-safe to call this method from any number of threads without
  9157. needing to worry about locking.
  9158. */
  9159. void triggerAsyncUpdate() throw();
  9160. /** This will stop any pending updates from happening.
  9161. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9162. callback happens, this will cancel the handleAsyncUpdate() callback.
  9163. */
  9164. void cancelPendingUpdate() throw();
  9165. /** If an update has been triggered and is pending, this will invoke it
  9166. synchronously.
  9167. Use this as a kind of "flush" operation - if an update is pending, the
  9168. handleAsyncUpdate() method will be called immediately; if no update is
  9169. pending, then nothing will be done.
  9170. */
  9171. void handleUpdateNowIfNeeded();
  9172. /** Called back to do whatever your class needs to do.
  9173. This method is called by the message thread at the next convenient time
  9174. after the triggerAsyncUpdate() method has been called.
  9175. */
  9176. virtual void handleAsyncUpdate() = 0;
  9177. private:
  9178. class AsyncUpdaterInternal : public MessageListener
  9179. {
  9180. public:
  9181. AsyncUpdaterInternal() throw() {}
  9182. ~AsyncUpdaterInternal() {}
  9183. void handleMessage (const Message&);
  9184. AsyncUpdater* owner;
  9185. private:
  9186. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  9187. AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  9188. };
  9189. AsyncUpdaterInternal internalAsyncHandler;
  9190. bool asyncMessagePending;
  9191. };
  9192. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9193. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9194. /*** Start of inlined file: juce_ListenerList.h ***/
  9195. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9196. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9197. /**
  9198. Holds a set of objects and can invoke a member function callback on each object
  9199. in the set with a single call.
  9200. Use a ListenerList to manage a set of objects which need a callback, and you
  9201. can invoke a member function by simply calling call() or callChecked().
  9202. E.g.
  9203. @code
  9204. class MyListenerType
  9205. {
  9206. public:
  9207. void myCallbackMethod (int foo, bool bar);
  9208. };
  9209. ListenerList <MyListenerType> listeners;
  9210. listeners.add (someCallbackObjects...);
  9211. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9212. // in the list...
  9213. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9214. @endcode
  9215. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9216. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9217. will be mistakenly called after they've been removed, but it may mean that some of the
  9218. listeners could be called more than once, or not at all, depending on the list's order.
  9219. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9220. list itself being deleted while it's still iterating - to survive this situation, you can
  9221. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9222. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9223. the list will check this after each callback to determine whether it should abort the
  9224. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9225. which can be used to check when a Component has been deleted. See also
  9226. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9227. */
  9228. template <class ListenerClass,
  9229. class ArrayType = Array <ListenerClass*> >
  9230. class ListenerList
  9231. {
  9232. // Horrible macros required to support VC6/7..
  9233. #if defined (_MSC_VER) && _MSC_VER <= 1400
  9234. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9235. #define LL_PARAM(a) Q##a& param##a
  9236. #else
  9237. #define LL_TEMPLATE(a) typename P##a
  9238. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9239. #endif
  9240. public:
  9241. /** Creates an empty list. */
  9242. ListenerList()
  9243. {
  9244. }
  9245. /** Destructor. */
  9246. ~ListenerList()
  9247. {
  9248. }
  9249. /** Adds a listener to the list.
  9250. A listener can only be added once, so if the listener is already in the list,
  9251. this method has no effect.
  9252. @see remove
  9253. */
  9254. void add (ListenerClass* const listenerToAdd)
  9255. {
  9256. // Listeners can't be null pointers!
  9257. jassert (listenerToAdd != 0);
  9258. if (listenerToAdd != 0)
  9259. listeners.addIfNotAlreadyThere (listenerToAdd);
  9260. }
  9261. /** Removes a listener from the list.
  9262. If the listener wasn't in the list, this has no effect.
  9263. */
  9264. void remove (ListenerClass* const listenerToRemove)
  9265. {
  9266. // Listeners can't be null pointers!
  9267. jassert (listenerToRemove != 0);
  9268. listeners.removeValue (listenerToRemove);
  9269. }
  9270. /** Returns the number of registered listeners. */
  9271. int size() const throw()
  9272. {
  9273. return listeners.size();
  9274. }
  9275. /** Returns true if any listeners are registered. */
  9276. bool isEmpty() const throw()
  9277. {
  9278. return listeners.size() == 0;
  9279. }
  9280. /** Returns true if the specified listener has been added to the list. */
  9281. bool contains (ListenerClass* const listener) const throw()
  9282. {
  9283. return listeners.contains (listener);
  9284. }
  9285. /** Calls a member function on each listener in the list, with no parameters. */
  9286. void call (void (ListenerClass::*callbackFunction) ())
  9287. {
  9288. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9289. }
  9290. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9291. See the class description for info about writing a bail-out checker. */
  9292. template <class BailOutCheckerType>
  9293. void callChecked (const BailOutCheckerType& bailOutChecker,
  9294. void (ListenerClass::*callbackFunction) ())
  9295. {
  9296. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9297. (iter.getListener()->*callbackFunction) ();
  9298. }
  9299. /** Calls a member function on each listener in the list, with 1 parameter. */
  9300. template <LL_TEMPLATE(1)>
  9301. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9302. {
  9303. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9304. (iter.getListener()->*callbackFunction) (param1);
  9305. }
  9306. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9307. See the class description for info about writing a bail-out checker. */
  9308. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9309. void callChecked (const BailOutCheckerType& bailOutChecker,
  9310. void (ListenerClass::*callbackFunction) (P1),
  9311. LL_PARAM(1))
  9312. {
  9313. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9314. (iter.getListener()->*callbackFunction) (param1);
  9315. }
  9316. /** Calls a member function on each listener in the list, with 2 parameters. */
  9317. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9318. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9319. LL_PARAM(1), LL_PARAM(2))
  9320. {
  9321. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9322. (iter.getListener()->*callbackFunction) (param1, param2);
  9323. }
  9324. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9325. See the class description for info about writing a bail-out checker. */
  9326. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9327. void callChecked (const BailOutCheckerType& bailOutChecker,
  9328. void (ListenerClass::*callbackFunction) (P1, P2),
  9329. LL_PARAM(1), LL_PARAM(2))
  9330. {
  9331. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9332. (iter.getListener()->*callbackFunction) (param1, param2);
  9333. }
  9334. /** Calls a member function on each listener in the list, with 3 parameters. */
  9335. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9336. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9337. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9338. {
  9339. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9340. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9341. }
  9342. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9343. See the class description for info about writing a bail-out checker. */
  9344. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9345. void callChecked (const BailOutCheckerType& bailOutChecker,
  9346. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9347. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9348. {
  9349. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9350. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9351. }
  9352. /** Calls a member function on each listener in the list, with 4 parameters. */
  9353. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9354. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9355. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9356. {
  9357. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9358. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9359. }
  9360. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9361. See the class description for info about writing a bail-out checker. */
  9362. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9363. void callChecked (const BailOutCheckerType& bailOutChecker,
  9364. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9365. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9366. {
  9367. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9368. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9369. }
  9370. /** Calls a member function on each listener in the list, with 5 parameters. */
  9371. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9372. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9373. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9374. {
  9375. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9376. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9377. }
  9378. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9379. See the class description for info about writing a bail-out checker. */
  9380. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9381. void callChecked (const BailOutCheckerType& bailOutChecker,
  9382. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9383. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9384. {
  9385. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9386. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9387. }
  9388. /** A dummy bail-out checker that always returns false.
  9389. See the ListenerList notes for more info about bail-out checkers.
  9390. */
  9391. class DummyBailOutChecker
  9392. {
  9393. public:
  9394. inline bool shouldBailOut() const throw() { return false; }
  9395. };
  9396. /** Iterates the listeners in a ListenerList. */
  9397. template <class BailOutCheckerType, class ListType>
  9398. class Iterator
  9399. {
  9400. public:
  9401. Iterator (const ListType& list_, const BailOutCheckerType& bailOutChecker_)
  9402. : list (list_), bailOutChecker (bailOutChecker_), index (list_.size())
  9403. {}
  9404. ~Iterator() {}
  9405. bool next()
  9406. {
  9407. if (index <= 0 || bailOutChecker.shouldBailOut())
  9408. return false;
  9409. const int listSize = list.size();
  9410. if (--index < listSize)
  9411. return true;
  9412. index = listSize - 1;
  9413. return index >= 0;
  9414. }
  9415. typename ListType::ListenerType* getListener() const throw()
  9416. {
  9417. return list.getListeners().getUnchecked (index);
  9418. }
  9419. private:
  9420. const ListType& list;
  9421. const BailOutCheckerType& bailOutChecker;
  9422. int index;
  9423. Iterator (const Iterator&);
  9424. Iterator& operator= (const Iterator&);
  9425. };
  9426. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9427. typedef ListenerClass ListenerType;
  9428. const ArrayType& getListeners() const throw() { return listeners; }
  9429. private:
  9430. ArrayType listeners;
  9431. ListenerList (const ListenerList&);
  9432. ListenerList& operator= (const ListenerList&);
  9433. #undef LL_TEMPLATE
  9434. #undef LL_PARAM
  9435. };
  9436. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9437. /*** End of inlined file: juce_ListenerList.h ***/
  9438. /**
  9439. Represents a shared variant value.
  9440. A Value object contains a reference to a var object, and can get and set its value.
  9441. Listeners can be attached to be told when the value is changed.
  9442. The Value class is a wrapper around a shared, reference-counted underlying data
  9443. object - this means that multiple Value objects can all refer to the same piece of
  9444. data, allowing all of them to be notified when any of them changes it.
  9445. When you create a Value with its default constructor, it acts as a wrapper around a
  9446. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9447. you can map the Value onto any kind of underlying data.
  9448. */
  9449. class JUCE_API Value
  9450. {
  9451. public:
  9452. /** Creates an empty Value, containing a void var. */
  9453. Value();
  9454. /** Creates a Value that refers to the same value as another one.
  9455. Note that this doesn't make a copy of the other value - both this and the other
  9456. Value will share the same underlying value, so that when either one alters it, both
  9457. will see it change.
  9458. */
  9459. Value (const Value& other);
  9460. /** Creates a Value that is set to the specified value. */
  9461. explicit Value (const var& initialValue);
  9462. /** Destructor. */
  9463. ~Value();
  9464. /** Returns the current value. */
  9465. const var getValue() const;
  9466. /** Returns the current value. */
  9467. operator const var() const;
  9468. /** Returns the value as a string.
  9469. This is alternative to writing things like "myValue.getValue().toString()".
  9470. */
  9471. const String toString() const;
  9472. /** Sets the current value.
  9473. You can also use operator= to set the value.
  9474. If there are any listeners registered, they will be notified of the
  9475. change asynchronously.
  9476. */
  9477. void setValue (const var& newValue);
  9478. /** Sets the current value.
  9479. This is the same as calling setValue().
  9480. If there are any listeners registered, they will be notified of the
  9481. change asynchronously.
  9482. */
  9483. Value& operator= (const var& newValue);
  9484. /** Makes this object refer to the same underlying ValueSource as another one.
  9485. Once this object has been connected to another one, changing either one
  9486. will update the other.
  9487. Existing listeners will still be registered after you call this method, and
  9488. they'll continue to receive messages when the new value changes.
  9489. */
  9490. void referTo (const Value& valueToReferTo);
  9491. /** Returns true if this value and the other one are references to the same value.
  9492. */
  9493. bool refersToSameSourceAs (const Value& other) const;
  9494. /** Compares two values.
  9495. This is a compare-by-value comparison, so is effectively the same as
  9496. saying (this->getValue() == other.getValue()).
  9497. */
  9498. bool operator== (const Value& other) const;
  9499. /** Compares two values.
  9500. This is a compare-by-value comparison, so is effectively the same as
  9501. saying (this->getValue() != other.getValue()).
  9502. */
  9503. bool operator!= (const Value& other) const;
  9504. /** Receives callbacks when a Value object changes.
  9505. @see Value::addListener
  9506. */
  9507. class JUCE_API Listener
  9508. {
  9509. public:
  9510. Listener() {}
  9511. virtual ~Listener() {}
  9512. /** Called when a Value object is changed.
  9513. Note that the Value object passed as a parameter may not be exactly the same
  9514. object that you registered the listener with - it might be a copy that refers
  9515. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  9516. */
  9517. virtual void valueChanged (Value& value) = 0;
  9518. };
  9519. /** Adds a listener to receive callbacks when the value changes.
  9520. The listener is added to this specific Value object, and not to the shared
  9521. object that it refers to. When this object is deleted, all the listeners will
  9522. be lost, even if other references to the same Value still exist. So when you're
  9523. adding a listener, make sure that you add it to a ValueTree instance that will last
  9524. for as long as you need the listener. In general, you'd never want to add a listener
  9525. to a local stack-based ValueTree, but more likely to one that's a member variable.
  9526. @see removeListener
  9527. */
  9528. void addListener (Listener* listener);
  9529. /** Removes a listener that was previously added with addListener(). */
  9530. void removeListener (Listener* listener);
  9531. /**
  9532. Used internally by the Value class as the base class for its shared value objects.
  9533. The Value class is essentially a reference-counted pointer to a shared instance
  9534. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  9535. ValueSource classes to allow Value objects to represent your own custom data items.
  9536. */
  9537. class JUCE_API ValueSource : public ReferenceCountedObject,
  9538. public AsyncUpdater
  9539. {
  9540. public:
  9541. ValueSource();
  9542. virtual ~ValueSource();
  9543. /** Returns the current value of this object. */
  9544. virtual const var getValue() const = 0;
  9545. /** Changes the current value.
  9546. This must also trigger a change message if the value actually changes.
  9547. */
  9548. virtual void setValue (const var& newValue) = 0;
  9549. /** Delivers a change message to all the listeners that are registered with
  9550. this value.
  9551. If dispatchSynchronously is true, the method will call all the listeners
  9552. before returning; otherwise it'll dispatch a message and make the call later.
  9553. */
  9554. void sendChangeMessage (bool dispatchSynchronously);
  9555. juce_UseDebuggingNewOperator
  9556. protected:
  9557. friend class Value;
  9558. SortedSet <Value*> valuesWithListeners;
  9559. void handleAsyncUpdate();
  9560. ValueSource (const ValueSource&);
  9561. ValueSource& operator= (const ValueSource&);
  9562. };
  9563. /** Creates a Value object that uses this valueSource object as its underlying data. */
  9564. explicit Value (ValueSource* valueSource);
  9565. /** Returns the ValueSource that this value is referring to. */
  9566. ValueSource& getValueSource() throw() { return *value; }
  9567. juce_UseDebuggingNewOperator
  9568. private:
  9569. friend class ValueSource;
  9570. ReferenceCountedObjectPtr <ValueSource> value;
  9571. ListenerList <Listener> listeners;
  9572. void callListeners();
  9573. // This is disallowed to avoid confusion about whether it should
  9574. // do a by-value or by-reference copy.
  9575. Value& operator= (const Value& other);
  9576. };
  9577. /** Writes a Value to an OutputStream as a UTF8 string. */
  9578. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  9579. #endif // __JUCE_VALUE_JUCEHEADER__
  9580. /*** End of inlined file: juce_Value.h ***/
  9581. #endif
  9582. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9583. /*** Start of inlined file: juce_ValueTree.h ***/
  9584. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9585. #define __JUCE_VALUETREE_JUCEHEADER__
  9586. /*** Start of inlined file: juce_UndoManager.h ***/
  9587. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9588. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9589. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  9590. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9591. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9592. /*** Start of inlined file: juce_ChangeListenerList.h ***/
  9593. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9594. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9595. /*** Start of inlined file: juce_ChangeListener.h ***/
  9596. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9597. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9598. /**
  9599. Receives callbacks about changes to some kind of object.
  9600. Many objects use a ChangeListenerList to keep a set of listeners which they
  9601. will inform when something changes. A subclass of ChangeListener
  9602. is used to receive these callbacks.
  9603. Note that the major difference between an ActionListener and a ChangeListener
  9604. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9605. callbacks, but ActionListeners perform one callback for every event posted.
  9606. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9607. */
  9608. class JUCE_API ChangeListener
  9609. {
  9610. public:
  9611. /** Destructor. */
  9612. virtual ~ChangeListener() {}
  9613. /** Overridden by your subclass to receive the callback.
  9614. @param objectThatHasChanged the value that was passed to the
  9615. ChangeListenerList::sendChangeMessage() method
  9616. */
  9617. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9618. };
  9619. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9620. /*** End of inlined file: juce_ChangeListener.h ***/
  9621. /*** Start of inlined file: juce_ScopedLock.h ***/
  9622. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9623. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9624. /**
  9625. Automatically locks and unlocks a CriticalSection object.
  9626. Use one of these as a local variable to control access to a CriticalSection.
  9627. e.g. @code
  9628. CriticalSection myCriticalSection;
  9629. for (;;)
  9630. {
  9631. const ScopedLock myScopedLock (myCriticalSection);
  9632. // myCriticalSection is now locked
  9633. ...do some stuff...
  9634. // myCriticalSection gets unlocked here.
  9635. }
  9636. @endcode
  9637. @see CriticalSection, ScopedUnlock
  9638. */
  9639. class JUCE_API ScopedLock
  9640. {
  9641. public:
  9642. /** Creates a ScopedLock.
  9643. As soon as it is created, this will lock the CriticalSection, and
  9644. when the ScopedLock object is deleted, the CriticalSection will
  9645. be unlocked.
  9646. Make sure this object is created and deleted by the same thread,
  9647. otherwise there are no guarantees what will happen! Best just to use it
  9648. as a local stack object, rather than creating one with the new() operator.
  9649. */
  9650. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9651. /** Destructor.
  9652. The CriticalSection will be unlocked when the destructor is called.
  9653. Make sure this object is created and deleted by the same thread,
  9654. otherwise there are no guarantees what will happen!
  9655. */
  9656. inline ~ScopedLock() throw() { lock_.exit(); }
  9657. private:
  9658. const CriticalSection& lock_;
  9659. ScopedLock (const ScopedLock&);
  9660. ScopedLock& operator= (const ScopedLock&);
  9661. };
  9662. /**
  9663. Automatically unlocks and re-locks a CriticalSection object.
  9664. This is the reverse of a ScopedLock object - instead of locking the critical
  9665. section for the lifetime of this object, it unlocks it.
  9666. Make sure you don't try to unlock critical sections that aren't actually locked!
  9667. e.g. @code
  9668. CriticalSection myCriticalSection;
  9669. for (;;)
  9670. {
  9671. const ScopedLock myScopedLock (myCriticalSection);
  9672. // myCriticalSection is now locked
  9673. ... do some stuff with it locked ..
  9674. while (xyz)
  9675. {
  9676. ... do some stuff with it locked ..
  9677. const ScopedUnlock unlocker (myCriticalSection);
  9678. // myCriticalSection is now unlocked for the remainder of this block,
  9679. // and re-locked at the end.
  9680. ...do some stuff with it unlocked ...
  9681. }
  9682. // myCriticalSection gets unlocked here.
  9683. }
  9684. @endcode
  9685. @see CriticalSection, ScopedLock
  9686. */
  9687. class ScopedUnlock
  9688. {
  9689. public:
  9690. /** Creates a ScopedUnlock.
  9691. As soon as it is created, this will unlock the CriticalSection, and
  9692. when the ScopedLock object is deleted, the CriticalSection will
  9693. be re-locked.
  9694. Make sure this object is created and deleted by the same thread,
  9695. otherwise there are no guarantees what will happen! Best just to use it
  9696. as a local stack object, rather than creating one with the new() operator.
  9697. */
  9698. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9699. /** Destructor.
  9700. The CriticalSection will be unlocked when the destructor is called.
  9701. Make sure this object is created and deleted by the same thread,
  9702. otherwise there are no guarantees what will happen!
  9703. */
  9704. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9705. private:
  9706. const CriticalSection& lock_;
  9707. ScopedUnlock (const ScopedLock&);
  9708. ScopedUnlock& operator= (const ScopedUnlock&);
  9709. };
  9710. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9711. /*** End of inlined file: juce_ScopedLock.h ***/
  9712. /**
  9713. A set of ChangeListeners.
  9714. Listeners can be added and removed from the list, and change messages can be
  9715. broadcast to all the listeners.
  9716. @see ChangeListener, ChangeBroadcaster
  9717. */
  9718. class JUCE_API ChangeListenerList : public MessageListener
  9719. {
  9720. public:
  9721. /** Creates an empty list. */
  9722. ChangeListenerList() throw();
  9723. /** Destructor. */
  9724. ~ChangeListenerList() throw();
  9725. /** Adds a listener to the list.
  9726. (Trying to add a listener that's already on the list will have no effect).
  9727. */
  9728. void addChangeListener (ChangeListener* listener) throw();
  9729. /** Removes a listener from the list.
  9730. If the listener isn't on the list, this won't have any effect.
  9731. */
  9732. void removeChangeListener (ChangeListener* listener) throw();
  9733. /** Removes all listeners from the list. */
  9734. void removeAllChangeListeners() throw();
  9735. /** Posts an asynchronous change message to all the listeners.
  9736. If a message has already been sent and hasn't yet been delivered, this
  9737. method won't send another - in this way it coalesces multiple frequent
  9738. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9739. with the ActionListener, which posts a new event for every call to its
  9740. sendActionMessage() method.
  9741. Only listeners which are on the list when the change event is delivered
  9742. will receive the event - and this may include listeners that weren't on
  9743. the list when the change message was sent.
  9744. @param objectThatHasChanged this pointer is passed to the
  9745. ChangeListener::changeListenerCallback() method,
  9746. and can be any value the application needs
  9747. @see sendSynchronousChangeMessage
  9748. */
  9749. void sendChangeMessage (void* objectThatHasChanged) throw();
  9750. /** This will synchronously callback all the ChangeListeners.
  9751. Use this if you need to synchronously force a call to all the
  9752. listeners' ChangeListener::changeListenerCallback() methods.
  9753. */
  9754. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9755. /** If a change message has been sent but not yet dispatched, this will
  9756. use sendSynchronousChangeMessage() to make the callback immediately.
  9757. */
  9758. void dispatchPendingMessages();
  9759. /** @internal */
  9760. void handleMessage (const Message&);
  9761. juce_UseDebuggingNewOperator
  9762. private:
  9763. SortedSet <void*> listeners;
  9764. CriticalSection lock;
  9765. void* lastChangedObject;
  9766. bool messagePending;
  9767. ChangeListenerList (const ChangeListenerList&);
  9768. ChangeListenerList& operator= (const ChangeListenerList&);
  9769. };
  9770. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9771. /*** End of inlined file: juce_ChangeListenerList.h ***/
  9772. /** Manages a list of ChangeListeners, and can send them messages.
  9773. To quickly add methods to your class that can add/remove change
  9774. listeners and broadcast to them, you can derive from this.
  9775. @see ChangeListenerList, ChangeListener
  9776. */
  9777. class JUCE_API ChangeBroadcaster
  9778. {
  9779. public:
  9780. /** Creates an ChangeBroadcaster. */
  9781. ChangeBroadcaster() throw();
  9782. /** Destructor. */
  9783. virtual ~ChangeBroadcaster();
  9784. /** Adds a listener to the list.
  9785. (Trying to add a listener that's already on the list will have no effect).
  9786. */
  9787. void addChangeListener (ChangeListener* listener) throw();
  9788. /** Removes a listener from the list.
  9789. If the listener isn't on the list, this won't have any effect.
  9790. */
  9791. void removeChangeListener (ChangeListener* listener) throw();
  9792. /** Removes all listeners from the list. */
  9793. void removeAllChangeListeners() throw();
  9794. /** Broadcasts a change message to all the registered listeners.
  9795. The message will be delivered asynchronously by the event thread, so this
  9796. method will not directly call any of the listeners. For a synchronous
  9797. message, use sendSynchronousChangeMessage().
  9798. @see ChangeListenerList::sendActionMessage
  9799. */
  9800. void sendChangeMessage (void* objectThatHasChanged) throw();
  9801. /** Sends a synchronous change message to all the registered listeners.
  9802. @see ChangeListenerList::sendSynchronousChangeMessage
  9803. */
  9804. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9805. /** If a change message has been sent but not yet dispatched, this will
  9806. use sendSynchronousChangeMessage() to make the callback immediately.
  9807. */
  9808. void dispatchPendingMessages();
  9809. private:
  9810. ChangeListenerList changeListenerList;
  9811. ChangeBroadcaster (const ChangeBroadcaster&);
  9812. ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9813. };
  9814. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9815. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  9816. /*** Start of inlined file: juce_UndoableAction.h ***/
  9817. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9818. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9819. /**
  9820. Used by the UndoManager class to store an action which can be done
  9821. and undone.
  9822. @see UndoManager
  9823. */
  9824. class JUCE_API UndoableAction
  9825. {
  9826. protected:
  9827. /** Creates an action. */
  9828. UndoableAction() throw() {}
  9829. public:
  9830. /** Destructor. */
  9831. virtual ~UndoableAction() {}
  9832. /** Overridden by a subclass to perform the action.
  9833. This method is called by the UndoManager, and shouldn't be used directly by
  9834. applications.
  9835. Be careful not to make any calls in a perform() method that could call
  9836. recursively back into the UndoManager::perform() method
  9837. @returns true if the action could be performed.
  9838. @see UndoManager::perform
  9839. */
  9840. virtual bool perform() = 0;
  9841. /** Overridden by a subclass to undo the action.
  9842. This method is called by the UndoManager, and shouldn't be used directly by
  9843. applications.
  9844. Be careful not to make any calls in an undo() method that could call
  9845. recursively back into the UndoManager::perform() method
  9846. @returns true if the action could be undone without any errors.
  9847. @see UndoManager::perform
  9848. */
  9849. virtual bool undo() = 0;
  9850. /** Returns a value to indicate how much memory this object takes up.
  9851. Because the UndoManager keeps a list of UndoableActions, this is used
  9852. to work out how much space each one will take up, so that the UndoManager
  9853. can work out how many to keep.
  9854. The default value returned here is 10 - units are arbitrary and
  9855. don't have to be accurate.
  9856. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9857. UndoManager::setMaxNumberOfStoredUnits
  9858. */
  9859. virtual int getSizeInUnits() { return 10; }
  9860. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  9861. If possible, this method should create and return a single action that does the same job as
  9862. this one followed by the supplied action.
  9863. If it's not possible to merge the two actions, the method should return zero.
  9864. */
  9865. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  9866. };
  9867. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9868. /*** End of inlined file: juce_UndoableAction.h ***/
  9869. /**
  9870. Manages a list of undo/redo commands.
  9871. An UndoManager object keeps a list of past actions and can use these actions
  9872. to move backwards and forwards through an undo history.
  9873. To use it, create subclasses of UndoableAction which perform all the
  9874. actions you need, then when you need to actually perform an action, create one
  9875. and pass it to the UndoManager's perform() method.
  9876. The manager also uses the concept of 'transactions' to group the actions
  9877. together - all actions performed between calls to beginNewTransaction() are
  9878. grouped together and are all undone/redone as a group.
  9879. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9880. when actions are performed or undone.
  9881. @see UndoableAction
  9882. */
  9883. class JUCE_API UndoManager : public ChangeBroadcaster
  9884. {
  9885. public:
  9886. /** Creates an UndoManager.
  9887. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9888. to indicate how much storage it takes up
  9889. (UndoableAction::getSizeInUnits()), so this
  9890. lets you specify the maximum total number of
  9891. units that the undomanager is allowed to
  9892. keep in memory before letting the older actions
  9893. drop off the end of the list.
  9894. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9895. that will be kept, even if this involves exceeding
  9896. the amount of space specified in maxNumberOfUnitsToKeep
  9897. */
  9898. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  9899. int minimumTransactionsToKeep = 30);
  9900. /** Destructor. */
  9901. ~UndoManager();
  9902. /** Deletes all stored actions in the list. */
  9903. void clearUndoHistory();
  9904. /** Returns the current amount of space to use for storing UndoableAction objects.
  9905. @see setMaxNumberOfStoredUnits
  9906. */
  9907. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9908. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9909. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9910. to indicate how much storage it takes up
  9911. (UndoableAction::getSizeInUnits()), so this
  9912. lets you specify the maximum total number of
  9913. units that the undomanager is allowed to
  9914. keep in memory before letting the older actions
  9915. drop off the end of the list.
  9916. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9917. that will be kept, even if this involves exceeding
  9918. the amount of space specified in maxNumberOfUnitsToKeep
  9919. @see getNumberOfUnitsTakenUpByStoredCommands
  9920. */
  9921. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  9922. int minimumTransactionsToKeep);
  9923. /** Performs an action and adds it to the undo history list.
  9924. @param action the action to perform - this will be deleted by the UndoManager
  9925. when no longer needed
  9926. @param actionName if this string is non-empty, the current transaction will be
  9927. given this name; if it's empty, the current transaction name will
  9928. be left unchanged. See setCurrentTransactionName()
  9929. @returns true if the command succeeds - see UndoableAction::perform
  9930. @see beginNewTransaction
  9931. */
  9932. bool perform (UndoableAction* action,
  9933. const String& actionName = String::empty);
  9934. /** Starts a new group of actions that together will be treated as a single transaction.
  9935. All actions that are passed to the perform() method between calls to this
  9936. method are grouped together and undone/redone together by a single call to
  9937. undo() or redo().
  9938. @param actionName a description of the transaction that is about to be
  9939. performed
  9940. */
  9941. void beginNewTransaction (const String& actionName = String::empty);
  9942. /** Changes the name stored for the current transaction.
  9943. Each transaction is given a name when the beginNewTransaction() method is
  9944. called, but this can be used to change that name without starting a new
  9945. transaction.
  9946. */
  9947. void setCurrentTransactionName (const String& newName);
  9948. /** Returns true if there's at least one action in the list to undo.
  9949. @see getUndoDescription, undo, canRedo
  9950. */
  9951. bool canUndo() const;
  9952. /** Returns the description of the transaction that would be next to get undone.
  9953. The description returned is the one that was passed into beginNewTransaction
  9954. before the set of actions was performed.
  9955. @see undo
  9956. */
  9957. const String getUndoDescription() const;
  9958. /** Tries to roll-back the last transaction.
  9959. @returns true if the transaction can be undone, and false if it fails, or
  9960. if there aren't any transactions to undo
  9961. */
  9962. bool undo();
  9963. /** Tries to roll-back any actions that were added to the current transaction.
  9964. This will perform an undo() only if there are some actions in the undo list
  9965. that were added after the last call to beginNewTransaction().
  9966. This is useful because it lets you call beginNewTransaction(), then
  9967. perform an operation which may or may not actually perform some actions, and
  9968. then call this method to get rid of any actions that might have been done
  9969. without it rolling back the previous transaction if nothing was actually
  9970. done.
  9971. @returns true if any actions were undone.
  9972. */
  9973. bool undoCurrentTransactionOnly();
  9974. /** Returns a list of the UndoableAction objects that have been performed during the
  9975. transaction that is currently open.
  9976. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9977. were to be called now.
  9978. The first item in the list is the earliest action performed.
  9979. */
  9980. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9981. /** Returns the number of UndoableAction objects that have been performed during the
  9982. transaction that is currently open.
  9983. @see getActionsInCurrentTransaction
  9984. */
  9985. int getNumActionsInCurrentTransaction() const;
  9986. /** Returns true if there's at least one action in the list to redo.
  9987. @see getRedoDescription, redo, canUndo
  9988. */
  9989. bool canRedo() const;
  9990. /** Returns the description of the transaction that would be next to get redone.
  9991. The description returned is the one that was passed into beginNewTransaction
  9992. before the set of actions was performed.
  9993. @see redo
  9994. */
  9995. const String getRedoDescription() const;
  9996. /** Tries to redo the last transaction that was undone.
  9997. @returns true if the transaction can be redone, and false if it fails, or
  9998. if there aren't any transactions to redo
  9999. */
  10000. bool redo();
  10001. juce_UseDebuggingNewOperator
  10002. private:
  10003. OwnedArray <OwnedArray <UndoableAction> > transactions;
  10004. StringArray transactionNames;
  10005. String currentTransactionName;
  10006. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  10007. bool newTransaction, reentrancyCheck;
  10008. // disallow copy constructor
  10009. UndoManager (const UndoManager&);
  10010. UndoManager& operator= (const UndoManager&);
  10011. };
  10012. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  10013. /*** End of inlined file: juce_UndoManager.h ***/
  10014. /**
  10015. A powerful tree structure that can be used to hold free-form data, and which can
  10016. handle its own undo and redo behaviour.
  10017. A ValueTree contains a list of named properties as var objects, and also holds
  10018. any number of sub-trees.
  10019. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  10020. they're simply a lightweight reference to a shared data container. Creating a copy
  10021. of another ValueTree simply creates a new reference to the same underlying object - to
  10022. make a separate, deep copy of a tree you should explicitly call createCopy().
  10023. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  10024. and much of the structure of a ValueTree is similar to an XmlElement tree.
  10025. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  10026. contain text elements, the conversion works well and makes a good serialisation
  10027. format. They can also be serialised to a binary format, which is very fast and compact.
  10028. All the methods that change data take an optional UndoManager, which will be used
  10029. to track any changes to the object. For this to work, you have to be careful to
  10030. consistently always use the same UndoManager for all operations to any node inside
  10031. the tree.
  10032. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  10033. one tree to another, be careful to always remove it first, before adding it. This
  10034. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  10035. assertions if you try to do anything dangerous, but there are still plenty of ways it
  10036. could go wrong.
  10037. Listeners can be added to a ValueTree to be told when properies change and when
  10038. nodes are added or removed.
  10039. @see var, XmlElement
  10040. */
  10041. class JUCE_API ValueTree
  10042. {
  10043. public:
  10044. /** Creates an empty, invalid ValueTree.
  10045. A ValueTree that is created with this constructor can't actually be used for anything,
  10046. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  10047. To create a real one, use the constructor that takes a string.
  10048. @see ValueTree::invalid
  10049. */
  10050. ValueTree() throw();
  10051. /** Creates an empty ValueTree with the given type name.
  10052. Like an XmlElement, each ValueTree node has a type, which you can access with
  10053. getType() and hasType().
  10054. */
  10055. explicit ValueTree (const Identifier& type);
  10056. /** Creates a reference to another ValueTree. */
  10057. ValueTree (const ValueTree& other);
  10058. /** Makes this object reference another node. */
  10059. ValueTree& operator= (const ValueTree& other);
  10060. /** Destructor. */
  10061. ~ValueTree();
  10062. /** Returns true if both this and the other tree node refer to the same underlying structure.
  10063. Note that this isn't a value comparison - two independently-created trees which
  10064. contain identical data are not considered equal.
  10065. */
  10066. bool operator== (const ValueTree& other) const throw();
  10067. /** Returns true if this and the other node refer to different underlying structures.
  10068. Note that this isn't a value comparison - two independently-created trees which
  10069. contain identical data are not considered equal.
  10070. */
  10071. bool operator!= (const ValueTree& other) const throw();
  10072. /** Performs a deep comparison between the properties and children of two trees.
  10073. If all the properties and children of the two trees are the same (recursively), this
  10074. returns true.
  10075. The normal operator==() only checks whether two trees refer to the same shared data
  10076. structure, so use this method if you need to do a proper value comparison.
  10077. */
  10078. bool isEquivalentTo (const ValueTree& other) const;
  10079. /** Returns true if this node refers to some valid data.
  10080. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  10081. call to getChild().
  10082. */
  10083. bool isValid() const { return object != 0; }
  10084. /** Returns a deep copy of this tree and all its sub-nodes. */
  10085. ValueTree createCopy() const;
  10086. /** Returns the type of this node.
  10087. The type is specified when the ValueTree is created.
  10088. @see hasType
  10089. */
  10090. const Identifier getType() const;
  10091. /** Returns true if the node has this type.
  10092. The comparison is case-sensitive.
  10093. */
  10094. bool hasType (const Identifier& typeName) const;
  10095. /** Returns the value of a named property.
  10096. If no such property has been set, this will return a void variant.
  10097. You can also use operator[] to get a property.
  10098. @see var, setProperty, hasProperty
  10099. */
  10100. const var& getProperty (const Identifier& name) const;
  10101. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  10102. If no such property has been set, this will return the value of defaultReturnValue.
  10103. You can also use operator[] and getProperty to get a property.
  10104. @see var, getProperty, setProperty, hasProperty
  10105. */
  10106. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10107. /** Returns the value of a named property.
  10108. If no such property has been set, this will return a void variant. This is the same as
  10109. calling getProperty().
  10110. @see getProperty
  10111. */
  10112. const var& operator[] (const Identifier& name) const;
  10113. /** Changes a named property of the node.
  10114. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10115. so that this change can be undone.
  10116. @see var, getProperty, removeProperty
  10117. */
  10118. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  10119. /** Returns true if the node contains a named property. */
  10120. bool hasProperty (const Identifier& name) const;
  10121. /** Removes a property from the node.
  10122. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10123. so that this change can be undone.
  10124. */
  10125. void removeProperty (const Identifier& name, UndoManager* undoManager);
  10126. /** Removes all properties from the node.
  10127. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10128. so that this change can be undone.
  10129. */
  10130. void removeAllProperties (UndoManager* undoManager);
  10131. /** Returns the total number of properties that the node contains.
  10132. @see getProperty.
  10133. */
  10134. int getNumProperties() const;
  10135. /** Returns the identifier of the property with a given index.
  10136. @see getNumProperties
  10137. */
  10138. const Identifier getPropertyName (int index) const;
  10139. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  10140. The Value object will maintain a reference to this tree, and will use the undo manager when
  10141. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10142. callbacks whenever the property changes.
  10143. */
  10144. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10145. /** Returns the number of child nodes belonging to this one.
  10146. @see getChild
  10147. */
  10148. int getNumChildren() const;
  10149. /** Returns one of this node's child nodes.
  10150. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10151. whether a node is valid).
  10152. */
  10153. ValueTree getChild (int index) const;
  10154. /** Returns the first child node with the speficied type name.
  10155. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10156. whether a node is valid).
  10157. @see getOrCreateChildWithName
  10158. */
  10159. ValueTree getChildWithName (const Identifier& type) const;
  10160. /** Returns the first child node with the speficied type name, creating and adding
  10161. a child with this name if there wasn't already one there.
  10162. The only time this will return an invalid object is when the object that you're calling
  10163. the method on is itself invalid.
  10164. @see getChildWithName
  10165. */
  10166. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10167. /** Looks for the first child node that has the speficied property value.
  10168. This will scan the child nodes in order, until it finds one that has property that matches
  10169. the specified value.
  10170. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10171. whether a node is valid).
  10172. */
  10173. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10174. /** Adds a child to this node.
  10175. Make sure that the child is removed from any former parent node before calling this, or
  10176. you'll hit an assertion.
  10177. If the index is < 0 or greater than the current number of child nodes, the new node will
  10178. be added at the end of the list.
  10179. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10180. so that this change can be undone.
  10181. */
  10182. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10183. /** Removes the specified child from this node's child-list.
  10184. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10185. so that this change can be undone.
  10186. */
  10187. void removeChild (const ValueTree& child, UndoManager* undoManager);
  10188. /** Removes a child from this node's child-list.
  10189. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10190. so that this change can be undone.
  10191. */
  10192. void removeChild (int childIndex, UndoManager* undoManager);
  10193. /** Removes all child-nodes from this node.
  10194. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10195. so that this change can be undone.
  10196. */
  10197. void removeAllChildren (UndoManager* undoManager);
  10198. /** Moves one of the children to a different index.
  10199. This will move the child to a specified index, shuffling along any intervening
  10200. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10201. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10202. @param currentIndex the index of the item to be moved. If this isn't a
  10203. valid index, then nothing will be done
  10204. @param newIndex the index at which you'd like this item to end up. If this
  10205. is less than zero, the value will be moved to the end
  10206. of the list
  10207. @param undoManager the optional UndoManager to use to store this transaction
  10208. */
  10209. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10210. /** Returns true if this node is anywhere below the specified parent node.
  10211. This returns true if the node is a child-of-a-child, as well as a direct child.
  10212. */
  10213. bool isAChildOf (const ValueTree& possibleParent) const;
  10214. /** Returns the index of a child item in this parent.
  10215. If the child isn't found, this returns -1.
  10216. */
  10217. int indexOf (const ValueTree& child) const;
  10218. /** Returns the parent node that contains this one.
  10219. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10220. whether a node is valid).
  10221. */
  10222. ValueTree getParent() const;
  10223. /** Returns one of this node's siblings in its parent's child list.
  10224. The delta specifies how far to move through the list, so a value of 1 would return the node
  10225. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  10226. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  10227. */
  10228. ValueTree getSibling (int delta) const;
  10229. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10230. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10231. be used to recreate a similar node by calling fromXml()
  10232. @see fromXml
  10233. */
  10234. XmlElement* createXml() const;
  10235. /** Tries to recreate a node from its XML representation.
  10236. This isn't designed to cope with random XML data - for a sensible result, it should only
  10237. be fed XML that was created by the createXml() method.
  10238. */
  10239. static ValueTree fromXml (const XmlElement& xml);
  10240. /** Stores this tree (and all its children) in a binary format.
  10241. Once written, the data can be read back with readFromStream().
  10242. It's much faster to load/save your tree in binary form than as XML, but
  10243. obviously isn't human-readable.
  10244. */
  10245. void writeToStream (OutputStream& output);
  10246. /** Reloads a tree from a stream that was written with writeToStream(). */
  10247. static ValueTree readFromStream (InputStream& input);
  10248. /** Reloads a tree from a data block that was written with writeToStream(). */
  10249. static ValueTree readFromData (const void* data, size_t numBytes);
  10250. /** Listener class for events that happen to a ValueTree.
  10251. To get events from a ValueTree, make your class implement this interface, and use
  10252. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10253. */
  10254. class JUCE_API Listener
  10255. {
  10256. public:
  10257. /** Destructor. */
  10258. virtual ~Listener() {}
  10259. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10260. changed.
  10261. The tree parameter indicates which tree has had its property changed, and the property
  10262. parameter indicates the property.
  10263. Note that when you register a listener to a tree, it will receive this callback for
  10264. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10265. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10266. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10267. */
  10268. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10269. const Identifier& property) = 0;
  10270. /** This method is called when a child sub-tree is added or removed.
  10271. The tree parameter indicates the tree whose child was added or removed.
  10272. Note that when you register a listener to a tree, it will receive this callback for
  10273. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10274. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10275. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10276. */
  10277. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10278. /** This method is called when a tree has been added or removed from a parent node.
  10279. This callback happens when the tree to which the listener was registered is added or
  10280. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10281. the listener is registered, and not to any of its children.
  10282. */
  10283. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10284. };
  10285. /** Adds a listener to receive callbacks when this node is changed.
  10286. The listener is added to this specific ValueTree object, and not to the shared
  10287. object that it refers to. When this object is deleted, all the listeners will
  10288. be lost, even if other references to the same ValueTree still exist. And if you
  10289. use the operator= to make this refer to a different ValueTree, any listeners will
  10290. begin listening to changes to the new tree instead of the old one.
  10291. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10292. will last for as long as you need the listener. In general, you'd never want to add a
  10293. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10294. @see removeListener
  10295. */
  10296. void addListener (Listener* listener);
  10297. /** Removes a listener that was previously added with addListener(). */
  10298. void removeListener (Listener* listener);
  10299. /** This method uses a comparator object to sort the tree's children into order.
  10300. The object provided must have a method of the form:
  10301. @code
  10302. int compareElements (const ValueTree& first, const ValueTree& second);
  10303. @endcode
  10304. ..and this method must return:
  10305. - a value of < 0 if the first comes before the second
  10306. - a value of 0 if the two objects are equivalent
  10307. - a value of > 0 if the second comes before the first
  10308. To improve performance, the compareElements() method can be declared as static or const.
  10309. @param comparator the comparator to use for comparing elements.
  10310. @param retainOrderOfEquivalentItems if this is true, then items
  10311. which the comparator says are equivalent will be
  10312. kept in the order in which they currently appear
  10313. in the array. This is slower to perform, but may
  10314. be important in some cases. If it's false, a faster
  10315. algorithm is used, but equivalent elements may be
  10316. rearranged.
  10317. */
  10318. template <typename ElementComparator>
  10319. void sort (ElementComparator& comparator, const bool retainOrderOfEquivalentItems = false)
  10320. {
  10321. if (object != 0)
  10322. {
  10323. ComparatorAdapter <ElementComparator> adapter (comparator);
  10324. object->children.sort (adapter, retainOrderOfEquivalentItems);
  10325. object->sendChildChangeMessage();
  10326. }
  10327. }
  10328. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10329. This invalid object is equivalent to ValueTree created with its default constructor.
  10330. */
  10331. static const ValueTree invalid;
  10332. juce_UseDebuggingNewOperator
  10333. private:
  10334. class SetPropertyAction;
  10335. friend class SetPropertyAction;
  10336. class AddOrRemoveChildAction;
  10337. friend class AddOrRemoveChildAction;
  10338. class MoveChildAction;
  10339. friend class MoveChildAction;
  10340. class JUCE_API SharedObject : public ReferenceCountedObject
  10341. {
  10342. public:
  10343. explicit SharedObject (const Identifier& type);
  10344. SharedObject (const SharedObject& other);
  10345. ~SharedObject();
  10346. const Identifier type;
  10347. NamedValueSet properties;
  10348. ReferenceCountedArray <SharedObject> children;
  10349. SortedSet <ValueTree*> valueTreesWithListeners;
  10350. SharedObject* parent;
  10351. void sendPropertyChangeMessage (const Identifier& property);
  10352. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10353. void sendChildChangeMessage();
  10354. void sendChildChangeMessage (ValueTree& tree);
  10355. void sendParentChangeMessage();
  10356. const var& getProperty (const Identifier& name) const;
  10357. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10358. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10359. bool hasProperty (const Identifier& name) const;
  10360. void removeProperty (const Identifier& name, UndoManager*);
  10361. void removeAllProperties (UndoManager*);
  10362. bool isAChildOf (const SharedObject* possibleParent) const;
  10363. int indexOf (const ValueTree& child) const;
  10364. ValueTree getChildWithName (const Identifier& type) const;
  10365. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10366. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10367. void addChild (SharedObject* child, int index, UndoManager*);
  10368. void removeChild (int childIndex, UndoManager*);
  10369. void removeAllChildren (UndoManager*);
  10370. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10371. bool isEquivalentTo (const SharedObject& other) const;
  10372. XmlElement* createXml() const;
  10373. juce_UseDebuggingNewOperator
  10374. private:
  10375. SharedObject& operator= (const SharedObject&);
  10376. };
  10377. template <typename ElementComparator>
  10378. class ComparatorAdapter
  10379. {
  10380. public:
  10381. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10382. int compareElements (SharedObject* const first, SharedObject* const second)
  10383. {
  10384. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10385. }
  10386. private:
  10387. ElementComparator& comparator;
  10388. ComparatorAdapter (const ComparatorAdapter&);
  10389. ComparatorAdapter& operator= (const ComparatorAdapter&);
  10390. };
  10391. friend class SharedObject;
  10392. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10393. SharedObjectPtr object;
  10394. ListenerList <Listener> listeners;
  10395. #if JUCE_MSVC && ! DOXYGEN
  10396. public: // (workaround for VC6)
  10397. #endif
  10398. explicit ValueTree (SharedObject*);
  10399. };
  10400. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10401. /*** End of inlined file: juce_ValueTree.h ***/
  10402. #endif
  10403. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10404. #endif
  10405. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  10406. #endif
  10407. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  10408. #endif
  10409. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10410. /*** Start of inlined file: juce_FileLogger.h ***/
  10411. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10412. #define __JUCE_FILELOGGER_JUCEHEADER__
  10413. /**
  10414. A simple implemenation of a Logger that writes to a file.
  10415. @see Logger
  10416. */
  10417. class JUCE_API FileLogger : public Logger
  10418. {
  10419. public:
  10420. /** Creates a FileLogger for a given file.
  10421. @param fileToWriteTo the file that to use - new messages will be appended
  10422. to the file. If the file doesn't exist, it will be created,
  10423. along with any parent directories that are needed.
  10424. @param welcomeMessage when opened, the logger will write a header to the log, along
  10425. with the current date and time, and this welcome message
  10426. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10427. but is larger than this number of bytes, then the start of the
  10428. file will be truncated to keep the size down. This prevents a log
  10429. file getting ridiculously large over time. The file will be truncated
  10430. at a new-line boundary. If this value is less than zero, no size limit
  10431. will be imposed; if it's zero, the file will always be deleted. Note that
  10432. the size is only checked once when this object is created - any logging
  10433. that is done later will be appended without any checking
  10434. */
  10435. FileLogger (const File& fileToWriteTo,
  10436. const String& welcomeMessage,
  10437. const int maxInitialFileSizeBytes = 128 * 1024);
  10438. /** Destructor. */
  10439. ~FileLogger();
  10440. void logMessage (const String& message);
  10441. const File getLogFile() const { return logFile; }
  10442. /** Helper function to create a log file in the correct place for this platform.
  10443. On Windows this will return a logger with a path such as:
  10444. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10445. On the Mac it'll create something like:
  10446. ~/Library/Logs/[logFileName]
  10447. The method might return 0 if the file can't be created for some reason.
  10448. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10449. it's best to use the something like the name of your application here.
  10450. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10451. call it "log.txt" because if it goes in a directory with logs
  10452. from other applications (as it will do on the Mac) then no-one
  10453. will know which one is yours!
  10454. @param welcomeMessage a message that will be written to the log when it's opened.
  10455. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10456. */
  10457. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10458. const String& logFileName,
  10459. const String& welcomeMessage,
  10460. const int maxInitialFileSizeBytes = 128 * 1024);
  10461. juce_UseDebuggingNewOperator
  10462. private:
  10463. File logFile;
  10464. CriticalSection logLock;
  10465. ScopedPointer <FileOutputStream> logStream;
  10466. void trimFileSize (int maxFileSizeBytes) const;
  10467. FileLogger (const FileLogger&);
  10468. FileLogger& operator= (const FileLogger&);
  10469. };
  10470. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10471. /*** End of inlined file: juce_FileLogger.h ***/
  10472. #endif
  10473. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10474. /*** Start of inlined file: juce_Initialisation.h ***/
  10475. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10476. #define __JUCE_INITIALISATION_JUCEHEADER__
  10477. /** Initialises Juce's GUI classes.
  10478. If you're embedding Juce into an application that uses its own event-loop rather
  10479. than using the START_JUCE_APPLICATION macro, call this function before making any
  10480. Juce calls, to make sure things are initialised correctly.
  10481. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10482. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10483. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10484. */
  10485. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  10486. /** Clears up any static data being used by Juce's GUI classes.
  10487. If you're embedding Juce into an application that uses its own event-loop rather
  10488. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10489. code to clean up any juce objects that might be lying around.
  10490. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10491. */
  10492. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  10493. /** Initialises the core parts of Juce.
  10494. If you're embedding Juce into either a command-line program, call this function
  10495. at the start of your main() function to make sure that Juce is initialised correctly.
  10496. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10497. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10498. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10499. */
  10500. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  10501. /** Clears up any static data being used by Juce's non-gui core classes.
  10502. If you're embedding Juce into either a command-line program, call this function
  10503. at the end of your main() function if you want to make sure any Juce objects are
  10504. cleaned up correctly.
  10505. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10506. */
  10507. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  10508. /** A utility object that helps you initialise and shutdown Juce correctly
  10509. using an RAII pattern.
  10510. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10511. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10512. make sure that these functions are matched correctly.
  10513. This class is particularly handy to use at the beginning of a console app's
  10514. main() function, because it'll take care of shutting down whenever you return
  10515. from the main() call.
  10516. @see ScopedJuceInitialiser_GUI
  10517. */
  10518. class ScopedJuceInitialiser_NonGUI
  10519. {
  10520. public:
  10521. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10522. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10523. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10524. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10525. };
  10526. /** A utility object that helps you initialise and shutdown Juce correctly
  10527. using an RAII pattern.
  10528. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10529. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10530. make sure that these functions are matched correctly.
  10531. This class is particularly handy to use at the beginning of a console app's
  10532. main() function, because it'll take care of shutting down whenever you return
  10533. from the main() call.
  10534. @see ScopedJuceInitialiser_NonGUI
  10535. */
  10536. class ScopedJuceInitialiser_GUI
  10537. {
  10538. public:
  10539. /** The constructor simply calls initialiseJuce_GUI(). */
  10540. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10541. /** The destructor simply calls shutdownJuce_GUI(). */
  10542. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10543. };
  10544. /*
  10545. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  10546. AppSubClass is the name of a class derived from JUCEApplication.
  10547. See the JUCEApplication class documentation (juce_Application.h) for more details.
  10548. */
  10549. #if defined (JUCE_GCC) || defined (__MWERKS__)
  10550. #define START_JUCE_APPLICATION(AppClass) \
  10551. int main (int argc, char* argv[]) \
  10552. { \
  10553. JUCE_NAMESPACE::ScopedJuceInitialiser_GUI libraryInitialiser; \
  10554. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv, new AppClass()); \
  10555. }
  10556. #elif JUCE_WINDOWS
  10557. #ifdef _CONSOLE
  10558. #define START_JUCE_APPLICATION(AppClass) \
  10559. int main (int, char* argv[]) \
  10560. { \
  10561. JUCE_NAMESPACE::ScopedJuceInitialiser_GUI libraryInitialiser; \
  10562. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams(), new AppClass()); \
  10563. }
  10564. #elif ! defined (_AFXDLL)
  10565. #ifdef _WINDOWS_
  10566. #define START_JUCE_APPLICATION(AppClass) \
  10567. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  10568. { \
  10569. JUCE_NAMESPACE::ScopedJuceInitialiser_GUI libraryInitialiser; \
  10570. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams(), new AppClass()); \
  10571. }
  10572. #else
  10573. #define START_JUCE_APPLICATION(AppClass) \
  10574. int __stdcall WinMain (int, int, const char*, int) \
  10575. { \
  10576. JUCE_NAMESPACE::ScopedJuceInitialiser_GUI libraryInitialiser; \
  10577. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams(), new AppClass()); \
  10578. }
  10579. #endif
  10580. #endif
  10581. #endif
  10582. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10583. /*** End of inlined file: juce_Initialisation.h ***/
  10584. #endif
  10585. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10586. #endif
  10587. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  10588. #endif
  10589. #ifndef __JUCE_MEMORY_JUCEHEADER__
  10590. #endif
  10591. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10592. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10593. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10594. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10595. /** A timer for measuring performance of code and dumping the results to a file.
  10596. e.g. @code
  10597. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10598. for (;;)
  10599. {
  10600. pc.start();
  10601. doSomethingFishy();
  10602. pc.stop();
  10603. }
  10604. @endcode
  10605. In this example, the time of each period between calling start/stop will be
  10606. measured and averaged over 50 runs, and the results printed to a file
  10607. every 50 times round the loop.
  10608. */
  10609. class JUCE_API PerformanceCounter
  10610. {
  10611. public:
  10612. /** Creates a PerformanceCounter object.
  10613. @param counterName the name used when printing out the statistics
  10614. @param runsPerPrintout the number of start/stop iterations before calling
  10615. printStatistics()
  10616. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10617. the results are just written to the debugger output
  10618. */
  10619. PerformanceCounter (const String& counterName,
  10620. int runsPerPrintout = 100,
  10621. const File& loggingFile = File::nonexistent);
  10622. /** Destructor. */
  10623. ~PerformanceCounter();
  10624. /** Starts timing.
  10625. @see stop
  10626. */
  10627. void start();
  10628. /** Stops timing and prints out the results.
  10629. The number of iterations before doing a printout of the
  10630. results is set in the constructor.
  10631. @see start
  10632. */
  10633. void stop();
  10634. /** Dumps the current metrics to the debugger output and to a file.
  10635. As well as using Logger::outputDebugString to print the results,
  10636. this will write then to the file specified in the constructor (if
  10637. this was valid).
  10638. */
  10639. void printStatistics();
  10640. juce_UseDebuggingNewOperator
  10641. private:
  10642. String name;
  10643. int numRuns, runsPerPrint;
  10644. double totalTime;
  10645. int64 started;
  10646. File outputFile;
  10647. };
  10648. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10649. /*** End of inlined file: juce_PerformanceCounter.h ***/
  10650. #endif
  10651. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  10652. #endif
  10653. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10654. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  10655. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10656. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10657. /**
  10658. A collection of miscellaneous platform-specific utilities.
  10659. */
  10660. class JUCE_API PlatformUtilities
  10661. {
  10662. public:
  10663. /** Plays the operating system's default alert 'beep' sound. */
  10664. static void beep();
  10665. /** Tries to launch the system's default reader for a given file or URL. */
  10666. static bool openDocument (const String& documentURL, const String& parameters);
  10667. /** Tries to launch the system's default email app to let the user create an email.
  10668. */
  10669. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  10670. const String& emailSubject,
  10671. const String& bodyText,
  10672. const StringArray& filesToAttach);
  10673. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  10674. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10675. static const String cfStringToJuceString (CFStringRef cfString);
  10676. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10677. static CFStringRef juceStringToCFString (const String& s);
  10678. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10679. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10680. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10681. static const String makePathFromFSRef (FSRef* file);
  10682. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10683. their precomposed equivalents.
  10684. */
  10685. static const String convertToPrecomposedUnicode (const String& s);
  10686. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10687. static OSType getTypeOfFile (const String& filename);
  10688. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10689. static bool isBundle (const String& filename);
  10690. /** MAC ONLY - Adds an item to the dock */
  10691. static void addItemToDock (const File& file);
  10692. /** MAC ONLY - Returns the current OS version number.
  10693. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  10694. */
  10695. static int getOSXMinorVersionNumber();
  10696. #endif
  10697. #if JUCE_WINDOWS || DOXYGEN
  10698. // Some registry helper functions:
  10699. /** WIN32 ONLY - Returns a string from the registry.
  10700. The path is a string for the entire path of a value in the registry,
  10701. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10702. */
  10703. static const String getRegistryValue (const String& regValuePath,
  10704. const String& defaultValue = String::empty);
  10705. /** WIN32 ONLY - Sets a registry value as a string.
  10706. This will take care of creating any groups needed to get to the given
  10707. registry value.
  10708. */
  10709. static void setRegistryValue (const String& regValuePath,
  10710. const String& value);
  10711. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10712. static bool registryValueExists (const String& regValuePath);
  10713. /** WIN32 ONLY - Deletes a registry value. */
  10714. static void deleteRegistryValue (const String& regValuePath);
  10715. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10716. static void deleteRegistryKey (const String& regKeyPath);
  10717. /** WIN32 ONLY - Creates a file association in the registry.
  10718. This lets you set the exe that should be launched by a given file extension.
  10719. @param fileExtension the file extension to associate, including the
  10720. initial dot, e.g. ".txt"
  10721. @param symbolicDescription a space-free short token to identify the file type
  10722. @param fullDescription a human-readable description of the file type
  10723. @param targetExecutable the executable that should be launched
  10724. @param iconResourceNumber the icon that gets displayed for the file type will be
  10725. found by looking up this resource number in the
  10726. executable. Pass 0 here to not use an icon
  10727. */
  10728. static void registerFileAssociation (const String& fileExtension,
  10729. const String& symbolicDescription,
  10730. const String& fullDescription,
  10731. const File& targetExecutable,
  10732. int iconResourceNumber);
  10733. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10734. In a normal Juce application this will be set to the module handle
  10735. of the application executable.
  10736. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10737. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10738. to set the correct module handle in your DllMain() function, because
  10739. the win32 system relies on the correct instance handle when opening windows.
  10740. */
  10741. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10742. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10743. @see getCurrentModuleInstanceHandle()
  10744. */
  10745. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10746. /** WIN32 ONLY - Gets the command-line params as a string.
  10747. This is needed to avoid unicode problems with the argc type params.
  10748. */
  10749. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  10750. #endif
  10751. /** Clears the floating point unit's flags.
  10752. Only has an effect under win32, currently.
  10753. */
  10754. static void fpuReset();
  10755. #if JUCE_LINUX || JUCE_WINDOWS
  10756. /** Loads a dynamically-linked library into the process's address space.
  10757. @param pathOrFilename the platform-dependent name and search path
  10758. @returns a handle which can be used by getProcedureEntryPoint(), or
  10759. zero if it fails.
  10760. @see freeDynamicLibrary, getProcedureEntryPoint
  10761. */
  10762. static void* loadDynamicLibrary (const String& pathOrFilename);
  10763. /** Frees a dynamically-linked library.
  10764. @param libraryHandle a handle created by loadDynamicLibrary
  10765. @see loadDynamicLibrary, getProcedureEntryPoint
  10766. */
  10767. static void freeDynamicLibrary (void* libraryHandle);
  10768. /** Finds a procedure call in a dynamically-linked library.
  10769. @param libraryHandle a library handle returned by loadDynamicLibrary
  10770. @param procedureName the name of the procedure call to try to load
  10771. @returns a pointer to the function if found, or 0 if it fails
  10772. @see loadDynamicLibrary
  10773. */
  10774. static void* getProcedureEntryPoint (void* libraryHandle,
  10775. const String& procedureName);
  10776. #endif
  10777. #if JUCE_LINUX || DOXYGEN
  10778. #endif
  10779. private:
  10780. PlatformUtilities();
  10781. PlatformUtilities (const PlatformUtilities&);
  10782. PlatformUtilities& operator= (const PlatformUtilities&);
  10783. };
  10784. #if JUCE_MAC || JUCE_IOS
  10785. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10786. using RAII.
  10787. */
  10788. class ScopedAutoReleasePool
  10789. {
  10790. public:
  10791. ScopedAutoReleasePool();
  10792. ~ScopedAutoReleasePool();
  10793. private:
  10794. void* pool;
  10795. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10796. ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10797. };
  10798. #define JUCE_AUTORELEASEPOOL const ScopedAutoReleasePool pool;
  10799. #else
  10800. #define JUCE_AUTORELEASEPOOL
  10801. #endif
  10802. #if JUCE_LINUX
  10803. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  10804. using an RAII approach.
  10805. */
  10806. class ScopedXLock
  10807. {
  10808. public:
  10809. /** Creating a ScopedXLock object locks the X display.
  10810. This uses XLockDisplay() to grab the display that Juce is using.
  10811. */
  10812. ScopedXLock();
  10813. /** Deleting a ScopedXLock object unlocks the X display.
  10814. This calls XUnlockDisplay() to release the lock.
  10815. */
  10816. ~ScopedXLock();
  10817. };
  10818. #endif
  10819. #if JUCE_MAC
  10820. /**
  10821. A wrapper class for picking up events from an Apple IR remote control device.
  10822. To use it, just create a subclass of this class, implementing the buttonPressed()
  10823. callback, then call start() and stop() to start or stop receiving events.
  10824. */
  10825. class JUCE_API AppleRemoteDevice
  10826. {
  10827. public:
  10828. AppleRemoteDevice();
  10829. virtual ~AppleRemoteDevice();
  10830. /** The set of buttons that may be pressed.
  10831. @see buttonPressed
  10832. */
  10833. enum ButtonType
  10834. {
  10835. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10836. playButton, /**< The play button. */
  10837. plusButton, /**< The plus or volume-up button. */
  10838. minusButton, /**< The minus or volume-down button. */
  10839. rightButton, /**< The right button (if it's held for a short time). */
  10840. leftButton, /**< The left button (if it's held for a short time). */
  10841. rightButton_Long, /**< The right button (if it's held for a long time). */
  10842. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10843. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10844. playButtonSleepMode,
  10845. switched
  10846. };
  10847. /** Override this method to receive the callback about a button press.
  10848. The callback will happen on the application's message thread.
  10849. Some buttons trigger matching up and down events, in which the isDown parameter
  10850. will be true and then false. Others only send a single event when the
  10851. button is pressed.
  10852. */
  10853. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10854. /** Starts the device running and responding to events.
  10855. Returns true if it managed to open the device.
  10856. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10857. and will not be available to any other part of the system. If
  10858. false, it will be shared with other apps.
  10859. @see stop
  10860. */
  10861. bool start (const bool inExclusiveMode);
  10862. /** Stops the device running.
  10863. @see start
  10864. */
  10865. void stop();
  10866. /** Returns true if the device has been started successfully.
  10867. */
  10868. bool isActive() const;
  10869. /** Returns the ID number of the remote, if it has sent one.
  10870. */
  10871. int getRemoteId() const { return remoteId; }
  10872. juce_UseDebuggingNewOperator
  10873. /** @internal */
  10874. void handleCallbackInternal();
  10875. private:
  10876. void* device;
  10877. void* queue;
  10878. int remoteId;
  10879. bool open (const bool openInExclusiveMode);
  10880. AppleRemoteDevice (const AppleRemoteDevice&);
  10881. AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10882. };
  10883. #endif
  10884. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10885. /*** End of inlined file: juce_PlatformUtilities.h ***/
  10886. #endif
  10887. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10888. /*** Start of inlined file: juce_Random.h ***/
  10889. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10890. #define __JUCE_RANDOM_JUCEHEADER__
  10891. /**
  10892. A simple pseudo-random number generator.
  10893. */
  10894. class JUCE_API Random
  10895. {
  10896. public:
  10897. /** Creates a Random object based on a seed value.
  10898. For a given seed value, the subsequent numbers generated by this object
  10899. will be predictable, so a good idea is to set this value based
  10900. on the time, e.g.
  10901. new Random (Time::currentTimeMillis())
  10902. */
  10903. explicit Random (int64 seedValue) throw();
  10904. /** Destructor. */
  10905. ~Random() throw();
  10906. /** Returns the next random 32 bit integer.
  10907. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10908. */
  10909. int nextInt() throw();
  10910. /** Returns the next random number, limited to a given range.
  10911. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10912. */
  10913. int nextInt (int maxValue) throw();
  10914. /** Returns the next 64-bit random number.
  10915. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10916. */
  10917. int64 nextInt64() throw();
  10918. /** Returns the next random floating-point number.
  10919. @returns a random value in the range 0 to 1.0
  10920. */
  10921. float nextFloat() throw();
  10922. /** Returns the next random floating-point number.
  10923. @returns a random value in the range 0 to 1.0
  10924. */
  10925. double nextDouble() throw();
  10926. /** Returns the next random boolean value.
  10927. */
  10928. bool nextBool() throw();
  10929. /** Returns a BigInteger containing a random number.
  10930. @returns a random value in the range 0 to (maximumValue - 1).
  10931. */
  10932. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  10933. /** Sets a range of bits in a BigInteger to random values. */
  10934. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  10935. /** To avoid the overhead of having to create a new Random object whenever
  10936. you need a number, this is a shared application-wide object that
  10937. can be used.
  10938. It's not thread-safe though, so threads should use their own Random object.
  10939. */
  10940. static Random& getSystemRandom() throw();
  10941. /** Resets this Random object to a given seed value. */
  10942. void setSeed (int64 newSeed) throw();
  10943. /** Merges this object's seed with another value.
  10944. This sets the seed to be a value created by combining the current seed and this
  10945. new value.
  10946. */
  10947. void combineSeed (int64 seedValue) throw();
  10948. /** Reseeds this generator using a value generated from various semi-random system
  10949. properties like the current time, etc.
  10950. Because this function convolves the time with the last seed value, calling
  10951. it repeatedly will increase the randomness of the final result.
  10952. */
  10953. void setSeedRandomly();
  10954. juce_UseDebuggingNewOperator
  10955. private:
  10956. int64 seed;
  10957. };
  10958. #endif // __JUCE_RANDOM_JUCEHEADER__
  10959. /*** End of inlined file: juce_Random.h ***/
  10960. #endif
  10961. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10962. #endif
  10963. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10964. /*** Start of inlined file: juce_Singleton.h ***/
  10965. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10966. #define __JUCE_SINGLETON_JUCEHEADER__
  10967. /**
  10968. Macro to declare member variables and methods for a singleton class.
  10969. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10970. to the class's definition.
  10971. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10972. implementation code.
  10973. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10974. destructor, in case it is deleted by other means than deleteInstance()
  10975. Clients can then call the static method MyClass::getInstance() to get a pointer
  10976. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10977. no instance currently exists.
  10978. e.g. @code
  10979. class MySingleton
  10980. {
  10981. public:
  10982. MySingleton()
  10983. {
  10984. }
  10985. ~MySingleton()
  10986. {
  10987. // this ensures that no dangling pointers are left when the
  10988. // singleton is deleted.
  10989. clearSingletonInstance();
  10990. }
  10991. juce_DeclareSingleton (MySingleton, false)
  10992. };
  10993. juce_ImplementSingleton (MySingleton)
  10994. // example of usage:
  10995. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10996. ...
  10997. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10998. @endcode
  10999. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  11000. than once during the process's lifetime - i.e. after you've created and deleted the
  11001. object, getInstance() will refuse to create another one. This can be useful to stop
  11002. objects being accidentally re-created during your app's shutdown code.
  11003. If you know that your object will only be created and deleted by a single thread, you
  11004. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  11005. of this one.
  11006. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  11007. */
  11008. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  11009. \
  11010. static classname* _singletonInstance; \
  11011. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  11012. \
  11013. static classname* JUCE_CALLTYPE getInstance() \
  11014. { \
  11015. if (_singletonInstance == 0) \
  11016. {\
  11017. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  11018. \
  11019. if (_singletonInstance == 0) \
  11020. { \
  11021. static bool alreadyInside = false; \
  11022. static bool createdOnceAlready = false; \
  11023. \
  11024. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  11025. jassert (! problem); \
  11026. if (! problem) \
  11027. { \
  11028. createdOnceAlready = true; \
  11029. alreadyInside = true; \
  11030. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11031. alreadyInside = false; \
  11032. \
  11033. _singletonInstance = newObject; \
  11034. } \
  11035. } \
  11036. } \
  11037. \
  11038. return _singletonInstance; \
  11039. } \
  11040. \
  11041. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  11042. { \
  11043. return _singletonInstance; \
  11044. } \
  11045. \
  11046. static void JUCE_CALLTYPE deleteInstance() \
  11047. { \
  11048. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  11049. if (_singletonInstance != 0) \
  11050. { \
  11051. classname* const old = _singletonInstance; \
  11052. _singletonInstance = 0; \
  11053. delete old; \
  11054. } \
  11055. } \
  11056. \
  11057. void clearSingletonInstance() throw() \
  11058. { \
  11059. if (_singletonInstance == this) \
  11060. _singletonInstance = 0; \
  11061. }
  11062. /** This is a counterpart to the juce_DeclareSingleton macro.
  11063. After adding the juce_DeclareSingleton to the class definition, this macro has
  11064. to be used in the cpp file.
  11065. */
  11066. #define juce_ImplementSingleton(classname) \
  11067. \
  11068. classname* classname::_singletonInstance = 0; \
  11069. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  11070. /**
  11071. Macro to declare member variables and methods for a singleton class.
  11072. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  11073. section to make access to it thread-safe. If you know that your object will
  11074. only ever be created or deleted by a single thread, then this is a
  11075. more efficient version to use.
  11076. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  11077. than once during the process's lifetime - i.e. after you've created and deleted the
  11078. object, getInstance() will refuse to create another one. This can be useful to stop
  11079. objects being accidentally re-created during your app's shutdown code.
  11080. See the documentation for juce_DeclareSingleton for more information about
  11081. how to use it, the only difference being that you have to use
  11082. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11083. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  11084. */
  11085. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  11086. \
  11087. static classname* _singletonInstance; \
  11088. \
  11089. static classname* getInstance() \
  11090. { \
  11091. if (_singletonInstance == 0) \
  11092. { \
  11093. static bool alreadyInside = false; \
  11094. static bool createdOnceAlready = false; \
  11095. \
  11096. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  11097. jassert (! problem); \
  11098. if (! problem) \
  11099. { \
  11100. createdOnceAlready = true; \
  11101. alreadyInside = true; \
  11102. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11103. alreadyInside = false; \
  11104. \
  11105. _singletonInstance = newObject; \
  11106. } \
  11107. } \
  11108. \
  11109. return _singletonInstance; \
  11110. } \
  11111. \
  11112. static inline classname* getInstanceWithoutCreating() throw() \
  11113. { \
  11114. return _singletonInstance; \
  11115. } \
  11116. \
  11117. static void deleteInstance() \
  11118. { \
  11119. if (_singletonInstance != 0) \
  11120. { \
  11121. classname* const old = _singletonInstance; \
  11122. _singletonInstance = 0; \
  11123. delete old; \
  11124. } \
  11125. } \
  11126. \
  11127. void clearSingletonInstance() throw() \
  11128. { \
  11129. if (_singletonInstance == this) \
  11130. _singletonInstance = 0; \
  11131. }
  11132. /**
  11133. Macro to declare member variables and methods for a singleton class.
  11134. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  11135. for recursion or repeated instantiation. It's intended for use as a lightweight
  11136. version of a singleton, where you're using it in very straightforward
  11137. circumstances and don't need the extra checking.
  11138. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  11139. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  11140. See the documentation for juce_DeclareSingleton for more information about
  11141. how to use it, the only difference being that you have to use
  11142. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11143. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  11144. */
  11145. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  11146. \
  11147. static classname* _singletonInstance; \
  11148. \
  11149. static classname* getInstance() \
  11150. { \
  11151. if (_singletonInstance == 0) \
  11152. _singletonInstance = new classname(); \
  11153. \
  11154. return _singletonInstance; \
  11155. } \
  11156. \
  11157. static inline classname* getInstanceWithoutCreating() throw() \
  11158. { \
  11159. return _singletonInstance; \
  11160. } \
  11161. \
  11162. static void deleteInstance() \
  11163. { \
  11164. if (_singletonInstance != 0) \
  11165. { \
  11166. classname* const old = _singletonInstance; \
  11167. _singletonInstance = 0; \
  11168. delete old; \
  11169. } \
  11170. } \
  11171. \
  11172. void clearSingletonInstance() throw() \
  11173. { \
  11174. if (_singletonInstance == this) \
  11175. _singletonInstance = 0; \
  11176. }
  11177. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  11178. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  11179. to the class definition, this macro has to be used somewhere in the cpp file.
  11180. */
  11181. #define juce_ImplementSingleton_SingleThreaded(classname) \
  11182. \
  11183. classname* classname::_singletonInstance = 0;
  11184. #endif // __JUCE_SINGLETON_JUCEHEADER__
  11185. /*** End of inlined file: juce_Singleton.h ***/
  11186. #endif
  11187. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  11188. #endif
  11189. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11190. /*** Start of inlined file: juce_SystemStats.h ***/
  11191. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11192. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  11193. /**
  11194. Contains methods for finding out about the current hardware and OS configuration.
  11195. */
  11196. class JUCE_API SystemStats
  11197. {
  11198. public:
  11199. /** Returns the current version of JUCE,
  11200. (just in case you didn't already know at compile-time.)
  11201. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11202. */
  11203. static const String getJUCEVersion();
  11204. /** The set of possible results of the getOperatingSystemType() method.
  11205. */
  11206. enum OperatingSystemType
  11207. {
  11208. UnknownOS = 0,
  11209. MacOSX = 0x1000,
  11210. Linux = 0x2000,
  11211. Win95 = 0x4001,
  11212. Win98 = 0x4002,
  11213. WinNT351 = 0x4103,
  11214. WinNT40 = 0x4104,
  11215. Win2000 = 0x4105,
  11216. WinXP = 0x4106,
  11217. WinVista = 0x4107,
  11218. Windows7 = 0x4108,
  11219. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11220. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11221. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11222. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11223. };
  11224. /** Returns the type of operating system we're running on.
  11225. @returns one of the values from the OperatingSystemType enum.
  11226. @see getOperatingSystemName
  11227. */
  11228. static OperatingSystemType getOperatingSystemType();
  11229. /** Returns the name of the type of operating system we're running on.
  11230. @returns a string describing the OS type.
  11231. @see getOperatingSystemType
  11232. */
  11233. static const String getOperatingSystemName();
  11234. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11235. */
  11236. static bool isOperatingSystem64Bit();
  11237. /** Returns the current user's name, if available.
  11238. @see getFullUserName()
  11239. */
  11240. static const String getLogonName();
  11241. /** Returns the current user's full name, if available.
  11242. On some OSes, this may just return the same value as getLogonName().
  11243. @see getLogonName()
  11244. */
  11245. static const String getFullUserName();
  11246. // CPU and memory information..
  11247. /** Returns the approximate CPU speed.
  11248. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11249. what year you're reading this...)
  11250. */
  11251. static int getCpuSpeedInMegaherz();
  11252. /** Returns a string to indicate the CPU vendor.
  11253. Might not be known on some systems.
  11254. */
  11255. static const String getCpuVendor();
  11256. /** Checks whether Intel MMX instructions are available. */
  11257. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  11258. /** Checks whether Intel SSE instructions are available. */
  11259. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  11260. /** Checks whether Intel SSE2 instructions are available. */
  11261. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  11262. /** Checks whether AMD 3DNOW instructions are available. */
  11263. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  11264. /** Returns the number of CPUs.
  11265. */
  11266. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  11267. /** Finds out how much RAM is in the machine.
  11268. @returns the approximate number of megabytes of memory, or zero if
  11269. something goes wrong when finding out.
  11270. */
  11271. static int getMemorySizeInMegabytes();
  11272. /** Returns the system page-size.
  11273. This is only used by programmers with beards.
  11274. */
  11275. static int getPageSize();
  11276. /** Returns a list of MAC addresses found on this machine.
  11277. @param addresses an array into which the MAC addresses should be copied
  11278. @param maxNum the number of elements in this array
  11279. @param littleEndian the endianness of the numbers to return. If this is true,
  11280. the least-significant byte of each number is the first byte
  11281. of the mac address. If false, the least significant byte is
  11282. the last number. Note that the default values of this parameter
  11283. are different on Mac/PC to avoid breaking old software that was
  11284. written before this parameter was added (when the two systems
  11285. defaulted to using different endiannesses). In newer
  11286. software you probably want to specify an explicit value
  11287. for this.
  11288. @returns the number of MAC addresses that were found
  11289. */
  11290. static int getMACAddresses (int64* addresses, int maxNum,
  11291. #if JUCE_MAC
  11292. bool littleEndian = true);
  11293. #else
  11294. bool littleEndian = false);
  11295. #endif
  11296. /** Returns a list of MAC addresses found on this machine.
  11297. @returns an array of strings containing the MAC addresses that were found
  11298. */
  11299. static const StringArray getMACAddressStrings();
  11300. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11301. static void initialiseStats();
  11302. private:
  11303. struct CPUFlags
  11304. {
  11305. int numCpus;
  11306. bool hasMMX : 1;
  11307. bool hasSSE : 1;
  11308. bool hasSSE2 : 1;
  11309. bool has3DNow : 1;
  11310. };
  11311. static CPUFlags cpuFlags;
  11312. SystemStats();
  11313. SystemStats (const SystemStats&);
  11314. SystemStats& operator= (const SystemStats&);
  11315. };
  11316. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11317. /*** End of inlined file: juce_SystemStats.h ***/
  11318. #endif
  11319. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11320. #endif
  11321. #ifndef __JUCE_TIME_JUCEHEADER__
  11322. #endif
  11323. #ifndef __JUCE_UUID_JUCEHEADER__
  11324. /*** Start of inlined file: juce_Uuid.h ***/
  11325. #ifndef __JUCE_UUID_JUCEHEADER__
  11326. #define __JUCE_UUID_JUCEHEADER__
  11327. /**
  11328. A universally unique 128-bit identifier.
  11329. This class generates very random unique numbers based on the system time
  11330. and MAC addresses if any are available. It's extremely unlikely that two identical
  11331. UUIDs would ever be created by chance.
  11332. The class includes methods for saving the ID as a string or as raw binary data.
  11333. */
  11334. class JUCE_API Uuid
  11335. {
  11336. public:
  11337. /** Creates a new unique ID. */
  11338. Uuid();
  11339. /** Destructor. */
  11340. ~Uuid() throw();
  11341. /** Creates a copy of another UUID. */
  11342. Uuid (const Uuid& other);
  11343. /** Copies another UUID. */
  11344. Uuid& operator= (const Uuid& other);
  11345. /** Returns true if the ID is zero. */
  11346. bool isNull() const throw();
  11347. /** Compares two UUIDs. */
  11348. bool operator== (const Uuid& other) const;
  11349. /** Compares two UUIDs. */
  11350. bool operator!= (const Uuid& other) const;
  11351. /** Returns a stringified version of this UUID.
  11352. A Uuid object can later be reconstructed from this string using operator= or
  11353. the constructor that takes a string parameter.
  11354. @returns a 32 character hex string.
  11355. */
  11356. const String toString() const;
  11357. /** Creates an ID from an encoded string version.
  11358. @see toString
  11359. */
  11360. Uuid (const String& uuidString);
  11361. /** Copies from a stringified UUID.
  11362. The string passed in should be one that was created with the toString() method.
  11363. */
  11364. Uuid& operator= (const String& uuidString);
  11365. /** Returns a pointer to the internal binary representation of the ID.
  11366. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11367. the constructor or operator= method that takes an array of uint8s.
  11368. */
  11369. const uint8* getRawData() const throw() { return value.asBytes; }
  11370. /** Creates a UUID from a 16-byte array.
  11371. @see getRawData
  11372. */
  11373. Uuid (const uint8* const rawData);
  11374. /** Sets this UUID from 16-bytes of raw data. */
  11375. Uuid& operator= (const uint8* const rawData);
  11376. juce_UseDebuggingNewOperator
  11377. private:
  11378. union
  11379. {
  11380. uint8 asBytes [16];
  11381. int asInt[4];
  11382. int64 asInt64[2];
  11383. } value;
  11384. };
  11385. #endif // __JUCE_UUID_JUCEHEADER__
  11386. /*** End of inlined file: juce_Uuid.h ***/
  11387. #endif
  11388. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11389. /*** Start of inlined file: juce_BlowFish.h ***/
  11390. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11391. #define __JUCE_BLOWFISH_JUCEHEADER__
  11392. /**
  11393. BlowFish encryption class.
  11394. */
  11395. class JUCE_API BlowFish
  11396. {
  11397. public:
  11398. /** Creates an object that can encode/decode based on the specified key.
  11399. The key data can be up to 72 bytes long.
  11400. */
  11401. BlowFish (const void* keyData, int keyBytes);
  11402. /** Creates a copy of another blowfish object. */
  11403. BlowFish (const BlowFish& other);
  11404. /** Copies another blowfish object. */
  11405. BlowFish& operator= (const BlowFish& other);
  11406. /** Destructor. */
  11407. ~BlowFish();
  11408. /** Encrypts a pair of 32-bit integers. */
  11409. void encrypt (uint32& data1, uint32& data2) const throw();
  11410. /** Decrypts a pair of 32-bit integers. */
  11411. void decrypt (uint32& data1, uint32& data2) const throw();
  11412. juce_UseDebuggingNewOperator
  11413. private:
  11414. uint32 p[18];
  11415. HeapBlock <uint32> s[4];
  11416. uint32 F (uint32 x) const throw();
  11417. };
  11418. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11419. /*** End of inlined file: juce_BlowFish.h ***/
  11420. #endif
  11421. #ifndef __JUCE_MD5_JUCEHEADER__
  11422. /*** Start of inlined file: juce_MD5.h ***/
  11423. #ifndef __JUCE_MD5_JUCEHEADER__
  11424. #define __JUCE_MD5_JUCEHEADER__
  11425. /**
  11426. MD5 checksum class.
  11427. Create one of these with a block of source data or a string, and it calculates the
  11428. MD5 checksum of that data.
  11429. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11430. */
  11431. class JUCE_API MD5
  11432. {
  11433. public:
  11434. /** Creates a null MD5 object. */
  11435. MD5();
  11436. /** Creates a copy of another MD5. */
  11437. MD5 (const MD5& other);
  11438. /** Copies another MD5. */
  11439. MD5& operator= (const MD5& other);
  11440. /** Creates a checksum for a block of binary data. */
  11441. explicit MD5 (const MemoryBlock& data);
  11442. /** Creates a checksum for a block of binary data. */
  11443. MD5 (const void* data, const size_t numBytes);
  11444. /** Creates a checksum for a string.
  11445. Note that this operates on the string as a block of unicode characters, so the
  11446. result you get will differ from the value you'd get if the string was treated
  11447. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11448. of this method with a checksum created by a different framework, which may have
  11449. used a different encoding.
  11450. */
  11451. explicit MD5 (const String& text);
  11452. /** Creates a checksum for the input from a stream.
  11453. This will read up to the given number of bytes from the stream, and produce the
  11454. checksum of that. If the number of bytes to read is negative, it'll read
  11455. until the stream is exhausted.
  11456. */
  11457. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11458. /** Creates a checksum for a file. */
  11459. explicit MD5 (const File& file);
  11460. /** Destructor. */
  11461. ~MD5();
  11462. /** Returns the checksum as a 16-byte block of data. */
  11463. const MemoryBlock getRawChecksumData() const;
  11464. /** Returns the checksum as a 32-digit hex string. */
  11465. const String toHexString() const;
  11466. /** Compares this to another MD5. */
  11467. bool operator== (const MD5& other) const;
  11468. /** Compares this to another MD5. */
  11469. bool operator!= (const MD5& other) const;
  11470. juce_UseDebuggingNewOperator
  11471. private:
  11472. uint8 result [16];
  11473. struct ProcessContext
  11474. {
  11475. uint8 buffer [64];
  11476. uint32 state [4];
  11477. uint32 count [2];
  11478. ProcessContext();
  11479. void processBlock (const void* data, size_t dataSize);
  11480. void transform (const void* buffer);
  11481. void finish (void* const result);
  11482. };
  11483. void processStream (InputStream& input, int64 numBytesToRead);
  11484. };
  11485. #endif // __JUCE_MD5_JUCEHEADER__
  11486. /*** End of inlined file: juce_MD5.h ***/
  11487. #endif
  11488. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11489. /*** Start of inlined file: juce_Primes.h ***/
  11490. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11491. #define __JUCE_PRIMES_JUCEHEADER__
  11492. /**
  11493. Prime number creation class.
  11494. This class contains static methods for generating and testing prime numbers.
  11495. @see BigInteger
  11496. */
  11497. class JUCE_API Primes
  11498. {
  11499. public:
  11500. /** Creates a random prime number with a given bit-length.
  11501. The certainty parameter specifies how many iterations to use when testing
  11502. for primality. A safe value might be anything over about 20-30.
  11503. The randomSeeds parameter lets you optionally pass it a set of values with
  11504. which to seed the random number generation, improving the security of the
  11505. keys generated.
  11506. */
  11507. static const BigInteger createProbablePrime (int bitLength,
  11508. int certainty,
  11509. const int* randomSeeds = 0,
  11510. int numRandomSeeds = 0);
  11511. /** Tests a number to see if it's prime.
  11512. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  11513. whether the number is prime.
  11514. The certainty parameter specifies how many iterations to use when testing - a
  11515. safe value might be anything over about 20-30.
  11516. */
  11517. static bool isProbablyPrime (const BigInteger& number, int certainty);
  11518. private:
  11519. Primes();
  11520. Primes (const Primes&);
  11521. Primes& operator= (const Primes&);
  11522. };
  11523. #endif // __JUCE_PRIMES_JUCEHEADER__
  11524. /*** End of inlined file: juce_Primes.h ***/
  11525. #endif
  11526. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11527. /*** Start of inlined file: juce_RSAKey.h ***/
  11528. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11529. #define __JUCE_RSAKEY_JUCEHEADER__
  11530. /**
  11531. RSA public/private key-pair encryption class.
  11532. An object of this type makes up one half of a public/private RSA key pair. Use the
  11533. createKeyPair() method to create a matching pair for encoding/decoding.
  11534. */
  11535. class JUCE_API RSAKey
  11536. {
  11537. public:
  11538. /** Creates a null key object.
  11539. Initialise a pair of objects for use with the createKeyPair() method.
  11540. */
  11541. RSAKey();
  11542. /** Loads a key from an encoded string representation.
  11543. This reloads a key from a string created by the toString() method.
  11544. */
  11545. explicit RSAKey (const String& stringRepresentation);
  11546. /** Destructor. */
  11547. ~RSAKey();
  11548. bool operator== (const RSAKey& other) const throw();
  11549. bool operator!= (const RSAKey& other) const throw();
  11550. /** Turns the key into a string representation.
  11551. This can be reloaded using the constructor that takes a string.
  11552. */
  11553. const String toString() const;
  11554. /** Encodes or decodes a value.
  11555. Call this on the public key object to encode some data, then use the matching
  11556. private key object to decode it.
  11557. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  11558. initialised correctly.
  11559. NOTE: This method dumbly applies this key to this data. If you encode some data
  11560. and then try to decode it with a key that doesn't match, this method will still
  11561. happily do its job and return true, but the result won't be what you were expecting.
  11562. It's your responsibility to check that the result is what you wanted.
  11563. */
  11564. bool applyToValue (BigInteger& value) const;
  11565. /** Creates a public/private key-pair.
  11566. Each key will perform one-way encryption that can only be reversed by
  11567. using the other key.
  11568. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  11569. sizes are more secure, but this method will take longer to execute.
  11570. The randomSeeds parameter lets you optionally pass it a set of values with
  11571. which to seed the random number generation, improving the security of the
  11572. keys generated. If you supply these, make sure you provide more than 2 values,
  11573. and the more your provide, the better the security.
  11574. */
  11575. static void createKeyPair (RSAKey& publicKey,
  11576. RSAKey& privateKey,
  11577. int numBits,
  11578. const int* randomSeeds = 0,
  11579. int numRandomSeeds = 0);
  11580. juce_UseDebuggingNewOperator
  11581. protected:
  11582. BigInteger part1, part2;
  11583. private:
  11584. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  11585. };
  11586. #endif // __JUCE_RSAKEY_JUCEHEADER__
  11587. /*** End of inlined file: juce_RSAKey.h ***/
  11588. #endif
  11589. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11590. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  11591. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11592. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11593. /**
  11594. Searches through a the files in a directory, returning each file that is found.
  11595. A DirectoryIterator will search through a directory and its subdirectories using
  11596. a wildcard filepattern match.
  11597. If you may be finding a large number of files, this is better than
  11598. using File::findChildFiles() because it doesn't block while it finds them
  11599. all, and this is more memory-efficient.
  11600. It can also guess how far it's got using a wildly inaccurate algorithm.
  11601. */
  11602. class JUCE_API DirectoryIterator
  11603. {
  11604. public:
  11605. /** Creates a DirectoryIterator for a given directory.
  11606. After creating one of these, call its next() method to get the
  11607. first file - e.g. @code
  11608. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  11609. while (iter.next())
  11610. {
  11611. File theFileItFound (iter.getFile());
  11612. ... etc
  11613. }
  11614. @endcode
  11615. @param directory the directory to search in
  11616. @param isRecursive whether all the subdirectories should also be searched
  11617. @param wildCard the file pattern to match
  11618. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  11619. whether to look for files, directories, or both.
  11620. */
  11621. DirectoryIterator (const File& directory,
  11622. bool isRecursive,
  11623. const String& wildCard = "*",
  11624. int whatToLookFor = File::findFiles);
  11625. /** Destructor. */
  11626. ~DirectoryIterator();
  11627. /** Moves the iterator along to the next file.
  11628. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11629. false if there are no more matching files.
  11630. */
  11631. bool next();
  11632. /** Moves the iterator along to the next file, and returns various properties of that file.
  11633. If you need to find out details about the file, it's more efficient to call this method than
  11634. to call the normal next() method and then find out the details afterwards.
  11635. All the parameters are optional, so pass null pointers for any items that you're not
  11636. interested in.
  11637. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11638. false if there are no more matching files. If it returns false, then none of the
  11639. parameters will be filled-in.
  11640. */
  11641. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  11642. Time* modTime, Time* creationTime, bool* isReadOnly);
  11643. /** Returns the file that the iterator is currently pointing at.
  11644. The result of this call is only valid after a call to next() has returned true.
  11645. */
  11646. const File getFile() const;
  11647. /** Returns a guess of how far through the search the iterator has got.
  11648. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  11649. very accurate.
  11650. */
  11651. float getEstimatedProgress() const;
  11652. juce_UseDebuggingNewOperator
  11653. private:
  11654. friend class File;
  11655. class NativeIterator
  11656. {
  11657. public:
  11658. NativeIterator (const File& directory, const String& wildCard);
  11659. ~NativeIterator();
  11660. bool next (String& filenameFound,
  11661. bool* isDirectory, bool* isHidden, int64* fileSize,
  11662. Time* modTime, Time* creationTime, bool* isReadOnly);
  11663. class Pimpl;
  11664. juce_UseDebuggingNewOperator
  11665. private:
  11666. friend class DirectoryIterator;
  11667. friend class ScopedPointer<Pimpl>;
  11668. ScopedPointer<Pimpl> pimpl;
  11669. NativeIterator (const NativeIterator&);
  11670. NativeIterator& operator= (const NativeIterator&);
  11671. };
  11672. friend class ScopedPointer<NativeIterator::Pimpl>;
  11673. NativeIterator fileFinder;
  11674. String wildCard, path;
  11675. int index;
  11676. mutable int totalNumFiles;
  11677. const int whatToLookFor;
  11678. const bool isRecursive;
  11679. ScopedPointer <DirectoryIterator> subIterator;
  11680. File currentFile;
  11681. DirectoryIterator (const DirectoryIterator&);
  11682. DirectoryIterator& operator= (const DirectoryIterator&);
  11683. };
  11684. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11685. /*** End of inlined file: juce_DirectoryIterator.h ***/
  11686. #endif
  11687. #ifndef __JUCE_FILE_JUCEHEADER__
  11688. #endif
  11689. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11690. /*** Start of inlined file: juce_FileInputStream.h ***/
  11691. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11692. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11693. /**
  11694. An input stream that reads from a local file.
  11695. @see InputStream, FileOutputStream, File::createInputStream
  11696. */
  11697. class JUCE_API FileInputStream : public InputStream
  11698. {
  11699. public:
  11700. /** Creates a FileInputStream.
  11701. @param fileToRead the file to read from - if the file can't be accessed for some
  11702. reason, then the stream will just contain no data
  11703. */
  11704. explicit FileInputStream (const File& fileToRead);
  11705. /** Destructor. */
  11706. ~FileInputStream();
  11707. const File& getFile() const throw() { return file; }
  11708. int64 getTotalLength();
  11709. int read (void* destBuffer, int maxBytesToRead);
  11710. bool isExhausted();
  11711. int64 getPosition();
  11712. bool setPosition (int64 pos);
  11713. juce_UseDebuggingNewOperator
  11714. private:
  11715. File file;
  11716. void* fileHandle;
  11717. int64 currentPosition, totalSize;
  11718. bool needToSeek;
  11719. FileInputStream (const FileInputStream&);
  11720. FileInputStream& operator= (const FileInputStream&);
  11721. };
  11722. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11723. /*** End of inlined file: juce_FileInputStream.h ***/
  11724. #endif
  11725. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11726. /*** Start of inlined file: juce_FileOutputStream.h ***/
  11727. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11728. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11729. /**
  11730. An output stream that writes into a local file.
  11731. @see OutputStream, FileInputStream, File::createOutputStream
  11732. */
  11733. class JUCE_API FileOutputStream : public OutputStream
  11734. {
  11735. public:
  11736. /** Creates a FileOutputStream.
  11737. If the file doesn't exist, it will first be created. If the file can't be
  11738. created or opened, the failedToOpen() method will return
  11739. true.
  11740. If the file already exists when opened, the stream's write-postion will
  11741. be set to the end of the file. To overwrite an existing file,
  11742. use File::deleteFile() before opening the stream, or use setPosition(0)
  11743. after it's opened (although this won't truncate the file).
  11744. It's better to use File::createOutputStream() to create one of these, rather
  11745. than using the class directly.
  11746. @see TemporaryFile
  11747. */
  11748. FileOutputStream (const File& fileToWriteTo,
  11749. int bufferSizeToUse = 16384);
  11750. /** Destructor. */
  11751. ~FileOutputStream();
  11752. /** Returns the file that this stream is writing to.
  11753. */
  11754. const File& getFile() const { return file; }
  11755. /** Returns true if the stream couldn't be opened for some reason.
  11756. */
  11757. bool failedToOpen() const { return fileHandle == 0; }
  11758. void flush();
  11759. int64 getPosition();
  11760. bool setPosition (int64 pos);
  11761. bool write (const void* data, int numBytes);
  11762. juce_UseDebuggingNewOperator
  11763. private:
  11764. File file;
  11765. void* fileHandle;
  11766. int64 currentPosition;
  11767. int bufferSize, bytesInBuffer;
  11768. HeapBlock <char> buffer;
  11769. void flushInternal();
  11770. int64 getPositionInternal() const;
  11771. FileOutputStream (const FileOutputStream&);
  11772. FileOutputStream& operator= (const FileOutputStream&);
  11773. };
  11774. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11775. /*** End of inlined file: juce_FileOutputStream.h ***/
  11776. #endif
  11777. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11778. /*** Start of inlined file: juce_FileSearchPath.h ***/
  11779. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11780. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  11781. /**
  11782. Encapsulates a set of folders that make up a search path.
  11783. @see File
  11784. */
  11785. class JUCE_API FileSearchPath
  11786. {
  11787. public:
  11788. /** Creates an empty search path. */
  11789. FileSearchPath();
  11790. /** Creates a search path from a string of pathnames.
  11791. The path can be semicolon- or comma-separated, e.g.
  11792. "/foo/bar;/foo/moose;/fish/moose"
  11793. The separate folders are tokenised and added to the search path.
  11794. */
  11795. FileSearchPath (const String& path);
  11796. /** Creates a copy of another search path. */
  11797. FileSearchPath (const FileSearchPath& other);
  11798. /** Destructor. */
  11799. ~FileSearchPath();
  11800. /** Uses a string containing a list of pathnames to re-initialise this list.
  11801. This search path is cleared and the semicolon- or comma-separated folders
  11802. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  11803. */
  11804. FileSearchPath& operator= (const String& path);
  11805. /** Returns the number of folders in this search path.
  11806. @see operator[]
  11807. */
  11808. int getNumPaths() const;
  11809. /** Returns one of the folders in this search path.
  11810. The file returned isn't guaranteed to actually be a valid directory.
  11811. @see getNumPaths
  11812. */
  11813. const File operator[] (int index) const;
  11814. /** Returns the search path as a semicolon-separated list of directories. */
  11815. const String toString() const;
  11816. /** Adds a new directory to the search path.
  11817. The new directory is added to the end of the list if the insertIndex parameter is
  11818. less than zero, otherwise it is inserted at the given index.
  11819. */
  11820. void add (const File& directoryToAdd,
  11821. int insertIndex = -1);
  11822. /** Adds a new directory to the search path if it's not already in there. */
  11823. void addIfNotAlreadyThere (const File& directoryToAdd);
  11824. /** Removes a directory from the search path. */
  11825. void remove (int indexToRemove);
  11826. /** Merges another search path into this one.
  11827. This will remove any duplicate directories.
  11828. */
  11829. void addPath (const FileSearchPath& other);
  11830. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  11831. If the search is intended to be recursive, there's no point having nested folders in the search
  11832. path, because they'll just get searched twice and you'll get duplicate results.
  11833. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  11834. */
  11835. void removeRedundantPaths();
  11836. /** Removes any directories that don't actually exist. */
  11837. void removeNonExistentPaths();
  11838. /** Searches the path for a wildcard.
  11839. This will search all the directories in the search path in order, adding any
  11840. matching files to the results array.
  11841. @param results an array to append the results to
  11842. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  11843. return files, directories, or both.
  11844. @param searchRecursively whether to recursively search the subdirectories too
  11845. @param wildCardPattern a pattern to match against the filenames
  11846. @returns the number of files added to the array
  11847. @see File::findChildFiles
  11848. */
  11849. int findChildFiles (Array<File>& results,
  11850. int whatToLookFor,
  11851. bool searchRecursively,
  11852. const String& wildCardPattern = "*") const;
  11853. /** Finds out whether a file is inside one of the path's directories.
  11854. This will return true if the specified file is a child of one of the
  11855. directories specified by this path. Note that this doesn't actually do any
  11856. searching or check that the files exist - it just looks at the pathnames
  11857. to work out whether the file would be inside a directory.
  11858. @param fileToCheck the file to look for
  11859. @param checkRecursively if true, then this will return true if the file is inside a
  11860. subfolder of one of the path's directories (at any depth). If false
  11861. it will only return true if the file is actually a direct child
  11862. of one of the directories.
  11863. @see File::isAChildOf
  11864. */
  11865. bool isFileInPath (const File& fileToCheck,
  11866. bool checkRecursively) const;
  11867. juce_UseDebuggingNewOperator
  11868. private:
  11869. StringArray directories;
  11870. void init (const String& path);
  11871. };
  11872. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  11873. /*** End of inlined file: juce_FileSearchPath.h ***/
  11874. #endif
  11875. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11876. /*** Start of inlined file: juce_NamedPipe.h ***/
  11877. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11878. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  11879. /**
  11880. A cross-process pipe that can have data written to and read from it.
  11881. Two or more processes can use these for inter-process communication.
  11882. @see InterprocessConnection
  11883. */
  11884. class JUCE_API NamedPipe
  11885. {
  11886. public:
  11887. /** Creates a NamedPipe. */
  11888. NamedPipe();
  11889. /** Destructor. */
  11890. ~NamedPipe();
  11891. /** Tries to open a pipe that already exists.
  11892. Returns true if it succeeds.
  11893. */
  11894. bool openExisting (const String& pipeName);
  11895. /** Tries to create a new pipe.
  11896. Returns true if it succeeds.
  11897. */
  11898. bool createNewPipe (const String& pipeName);
  11899. /** Closes the pipe, if it's open. */
  11900. void close();
  11901. /** True if the pipe is currently open. */
  11902. bool isOpen() const;
  11903. /** Returns the last name that was used to try to open this pipe. */
  11904. const String getName() const;
  11905. /** Reads data from the pipe.
  11906. This will block until another thread has written enough data into the pipe to fill
  11907. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11908. method.
  11909. If the operation fails, it returns -1, otherwise, it will return the number of
  11910. bytes read.
  11911. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11912. this is a maximum timeout for reading from the pipe.
  11913. */
  11914. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11915. /** Writes some data to the pipe.
  11916. If the operation fails, it returns -1, otherwise, it will return the number of
  11917. bytes written.
  11918. */
  11919. int write (const void* sourceBuffer, int numBytesToWrite,
  11920. int timeOutMilliseconds = 2000);
  11921. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11922. */
  11923. void cancelPendingReads();
  11924. juce_UseDebuggingNewOperator
  11925. private:
  11926. void* internal;
  11927. String currentPipeName;
  11928. CriticalSection lock;
  11929. NamedPipe (const NamedPipe&);
  11930. NamedPipe& operator= (const NamedPipe&);
  11931. bool openInternal (const String& pipeName, const bool createPipe);
  11932. };
  11933. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11934. /*** End of inlined file: juce_NamedPipe.h ***/
  11935. #endif
  11936. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11937. /*** Start of inlined file: juce_TemporaryFile.h ***/
  11938. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11939. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  11940. /**
  11941. Manages a temporary file, which will be deleted when this object is deleted.
  11942. This object is intended to be used as a stack based object, using its scope
  11943. to make sure the temporary file isn't left lying around.
  11944. For example:
  11945. @code
  11946. {
  11947. File myTargetFile ("~/myfile.txt");
  11948. // this will choose a file called something like "~/myfile_temp239348.txt"
  11949. // which definitely doesn't exist at the time the constructor is called.
  11950. TemporaryFile temp (myTargetFile);
  11951. // create a stream to the temporary file, and write some data to it...
  11952. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  11953. if (out != 0)
  11954. {
  11955. out->write ( ...etc )
  11956. out->flush();
  11957. out = 0; // (deletes the stream)
  11958. // ..now we've finished writing, this will rename the temp file to
  11959. // make it replace the target file we specified above.
  11960. bool succeeded = temp.overwriteTargetFileWithTemporary();
  11961. }
  11962. // ..and even if something went wrong and our overwrite failed,
  11963. // as the TemporaryFile object goes out of scope here, it'll make sure
  11964. // that the temp file gets deleted.
  11965. }
  11966. @endcode
  11967. @see File, FileOutputStream
  11968. */
  11969. class JUCE_API TemporaryFile
  11970. {
  11971. public:
  11972. enum OptionFlags
  11973. {
  11974. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  11975. i.e. its name should start with a dot. */
  11976. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  11977. the file is unique, they should go in brackets rather
  11978. than just being appended (see File::getNonexistentSibling() )*/
  11979. };
  11980. /** Creates a randomly-named temporary file in the default temp directory.
  11981. @param suffix a file suffix to use for the file
  11982. @param optionFlags a combination of the values listed in the OptionFlags enum
  11983. The file will not be created until you write to it. And remember that when
  11984. this object is deleted, the file will also be deleted!
  11985. */
  11986. TemporaryFile (const String& suffix = String::empty,
  11987. int optionFlags = 0);
  11988. /** Creates a temporary file in the same directory as a specified file.
  11989. This is useful if you have a file that you want to overwrite, but don't
  11990. want to harm the original file if the write operation fails. You can
  11991. use this to create a temporary file next to the target file, then
  11992. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  11993. to replace the target file with the one you've just written.
  11994. This class won't create any files until you actually write to them. And remember
  11995. that when this object is deleted, the temporary file will also be deleted!
  11996. @param targetFile the file that you intend to overwrite - the temporary
  11997. file will be created in the same directory as this
  11998. @param optionFlags a combination of the values listed in the OptionFlags enum
  11999. */
  12000. TemporaryFile (const File& targetFile,
  12001. int optionFlags = 0);
  12002. /** Destructor.
  12003. When this object is deleted it will make sure that its temporary file is
  12004. also deleted! If the operation fails, it'll throw an assertion in debug
  12005. mode.
  12006. */
  12007. ~TemporaryFile();
  12008. /** Returns the temporary file. */
  12009. const File getFile() const { return temporaryFile; }
  12010. /** Returns the target file that was specified in the constructor. */
  12011. const File getTargetFile() const { return targetFile; }
  12012. /** Tries to move the temporary file to overwrite the target file that was
  12013. specified in the constructor.
  12014. If you used the constructor that specified a target file, this will attempt
  12015. to replace that file with the temporary one.
  12016. Before calling this, make sure:
  12017. - that you've actually written to the temporary file
  12018. - that you've closed any open streams that you were using to write to it
  12019. - and that you don't have any streams open to the target file, which would
  12020. prevent it being overwritten
  12021. If the file move succeeds, this returns false, and the temporary file will
  12022. have disappeared. If it fails, the temporary file will probably still exist,
  12023. but will be deleted when this object is destroyed.
  12024. */
  12025. bool overwriteTargetFileWithTemporary() const;
  12026. juce_UseDebuggingNewOperator
  12027. private:
  12028. File temporaryFile, targetFile;
  12029. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  12030. TemporaryFile (const TemporaryFile&);
  12031. TemporaryFile& operator= (const TemporaryFile&);
  12032. };
  12033. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  12034. /*** End of inlined file: juce_TemporaryFile.h ***/
  12035. #endif
  12036. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  12037. /*** Start of inlined file: juce_ZipFile.h ***/
  12038. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  12039. #define __JUCE_ZIPFILE_JUCEHEADER__
  12040. /*** Start of inlined file: juce_InputSource.h ***/
  12041. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12042. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  12043. /**
  12044. A lightweight object that can create a stream to read some kind of resource.
  12045. This may be used to refer to a file, or some other kind of source, allowing a
  12046. caller to create an input stream that can read from it when required.
  12047. @see FileInputSource
  12048. */
  12049. class JUCE_API InputSource
  12050. {
  12051. public:
  12052. InputSource() throw() {}
  12053. /** Destructor. */
  12054. virtual ~InputSource() {}
  12055. /** Returns a new InputStream to read this item.
  12056. @returns an inputstream that the caller will delete, or 0 if
  12057. the filename isn't found.
  12058. */
  12059. virtual InputStream* createInputStream() = 0;
  12060. /** Returns a new InputStream to read an item, relative.
  12061. @param relatedItemPath the relative pathname of the resource that is required
  12062. @returns an inputstream that the caller will delete, or 0 if
  12063. the item isn't found.
  12064. */
  12065. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  12066. /** Returns a hash code that uniquely represents this item.
  12067. */
  12068. virtual int64 hashCode() const = 0;
  12069. juce_UseDebuggingNewOperator
  12070. };
  12071. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  12072. /*** End of inlined file: juce_InputSource.h ***/
  12073. /**
  12074. Decodes a ZIP file from a stream.
  12075. This can enumerate the items in a ZIP file and can create suitable stream objects
  12076. to read each one.
  12077. */
  12078. class JUCE_API ZipFile
  12079. {
  12080. public:
  12081. /** Creates a ZipFile for a given stream.
  12082. @param inputStream the stream to read from
  12083. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  12084. will be deleted when this ZipFile object is deleted
  12085. */
  12086. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  12087. /** Creates a ZipFile based for a file. */
  12088. ZipFile (const File& file);
  12089. /** Creates a ZipFile for an input source.
  12090. The inputSource object will be owned by the zip file, which will delete
  12091. it later when not needed.
  12092. */
  12093. ZipFile (InputSource* inputSource);
  12094. /** Destructor. */
  12095. ~ZipFile();
  12096. /**
  12097. Contains information about one of the entries in a ZipFile.
  12098. @see ZipFile::getEntry
  12099. */
  12100. struct ZipEntry
  12101. {
  12102. /** The name of the file, which may also include a partial pathname. */
  12103. String filename;
  12104. /** The file's original size. */
  12105. unsigned int uncompressedSize;
  12106. /** The last time the file was modified. */
  12107. Time fileTime;
  12108. };
  12109. /** Returns the number of items in the zip file. */
  12110. int getNumEntries() const throw();
  12111. /** Returns a structure that describes one of the entries in the zip file.
  12112. This may return zero if the index is out of range.
  12113. @see ZipFile::ZipEntry
  12114. */
  12115. const ZipEntry* getEntry (int index) const throw();
  12116. /** Returns the index of the first entry with a given filename.
  12117. This uses a case-sensitive comparison to look for a filename in the
  12118. list of entries. It might return -1 if no match is found.
  12119. @see ZipFile::ZipEntry
  12120. */
  12121. int getIndexOfFileName (const String& fileName) const throw();
  12122. /** Returns a structure that describes one of the entries in the zip file.
  12123. This uses a case-sensitive comparison to look for a filename in the
  12124. list of entries. It might return 0 if no match is found.
  12125. @see ZipFile::ZipEntry
  12126. */
  12127. const ZipEntry* getEntry (const String& fileName) const throw();
  12128. /** Sorts the list of entries, based on the filename.
  12129. */
  12130. void sortEntriesByFilename();
  12131. /** Creates a stream that can read from one of the zip file's entries.
  12132. The stream that is returned must be deleted by the caller (and
  12133. zero might be returned if a stream can't be opened for some reason).
  12134. The stream must not be used after the ZipFile object that created
  12135. has been deleted.
  12136. */
  12137. InputStream* createStreamForEntry (int index);
  12138. /** Uncompresses all of the files in the zip file.
  12139. This will expand all the entires into a target directory. The relative
  12140. paths of the entries are used.
  12141. @param targetDirectory the root folder to uncompress to
  12142. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12143. */
  12144. void uncompressTo (const File& targetDirectory,
  12145. bool shouldOverwriteFiles = true);
  12146. juce_UseDebuggingNewOperator
  12147. private:
  12148. class ZipInputStream;
  12149. class ZipFilenameComparator;
  12150. class ZipEntryInfo;
  12151. friend class ZipInputStream;
  12152. friend class ZipFilenameComparator;
  12153. friend class ZipEntryInfo;
  12154. OwnedArray <ZipEntryInfo> entries;
  12155. CriticalSection lock;
  12156. InputStream* inputStream;
  12157. ScopedPointer <InputStream> streamToDelete;
  12158. ScopedPointer <InputSource> inputSource;
  12159. #if JUCE_DEBUG
  12160. int numOpenStreams;
  12161. #endif
  12162. void init();
  12163. int findEndOfZipEntryTable (InputStream* in, int& numEntries);
  12164. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  12165. ZipFile (const ZipFile&);
  12166. ZipFile& operator= (const ZipFile&);
  12167. };
  12168. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  12169. /*** End of inlined file: juce_ZipFile.h ***/
  12170. #endif
  12171. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12172. /*** Start of inlined file: juce_Socket.h ***/
  12173. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12174. #define __JUCE_SOCKET_JUCEHEADER__
  12175. /**
  12176. A wrapper for a streaming (TCP) socket.
  12177. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12178. sockets, you could also try the InterprocessConnection class.
  12179. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12180. */
  12181. class JUCE_API StreamingSocket
  12182. {
  12183. public:
  12184. /** Creates an uninitialised socket.
  12185. To connect it, use the connect() method, after which you can read() or write()
  12186. to it.
  12187. To wait for other sockets to connect to this one, the createListener() method
  12188. enters "listener" mode, and can be used to spawn new sockets for each connection
  12189. that comes along.
  12190. */
  12191. StreamingSocket();
  12192. /** Destructor. */
  12193. ~StreamingSocket();
  12194. /** Binds the socket to the specified local port.
  12195. @returns true on success; false may indicate that another socket is already bound
  12196. on the same port
  12197. */
  12198. bool bindToPort (int localPortNumber);
  12199. /** Tries to connect the socket to hostname:port.
  12200. If timeOutMillisecs is 0, then this method will block until the operating system
  12201. rejects the connection (which could take a long time).
  12202. @returns true if it succeeds.
  12203. @see isConnected
  12204. */
  12205. bool connect (const String& remoteHostname,
  12206. int remotePortNumber,
  12207. int timeOutMillisecs = 3000);
  12208. /** True if the socket is currently connected. */
  12209. bool isConnected() const throw() { return connected; }
  12210. /** Closes the connection. */
  12211. void close();
  12212. /** Returns the name of the currently connected host. */
  12213. const String& getHostName() const throw() { return hostName; }
  12214. /** Returns the port number that's currently open. */
  12215. int getPort() const throw() { return portNumber; }
  12216. /** True if the socket is connected to this machine rather than over the network. */
  12217. bool isLocal() const throw();
  12218. /** Waits until the socket is ready for reading or writing.
  12219. If readyForReading is true, it will wait until the socket is ready for
  12220. reading; if false, it will wait until it's ready for writing.
  12221. If the timeout is < 0, it will wait forever, or else will give up after
  12222. the specified time.
  12223. If the socket is ready on return, this returns 1. If it times-out before
  12224. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12225. */
  12226. int waitUntilReady (bool readyForReading,
  12227. int timeoutMsecs) const;
  12228. /** Reads bytes from the socket.
  12229. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12230. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12231. flag is false, the method will return as much data as is currently available
  12232. without blocking.
  12233. @returns the number of bytes read, or -1 if there was an error.
  12234. @see waitUntilReady
  12235. */
  12236. int read (void* destBuffer, int maxBytesToRead,
  12237. bool blockUntilSpecifiedAmountHasArrived);
  12238. /** Writes bytes to the socket from a buffer.
  12239. Note that this method will block unless you have checked the socket is ready
  12240. for writing before calling it (see the waitUntilReady() method).
  12241. @returns the number of bytes written, or -1 if there was an error.
  12242. */
  12243. int write (const void* sourceBuffer, int numBytesToWrite);
  12244. /** Puts this socket into "listener" mode.
  12245. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12246. which will spawn new sockets for each new connection, so that these can
  12247. be handled in parallel by other threads.
  12248. @param portNumber the port number to listen on
  12249. @param localHostName the interface address to listen on - pass an empty
  12250. string to listen on all addresses
  12251. @returns true if it manages to open the socket successfully.
  12252. @see waitForNextConnection
  12253. */
  12254. bool createListener (int portNumber, const String& localHostName = String::empty);
  12255. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12256. socket.
  12257. The object that gets returned will be owned by the caller.
  12258. This method can only be called after using createListener().
  12259. @see createListener
  12260. */
  12261. StreamingSocket* waitForNextConnection() const;
  12262. juce_UseDebuggingNewOperator
  12263. private:
  12264. String hostName;
  12265. int volatile portNumber, handle;
  12266. bool connected, isListener;
  12267. StreamingSocket (const String& hostname, int portNumber, int handle);
  12268. StreamingSocket (const StreamingSocket&);
  12269. StreamingSocket& operator= (const StreamingSocket&);
  12270. };
  12271. /**
  12272. A wrapper for a datagram (UDP) socket.
  12273. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12274. sockets, you could also try the InterprocessConnection class.
  12275. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12276. */
  12277. class JUCE_API DatagramSocket
  12278. {
  12279. public:
  12280. /**
  12281. Creates an (uninitialised) datagram socket.
  12282. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12283. the port number is assigned by the operating system.
  12284. To use the socket for sending, call the connect() method. This will not immediately
  12285. make a connection, but will save the destination you've provided. After this, you can
  12286. call read() or write().
  12287. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12288. (may require extra privileges on linux)
  12289. To wait for other sockets to connect to this one, call waitForNextConnection().
  12290. */
  12291. DatagramSocket (int localPortNumber,
  12292. bool enableBroadcasting = false);
  12293. /** Destructor. */
  12294. ~DatagramSocket();
  12295. /** Binds the socket to the specified local port.
  12296. @returns true on success; false may indicate that another socket is already bound
  12297. on the same port
  12298. */
  12299. bool bindToPort (int localPortNumber);
  12300. /** Tries to connect the socket to hostname:port.
  12301. If timeOutMillisecs is 0, then this method will block until the operating system
  12302. rejects the connection (which could take a long time).
  12303. @returns true if it succeeds.
  12304. @see isConnected
  12305. */
  12306. bool connect (const String& remoteHostname,
  12307. int remotePortNumber,
  12308. int timeOutMillisecs = 3000);
  12309. /** True if the socket is currently connected. */
  12310. bool isConnected() const throw() { return connected; }
  12311. /** Closes the connection. */
  12312. void close();
  12313. /** Returns the name of the currently connected host. */
  12314. const String& getHostName() const throw() { return hostName; }
  12315. /** Returns the port number that's currently open. */
  12316. int getPort() const throw() { return portNumber; }
  12317. /** True if the socket is connected to this machine rather than over the network. */
  12318. bool isLocal() const throw();
  12319. /** Waits until the socket is ready for reading or writing.
  12320. If readyForReading is true, it will wait until the socket is ready for
  12321. reading; if false, it will wait until it's ready for writing.
  12322. If the timeout is < 0, it will wait forever, or else will give up after
  12323. the specified time.
  12324. If the socket is ready on return, this returns 1. If it times-out before
  12325. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12326. */
  12327. int waitUntilReady (bool readyForReading,
  12328. int timeoutMsecs) const;
  12329. /** Reads bytes from the socket.
  12330. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12331. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12332. flag is false, the method will return as much data as is currently available
  12333. without blocking.
  12334. @returns the number of bytes read, or -1 if there was an error.
  12335. @see waitUntilReady
  12336. */
  12337. int read (void* destBuffer, int maxBytesToRead,
  12338. bool blockUntilSpecifiedAmountHasArrived);
  12339. /** Writes bytes to the socket from a buffer.
  12340. Note that this method will block unless you have checked the socket is ready
  12341. for writing before calling it (see the waitUntilReady() method).
  12342. @returns the number of bytes written, or -1 if there was an error.
  12343. */
  12344. int write (const void* sourceBuffer, int numBytesToWrite);
  12345. /** This waits for incoming data to be sent, and returns a socket that can be used
  12346. to read it.
  12347. The object that gets returned is owned by the caller, and can't be used for
  12348. sending, but can be used to read the data.
  12349. */
  12350. DatagramSocket* waitForNextConnection() const;
  12351. juce_UseDebuggingNewOperator
  12352. private:
  12353. String hostName;
  12354. int volatile portNumber, handle;
  12355. bool connected, allowBroadcast;
  12356. void* serverAddress;
  12357. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12358. DatagramSocket (const DatagramSocket&);
  12359. DatagramSocket& operator= (const DatagramSocket&);
  12360. };
  12361. #endif // __JUCE_SOCKET_JUCEHEADER__
  12362. /*** End of inlined file: juce_Socket.h ***/
  12363. #endif
  12364. #ifndef __JUCE_URL_JUCEHEADER__
  12365. /*** Start of inlined file: juce_URL.h ***/
  12366. #ifndef __JUCE_URL_JUCEHEADER__
  12367. #define __JUCE_URL_JUCEHEADER__
  12368. /**
  12369. Represents a URL and has a bunch of useful functions to manipulate it.
  12370. This class can be used to launch URLs in browsers, and also to create
  12371. InputStreams that can read from remote http or ftp sources.
  12372. */
  12373. class JUCE_API URL
  12374. {
  12375. public:
  12376. /** Creates an empty URL. */
  12377. URL();
  12378. /** Creates a URL from a string. */
  12379. URL (const String& url);
  12380. /** Creates a copy of another URL. */
  12381. URL (const URL& other);
  12382. /** Destructor. */
  12383. ~URL();
  12384. /** Copies this URL from another one. */
  12385. URL& operator= (const URL& other);
  12386. /** Returns a string version of the URL.
  12387. If includeGetParameters is true and any parameters have been set with the
  12388. withParameter() method, then the string will have these appended on the
  12389. end and url-encoded.
  12390. */
  12391. const String toString (bool includeGetParameters) const;
  12392. /** True if it seems to be valid. */
  12393. bool isWellFormed() const;
  12394. /** Returns just the domain part of the URL.
  12395. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  12396. */
  12397. const String getDomain() const;
  12398. /** Returns the path part of the URL.
  12399. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  12400. */
  12401. const String getSubPath() const;
  12402. /** Returns the scheme of the URL.
  12403. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  12404. include the colon).
  12405. */
  12406. const String getScheme() const;
  12407. /** Returns a new version of this URL that uses a different sub-path.
  12408. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  12409. "bar", it'll return "http://www.xyz.com/bar?x=1".
  12410. */
  12411. const URL withNewSubPath (const String& newPath) const;
  12412. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  12413. Any control characters in the value will be encoded.
  12414. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  12415. would produce a new url whose toString(true) method would return
  12416. "www.fish.com?amount=some+fish".
  12417. */
  12418. const URL withParameter (const String& parameterName,
  12419. const String& parameterValue) const;
  12420. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  12421. When performing a POST where one of your parameters is a binary file, this
  12422. lets you specify the file.
  12423. Note that the filename is stored, but the file itself won't actually be read
  12424. until this URL is later used to create a network input stream.
  12425. */
  12426. const URL withFileToUpload (const String& parameterName,
  12427. const File& fileToUpload,
  12428. const String& mimeType) const;
  12429. /** Returns a set of all the parameters encoded into the url.
  12430. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  12431. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  12432. The values returned will have been cleaned up to remove any escape characters.
  12433. @see getNamedParameter, withParameter
  12434. */
  12435. const StringPairArray& getParameters() const;
  12436. /** Returns the set of files that should be uploaded as part of a POST operation.
  12437. This is the set of files that were added to the URL with the withFileToUpload()
  12438. method.
  12439. */
  12440. const StringPairArray& getFilesToUpload() const;
  12441. /** Returns the set of mime types associated with each of the upload files.
  12442. */
  12443. const StringPairArray& getMimeTypesOfUploadFiles() const;
  12444. /** Returns a copy of this URL, with a block of data to send as the POST data.
  12445. If you're setting the POST data, be careful not to have any parameters set
  12446. as well, otherwise it'll all get thrown in together, and might not have the
  12447. desired effect.
  12448. If the URL already contains some POST data, this will replace it, rather
  12449. than being appended to it.
  12450. This data will only be used if you specify a post operation when you call
  12451. createInputStream().
  12452. */
  12453. const URL withPOSTData (const String& postData) const;
  12454. /** Returns the data that was set using withPOSTData().
  12455. */
  12456. const String getPostData() const { return postData; }
  12457. /** Tries to launch the system's default browser to open the URL.
  12458. Returns true if this seems to have worked.
  12459. */
  12460. bool launchInDefaultBrowser() const;
  12461. /** Takes a guess as to whether a string might be a valid website address.
  12462. This isn't foolproof!
  12463. */
  12464. static bool isProbablyAWebsiteURL (const String& possibleURL);
  12465. /** Takes a guess as to whether a string might be a valid email address.
  12466. This isn't foolproof!
  12467. */
  12468. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  12469. /** This callback function can be used by the createInputStream() method.
  12470. It allows your app to receive progress updates during a lengthy POST operation. If you
  12471. want to continue the operation, this should return true, or false to abort.
  12472. */
  12473. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  12474. /** Attempts to open a stream that can read from this URL.
  12475. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  12476. the paramters, otherwise it'll encode them into the
  12477. URL and do a 'GET'.
  12478. @param progressCallback if this is non-zero, it lets you supply a callback function
  12479. to keep track of the operation's progress. This can be useful
  12480. for lengthy POST operations, so that you can provide user feedback.
  12481. @param progressCallbackContext if a callback is specified, this value will be passed to
  12482. the function
  12483. @param extraHeaders if not empty, this string is appended onto the headers that
  12484. are used for the request. It must therefore be a valid set of HTML
  12485. header directives, separated by newlines.
  12486. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  12487. a negative number, it will be infinite. Otherwise it specifies a
  12488. time in milliseconds.
  12489. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  12490. in the response will be stored in this array
  12491. @returns an input stream that the caller must delete, or a null pointer if there was an
  12492. error trying to open it.
  12493. */
  12494. InputStream* createInputStream (bool usePostCommand,
  12495. OpenStreamProgressCallback* progressCallback = 0,
  12496. void* progressCallbackContext = 0,
  12497. const String& extraHeaders = String::empty,
  12498. int connectionTimeOutMs = 0,
  12499. StringPairArray* responseHeaders = 0) const;
  12500. /** Tries to download the entire contents of this URL into a binary data block.
  12501. If it succeeds, this will return true and append the data it read onto the end
  12502. of the memory block.
  12503. @param destData the memory block to append the new data to
  12504. @param usePostCommand whether to use a POST command to get the data (uses
  12505. a GET command if this is false)
  12506. @see readEntireTextStream, readEntireXmlStream
  12507. */
  12508. bool readEntireBinaryStream (MemoryBlock& destData,
  12509. bool usePostCommand = false) const;
  12510. /** Tries to download the entire contents of this URL as a string.
  12511. If it fails, this will return an empty string, otherwise it will return the
  12512. contents of the downloaded file. If you need to distinguish between a read
  12513. operation that fails and one that returns an empty string, you'll need to use
  12514. a different method, such as readEntireBinaryStream().
  12515. @param usePostCommand whether to use a POST command to get the data (uses
  12516. a GET command if this is false)
  12517. @see readEntireBinaryStream, readEntireXmlStream
  12518. */
  12519. const String readEntireTextStream (bool usePostCommand = false) const;
  12520. /** Tries to download the entire contents of this URL and parse it as XML.
  12521. If it fails, or if the text that it reads can't be parsed as XML, this will
  12522. return 0.
  12523. When it returns a valid XmlElement object, the caller is responsibile for deleting
  12524. this object when no longer needed.
  12525. @param usePostCommand whether to use a POST command to get the data (uses
  12526. a GET command if this is false)
  12527. @see readEntireBinaryStream, readEntireTextStream
  12528. */
  12529. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  12530. /** Adds escape sequences to a string to encode any characters that aren't
  12531. legal in a URL.
  12532. E.g. any spaces will be replaced with "%20".
  12533. This is the opposite of removeEscapeChars().
  12534. If isParameter is true, it means that the string is going to be used
  12535. as a parameter, so it also encodes '$' and ',' (which would otherwise
  12536. be legal in a URL.
  12537. @see removeEscapeChars
  12538. */
  12539. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  12540. bool isParameter);
  12541. /** Replaces any escape character sequences in a string with their original
  12542. character codes.
  12543. E.g. any instances of "%20" will be replaced by a space.
  12544. This is the opposite of addEscapeChars().
  12545. @see addEscapeChars
  12546. */
  12547. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  12548. juce_UseDebuggingNewOperator
  12549. private:
  12550. String url, postData;
  12551. StringPairArray parameters, filesToUpload, mimeTypes;
  12552. };
  12553. #endif // __JUCE_URL_JUCEHEADER__
  12554. /*** End of inlined file: juce_URL.h ***/
  12555. #endif
  12556. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12557. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  12558. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12559. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12560. /** Wraps another input stream, and reads from it using an intermediate buffer
  12561. If you're using an input stream such as a file input stream, and making lots of
  12562. small read accesses to it, it's probably sensible to wrap it in one of these,
  12563. so that the source stream gets accessed in larger chunk sizes, meaning less
  12564. work for the underlying stream.
  12565. */
  12566. class JUCE_API BufferedInputStream : public InputStream
  12567. {
  12568. public:
  12569. /** Creates a BufferedInputStream from an input source.
  12570. @param sourceStream the source stream to read from
  12571. @param bufferSize the size of reservoir to use to buffer the source
  12572. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12573. deleted by this object when it is itself deleted.
  12574. */
  12575. BufferedInputStream (InputStream* sourceStream,
  12576. int bufferSize,
  12577. bool deleteSourceWhenDestroyed);
  12578. /** Destructor.
  12579. This may also delete the source stream, if that option was chosen when the
  12580. buffered stream was created.
  12581. */
  12582. ~BufferedInputStream();
  12583. int64 getTotalLength();
  12584. int64 getPosition();
  12585. bool setPosition (int64 newPosition);
  12586. int read (void* destBuffer, int maxBytesToRead);
  12587. const String readString();
  12588. bool isExhausted();
  12589. juce_UseDebuggingNewOperator
  12590. private:
  12591. InputStream* const source;
  12592. ScopedPointer <InputStream> sourceToDelete;
  12593. int bufferSize;
  12594. int64 position, lastReadPos, bufferStart, bufferOverlap;
  12595. HeapBlock <char> buffer;
  12596. void ensureBuffered();
  12597. BufferedInputStream (const BufferedInputStream&);
  12598. BufferedInputStream& operator= (const BufferedInputStream&);
  12599. };
  12600. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12601. /*** End of inlined file: juce_BufferedInputStream.h ***/
  12602. #endif
  12603. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12604. /*** Start of inlined file: juce_FileInputSource.h ***/
  12605. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12606. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12607. /**
  12608. A type of InputSource that represents a normal file.
  12609. @see InputSource
  12610. */
  12611. class JUCE_API FileInputSource : public InputSource
  12612. {
  12613. public:
  12614. FileInputSource (const File& file);
  12615. ~FileInputSource();
  12616. InputStream* createInputStream();
  12617. InputStream* createInputStreamFor (const String& relatedItemPath);
  12618. int64 hashCode() const;
  12619. juce_UseDebuggingNewOperator
  12620. private:
  12621. const File file;
  12622. FileInputSource (const FileInputSource&);
  12623. FileInputSource& operator= (const FileInputSource&);
  12624. };
  12625. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12626. /*** End of inlined file: juce_FileInputSource.h ***/
  12627. #endif
  12628. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12629. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12630. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12631. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12632. class GZIPCompressorHelper;
  12633. /**
  12634. A stream which uses zlib to compress the data written into it.
  12635. @see GZIPDecompressorInputStream
  12636. */
  12637. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  12638. {
  12639. public:
  12640. /** Creates a compression stream.
  12641. @param destStream the stream into which the compressed data should
  12642. be written
  12643. @param compressionLevel how much to compress the data, between 1 and 9, where
  12644. 1 is the fastest/lowest compression, and 9 is the
  12645. slowest/highest compression. Any value outside this range
  12646. indicates that a default compression level should be used.
  12647. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  12648. this stream is destroyed
  12649. @param noWrap this is used internally by the ZipFile class
  12650. and should be ignored by user applications
  12651. */
  12652. GZIPCompressorOutputStream (OutputStream* destStream,
  12653. int compressionLevel = 0,
  12654. bool deleteDestStreamWhenDestroyed = false,
  12655. bool noWrap = false);
  12656. /** Destructor. */
  12657. ~GZIPCompressorOutputStream();
  12658. void flush();
  12659. int64 getPosition();
  12660. bool setPosition (int64 newPosition);
  12661. bool write (const void* destBuffer, int howMany);
  12662. juce_UseDebuggingNewOperator
  12663. private:
  12664. OutputStream* const destStream;
  12665. ScopedPointer <OutputStream> streamToDelete;
  12666. HeapBlock <uint8> buffer;
  12667. ScopedPointer <GZIPCompressorHelper> helper;
  12668. bool doNextBlock();
  12669. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  12670. GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  12671. };
  12672. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12673. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12674. #endif
  12675. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12676. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12677. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12678. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12679. class GZIPDecompressHelper;
  12680. /**
  12681. This stream will decompress a source-stream using zlib.
  12682. Tip: if you're reading lots of small items from one of these streams, you
  12683. can increase the performance enormously by passing it through a
  12684. BufferedInputStream, so that it has to read larger blocks less often.
  12685. @see GZIPCompressorOutputStream
  12686. */
  12687. class JUCE_API GZIPDecompressorInputStream : public InputStream
  12688. {
  12689. public:
  12690. /** Creates a decompressor stream.
  12691. @param sourceStream the stream to read from
  12692. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  12693. when this object is destroyed
  12694. @param noWrap this is used internally by the ZipFile class
  12695. and should be ignored by user applications
  12696. @param uncompressedStreamLength if the creator knows the length that the
  12697. uncompressed stream will be, then it can supply this
  12698. value, which will be returned by getTotalLength()
  12699. */
  12700. GZIPDecompressorInputStream (InputStream* sourceStream,
  12701. bool deleteSourceWhenDestroyed,
  12702. bool noWrap = false,
  12703. int64 uncompressedStreamLength = -1);
  12704. /** Destructor. */
  12705. ~GZIPDecompressorInputStream();
  12706. int64 getPosition();
  12707. bool setPosition (int64 pos);
  12708. int64 getTotalLength();
  12709. bool isExhausted();
  12710. int read (void* destBuffer, int maxBytesToRead);
  12711. juce_UseDebuggingNewOperator
  12712. private:
  12713. InputStream* const sourceStream;
  12714. ScopedPointer <InputStream> streamToDelete;
  12715. const int64 uncompressedStreamLength;
  12716. const bool noWrap;
  12717. bool isEof;
  12718. int activeBufferSize;
  12719. int64 originalSourcePos, currentPos;
  12720. HeapBlock <uint8> buffer;
  12721. ScopedPointer <GZIPDecompressHelper> helper;
  12722. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  12723. GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  12724. };
  12725. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12726. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12727. #endif
  12728. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12729. #endif
  12730. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  12731. #endif
  12732. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12733. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  12734. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12735. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12736. /**
  12737. Allows a block of data and to be accessed as a stream.
  12738. This can either be used to refer to a shared block of memory, or can make its
  12739. own internal copy of the data when the MemoryInputStream is created.
  12740. */
  12741. class JUCE_API MemoryInputStream : public InputStream
  12742. {
  12743. public:
  12744. /** Creates a MemoryInputStream.
  12745. @param sourceData the block of data to use as the stream's source
  12746. @param sourceDataSize the number of bytes in the source data block
  12747. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  12748. the source data, so this data shouldn't be changed
  12749. for the lifetime of the stream; if this parameter is
  12750. true, the stream will make its own copy of the
  12751. data and use that.
  12752. */
  12753. MemoryInputStream (const void* sourceData,
  12754. size_t sourceDataSize,
  12755. bool keepInternalCopyOfData);
  12756. /** Creates a MemoryInputStream.
  12757. @param data a block of data to use as the stream's source
  12758. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  12759. the source data, so this data shouldn't be changed
  12760. for the lifetime of the stream; if this parameter is
  12761. true, the stream will make its own copy of the
  12762. data and use that.
  12763. */
  12764. MemoryInputStream (const MemoryBlock& data,
  12765. bool keepInternalCopyOfData);
  12766. /** Destructor. */
  12767. ~MemoryInputStream();
  12768. int64 getPosition();
  12769. bool setPosition (int64 pos);
  12770. int64 getTotalLength();
  12771. bool isExhausted();
  12772. int read (void* destBuffer, int maxBytesToRead);
  12773. juce_UseDebuggingNewOperator
  12774. private:
  12775. const char* data;
  12776. size_t dataSize, position;
  12777. MemoryBlock internalCopy;
  12778. MemoryInputStream (const MemoryInputStream&);
  12779. MemoryInputStream& operator= (const MemoryInputStream&);
  12780. };
  12781. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12782. /*** End of inlined file: juce_MemoryInputStream.h ***/
  12783. #endif
  12784. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12785. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  12786. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12787. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12788. /** Writes data to an internal memory buffer, which grows as required.
  12789. The data that was written into the stream can then be accessed later as
  12790. a contiguous block of memory.
  12791. */
  12792. class JUCE_API MemoryOutputStream : public OutputStream
  12793. {
  12794. public:
  12795. /** Creates an empty memory stream ready for writing into.
  12796. @param initialSize the intial amount of capacity to allocate for writing into
  12797. */
  12798. MemoryOutputStream (size_t initialSize = 256);
  12799. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  12800. Note that the destination block will always be larger than the amount of data
  12801. that has been written to the stream, because the MemoryOutputStream keeps some
  12802. spare capactity at its end. To trim the block's size down to fit the actual
  12803. data, call flush(), or delete the MemoryOutputStream.
  12804. @param memoryBlockToWriteTo the block into which new data will be written.
  12805. @param appendToExistingBlockContent if this is true, the contents of the block will be
  12806. kept, and new data will be appended to it. If false,
  12807. the block will be cleared before use
  12808. */
  12809. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  12810. bool appendToExistingBlockContent);
  12811. /** Destructor.
  12812. This will free any data that was written to it.
  12813. */
  12814. ~MemoryOutputStream();
  12815. /** Returns a pointer to the data that has been written to the stream.
  12816. @see getDataSize
  12817. */
  12818. const void* getData() const throw();
  12819. /** Returns the number of bytes of data that have been written to the stream.
  12820. @see getData
  12821. */
  12822. size_t getDataSize() const throw() { return size; }
  12823. /** Resets the stream, clearing any data that has been written to it so far. */
  12824. void reset() throw();
  12825. /** Increases the internal storage capacity to be able to contain at least the specified
  12826. amount of data without needing to be resized.
  12827. */
  12828. void preallocate (size_t bytesToPreallocate);
  12829. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  12830. const String toUTF8() const;
  12831. /** Attempts to detect the encoding of the data and convert it to a string.
  12832. @see String::createStringFromData
  12833. */
  12834. const String toString() const;
  12835. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  12836. capacity off the block, so that its length matches the amount of actual data that
  12837. has been written so far.
  12838. */
  12839. void flush();
  12840. bool write (const void* buffer, int howMany);
  12841. int64 getPosition() { return position; }
  12842. bool setPosition (int64 newPosition);
  12843. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  12844. juce_UseDebuggingNewOperator
  12845. private:
  12846. MemoryBlock& data;
  12847. MemoryBlock internalBlock;
  12848. size_t position, size;
  12849. MemoryOutputStream (const MemoryOutputStream&);
  12850. MemoryOutputStream& operator= (const MemoryOutputStream&);
  12851. };
  12852. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  12853. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  12854. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12855. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  12856. #endif
  12857. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  12858. #endif
  12859. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12860. /*** Start of inlined file: juce_SubregionStream.h ***/
  12861. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12862. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12863. /** Wraps another input stream, and reads from a specific part of it.
  12864. This lets you take a subsection of a stream and present it as an entire
  12865. stream in its own right.
  12866. */
  12867. class JUCE_API SubregionStream : public InputStream
  12868. {
  12869. public:
  12870. /** Creates a SubregionStream from an input source.
  12871. @param sourceStream the source stream to read from
  12872. @param startPositionInSourceStream this is the position in the source stream that
  12873. corresponds to position 0 in this stream
  12874. @param lengthOfSourceStream this specifies the maximum number of bytes
  12875. from the source stream that will be passed through
  12876. by this stream. When the position of this stream
  12877. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  12878. If the length passed in here is greater than the length
  12879. of the source stream (as returned by getTotalLength()),
  12880. then the smaller value will be used.
  12881. Passing a negative value for this parameter means it
  12882. will keep reading until the source's end-of-stream.
  12883. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12884. deleted by this object when it is itself deleted.
  12885. */
  12886. SubregionStream (InputStream* sourceStream,
  12887. int64 startPositionInSourceStream,
  12888. int64 lengthOfSourceStream,
  12889. bool deleteSourceWhenDestroyed);
  12890. /** Destructor.
  12891. This may also delete the source stream, if that option was chosen when the
  12892. buffered stream was created.
  12893. */
  12894. ~SubregionStream();
  12895. int64 getTotalLength();
  12896. int64 getPosition();
  12897. bool setPosition (int64 newPosition);
  12898. int read (void* destBuffer, int maxBytesToRead);
  12899. bool isExhausted();
  12900. juce_UseDebuggingNewOperator
  12901. private:
  12902. InputStream* const source;
  12903. ScopedPointer <InputStream> sourceToDelete;
  12904. const int64 startPositionInSourceStream, lengthOfSourceStream;
  12905. SubregionStream (const SubregionStream&);
  12906. SubregionStream& operator= (const SubregionStream&);
  12907. };
  12908. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12909. /*** End of inlined file: juce_SubregionStream.h ***/
  12910. #endif
  12911. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  12912. #endif
  12913. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12914. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  12915. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12916. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12917. /** Used in the same way as the T(text) macro, this will attempt to translate a
  12918. string into a localised version using the LocalisedStrings class.
  12919. @see LocalisedStrings
  12920. */
  12921. #define TRANS(stringLiteral) \
  12922. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  12923. /**
  12924. Used to convert strings to localised foreign-language versions.
  12925. This is basically a look-up table of strings and their translated equivalents.
  12926. It can be loaded from a text file, so that you can supply a set of localised
  12927. versions of strings that you use in your app.
  12928. To use it in your code, simply call the translate() method on each string that
  12929. might have foreign versions, and if none is found, the method will just return
  12930. the original string.
  12931. The translation file should start with some lines specifying a description of
  12932. the language it contains, and also a list of ISO country codes where it might
  12933. be appropriate to use the file. After that, each line of the file should contain
  12934. a pair of quoted strings with an '=' sign.
  12935. E.g. for a french translation, the file might be:
  12936. @code
  12937. language: French
  12938. countries: fr be mc ch lu
  12939. "hello" = "bonjour"
  12940. "goodbye" = "au revoir"
  12941. @endcode
  12942. If the strings need to contain a quote character, they can use '\"' instead, and
  12943. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  12944. (you can use this to add comments).
  12945. Note that this is a singleton class, so don't create or destroy the object directly.
  12946. There's also a TRANS(text) macro defined to make it easy to use the this.
  12947. E.g. @code
  12948. printSomething (TRANS("hello"));
  12949. @endcode
  12950. This macro is used in the Juce classes themselves, so your application has a chance to
  12951. intercept and translate any internal Juce text strings that might be shown. (You can easily
  12952. get a list of all the messages by searching for the TRANS() macro in the Juce source
  12953. code).
  12954. */
  12955. class JUCE_API LocalisedStrings
  12956. {
  12957. public:
  12958. /** Creates a set of translations from the text of a translation file.
  12959. When you create one of these, you can call setCurrentMappings() to make it
  12960. the set of mappings that the system's using.
  12961. */
  12962. LocalisedStrings (const String& fileContents);
  12963. /** Creates a set of translations from a file.
  12964. When you create one of these, you can call setCurrentMappings() to make it
  12965. the set of mappings that the system's using.
  12966. */
  12967. LocalisedStrings (const File& fileToLoad);
  12968. /** Destructor. */
  12969. ~LocalisedStrings();
  12970. /** Selects the current set of mappings to be used by the system.
  12971. The object you pass in will be automatically deleted when no longer needed, so
  12972. don't keep a pointer to it. You can also pass in zero to remove the current
  12973. mappings.
  12974. See also the TRANS() macro, which uses the current set to do its translation.
  12975. @see translateWithCurrentMappings
  12976. */
  12977. static void setCurrentMappings (LocalisedStrings* newTranslations);
  12978. /** Returns the currently selected set of mappings.
  12979. This is the object that was last passed to setCurrentMappings(). It may
  12980. be 0 if none has been created.
  12981. */
  12982. static LocalisedStrings* getCurrentMappings();
  12983. /** Tries to translate a string using the currently selected set of mappings.
  12984. If no mapping has been set, or if the mapping doesn't contain a translation
  12985. for the string, this will just return the original string.
  12986. See also the TRANS() macro, which uses this method to do its translation.
  12987. @see setCurrentMappings, getCurrentMappings
  12988. */
  12989. static const String translateWithCurrentMappings (const String& text);
  12990. /** Tries to translate a string using the currently selected set of mappings.
  12991. If no mapping has been set, or if the mapping doesn't contain a translation
  12992. for the string, this will just return the original string.
  12993. See also the TRANS() macro, which uses this method to do its translation.
  12994. @see setCurrentMappings, getCurrentMappings
  12995. */
  12996. static const String translateWithCurrentMappings (const char* text);
  12997. /** Attempts to look up a string and return its localised version.
  12998. If the string isn't found in the list, the original string will be returned.
  12999. */
  13000. const String translate (const String& text) const;
  13001. /** Returns the name of the language specified in the translation file.
  13002. This is specified in the file using a line starting with "language:", e.g.
  13003. @code
  13004. language: german
  13005. @endcode
  13006. */
  13007. const String getLanguageName() const { return languageName; }
  13008. /** Returns the list of suitable country codes listed in the translation file.
  13009. These is specified in the file using a line starting with "countries:", e.g.
  13010. @code
  13011. countries: fr be mc ch lu
  13012. @endcode
  13013. The country codes are supposed to be 2-character ISO complient codes.
  13014. */
  13015. const StringArray getCountryCodes() const { return countryCodes; }
  13016. /** Indicates whether to use a case-insensitive search when looking up a string.
  13017. This defaults to true.
  13018. */
  13019. void setIgnoresCase (const bool shouldIgnoreCase);
  13020. juce_UseDebuggingNewOperator
  13021. private:
  13022. String languageName;
  13023. StringArray countryCodes;
  13024. StringPairArray translations;
  13025. void loadFromText (const String& fileContents);
  13026. };
  13027. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  13028. /*** End of inlined file: juce_LocalisedStrings.h ***/
  13029. #endif
  13030. #ifndef __JUCE_STRING_JUCEHEADER__
  13031. #endif
  13032. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  13033. #endif
  13034. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  13035. #endif
  13036. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  13037. #endif
  13038. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  13039. /*** Start of inlined file: juce_XmlDocument.h ***/
  13040. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  13041. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  13042. /**
  13043. Parses a text-based XML document and creates an XmlElement object from it.
  13044. The parser will parse DTDs to load external entities but won't
  13045. check the document for validity against the DTD.
  13046. e.g.
  13047. @code
  13048. XmlDocument myDocument (File ("myfile.xml"));
  13049. XmlElement* mainElement = myDocument.getDocumentElement();
  13050. if (mainElement == 0)
  13051. {
  13052. String error = myDocument.getLastParseError();
  13053. }
  13054. else
  13055. {
  13056. ..use the element
  13057. }
  13058. @endcode
  13059. @see XmlElement
  13060. */
  13061. class JUCE_API XmlDocument
  13062. {
  13063. public:
  13064. /** Creates an XmlDocument from the xml text.
  13065. The text doesn't actually get parsed until the getDocumentElement() method is
  13066. called.
  13067. */
  13068. XmlDocument (const String& documentText);
  13069. /** Creates an XmlDocument from a file.
  13070. The text doesn't actually get parsed until the getDocumentElement() method is
  13071. called.
  13072. */
  13073. XmlDocument (const File& file);
  13074. /** Destructor. */
  13075. ~XmlDocument();
  13076. /** Creates an XmlElement object to represent the main document node.
  13077. This method will do the actual parsing of the text, and if there's a
  13078. parse error, it may returns 0 (and you can find out the error using
  13079. the getLastParseError() method).
  13080. @param onlyReadOuterDocumentElement if true, the parser will only read the
  13081. first section of the file, and will only
  13082. return the outer document element - this
  13083. allows quick checking of large files to
  13084. see if they contain the correct type of
  13085. tag, without having to parse the entire file
  13086. @returns a new XmlElement which the caller will need to delete, or null if
  13087. there was an error.
  13088. @see getLastParseError
  13089. */
  13090. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  13091. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  13092. @returns the error, or an empty string if there was no error.
  13093. */
  13094. const String& getLastParseError() const throw();
  13095. /** Sets an input source object to use for parsing documents that reference external entities.
  13096. If the document has been created from a file, this probably won't be needed, but
  13097. if you're parsing some text and there might be a DTD that references external
  13098. files, you may need to create a custom input source that can retrieve the
  13099. other files it needs.
  13100. The object that is passed-in will be deleted automatically when no longer needed.
  13101. @see InputSource
  13102. */
  13103. void setInputSource (InputSource* const newSource) throw();
  13104. /** Sets a flag to change the treatment of empty text elements.
  13105. If this is true (the default state), then any text elements that contain only
  13106. whitespace characters will be ingored during parsing. If you need to catch
  13107. whitespace-only text, then you should set this to false before calling the
  13108. getDocumentElement() method.
  13109. */
  13110. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  13111. juce_UseDebuggingNewOperator
  13112. private:
  13113. String originalText;
  13114. const juce_wchar* input;
  13115. bool outOfData, errorOccurred;
  13116. bool identifierLookupTable [128];
  13117. String lastError, dtdText;
  13118. StringArray tokenisedDTD;
  13119. bool needToLoadDTD, ignoreEmptyTextElements;
  13120. ScopedPointer <InputSource> inputSource;
  13121. void setLastError (const String& desc, const bool carryOn);
  13122. void skipHeader();
  13123. void skipNextWhiteSpace();
  13124. juce_wchar readNextChar() throw();
  13125. XmlElement* readNextElement (const bool alsoParseSubElements);
  13126. void readChildElements (XmlElement* parent);
  13127. int findNextTokenLength() throw();
  13128. void readQuotedString (String& result);
  13129. void readEntity (String& result);
  13130. static bool isXmlIdentifierCharSlow (juce_wchar c) throw();
  13131. bool isXmlIdentifierChar (juce_wchar c) const throw();
  13132. const String getFileContents (const String& filename) const;
  13133. const String expandEntity (const String& entity);
  13134. const String expandExternalEntity (const String& entity);
  13135. const String getParameterEntity (const String& entity);
  13136. XmlDocument (const XmlDocument&);
  13137. XmlDocument& operator= (const XmlDocument&);
  13138. };
  13139. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  13140. /*** End of inlined file: juce_XmlDocument.h ***/
  13141. #endif
  13142. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  13143. #endif
  13144. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  13145. #endif
  13146. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13147. /*** Start of inlined file: juce_InterProcessLock.h ***/
  13148. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13149. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13150. /**
  13151. Acts as a critical section which processes can use to block each other.
  13152. @see CriticalSection
  13153. */
  13154. class JUCE_API InterProcessLock
  13155. {
  13156. public:
  13157. /** Creates a lock object.
  13158. @param name a name that processes will use to identify this lock object
  13159. */
  13160. explicit InterProcessLock (const String& name);
  13161. /** Destructor.
  13162. This will also release the lock if it's currently held by this process.
  13163. */
  13164. ~InterProcessLock();
  13165. /** Attempts to lock the critical section.
  13166. @param timeOutMillisecs how many milliseconds to wait if the lock
  13167. is already held by another process - a value of
  13168. 0 will return immediately, negative values will wait
  13169. forever
  13170. @returns true if the lock could be gained within the timeout period, or
  13171. false if the timeout expired.
  13172. */
  13173. bool enter (int timeOutMillisecs = -1);
  13174. /** Releases the lock if it's currently held by this process.
  13175. */
  13176. void exit();
  13177. /**
  13178. Automatically locks and unlocks an InterProcessLock object.
  13179. This works like a ScopedLock, but using an InterprocessLock rather than
  13180. a CriticalSection.
  13181. @see ScopedLock
  13182. */
  13183. class ScopedLockType
  13184. {
  13185. public:
  13186. /** Creates a scoped lock.
  13187. As soon as it is created, this will lock the InterProcessLock, and
  13188. when the ScopedLockType object is deleted, the InterProcessLock will
  13189. be unlocked.
  13190. Note that since an InterprocessLock can fail due to errors, you should check
  13191. isLocked() to make sure that the lock was successful before using it.
  13192. Make sure this object is created and deleted by the same thread,
  13193. otherwise there are no guarantees what will happen! Best just to use it
  13194. as a local stack object, rather than creating one with the new() operator.
  13195. */
  13196. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  13197. /** Destructor.
  13198. The InterProcessLock will be unlocked when the destructor is called.
  13199. Make sure this object is created and deleted by the same thread,
  13200. otherwise there are no guarantees what will happen!
  13201. */
  13202. inline ~ScopedLockType() { lock_.exit(); }
  13203. /** Returns true if the InterProcessLock was successfully locked. */
  13204. bool isLocked() const throw() { return lockWasSuccessful; }
  13205. private:
  13206. InterProcessLock& lock_;
  13207. bool lockWasSuccessful;
  13208. ScopedLockType (const ScopedLockType&);
  13209. ScopedLockType& operator= (const ScopedLockType&);
  13210. };
  13211. juce_UseDebuggingNewOperator
  13212. private:
  13213. class Pimpl;
  13214. friend class ScopedPointer <Pimpl>;
  13215. ScopedPointer <Pimpl> pimpl;
  13216. CriticalSection lock;
  13217. String name;
  13218. InterProcessLock (const InterProcessLock&);
  13219. InterProcessLock& operator= (const InterProcessLock&);
  13220. };
  13221. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13222. /*** End of inlined file: juce_InterProcessLock.h ***/
  13223. #endif
  13224. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13225. /*** Start of inlined file: juce_Process.h ***/
  13226. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13227. #define __JUCE_PROCESS_JUCEHEADER__
  13228. /** Represents the current executable's process.
  13229. This contains methods for controlling the current application at the
  13230. process-level.
  13231. @see Thread, JUCEApplication
  13232. */
  13233. class JUCE_API Process
  13234. {
  13235. public:
  13236. enum ProcessPriority
  13237. {
  13238. LowPriority = 0,
  13239. NormalPriority = 1,
  13240. HighPriority = 2,
  13241. RealtimePriority = 3
  13242. };
  13243. /** Changes the current process's priority.
  13244. @param priority the process priority, where
  13245. 0=low, 1=normal, 2=high, 3=realtime
  13246. */
  13247. static void setPriority (const ProcessPriority priority);
  13248. /** Kills the current process immediately.
  13249. This is an emergency process terminator that kills the application
  13250. immediately - it's intended only for use only when something goes
  13251. horribly wrong.
  13252. @see JUCEApplication::quit
  13253. */
  13254. static void terminate();
  13255. /** Returns true if this application process is the one that the user is
  13256. currently using.
  13257. */
  13258. static bool isForegroundProcess();
  13259. /** Raises the current process's privilege level.
  13260. Does nothing if this isn't supported by the current OS, or if process
  13261. privilege level is fixed.
  13262. */
  13263. static void raisePrivilege();
  13264. /** Lowers the current process's privilege level.
  13265. Does nothing if this isn't supported by the current OS, or if process
  13266. privilege level is fixed.
  13267. */
  13268. static void lowerPrivilege();
  13269. /** Returns true if this process is being hosted by a debugger.
  13270. */
  13271. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  13272. private:
  13273. Process();
  13274. Process (const Process&);
  13275. Process& operator= (const Process&);
  13276. };
  13277. #endif // __JUCE_PROCESS_JUCEHEADER__
  13278. /*** End of inlined file: juce_Process.h ***/
  13279. #endif
  13280. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13281. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  13282. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13283. #define __JUCE_READWRITELOCK_JUCEHEADER__
  13284. /*** Start of inlined file: juce_WaitableEvent.h ***/
  13285. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13286. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  13287. /**
  13288. Allows threads to wait for events triggered by other threads.
  13289. A thread can call wait() on a WaitableObject, and this will suspend the
  13290. calling thread until another thread wakes it up by calling the signal()
  13291. method.
  13292. */
  13293. class JUCE_API WaitableEvent
  13294. {
  13295. public:
  13296. /** Creates a WaitableEvent object.
  13297. @param manualReset If this is false, the event will be reset automatically when the wait()
  13298. method is called. If manualReset is true, then once the event is signalled,
  13299. the only way to reset it will be by calling the reset() method.
  13300. */
  13301. WaitableEvent (bool manualReset = false) throw();
  13302. /** Destructor.
  13303. If other threads are waiting on this object when it gets deleted, this
  13304. can cause nasty errors, so be careful!
  13305. */
  13306. ~WaitableEvent() throw();
  13307. /** Suspends the calling thread until the event has been signalled.
  13308. This will wait until the object's signal() method is called by another thread,
  13309. or until the timeout expires.
  13310. After the event has been signalled, this method will return true and if manualReset
  13311. was set to false in the WaitableEvent's constructor, then the event will be reset.
  13312. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  13313. value will cause it to wait forever.
  13314. @returns true if the object has been signalled, false if the timeout expires first.
  13315. @see signal, reset
  13316. */
  13317. bool wait (int timeOutMilliseconds = -1) const throw();
  13318. /** Wakes up any threads that are currently waiting on this object.
  13319. If signal() is called when nothing is waiting, the next thread to call wait()
  13320. will return immediately and reset the signal.
  13321. @see wait, reset
  13322. */
  13323. void signal() const throw();
  13324. /** Resets the event to an unsignalled state.
  13325. If it's not already signalled, this does nothing.
  13326. */
  13327. void reset() const throw();
  13328. juce_UseDebuggingNewOperator
  13329. private:
  13330. void* internal;
  13331. WaitableEvent (const WaitableEvent&);
  13332. WaitableEvent& operator= (const WaitableEvent&);
  13333. };
  13334. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  13335. /*** End of inlined file: juce_WaitableEvent.h ***/
  13336. /*** Start of inlined file: juce_Thread.h ***/
  13337. #ifndef __JUCE_THREAD_JUCEHEADER__
  13338. #define __JUCE_THREAD_JUCEHEADER__
  13339. /**
  13340. Encapsulates a thread.
  13341. Subclasses derive from Thread and implement the run() method, in which they
  13342. do their business. The thread can then be started with the startThread() method
  13343. and controlled with various other methods.
  13344. This class also contains some thread-related static methods, such
  13345. as sleep(), yield(), getCurrentThreadId() etc.
  13346. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  13347. MessageManagerLock
  13348. */
  13349. class JUCE_API Thread
  13350. {
  13351. public:
  13352. /**
  13353. Creates a thread.
  13354. When first created, the thread is not running. Use the startThread()
  13355. method to start it.
  13356. */
  13357. explicit Thread (const String& threadName);
  13358. /** Destructor.
  13359. Deleting a Thread object that is running will only give the thread a
  13360. brief opportunity to stop itself cleanly, so it's recommended that you
  13361. should always call stopThread() with a decent timeout before deleting,
  13362. to avoid the thread being forcibly killed (which is a Bad Thing).
  13363. */
  13364. virtual ~Thread();
  13365. /** Must be implemented to perform the thread's actual code.
  13366. Remember that the thread must regularly check the threadShouldExit()
  13367. method whilst running, and if this returns true it should return from
  13368. the run() method as soon as possible to avoid being forcibly killed.
  13369. @see threadShouldExit, startThread
  13370. */
  13371. virtual void run() = 0;
  13372. // Thread control functions..
  13373. /** Starts the thread running.
  13374. This will start the thread's run() method.
  13375. (if it's already started, startThread() won't do anything).
  13376. @see stopThread
  13377. */
  13378. void startThread();
  13379. /** Starts the thread with a given priority.
  13380. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  13381. If the thread is already running, its priority will be changed.
  13382. @see startThread, setPriority
  13383. */
  13384. void startThread (int priority);
  13385. /** Attempts to stop the thread running.
  13386. This method will cause the threadShouldExit() method to return true
  13387. and call notify() in case the thread is currently waiting.
  13388. Hopefully the thread will then respond to this by exiting cleanly, and
  13389. the stopThread method will wait for a given time-period for this to
  13390. happen.
  13391. If the thread is stuck and fails to respond after the time-out, it gets
  13392. forcibly killed, which is a very bad thing to happen, as it could still
  13393. be holding locks, etc. which are needed by other parts of your program.
  13394. @param timeOutMilliseconds The number of milliseconds to wait for the
  13395. thread to finish before killing it by force. A negative
  13396. value in here will wait forever.
  13397. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  13398. */
  13399. void stopThread (int timeOutMilliseconds);
  13400. /** Returns true if the thread is currently active */
  13401. bool isThreadRunning() const;
  13402. /** Sets a flag to tell the thread it should stop.
  13403. Calling this means that the threadShouldExit() method will then return true.
  13404. The thread should be regularly checking this to see whether it should exit.
  13405. If your thread makes use of wait(), you might want to call notify() after calling
  13406. this method, to interrupt any waits that might be in progress, and allow it
  13407. to reach a point where it can exit.
  13408. @see threadShouldExit
  13409. @see waitForThreadToExit
  13410. */
  13411. void signalThreadShouldExit();
  13412. /** Checks whether the thread has been told to stop running.
  13413. Threads need to check this regularly, and if it returns true, they should
  13414. return from their run() method at the first possible opportunity.
  13415. @see signalThreadShouldExit
  13416. */
  13417. inline bool threadShouldExit() const { return threadShouldExit_; }
  13418. /** Waits for the thread to stop.
  13419. This will waits until isThreadRunning() is false or until a timeout expires.
  13420. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  13421. is less than zero, it will wait forever.
  13422. @returns true if the thread exits, or false if the timeout expires first.
  13423. */
  13424. bool waitForThreadToExit (int timeOutMilliseconds) const;
  13425. /** Changes the thread's priority.
  13426. May return false if for some reason the priority can't be changed.
  13427. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  13428. of 5 is normal.
  13429. */
  13430. bool setPriority (int priority);
  13431. /** Changes the priority of the caller thread.
  13432. Similar to setPriority(), but this static method acts on the caller thread.
  13433. May return false if for some reason the priority can't be changed.
  13434. @see setPriority
  13435. */
  13436. static bool setCurrentThreadPriority (int priority);
  13437. /** Sets the affinity mask for the thread.
  13438. This will only have an effect next time the thread is started - i.e. if the
  13439. thread is already running when called, it'll have no effect.
  13440. @see setCurrentThreadAffinityMask
  13441. */
  13442. void setAffinityMask (uint32 affinityMask);
  13443. /** Changes the affinity mask for the caller thread.
  13444. This will change the affinity mask for the thread that calls this static method.
  13445. @see setAffinityMask
  13446. */
  13447. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  13448. // this can be called from any thread that needs to pause..
  13449. static void JUCE_CALLTYPE sleep (int milliseconds);
  13450. /** Yields the calling thread's current time-slot. */
  13451. static void JUCE_CALLTYPE yield();
  13452. /** Makes the thread wait for a notification.
  13453. This puts the thread to sleep until either the timeout period expires, or
  13454. another thread calls the notify() method to wake it up.
  13455. A negative time-out value means that the method will wait indefinitely.
  13456. @returns true if the event has been signalled, false if the timeout expires.
  13457. */
  13458. bool wait (int timeOutMilliseconds) const;
  13459. /** Wakes up the thread.
  13460. If the thread has called the wait() method, this will wake it up.
  13461. @see wait
  13462. */
  13463. void notify() const;
  13464. /** A value type used for thread IDs.
  13465. @see getCurrentThreadId(), getThreadId()
  13466. */
  13467. typedef void* ThreadID;
  13468. /** Returns an id that identifies the caller thread.
  13469. To find the ID of a particular thread object, use getThreadId().
  13470. @returns a unique identifier that identifies the calling thread.
  13471. @see getThreadId
  13472. */
  13473. static ThreadID getCurrentThreadId();
  13474. /** Finds the thread object that is currently running.
  13475. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  13476. object associated with them, so this will return 0.
  13477. */
  13478. static Thread* getCurrentThread();
  13479. /** Returns the ID of this thread.
  13480. That means the ID of this thread object - not of the thread that's calling the method.
  13481. This can change when the thread is started and stopped, and will be invalid if the
  13482. thread's not actually running.
  13483. @see getCurrentThreadId
  13484. */
  13485. ThreadID getThreadId() const throw() { return threadId_; }
  13486. /** Returns the name of the thread.
  13487. This is the name that gets set in the constructor.
  13488. */
  13489. const String getThreadName() const { return threadName_; }
  13490. /** Returns the number of currently-running threads.
  13491. @returns the number of Thread objects known to be currently running.
  13492. @see stopAllThreads
  13493. */
  13494. static int getNumRunningThreads();
  13495. /** Tries to stop all currently-running threads.
  13496. This will attempt to stop all the threads known to be running at the moment.
  13497. */
  13498. static void stopAllThreads (int timeoutInMillisecs);
  13499. juce_UseDebuggingNewOperator
  13500. private:
  13501. const String threadName_;
  13502. void* volatile threadHandle_;
  13503. CriticalSection startStopLock;
  13504. WaitableEvent startSuspensionEvent_, defaultEvent_;
  13505. int threadPriority_;
  13506. ThreadID threadId_;
  13507. uint32 affinityMask_;
  13508. bool volatile threadShouldExit_;
  13509. friend void JUCE_API juce_threadEntryPoint (void*);
  13510. static void threadEntryPoint (Thread* thread);
  13511. static Array<Thread*> runningThreads;
  13512. static CriticalSection runningThreadsLock;
  13513. Thread (const Thread&);
  13514. Thread& operator= (const Thread&);
  13515. };
  13516. #endif // __JUCE_THREAD_JUCEHEADER__
  13517. /*** End of inlined file: juce_Thread.h ***/
  13518. /**
  13519. A critical section that allows multiple simultaneous readers.
  13520. Features of this type of lock are:
  13521. - Multiple readers can hold the lock at the same time, but only one writer
  13522. can hold it at once.
  13523. - Writers trying to gain the lock will be blocked until all readers and writers
  13524. have released it
  13525. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  13526. blocked until the writer has obtained and released it
  13527. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  13528. there are no other readers
  13529. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  13530. - Recursive locking is supported.
  13531. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  13532. */
  13533. class JUCE_API ReadWriteLock
  13534. {
  13535. public:
  13536. /**
  13537. Creates a ReadWriteLock object.
  13538. */
  13539. ReadWriteLock() throw();
  13540. /** Destructor.
  13541. If the object is deleted whilst locked, any subsequent behaviour
  13542. is unpredictable.
  13543. */
  13544. ~ReadWriteLock() throw();
  13545. /** Locks this object for reading.
  13546. Multiple threads can simulaneously lock the object for reading, but if another
  13547. thread has it locked for writing, then this will block until it releases the
  13548. lock.
  13549. @see exitRead, ScopedReadLock
  13550. */
  13551. void enterRead() const throw();
  13552. /** Releases the read-lock.
  13553. If the caller thread hasn't got the lock, this can have unpredictable results.
  13554. If the enterRead() method has been called multiple times by the thread, each
  13555. call must be matched by a call to exitRead() before other threads will be allowed
  13556. to take over the lock.
  13557. @see enterRead, ScopedReadLock
  13558. */
  13559. void exitRead() const throw();
  13560. /** Locks this object for writing.
  13561. This will block until any other threads that have it locked for reading or
  13562. writing have released their lock.
  13563. @see exitWrite, ScopedWriteLock
  13564. */
  13565. void enterWrite() const throw();
  13566. /** Tries to lock this object for writing.
  13567. This is like enterWrite(), but doesn't block - it returns true if it manages
  13568. to obtain the lock.
  13569. @see enterWrite
  13570. */
  13571. bool tryEnterWrite() const throw();
  13572. /** Releases the write-lock.
  13573. If the caller thread hasn't got the lock, this can have unpredictable results.
  13574. If the enterWrite() method has been called multiple times by the thread, each
  13575. call must be matched by a call to exit() before other threads will be allowed
  13576. to take over the lock.
  13577. @see enterWrite, ScopedWriteLock
  13578. */
  13579. void exitWrite() const throw();
  13580. juce_UseDebuggingNewOperator
  13581. private:
  13582. CriticalSection accessLock;
  13583. WaitableEvent waitEvent;
  13584. mutable int numWaitingWriters, numWriters;
  13585. mutable Thread::ThreadID writerThreadId;
  13586. mutable Array <Thread::ThreadID> readerThreads;
  13587. ReadWriteLock (const ReadWriteLock&);
  13588. ReadWriteLock& operator= (const ReadWriteLock&);
  13589. };
  13590. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  13591. /*** End of inlined file: juce_ReadWriteLock.h ***/
  13592. #endif
  13593. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13594. #endif
  13595. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13596. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  13597. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13598. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13599. /**
  13600. Automatically locks and unlocks a ReadWriteLock object.
  13601. Use one of these as a local variable to control access to a ReadWriteLock.
  13602. e.g. @code
  13603. ReadWriteLock myLock;
  13604. for (;;)
  13605. {
  13606. const ScopedReadLock myScopedLock (myLock);
  13607. // myLock is now locked
  13608. ...do some stuff...
  13609. // myLock gets unlocked here.
  13610. }
  13611. @endcode
  13612. @see ReadWriteLock, ScopedWriteLock
  13613. */
  13614. class JUCE_API ScopedReadLock
  13615. {
  13616. public:
  13617. /** Creates a ScopedReadLock.
  13618. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  13619. when the ScopedReadLock object is deleted, the ReadWriteLock will
  13620. be unlocked.
  13621. Make sure this object is created and deleted by the same thread,
  13622. otherwise there are no guarantees what will happen! Best just to use it
  13623. as a local stack object, rather than creating one with the new() operator.
  13624. */
  13625. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  13626. /** Destructor.
  13627. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  13628. Make sure this object is created and deleted by the same thread,
  13629. otherwise there are no guarantees what will happen!
  13630. */
  13631. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  13632. private:
  13633. const ReadWriteLock& lock_;
  13634. ScopedReadLock (const ScopedReadLock&);
  13635. ScopedReadLock& operator= (const ScopedReadLock&);
  13636. };
  13637. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13638. /*** End of inlined file: juce_ScopedReadLock.h ***/
  13639. #endif
  13640. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13641. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  13642. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13643. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13644. /**
  13645. Automatically tries to lock and unlock a CriticalSection object.
  13646. Use one of these as a local variable to control access to a CriticalSection.
  13647. e.g. @code
  13648. CriticalSection myCriticalSection;
  13649. for (;;)
  13650. {
  13651. const ScopedTryLock myScopedTryLock (myCriticalSection);
  13652. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  13653. // should test this with the isLocked() method before doing your thread-unsafe
  13654. // action..
  13655. if (myScopedTryLock.isLocked())
  13656. {
  13657. ...do some stuff...
  13658. }
  13659. else
  13660. {
  13661. ..our attempt at locking failed because another thread had already locked it..
  13662. }
  13663. // myCriticalSection gets unlocked here (if it was locked)
  13664. }
  13665. @endcode
  13666. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  13667. */
  13668. class JUCE_API ScopedTryLock
  13669. {
  13670. public:
  13671. /** Creates a ScopedTryLock.
  13672. As soon as it is created, this will try to lock the CriticalSection, and
  13673. when the ScopedTryLock object is deleted, the CriticalSection will
  13674. be unlocked if the lock was successful.
  13675. Make sure this object is created and deleted by the same thread,
  13676. otherwise there are no guarantees what will happen! Best just to use it
  13677. as a local stack object, rather than creating one with the new() operator.
  13678. */
  13679. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  13680. /** Destructor.
  13681. The CriticalSection will be unlocked (if locked) when the destructor is called.
  13682. Make sure this object is created and deleted by the same thread,
  13683. otherwise there are no guarantees what will happen!
  13684. */
  13685. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  13686. /** Returns true if the CriticalSection was successfully locked. */
  13687. bool isLocked() const throw() { return lockWasSuccessful; }
  13688. private:
  13689. const CriticalSection& lock_;
  13690. const bool lockWasSuccessful;
  13691. ScopedTryLock (const ScopedTryLock&);
  13692. ScopedTryLock& operator= (const ScopedTryLock&);
  13693. };
  13694. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13695. /*** End of inlined file: juce_ScopedTryLock.h ***/
  13696. #endif
  13697. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13698. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  13699. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13700. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13701. /**
  13702. Automatically locks and unlocks a ReadWriteLock object.
  13703. Use one of these as a local variable to control access to a ReadWriteLock.
  13704. e.g. @code
  13705. ReadWriteLock myLock;
  13706. for (;;)
  13707. {
  13708. const ScopedWriteLock myScopedLock (myLock);
  13709. // myLock is now locked
  13710. ...do some stuff...
  13711. // myLock gets unlocked here.
  13712. }
  13713. @endcode
  13714. @see ReadWriteLock, ScopedReadLock
  13715. */
  13716. class JUCE_API ScopedWriteLock
  13717. {
  13718. public:
  13719. /** Creates a ScopedWriteLock.
  13720. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  13721. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  13722. be unlocked.
  13723. Make sure this object is created and deleted by the same thread,
  13724. otherwise there are no guarantees what will happen! Best just to use it
  13725. as a local stack object, rather than creating one with the new() operator.
  13726. */
  13727. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  13728. /** Destructor.
  13729. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  13730. Make sure this object is created and deleted by the same thread,
  13731. otherwise there are no guarantees what will happen!
  13732. */
  13733. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  13734. private:
  13735. const ReadWriteLock& lock_;
  13736. ScopedWriteLock (const ScopedWriteLock&);
  13737. ScopedWriteLock& operator= (const ScopedWriteLock&);
  13738. };
  13739. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13740. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  13741. #endif
  13742. #ifndef __JUCE_THREAD_JUCEHEADER__
  13743. #endif
  13744. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13745. /*** Start of inlined file: juce_ThreadPool.h ***/
  13746. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13747. #define __JUCE_THREADPOOL_JUCEHEADER__
  13748. class ThreadPool;
  13749. class ThreadPoolThread;
  13750. /**
  13751. A task that is executed by a ThreadPool object.
  13752. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  13753. its threads.
  13754. The runJob() method needs to be implemented to do the task, and if the code that
  13755. does the work takes a significant time to run, it must keep checking the shouldExit()
  13756. method to see if something is trying to interrupt the job. If shouldExit() returns
  13757. true, the runJob() method must return immediately.
  13758. @see ThreadPool, Thread
  13759. */
  13760. class JUCE_API ThreadPoolJob
  13761. {
  13762. public:
  13763. /** Creates a thread pool job object.
  13764. After creating your job, add it to a thread pool with ThreadPool::addJob().
  13765. */
  13766. explicit ThreadPoolJob (const String& name);
  13767. /** Destructor. */
  13768. virtual ~ThreadPoolJob();
  13769. /** Returns the name of this job.
  13770. @see setJobName
  13771. */
  13772. const String getJobName() const;
  13773. /** Changes the job's name.
  13774. @see getJobName
  13775. */
  13776. void setJobName (const String& newName);
  13777. /** These are the values that can be returned by the runJob() method.
  13778. */
  13779. enum JobStatus
  13780. {
  13781. jobHasFinished = 0, /**< indicates that the job has finished and can be
  13782. removed from the pool. */
  13783. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  13784. should be automatically deleted by the pool. */
  13785. jobNeedsRunningAgain /**< indicates that the job would like to be called
  13786. again when a thread is free. */
  13787. };
  13788. /** Peforms the actual work that this job needs to do.
  13789. Your subclass must implement this method, in which is does its work.
  13790. If the code in this method takes a significant time to run, it must repeatedly check
  13791. the shouldExit() method to see if something is trying to interrupt the job.
  13792. If shouldExit() ever returns true, the runJob() method must return immediately.
  13793. If this method returns jobHasFinished, then the job will be removed from the pool
  13794. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  13795. pool and will get a chance to run again as soon as a thread is free.
  13796. @see shouldExit()
  13797. */
  13798. virtual JobStatus runJob() = 0;
  13799. /** Returns true if this job is currently running its runJob() method. */
  13800. bool isRunning() const { return isActive; }
  13801. /** Returns true if something is trying to interrupt this job and make it stop.
  13802. Your runJob() method must call this whenever it gets a chance, and if it ever
  13803. returns true, the runJob() method must return immediately.
  13804. @see signalJobShouldExit()
  13805. */
  13806. bool shouldExit() const { return shouldStop; }
  13807. /** Calling this will cause the shouldExit() method to return true, and the job
  13808. should (if it's been implemented correctly) stop as soon as possible.
  13809. @see shouldExit()
  13810. */
  13811. void signalJobShouldExit();
  13812. juce_UseDebuggingNewOperator
  13813. private:
  13814. friend class ThreadPool;
  13815. friend class ThreadPoolThread;
  13816. String jobName;
  13817. ThreadPool* pool;
  13818. bool shouldStop, isActive, shouldBeDeleted;
  13819. ThreadPoolJob (const ThreadPoolJob&);
  13820. ThreadPoolJob& operator= (const ThreadPoolJob&);
  13821. };
  13822. /**
  13823. A set of threads that will run a list of jobs.
  13824. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  13825. will be called by the next pooled thread that becomes free.
  13826. @see ThreadPoolJob, Thread
  13827. */
  13828. class JUCE_API ThreadPool
  13829. {
  13830. public:
  13831. /** Creates a thread pool.
  13832. Once you've created a pool, you can give it some things to do with the addJob()
  13833. method.
  13834. @param numberOfThreads the maximum number of actual threads to run.
  13835. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  13836. until there are some jobs to run. If false, then
  13837. all the threads will be fired-up immediately so that
  13838. they're ready for action
  13839. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  13840. inactive for this length of time, they will automatically
  13841. be stopped until more jobs come along and they're needed
  13842. */
  13843. ThreadPool (int numberOfThreads,
  13844. bool startThreadsOnlyWhenNeeded = true,
  13845. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  13846. /** Destructor.
  13847. This will attempt to remove all the jobs before deleting, but if you want to
  13848. specify a timeout, you should call removeAllJobs() explicitly before deleting
  13849. the pool.
  13850. */
  13851. ~ThreadPool();
  13852. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  13853. for some kind of operation.
  13854. @see ThreadPool::removeAllJobs
  13855. */
  13856. class JUCE_API JobSelector
  13857. {
  13858. public:
  13859. virtual ~JobSelector() {}
  13860. /** Should return true if the specified thread matches your criteria for whatever
  13861. operation that this object is being used for.
  13862. Any implementation of this method must be extremely fast and thread-safe!
  13863. */
  13864. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  13865. };
  13866. /** Adds a job to the queue.
  13867. Once a job has been added, then the next time a thread is free, it will run
  13868. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  13869. runJob() method, the pool will either remove the job from the pool or add it to
  13870. the back of the queue to be run again.
  13871. */
  13872. void addJob (ThreadPoolJob* job);
  13873. /** Tries to remove a job from the pool.
  13874. If the job isn't yet running, this will simply remove it. If it is running, it
  13875. will wait for it to finish.
  13876. If the timeout period expires before the job finishes running, then the job will be
  13877. left in the pool and this will return false. It returns true if the job is sucessfully
  13878. stopped and removed.
  13879. @param job the job to remove
  13880. @param interruptIfRunning if true, then if the job is currently busy, its
  13881. ThreadPoolJob::signalJobShouldExit() method will be called to try
  13882. to interrupt it. If false, then if the job will be allowed to run
  13883. until it stops normally (or the timeout expires)
  13884. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  13885. before giving up and returning false
  13886. */
  13887. bool removeJob (ThreadPoolJob* job,
  13888. bool interruptIfRunning,
  13889. int timeOutMilliseconds);
  13890. /** Tries to remove all jobs from the pool.
  13891. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  13892. methods called to try to interrupt them
  13893. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  13894. before giving up and returning false
  13895. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  13896. they will simply be removed from the pool. Jobs that are already running when
  13897. this method is called can choose whether they should be deleted by
  13898. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  13899. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  13900. jobs should be removed. If it is zero, all jobs are removed
  13901. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  13902. expires while waiting for one or more jobs to stop
  13903. */
  13904. bool removeAllJobs (bool interruptRunningJobs,
  13905. int timeOutMilliseconds,
  13906. bool deleteInactiveJobs = false,
  13907. JobSelector* selectedJobsToRemove = 0);
  13908. /** Returns the number of jobs currently running or queued.
  13909. */
  13910. int getNumJobs() const;
  13911. /** Returns one of the jobs in the queue.
  13912. Note that this can be a very volatile list as jobs might be continuously getting shifted
  13913. around in the list, and this method may return 0 if the index is currently out-of-range.
  13914. */
  13915. ThreadPoolJob* getJob (int index) const;
  13916. /** Returns true if the given job is currently queued or running.
  13917. @see isJobRunning()
  13918. */
  13919. bool contains (const ThreadPoolJob* job) const;
  13920. /** Returns true if the given job is currently being run by a thread.
  13921. */
  13922. bool isJobRunning (const ThreadPoolJob* job) const;
  13923. /** Waits until a job has finished running and has been removed from the pool.
  13924. This will wait until the job is no longer in the pool - i.e. until its
  13925. runJob() method returns ThreadPoolJob::jobHasFinished.
  13926. If the timeout period expires before the job finishes, this will return false;
  13927. it returns true if the job has finished successfully.
  13928. */
  13929. bool waitForJobToFinish (const ThreadPoolJob* job,
  13930. int timeOutMilliseconds) const;
  13931. /** Returns a list of the names of all the jobs currently running or queued.
  13932. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  13933. */
  13934. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  13935. /** Changes the priority of all the threads.
  13936. This will call Thread::setPriority() for each thread in the pool.
  13937. May return false if for some reason the priority can't be changed.
  13938. */
  13939. bool setThreadPriorities (int newPriority);
  13940. juce_UseDebuggingNewOperator
  13941. private:
  13942. const int threadStopTimeout;
  13943. int priority;
  13944. class ThreadPoolThread;
  13945. OwnedArray <ThreadPoolThread> threads;
  13946. Array <ThreadPoolJob*> jobs;
  13947. CriticalSection lock;
  13948. uint32 lastJobEndTime;
  13949. WaitableEvent jobFinishedSignal;
  13950. friend class ThreadPoolThread;
  13951. bool runNextJob();
  13952. ThreadPool (const ThreadPool&);
  13953. ThreadPool& operator= (const ThreadPool&);
  13954. };
  13955. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  13956. /*** End of inlined file: juce_ThreadPool.h ***/
  13957. #endif
  13958. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13959. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  13960. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13961. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13962. /**
  13963. Used by the TimeSliceThread class.
  13964. To register your class with a TimeSliceThread, derive from this class and
  13965. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  13966. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  13967. deleting your client!
  13968. @see TimeSliceThread
  13969. */
  13970. class JUCE_API TimeSliceClient
  13971. {
  13972. public:
  13973. /** Destructor. */
  13974. virtual ~TimeSliceClient() {}
  13975. /** Called back by a TimeSliceThread.
  13976. When you register this class with it, a TimeSliceThread will repeatedly call
  13977. this method.
  13978. The implementation of this method should use its time-slice to do something that's
  13979. quick - never block for longer than absolutely necessary.
  13980. @returns Your method should return true if it needs more time, or false if it's
  13981. not too busy and doesn't need calling back urgently. If all the thread's
  13982. clients indicate that they're not busy, then it'll save CPU by sleeping for
  13983. up to half a second in between callbacks. You can force the TimeSliceThread
  13984. to wake up and poll again immediately by calling its notify() method.
  13985. */
  13986. virtual bool useTimeSlice() = 0;
  13987. };
  13988. /**
  13989. A thread that keeps a list of clients, and calls each one in turn, giving them
  13990. all a chance to run some sort of short task.
  13991. @see TimeSliceClient, Thread
  13992. */
  13993. class JUCE_API TimeSliceThread : public Thread
  13994. {
  13995. public:
  13996. /**
  13997. Creates a TimeSliceThread.
  13998. When first created, the thread is not running. Use the startThread()
  13999. method to start it.
  14000. */
  14001. explicit TimeSliceThread (const String& threadName);
  14002. /** Destructor.
  14003. Deleting a Thread object that is running will only give the thread a
  14004. brief opportunity to stop itself cleanly, so it's recommended that you
  14005. should always call stopThread() with a decent timeout before deleting,
  14006. to avoid the thread being forcibly killed (which is a Bad Thing).
  14007. */
  14008. ~TimeSliceThread();
  14009. /** Adds a client to the list.
  14010. The client's callbacks will start immediately (possibly before the method
  14011. has returned).
  14012. */
  14013. void addTimeSliceClient (TimeSliceClient* client);
  14014. /** Removes a client from the list.
  14015. This method will make sure that all callbacks to the client have completely
  14016. finished before the method returns.
  14017. */
  14018. void removeTimeSliceClient (TimeSliceClient* client);
  14019. /** Returns the number of registered clients. */
  14020. int getNumClients() const;
  14021. /** Returns one of the registered clients. */
  14022. TimeSliceClient* getClient (int index) const;
  14023. /** @internal */
  14024. void run();
  14025. juce_UseDebuggingNewOperator
  14026. private:
  14027. CriticalSection callbackLock, listLock;
  14028. Array <TimeSliceClient*> clients;
  14029. int index;
  14030. TimeSliceClient* clientBeingCalled;
  14031. bool clientsChanged;
  14032. TimeSliceThread (const TimeSliceThread&);
  14033. TimeSliceThread& operator= (const TimeSliceThread&);
  14034. };
  14035. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  14036. /*** End of inlined file: juce_TimeSliceThread.h ***/
  14037. #endif
  14038. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  14039. #endif
  14040. #endif
  14041. /*** End of inlined file: juce_core_includes.h ***/
  14042. // if you're compiling a command-line app, you might want to just include the core headers,
  14043. // so you can set this macro before including juce.h
  14044. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  14045. /*** Start of inlined file: juce_app_includes.h ***/
  14046. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  14047. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  14048. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  14049. /*** Start of inlined file: juce_Application.h ***/
  14050. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  14051. #define __JUCE_APPLICATION_JUCEHEADER__
  14052. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  14053. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  14054. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  14055. /*** Start of inlined file: juce_Component.h ***/
  14056. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  14057. #define __JUCE_COMPONENT_JUCEHEADER__
  14058. /*** Start of inlined file: juce_MouseCursor.h ***/
  14059. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  14060. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  14061. class Image;
  14062. class ComponentPeer;
  14063. class Component;
  14064. /**
  14065. Represents a mouse cursor image.
  14066. This object can either be used to represent one of the standard mouse
  14067. cursor shapes, or a custom one generated from an image.
  14068. */
  14069. class JUCE_API MouseCursor
  14070. {
  14071. public:
  14072. /** The set of available standard mouse cursors. */
  14073. enum StandardCursorType
  14074. {
  14075. NoCursor = 0, /**< An invisible cursor. */
  14076. NormalCursor, /**< The stardard arrow cursor. */
  14077. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  14078. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  14079. CrosshairCursor, /**< A pair of crosshairs. */
  14080. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  14081. that you're dragging a copy of something. */
  14082. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  14083. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  14084. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  14085. UpDownResizeCursor, /**< an arrow pointing up and down. */
  14086. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  14087. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  14088. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  14089. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  14090. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  14091. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  14092. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  14093. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  14094. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  14095. };
  14096. /** Creates the standard arrow cursor. */
  14097. MouseCursor();
  14098. /** Creates one of the standard mouse cursor */
  14099. MouseCursor (StandardCursorType type);
  14100. /** Creates a custom cursor from an image.
  14101. @param image the image to use for the cursor - if this is bigger than the
  14102. system can manage, it might get scaled down first, and might
  14103. also have to be turned to black-and-white if it can't do colour
  14104. cursors.
  14105. @param hotSpotX the x position of the cursor's hotspot within the image
  14106. @param hotSpotY the y position of the cursor's hotspot within the image
  14107. */
  14108. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  14109. /** Creates a copy of another cursor object. */
  14110. MouseCursor (const MouseCursor& other);
  14111. /** Copies this cursor from another object. */
  14112. MouseCursor& operator= (const MouseCursor& other);
  14113. /** Destructor. */
  14114. ~MouseCursor();
  14115. /** Checks whether two mouse cursors are the same.
  14116. For custom cursors, two cursors created from the same image won't be
  14117. recognised as the same, only MouseCursor objects that have been
  14118. copied from the same object.
  14119. */
  14120. bool operator== (const MouseCursor& other) const throw();
  14121. /** Checks whether two mouse cursors are the same.
  14122. For custom cursors, two cursors created from the same image won't be
  14123. recognised as the same, only MouseCursor objects that have been
  14124. copied from the same object.
  14125. */
  14126. bool operator!= (const MouseCursor& other) const throw();
  14127. /** Makes the system show its default 'busy' cursor.
  14128. This will turn the system cursor to an hourglass or spinning beachball
  14129. until the next time the mouse is moved, or hideWaitCursor() is called.
  14130. This is handy if the message loop is about to block for a couple of
  14131. seconds while busy and you want to give the user feedback about this.
  14132. @see MessageManager::setTimeBeforeShowingWaitCursor
  14133. */
  14134. static void showWaitCursor();
  14135. /** If showWaitCursor has been called, this will return the mouse to its
  14136. normal state.
  14137. This will look at what component is under the mouse, and update the
  14138. cursor to be the correct one for that component.
  14139. @see showWaitCursor
  14140. */
  14141. static void hideWaitCursor();
  14142. juce_UseDebuggingNewOperator
  14143. private:
  14144. class SharedCursorHandle;
  14145. friend class SharedCursorHandle;
  14146. SharedCursorHandle* cursorHandle;
  14147. friend class MouseInputSourceInternal;
  14148. void showInWindow (ComponentPeer* window) const;
  14149. void showInAllWindows() const;
  14150. void* getHandle() const throw();
  14151. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  14152. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  14153. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  14154. };
  14155. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  14156. /*** End of inlined file: juce_MouseCursor.h ***/
  14157. /*** Start of inlined file: juce_MouseListener.h ***/
  14158. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  14159. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  14160. class MouseEvent;
  14161. /**
  14162. A MouseListener can be registered with a component to receive callbacks
  14163. about mouse events that happen to that component.
  14164. @see Component::addMouseListener, Component::removeMouseListener
  14165. */
  14166. class JUCE_API MouseListener
  14167. {
  14168. public:
  14169. /** Destructor. */
  14170. virtual ~MouseListener() {}
  14171. /** Called when the mouse moves inside a component.
  14172. If the mouse button isn't pressed and the mouse moves over a component,
  14173. this will be called to let the component react to this.
  14174. A component will always get a mouseEnter callback before a mouseMove.
  14175. @param e details about the position and status of the mouse event, including
  14176. the source component in which it occurred
  14177. @see mouseEnter, mouseExit, mouseDrag, contains
  14178. */
  14179. virtual void mouseMove (const MouseEvent& e);
  14180. /** Called when the mouse first enters a component.
  14181. If the mouse button isn't pressed and the mouse moves into a component,
  14182. this will be called to let the component react to this.
  14183. When the mouse button is pressed and held down while being moved in
  14184. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  14185. mouseDrag messages are sent to the component that the mouse was originally
  14186. clicked on, until the button is released.
  14187. @param e details about the position and status of the mouse event, including
  14188. the source component in which it occurred
  14189. @see mouseExit, mouseDrag, mouseMove, contains
  14190. */
  14191. virtual void mouseEnter (const MouseEvent& e);
  14192. /** Called when the mouse moves out of a component.
  14193. This will be called when the mouse moves off the edge of this
  14194. component.
  14195. If the mouse button was pressed, and it was then dragged off the
  14196. edge of the component and released, then this callback will happen
  14197. when the button is released, after the mouseUp callback.
  14198. @param e details about the position and status of the mouse event, including
  14199. the source component in which it occurred
  14200. @see mouseEnter, mouseDrag, mouseMove, contains
  14201. */
  14202. virtual void mouseExit (const MouseEvent& e);
  14203. /** Called when a mouse button is pressed.
  14204. The MouseEvent object passed in contains lots of methods for finding out
  14205. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14206. were held down at the time.
  14207. Once a button is held down, the mouseDrag method will be called when the
  14208. mouse moves, until the button is released.
  14209. @param e details about the position and status of the mouse event, including
  14210. the source component in which it occurred
  14211. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  14212. */
  14213. virtual void mouseDown (const MouseEvent& e);
  14214. /** Called when the mouse is moved while a button is held down.
  14215. When a mouse button is pressed inside a component, that component
  14216. receives mouseDrag callbacks each time the mouse moves, even if the
  14217. mouse strays outside the component's bounds.
  14218. @param e details about the position and status of the mouse event, including
  14219. the source component in which it occurred
  14220. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  14221. */
  14222. virtual void mouseDrag (const MouseEvent& e);
  14223. /** Called when a mouse button is released.
  14224. A mouseUp callback is sent to the component in which a button was pressed
  14225. even if the mouse is actually over a different component when the
  14226. button is released.
  14227. The MouseEvent object passed in contains lots of methods for finding out
  14228. which buttons were down just before they were released.
  14229. @param e details about the position and status of the mouse event, including
  14230. the source component in which it occurred
  14231. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  14232. */
  14233. virtual void mouseUp (const MouseEvent& e);
  14234. /** Called when a mouse button has been double-clicked on a component.
  14235. The MouseEvent object passed in contains lots of methods for finding out
  14236. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14237. were held down at the time.
  14238. @param e details about the position and status of the mouse event, including
  14239. the source component in which it occurred
  14240. @see mouseDown, mouseUp
  14241. */
  14242. virtual void mouseDoubleClick (const MouseEvent& e);
  14243. /** Called when the mouse-wheel is moved.
  14244. This callback is sent to the component that the mouse is over when the
  14245. wheel is moved.
  14246. If not overridden, the component will forward this message to its parent, so
  14247. that parent components can collect mouse-wheel messages that happen to
  14248. child components which aren't interested in them.
  14249. @param e details about the position and status of the mouse event, including
  14250. the source component in which it occurred
  14251. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  14252. value means the wheel has been pushed to the right, negative means it
  14253. was pushed to the left
  14254. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  14255. value means the wheel has been pushed upwards, negative means it
  14256. was pushed downwards
  14257. */
  14258. virtual void mouseWheelMove (const MouseEvent& e,
  14259. float wheelIncrementX,
  14260. float wheelIncrementY);
  14261. };
  14262. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  14263. /*** End of inlined file: juce_MouseListener.h ***/
  14264. /*** Start of inlined file: juce_MouseEvent.h ***/
  14265. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  14266. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  14267. class Component;
  14268. class MouseInputSource;
  14269. /*** Start of inlined file: juce_ModifierKeys.h ***/
  14270. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  14271. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  14272. /**
  14273. Represents the state of the mouse buttons and modifier keys.
  14274. This is used both by mouse events and by KeyPress objects to describe
  14275. the state of keys such as shift, control, alt, etc.
  14276. @see KeyPress, MouseEvent::mods
  14277. */
  14278. class JUCE_API ModifierKeys
  14279. {
  14280. public:
  14281. /** Creates a ModifierKeys object from a raw set of flags.
  14282. @param flags to represent the keys that are down
  14283. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  14284. rightButtonModifier, commandModifier, popupMenuClickModifier
  14285. */
  14286. ModifierKeys (int flags = 0) throw();
  14287. /** Creates a copy of another object. */
  14288. ModifierKeys (const ModifierKeys& other) throw();
  14289. /** Copies this object from another one. */
  14290. ModifierKeys& operator= (const ModifierKeys& other) throw();
  14291. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  14292. This is a platform-agnostic way of checking for the operating system's
  14293. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  14294. Windows/Linux, it's actually checking for the CTRL key.
  14295. */
  14296. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  14297. /** Checks whether the user is trying to launch a pop-up menu.
  14298. This checks for platform-specific modifiers that might indicate that the user
  14299. is following the operating system's normal method of showing a pop-up menu.
  14300. So on Windows/Linux, this method is really testing for a right-click.
  14301. On the Mac, it tests for either the CTRL key being down, or a right-click.
  14302. */
  14303. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  14304. /** Checks whether the flag is set for the left mouse-button. */
  14305. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  14306. /** Checks whether the flag is set for the right mouse-button.
  14307. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  14308. this is platform-independent (and makes your code more explanatory too).
  14309. */
  14310. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  14311. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  14312. /** Tests for any of the mouse-button flags. */
  14313. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  14314. /** Tests for any of the modifier key flags. */
  14315. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  14316. /** Checks whether the shift key's flag is set. */
  14317. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  14318. /** Checks whether the CTRL key's flag is set.
  14319. Remember that it's better to use the platform-agnostic routines to test for command-key and
  14320. popup-menu modifiers.
  14321. @see isCommandDown, isPopupMenu
  14322. */
  14323. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  14324. /** Checks whether the shift key's flag is set. */
  14325. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  14326. /** Flags that represent the different keys. */
  14327. enum Flags
  14328. {
  14329. /** Shift key flag. */
  14330. shiftModifier = 1,
  14331. /** CTRL key flag. */
  14332. ctrlModifier = 2,
  14333. /** ALT key flag. */
  14334. altModifier = 4,
  14335. /** Left mouse button flag. */
  14336. leftButtonModifier = 16,
  14337. /** Right mouse button flag. */
  14338. rightButtonModifier = 32,
  14339. /** Middle mouse button flag. */
  14340. middleButtonModifier = 64,
  14341. #if JUCE_MAC
  14342. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14343. commandModifier = 8,
  14344. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14345. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14346. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  14347. #else
  14348. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14349. commandModifier = ctrlModifier,
  14350. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14351. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14352. popupMenuClickModifier = rightButtonModifier,
  14353. #endif
  14354. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  14355. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  14356. /** Represents a combination of all the mouse buttons at once. */
  14357. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  14358. };
  14359. /** Returns a copy of only the mouse-button flags */
  14360. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  14361. /** Returns a copy of only the non-mouse flags */
  14362. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  14363. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  14364. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  14365. /** Returns the raw flags for direct testing. */
  14366. inline int getRawFlags() const throw() { return flags; }
  14367. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  14368. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  14369. /** Tests a combination of flags and returns true if any of them are set. */
  14370. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14371. /** Returns the total number of mouse buttons that are down. */
  14372. int getNumMouseButtonsDown() const throw();
  14373. /** Creates a ModifierKeys object to represent the last-known state of the
  14374. keyboard and mouse buttons.
  14375. @see getCurrentModifiersRealtime
  14376. */
  14377. static const ModifierKeys getCurrentModifiers() throw();
  14378. /** Creates a ModifierKeys object to represent the current state of the
  14379. keyboard and mouse buttons.
  14380. This isn't often needed and isn't recommended, but will actively check all the
  14381. mouse and key states rather than just returning their last-known state like
  14382. getCurrentModifiers() does.
  14383. This is only needed in special circumstances for up-to-date modifier information
  14384. at times when the app's event loop isn't running normally.
  14385. */
  14386. static const ModifierKeys getCurrentModifiersRealtime() throw();
  14387. private:
  14388. int flags;
  14389. static ModifierKeys currentModifiers;
  14390. friend class ComponentPeer;
  14391. friend class MouseInputSource;
  14392. friend class MouseInputSourceInternal;
  14393. static void updateCurrentModifiers() throw();
  14394. };
  14395. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  14396. /*** End of inlined file: juce_ModifierKeys.h ***/
  14397. /*** Start of inlined file: juce_Point.h ***/
  14398. #ifndef __JUCE_POINT_JUCEHEADER__
  14399. #define __JUCE_POINT_JUCEHEADER__
  14400. /*** Start of inlined file: juce_AffineTransform.h ***/
  14401. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14402. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14403. /**
  14404. Represents a 2D affine-transformation matrix.
  14405. An affine transformation is a transformation such as a rotation, scale, shear,
  14406. resize or translation.
  14407. These are used for various 2D transformation tasks, e.g. with Path objects.
  14408. @see Path, Point, Line
  14409. */
  14410. class JUCE_API AffineTransform
  14411. {
  14412. public:
  14413. /** Creates an identity transform. */
  14414. AffineTransform() throw();
  14415. /** Creates a copy of another transform. */
  14416. AffineTransform (const AffineTransform& other) throw();
  14417. /** Creates a transform from a set of raw matrix values.
  14418. The resulting matrix is:
  14419. (mat00 mat01 mat02)
  14420. (mat10 mat11 mat12)
  14421. ( 0 0 1 )
  14422. */
  14423. AffineTransform (float mat00, float mat01, float mat02,
  14424. float mat10, float mat11, float mat12) throw();
  14425. /** Copies from another AffineTransform object */
  14426. AffineTransform& operator= (const AffineTransform& other) throw();
  14427. /** Compares two transforms. */
  14428. bool operator== (const AffineTransform& other) const throw();
  14429. /** Compares two transforms. */
  14430. bool operator!= (const AffineTransform& other) const throw();
  14431. /** A ready-to-use identity transform, which you can use to append other
  14432. transformations to.
  14433. e.g. @code
  14434. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  14435. .scaled (2.0f);
  14436. @endcode
  14437. */
  14438. static const AffineTransform identity;
  14439. /** Transforms a 2D co-ordinate using this matrix. */
  14440. template <typename ValueType>
  14441. void transformPoint (ValueType& x, ValueType& y) const throw()
  14442. {
  14443. const ValueType oldX = x;
  14444. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  14445. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  14446. }
  14447. /** Transforms two 2D co-ordinates using this matrix.
  14448. This is just a shortcut for calling transformPoint() on each of these pairs of
  14449. coordinates in turn. (And putting all the calculations into one function hopefully
  14450. also gives the compiler a bit more scope for pipelining it).
  14451. */
  14452. template <typename ValueType>
  14453. void transformPoints (ValueType& x1, ValueType& y1,
  14454. ValueType& x2, ValueType& y2) const throw()
  14455. {
  14456. const ValueType oldX1 = x1, oldX2 = x2;
  14457. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  14458. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  14459. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  14460. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  14461. }
  14462. /** Transforms three 2D co-ordinates using this matrix.
  14463. This is just a shortcut for calling transformPoint() on each of these pairs of
  14464. coordinates in turn. (And putting all the calculations into one function hopefully
  14465. also gives the compiler a bit more scope for pipelining it).
  14466. */
  14467. template <typename ValueType>
  14468. void transformPoints (ValueType& x1, ValueType& y1,
  14469. ValueType& x2, ValueType& y2,
  14470. ValueType& x3, ValueType& y3) const throw()
  14471. {
  14472. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  14473. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  14474. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  14475. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  14476. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  14477. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  14478. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  14479. }
  14480. /** Returns a new transform which is the same as this one followed by a translation. */
  14481. const AffineTransform translated (float deltaX,
  14482. float deltaY) const throw();
  14483. /** Returns a new transform which is a translation. */
  14484. static const AffineTransform translation (float deltaX,
  14485. float deltaY) throw();
  14486. /** Returns a transform which is the same as this one followed by a rotation.
  14487. The rotation is specified by a number of radians to rotate clockwise, centred around
  14488. the origin (0, 0).
  14489. */
  14490. const AffineTransform rotated (float angleInRadians) const throw();
  14491. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  14492. The rotation is specified by a number of radians to rotate clockwise, centred around
  14493. the co-ordinates passed in.
  14494. */
  14495. const AffineTransform rotated (float angleInRadians,
  14496. float pivotX,
  14497. float pivotY) const throw();
  14498. /** Returns a new transform which is a rotation about (0, 0). */
  14499. static const AffineTransform rotation (float angleInRadians) throw();
  14500. /** Returns a new transform which is a rotation about a given point. */
  14501. static const AffineTransform rotation (float angleInRadians,
  14502. float pivotX,
  14503. float pivotY) throw();
  14504. /** Returns a transform which is the same as this one followed by a re-scaling.
  14505. The scaling is centred around the origin (0, 0).
  14506. */
  14507. const AffineTransform scaled (float factorX,
  14508. float factorY) const throw();
  14509. /** Returns a new transform which is a re-scale about the origin. */
  14510. static const AffineTransform scale (float factorX,
  14511. float factorY) throw();
  14512. /** Returns a transform which is the same as this one followed by a shear.
  14513. The shear is centred around the origin (0, 0).
  14514. */
  14515. const AffineTransform sheared (float shearX,
  14516. float shearY) const throw();
  14517. /** Returns a matrix which is the inverse operation of this one.
  14518. Some matrices don't have an inverse - in this case, the method will just return
  14519. an identity transform.
  14520. */
  14521. const AffineTransform inverted() const throw();
  14522. /** Returns the transform that will map three known points onto three coordinates
  14523. that are supplied.
  14524. This returns the transform that will transform (0, 0) into (x00, y00),
  14525. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  14526. */
  14527. static const AffineTransform fromTargetPoints (float x00, float y00,
  14528. float x10, float y10,
  14529. float x01, float y01) throw();
  14530. /** Returns the transform that will map three specified points onto three target points.
  14531. */
  14532. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  14533. float sourceX2, float sourceY2, float targetX2, float targetY2,
  14534. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  14535. /** Returns the result of concatenating another transformation after this one. */
  14536. const AffineTransform followedBy (const AffineTransform& other) const throw();
  14537. /** Returns true if this transform has no effect on points. */
  14538. bool isIdentity() const throw();
  14539. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  14540. bool isSingularity() const throw();
  14541. /** Returns true if the transform only translates, and doesn't scale or rotate the
  14542. points. */
  14543. bool isOnlyTranslation() const throw();
  14544. /** If this transform is only a translation, this returns the X offset.
  14545. @see isOnlyTranslation
  14546. */
  14547. float getTranslationX() const throw() { return mat02; }
  14548. /** If this transform is only a translation, this returns the X offset.
  14549. @see isOnlyTranslation
  14550. */
  14551. float getTranslationY() const throw() { return mat12; }
  14552. /* The transform matrix is:
  14553. (mat00 mat01 mat02)
  14554. (mat10 mat11 mat12)
  14555. ( 0 0 1 )
  14556. */
  14557. float mat00, mat01, mat02;
  14558. float mat10, mat11, mat12;
  14559. juce_UseDebuggingNewOperator
  14560. private:
  14561. const AffineTransform followedBy (float mat00, float mat01, float mat02,
  14562. float mat10, float mat11, float mat12) const throw();
  14563. };
  14564. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14565. /*** End of inlined file: juce_AffineTransform.h ***/
  14566. /**
  14567. A pair of (x, y) co-ordinates.
  14568. The ValueType template should be a primitive type such as int, float, double,
  14569. rather than a class.
  14570. @see Line, Path, AffineTransform
  14571. */
  14572. template <typename ValueType>
  14573. class Point
  14574. {
  14575. public:
  14576. /** Creates a point with co-ordinates (0, 0). */
  14577. Point() throw() : x (0), y (0) {}
  14578. /** Creates a copy of another point. */
  14579. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  14580. /** Creates a point from an (x, y) position. */
  14581. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  14582. /** Destructor. */
  14583. ~Point() throw() {}
  14584. /** Copies this point from another one. */
  14585. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  14586. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  14587. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  14588. /** Returns true if the point is (0, 0). */
  14589. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  14590. /** Returns the point's x co-ordinate. */
  14591. inline ValueType getX() const throw() { return x; }
  14592. /** Returns the point's y co-ordinate. */
  14593. inline ValueType getY() const throw() { return y; }
  14594. /** Sets the point's x co-ordinate. */
  14595. inline void setX (const ValueType newX) throw() { x = newX; }
  14596. /** Sets the point's y co-ordinate. */
  14597. inline void setY (const ValueType newY) throw() { y = newY; }
  14598. /** Returns a point which has the same Y position as this one, but a new X. */
  14599. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  14600. /** Returns a point which has the same X position as this one, but a new Y. */
  14601. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  14602. /** Changes the point's x and y co-ordinates. */
  14603. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  14604. /** Adds a pair of co-ordinates to this value. */
  14605. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  14606. /** Returns a point with a given offset from this one. */
  14607. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  14608. /** Adds two points together. */
  14609. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  14610. /** Adds another point's co-ordinates to this one. */
  14611. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  14612. /** Subtracts one points from another. */
  14613. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  14614. /** Subtracts another point's co-ordinates to this one. */
  14615. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  14616. /** Returns a point whose coordinates are multiplied by a given value. */
  14617. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  14618. /** Multiplies the point's co-ordinates by a value. */
  14619. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  14620. /** Returns a point whose coordinates are divided by a given value. */
  14621. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  14622. /** Divides the point's co-ordinates by a value. */
  14623. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  14624. /** Returns the inverse of this point. */
  14625. const Point operator-() const throw() { return Point (-x, -y); }
  14626. /** Returns the straight-line distance between this point and another one. */
  14627. ValueType getDistanceFromOrigin() const throw() { return (ValueType) juce_hypot (x, y); }
  14628. /** Returns the straight-line distance between this point and another one. */
  14629. ValueType getDistanceFrom (const Point& other) const throw() { return (ValueType) juce_hypot (x - other.x, y - other.y); }
  14630. /** Returns the angle from this point to another one.
  14631. The return value is the number of radians clockwise from the 3 o'clock direction,
  14632. where this point is the centre and the other point is on the circumference.
  14633. */
  14634. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  14635. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  14636. @param radius the radius of the circle.
  14637. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14638. */
  14639. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  14640. y - radius * std::cos (angle)); }
  14641. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  14642. @param radiusX the horizontal radius of the circle.
  14643. @param radiusY the vertical radius of the circle.
  14644. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14645. */
  14646. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  14647. y - radiusY * std::cos (angle)); }
  14648. /** Uses a transform to change the point's co-ordinates.
  14649. This will only compile if ValueType = float!
  14650. @see AffineTransform::transformPoint
  14651. */
  14652. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  14653. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  14654. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  14655. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  14656. /** Casts this point to a Point<float> object. */
  14657. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  14658. /** Casts this point to a Point<int> object. */
  14659. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  14660. /** Returns the point as a string in the form "x, y". */
  14661. const String toString() const { return String (x) + ", " + String (y); }
  14662. juce_UseDebuggingNewOperator
  14663. private:
  14664. ValueType x, y;
  14665. };
  14666. #endif // __JUCE_POINT_JUCEHEADER__
  14667. /*** End of inlined file: juce_Point.h ***/
  14668. /**
  14669. Contains position and status information about a mouse event.
  14670. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  14671. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  14672. */
  14673. class JUCE_API MouseEvent
  14674. {
  14675. public:
  14676. /** Creates a MouseEvent.
  14677. Normally an application will never need to use this.
  14678. @param source the source that's invoking the event
  14679. @param position the position of the mouse, relative to the component that is passed-in
  14680. @param modifiers the key modifiers at the time of the event
  14681. @param eventComponent the component that the mouse event applies to
  14682. @param originator the component that originally received the event
  14683. @param eventTime the time the event happened
  14684. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  14685. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14686. the same as the current mouse-x position.
  14687. @param mouseDownTime the time at which the corresponding mouse-down event happened
  14688. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14689. the same as the current mouse-event time.
  14690. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  14691. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  14692. */
  14693. MouseEvent (MouseInputSource& source,
  14694. const Point<int>& position,
  14695. const ModifierKeys& modifiers,
  14696. Component* eventComponent,
  14697. Component* originator,
  14698. const Time& eventTime,
  14699. const Point<int> mouseDownPos,
  14700. const Time& mouseDownTime,
  14701. int numberOfClicks,
  14702. bool mouseWasDragged) throw();
  14703. /** Destructor. */
  14704. ~MouseEvent() throw();
  14705. /** The x-position of the mouse when the event occurred.
  14706. This value is relative to the top-left of the component to which the
  14707. event applies (as indicated by the MouseEvent::eventComponent field).
  14708. */
  14709. const int x;
  14710. /** The y-position of the mouse when the event occurred.
  14711. This value is relative to the top-left of the component to which the
  14712. event applies (as indicated by the MouseEvent::eventComponent field).
  14713. */
  14714. const int y;
  14715. /** The key modifiers associated with the event.
  14716. This will let you find out which mouse buttons were down, as well as which
  14717. modifier keys were held down.
  14718. When used for mouse-up events, this will indicate the state of the mouse buttons
  14719. just before they were released, so that you can tell which button they let go of.
  14720. */
  14721. const ModifierKeys mods;
  14722. /** The component that this event applies to.
  14723. This is usually the component that the mouse was over at the time, but for mouse-drag
  14724. events the mouse could actually be over a different component and the events are
  14725. still sent to the component that the button was originally pressed on.
  14726. The x and y member variables are relative to this component's position.
  14727. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14728. component, this pointer will be updated, but originalComponent remains unchanged.
  14729. @see originalComponent
  14730. */
  14731. Component* const eventComponent;
  14732. /** The component that the event first occurred on.
  14733. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14734. component, this value remains unchanged to indicate the first component that received it.
  14735. @see eventComponent
  14736. */
  14737. Component* const originalComponent;
  14738. /** The time that this mouse-event occurred.
  14739. */
  14740. const Time eventTime;
  14741. /** The source device that generated this event.
  14742. */
  14743. MouseInputSource& source;
  14744. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  14745. The co-ordinate is relative to the component specified in MouseEvent::component.
  14746. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14747. */
  14748. int getMouseDownX() const throw();
  14749. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  14750. The co-ordinate is relative to the component specified in MouseEvent::component.
  14751. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14752. */
  14753. int getMouseDownY() const throw();
  14754. /** Returns the co-ordinates of the last place that a mouse was pressed.
  14755. The co-ordinates are relative to the component specified in MouseEvent::component.
  14756. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14757. */
  14758. const Point<int> getMouseDownPosition() const throw();
  14759. /** Returns the straight-line distance between where the mouse is now and where it
  14760. was the last time the button was pressed.
  14761. This is quite handy for things like deciding whether the user has moved far enough
  14762. for it to be considered a drag operation.
  14763. @see getDistanceFromDragStartX
  14764. */
  14765. int getDistanceFromDragStart() const throw();
  14766. /** Returns the difference between the mouse's current x postion and where it was
  14767. when the button was last pressed.
  14768. @see getDistanceFromDragStart
  14769. */
  14770. int getDistanceFromDragStartX() const throw();
  14771. /** Returns the difference between the mouse's current y postion and where it was
  14772. when the button was last pressed.
  14773. @see getDistanceFromDragStart
  14774. */
  14775. int getDistanceFromDragStartY() const throw();
  14776. /** Returns the difference between the mouse's current postion and where it was
  14777. when the button was last pressed.
  14778. @see getDistanceFromDragStart
  14779. */
  14780. const Point<int> getOffsetFromDragStart() const throw();
  14781. /** Returns true if the mouse has just been clicked.
  14782. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  14783. the user has dragged the mouse more than a few pixels from the place where the
  14784. mouse-down occurred.
  14785. Once they have dragged it far enough for this method to return false, it will continue
  14786. to return false until the mouse-up, even if they move the mouse back to the same
  14787. position where they originally pressed it. This means that it's very handy for
  14788. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  14789. callback to ignore any small movements they might make while clicking.
  14790. @returns true if the mouse wasn't dragged by more than a few pixels between
  14791. the last time the button was pressed and released.
  14792. */
  14793. bool mouseWasClicked() const throw();
  14794. /** For a click event, the number of times the mouse was clicked in succession.
  14795. So for example a double-click event will return 2, a triple-click 3, etc.
  14796. */
  14797. int getNumberOfClicks() const throw() { return numberOfClicks; }
  14798. /** Returns the time that the mouse button has been held down for.
  14799. If called from a mouseDrag or mouseUp callback, this will return the
  14800. number of milliseconds since the corresponding mouseDown event occurred.
  14801. If called in other contexts, e.g. a mouseMove, then the returned value
  14802. may be 0 or an undefined value.
  14803. */
  14804. int getLengthOfMousePress() const throw();
  14805. /** The position of the mouse when the event occurred.
  14806. This position is relative to the top-left of the component to which the
  14807. event applies (as indicated by the MouseEvent::eventComponent field).
  14808. */
  14809. const Point<int> getPosition() const throw();
  14810. /** Returns the mouse x position of this event, in global screen co-ordinates.
  14811. The co-ordinates are relative to the top-left of the main monitor.
  14812. @see getScreenPosition
  14813. */
  14814. int getScreenX() const;
  14815. /** Returns the mouse y position of this event, in global screen co-ordinates.
  14816. The co-ordinates are relative to the top-left of the main monitor.
  14817. @see getScreenPosition
  14818. */
  14819. int getScreenY() const;
  14820. /** Returns the mouse position of this event, in global screen co-ordinates.
  14821. The co-ordinates are relative to the top-left of the main monitor.
  14822. @see getMouseDownScreenPosition
  14823. */
  14824. const Point<int> getScreenPosition() const;
  14825. /** Returns the x co-ordinate at which the mouse button was last pressed.
  14826. The co-ordinates are relative to the top-left of the main monitor.
  14827. @see getMouseDownScreenPosition
  14828. */
  14829. int getMouseDownScreenX() const;
  14830. /** Returns the y co-ordinate at which the mouse button was last pressed.
  14831. The co-ordinates are relative to the top-left of the main monitor.
  14832. @see getMouseDownScreenPosition
  14833. */
  14834. int getMouseDownScreenY() const;
  14835. /** Returns the co-ordinates at which the mouse button was last pressed.
  14836. The co-ordinates are relative to the top-left of the main monitor.
  14837. @see getScreenPosition
  14838. */
  14839. const Point<int> getMouseDownScreenPosition() const;
  14840. /** Creates a version of this event that is relative to a different component.
  14841. The x and y positions of the event that is returned will have been
  14842. adjusted to be relative to the new component.
  14843. */
  14844. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  14845. /** Creates a copy of this event with a different position.
  14846. All other members of the event object are the same, but the x and y are
  14847. replaced with these new values.
  14848. */
  14849. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  14850. /** Changes the application-wide setting for the double-click time limit.
  14851. This is the maximum length of time between mouse-clicks for it to be
  14852. considered a double-click. It's used by the Component class.
  14853. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  14854. */
  14855. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  14856. /** Returns the application-wide setting for the double-click time limit.
  14857. This is the maximum length of time between mouse-clicks for it to be
  14858. considered a double-click. It's used by the Component class.
  14859. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  14860. */
  14861. static int getDoubleClickTimeout() throw();
  14862. juce_UseDebuggingNewOperator
  14863. private:
  14864. const Point<int> mouseDownPos;
  14865. const Time mouseDownTime;
  14866. const int numberOfClicks;
  14867. const bool wasMovedSinceMouseDown;
  14868. static int doubleClickTimeOutMs;
  14869. MouseEvent& operator= (const MouseEvent&);
  14870. };
  14871. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  14872. /*** End of inlined file: juce_MouseEvent.h ***/
  14873. /*** Start of inlined file: juce_ComponentListener.h ***/
  14874. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14875. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14876. class Component;
  14877. /**
  14878. Gets informed about changes to a component's hierarchy or position.
  14879. To monitor a component for changes, register a subclass of ComponentListener
  14880. with the component using Component::addComponentListener().
  14881. Be sure to deregister listeners before you delete them!
  14882. @see Component::addComponentListener, Component::removeComponentListener
  14883. */
  14884. class JUCE_API ComponentListener
  14885. {
  14886. public:
  14887. /** Destructor. */
  14888. virtual ~ComponentListener() {}
  14889. /** Called when the component's position or size changes.
  14890. @param component the component that was moved or resized
  14891. @param wasMoved true if the component's top-left corner has just moved
  14892. @param wasResized true if the component's width or height has just changed
  14893. @see Component::setBounds, Component::resized, Component::moved
  14894. */
  14895. virtual void componentMovedOrResized (Component& component,
  14896. bool wasMoved,
  14897. bool wasResized);
  14898. /** Called when the component is brought to the top of the z-order.
  14899. @param component the component that was moved
  14900. @see Component::toFront, Component::broughtToFront
  14901. */
  14902. virtual void componentBroughtToFront (Component& component);
  14903. /** Called when the component is made visible or invisible.
  14904. @param component the component that changed
  14905. @see Component::setVisible
  14906. */
  14907. virtual void componentVisibilityChanged (Component& component);
  14908. /** Called when the component has children added or removed.
  14909. @param component the component whose children were changed
  14910. @see Component::childrenChanged, Component::addChildComponent,
  14911. Component::removeChildComponent
  14912. */
  14913. virtual void componentChildrenChanged (Component& component);
  14914. /** Called to indicate that the component's parents have changed.
  14915. When a component is added or removed from its parent, all of its children
  14916. will produce this notification (recursively - so all children of its
  14917. children will also be called as well).
  14918. @param component the component that this listener is registered with
  14919. @see Component::parentHierarchyChanged
  14920. */
  14921. virtual void componentParentHierarchyChanged (Component& component);
  14922. /** Called when the component's name is changed.
  14923. @see Component::setName, Component::getName
  14924. */
  14925. virtual void componentNameChanged (Component& component);
  14926. /** Called when the component is in the process of being deleted.
  14927. This callback is made from inside the destructor, so be very, very cautious
  14928. about what you do in here.
  14929. In particular, bear in mind that it's the Component base class's destructor that calls
  14930. this - so if the object that's being deleted is a subclass of Component, then the
  14931. subclass layers of the object will already have been destructed when it gets to this
  14932. point!
  14933. */
  14934. virtual void componentBeingDeleted (Component& component);
  14935. };
  14936. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14937. /*** End of inlined file: juce_ComponentListener.h ***/
  14938. /*** Start of inlined file: juce_KeyListener.h ***/
  14939. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  14940. #define __JUCE_KEYLISTENER_JUCEHEADER__
  14941. /*** Start of inlined file: juce_KeyPress.h ***/
  14942. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  14943. #define __JUCE_KEYPRESS_JUCEHEADER__
  14944. /**
  14945. Represents a key press, including any modifier keys that are needed.
  14946. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  14947. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  14948. */
  14949. class JUCE_API KeyPress
  14950. {
  14951. public:
  14952. /** Creates an (invalid) KeyPress.
  14953. @see isValid
  14954. */
  14955. KeyPress() throw();
  14956. /** Creates a KeyPress for a key and some modifiers.
  14957. e.g.
  14958. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  14959. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  14960. @param keyCode a code that represents the key - this value must be
  14961. one of special constants listed in this class, or an
  14962. 8-bit character code such as a letter (case is ignored),
  14963. digit or a simple key like "," or ".". Note that this
  14964. isn't the same as the textCharacter parameter, so for example
  14965. a keyCode of 'a' and a shift-key modifier should have a
  14966. textCharacter value of 'A'.
  14967. @param modifiers the modifiers to associate with the keystroke
  14968. @param textCharacter the character that would be printed if someone typed
  14969. this keypress into a text editor. This value may be
  14970. null if the keypress is a non-printing character
  14971. @see getKeyCode, isKeyCode, getModifiers
  14972. */
  14973. KeyPress (int keyCode,
  14974. const ModifierKeys& modifiers,
  14975. juce_wchar textCharacter) throw();
  14976. /** Creates a keypress with a keyCode but no modifiers or text character.
  14977. */
  14978. KeyPress (int keyCode) throw();
  14979. /** Creates a copy of another KeyPress. */
  14980. KeyPress (const KeyPress& other) throw();
  14981. /** Copies this KeyPress from another one. */
  14982. KeyPress& operator= (const KeyPress& other) throw();
  14983. /** Compares two KeyPress objects. */
  14984. bool operator== (const KeyPress& other) const throw();
  14985. /** Compares two KeyPress objects. */
  14986. bool operator!= (const KeyPress& other) const throw();
  14987. /** Returns true if this is a valid KeyPress.
  14988. A null keypress can be created by the default constructor, in case it's
  14989. needed.
  14990. */
  14991. bool isValid() const throw() { return keyCode != 0; }
  14992. /** Returns the key code itself.
  14993. This will either be one of the special constants defined in this class,
  14994. or an 8-bit character code.
  14995. */
  14996. int getKeyCode() const throw() { return keyCode; }
  14997. /** Returns the key modifiers.
  14998. @see ModifierKeys
  14999. */
  15000. const ModifierKeys getModifiers() const throw() { return mods; }
  15001. /** Returns the character that is associated with this keypress.
  15002. This is the character that you'd expect to see printed if you press this
  15003. keypress in a text editor or similar component.
  15004. */
  15005. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  15006. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  15007. the modifiers.
  15008. The values for key codes can either be one of the special constants defined in
  15009. this class, or an 8-bit character code.
  15010. @see getKeyCode
  15011. */
  15012. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  15013. /** Converts a textual key description to a KeyPress.
  15014. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  15015. This isn't designed to cope with any kind of input, but should be given the
  15016. strings that are created by the getTextDescription() method.
  15017. If the string can't be parsed, the object returned will be invalid.
  15018. @see getTextDescription
  15019. */
  15020. static const KeyPress createFromDescription (const String& textVersion);
  15021. /** Creates a textual description of the key combination.
  15022. e.g. "CTRL + C" or "DELETE".
  15023. To store a keypress in a file, use this method, along with createFromDescription()
  15024. to retrieve it later.
  15025. */
  15026. const String getTextDescription() const;
  15027. /** Checks whether the user is currently holding down the keys that make up this
  15028. KeyPress.
  15029. Note that this will return false if any extra modifier keys are
  15030. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  15031. then it will be false.
  15032. */
  15033. bool isCurrentlyDown() const;
  15034. /** Checks whether a particular key is held down, irrespective of modifiers.
  15035. The values for key codes can either be one of the special constants defined in
  15036. this class, or an 8-bit character code.
  15037. */
  15038. static bool isKeyCurrentlyDown (int keyCode);
  15039. // Key codes
  15040. //
  15041. // Note that the actual values of these are platform-specific and may change
  15042. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  15043. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  15044. //
  15045. static const int spaceKey; /**< key-code for the space bar */
  15046. static const int escapeKey; /**< key-code for the escape key */
  15047. static const int returnKey; /**< key-code for the return key*/
  15048. static const int tabKey; /**< key-code for the tab key*/
  15049. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  15050. static const int backspaceKey; /**< key-code for the backspace key */
  15051. static const int insertKey; /**< key-code for the insert key */
  15052. static const int upKey; /**< key-code for the cursor-up key */
  15053. static const int downKey; /**< key-code for the cursor-down key */
  15054. static const int leftKey; /**< key-code for the cursor-left key */
  15055. static const int rightKey; /**< key-code for the cursor-right key */
  15056. static const int pageUpKey; /**< key-code for the page-up key */
  15057. static const int pageDownKey; /**< key-code for the page-down key */
  15058. static const int homeKey; /**< key-code for the home key */
  15059. static const int endKey; /**< key-code for the end key */
  15060. static const int F1Key; /**< key-code for the F1 key */
  15061. static const int F2Key; /**< key-code for the F2 key */
  15062. static const int F3Key; /**< key-code for the F3 key */
  15063. static const int F4Key; /**< key-code for the F4 key */
  15064. static const int F5Key; /**< key-code for the F5 key */
  15065. static const int F6Key; /**< key-code for the F6 key */
  15066. static const int F7Key; /**< key-code for the F7 key */
  15067. static const int F8Key; /**< key-code for the F8 key */
  15068. static const int F9Key; /**< key-code for the F9 key */
  15069. static const int F10Key; /**< key-code for the F10 key */
  15070. static const int F11Key; /**< key-code for the F11 key */
  15071. static const int F12Key; /**< key-code for the F12 key */
  15072. static const int F13Key; /**< key-code for the F13 key */
  15073. static const int F14Key; /**< key-code for the F14 key */
  15074. static const int F15Key; /**< key-code for the F15 key */
  15075. static const int F16Key; /**< key-code for the F16 key */
  15076. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  15077. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  15078. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  15079. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  15080. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  15081. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  15082. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  15083. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  15084. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  15085. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  15086. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  15087. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  15088. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  15089. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  15090. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  15091. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  15092. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  15093. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  15094. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  15095. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  15096. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  15097. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  15098. juce_UseDebuggingNewOperator
  15099. private:
  15100. int keyCode;
  15101. ModifierKeys mods;
  15102. juce_wchar textCharacter;
  15103. };
  15104. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  15105. /*** End of inlined file: juce_KeyPress.h ***/
  15106. class Component;
  15107. /**
  15108. Receives callbacks when keys are pressed.
  15109. You can add a key listener to a component to be informed when that component
  15110. gets key events. See the Component::addListener method for more details.
  15111. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  15112. */
  15113. class JUCE_API KeyListener
  15114. {
  15115. public:
  15116. /** Destructor. */
  15117. virtual ~KeyListener() {}
  15118. /** Called to indicate that a key has been pressed.
  15119. If your implementation returns true, then the key event is considered to have
  15120. been consumed, and will not be passed on to any other components. If it returns
  15121. false, then the key will be passed to other components that might want to use it.
  15122. @param key the keystroke, including modifier keys
  15123. @param originatingComponent the component that received the key event
  15124. @see keyStateChanged, Component::keyPressed
  15125. */
  15126. virtual bool keyPressed (const KeyPress& key,
  15127. Component* originatingComponent) = 0;
  15128. /** Called when any key is pressed or released.
  15129. When this is called, classes that might be interested in
  15130. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  15131. check whether their key has changed.
  15132. If your implementation returns true, then the key event is considered to have
  15133. been consumed, and will not be passed on to any other components. If it returns
  15134. false, then the key will be passed to other components that might want to use it.
  15135. @param originatingComponent the component that received the key event
  15136. @param isKeyDown true if a key is being pressed, false if one is being released
  15137. @see KeyPress, Component::keyStateChanged
  15138. */
  15139. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  15140. };
  15141. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  15142. /*** End of inlined file: juce_KeyListener.h ***/
  15143. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  15144. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15145. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15146. class Component;
  15147. /**
  15148. Controls the order in which focus moves between components.
  15149. The default algorithm used by this class to work out the order of traversal
  15150. is as follows:
  15151. - if two components both have an explicit focus order specified, then the
  15152. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  15153. method).
  15154. - any component with an explicit focus order greater than 0 comes before ones
  15155. that don't have an order specified.
  15156. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  15157. order.
  15158. If you need traversal in a more customised way, you can create a subclass
  15159. of KeyboardFocusTraverser that uses your own algorithm, and use
  15160. Component::createFocusTraverser() to create it.
  15161. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  15162. */
  15163. class JUCE_API KeyboardFocusTraverser
  15164. {
  15165. public:
  15166. KeyboardFocusTraverser();
  15167. /** Destructor. */
  15168. virtual ~KeyboardFocusTraverser();
  15169. /** Returns the component that should be given focus after the specified one
  15170. when moving "forwards".
  15171. The default implementation will return the next component which is to the
  15172. right of or below this one.
  15173. This may return 0 if there's no suitable candidate.
  15174. */
  15175. virtual Component* getNextComponent (Component* current);
  15176. /** Returns the component that should be given focus after the specified one
  15177. when moving "backwards".
  15178. The default implementation will return the next component which is to the
  15179. left of or above this one.
  15180. This may return 0 if there's no suitable candidate.
  15181. */
  15182. virtual Component* getPreviousComponent (Component* current);
  15183. /** Returns the component that should receive focus be default within the given
  15184. parent component.
  15185. The default implementation will just return the foremost child component that
  15186. wants focus.
  15187. This may return 0 if there's no suitable candidate.
  15188. */
  15189. virtual Component* getDefaultComponent (Component* parentComponent);
  15190. };
  15191. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15192. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  15193. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  15194. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15195. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15196. /*** Start of inlined file: juce_Graphics.h ***/
  15197. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  15198. #define __JUCE_GRAPHICS_JUCEHEADER__
  15199. /*** Start of inlined file: juce_Font.h ***/
  15200. #ifndef __JUCE_FONT_JUCEHEADER__
  15201. #define __JUCE_FONT_JUCEHEADER__
  15202. /*** Start of inlined file: juce_Typeface.h ***/
  15203. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  15204. #define __JUCE_TYPEFACE_JUCEHEADER__
  15205. /*** Start of inlined file: juce_Path.h ***/
  15206. #ifndef __JUCE_PATH_JUCEHEADER__
  15207. #define __JUCE_PATH_JUCEHEADER__
  15208. /*** Start of inlined file: juce_Line.h ***/
  15209. #ifndef __JUCE_LINE_JUCEHEADER__
  15210. #define __JUCE_LINE_JUCEHEADER__
  15211. /**
  15212. Represents a line.
  15213. This class contains a bunch of useful methods for various geometric
  15214. tasks.
  15215. The ValueType template parameter should be a primitive type - float or double
  15216. are what it's designed for. Integer types will work in a basic way, but some methods
  15217. that perform mathematical operations may not compile, or they may not produce
  15218. sensible results.
  15219. @see Point, Rectangle, Path, Graphics::drawLine
  15220. */
  15221. template <typename ValueType>
  15222. class Line
  15223. {
  15224. public:
  15225. /** Creates a line, using (0, 0) as its start and end points. */
  15226. Line() throw() {}
  15227. /** Creates a copy of another line. */
  15228. Line (const Line& other) throw()
  15229. : start (other.start),
  15230. end (other.end)
  15231. {
  15232. }
  15233. /** Creates a line based on the co-ordinates of its start and end points. */
  15234. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  15235. : start (startX, startY),
  15236. end (endX, endY)
  15237. {
  15238. }
  15239. /** Creates a line from its start and end points. */
  15240. Line (const Point<ValueType>& startPoint,
  15241. const Point<ValueType>& endPoint) throw()
  15242. : start (startPoint),
  15243. end (endPoint)
  15244. {
  15245. }
  15246. /** Copies a line from another one. */
  15247. Line& operator= (const Line& other) throw()
  15248. {
  15249. start = other.start;
  15250. end = other.end;
  15251. return *this;
  15252. }
  15253. /** Destructor. */
  15254. ~Line() throw() {}
  15255. /** Returns the x co-ordinate of the line's start point. */
  15256. inline ValueType getStartX() const throw() { return start.getX(); }
  15257. /** Returns the y co-ordinate of the line's start point. */
  15258. inline ValueType getStartY() const throw() { return start.getY(); }
  15259. /** Returns the x co-ordinate of the line's end point. */
  15260. inline ValueType getEndX() const throw() { return end.getX(); }
  15261. /** Returns the y co-ordinate of the line's end point. */
  15262. inline ValueType getEndY() const throw() { return end.getY(); }
  15263. /** Returns the line's start point. */
  15264. inline const Point<ValueType>& getStart() const throw() { return start; }
  15265. /** Returns the line's end point. */
  15266. inline const Point<ValueType>& getEnd() const throw() { return end; }
  15267. /** Changes this line's start point */
  15268. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  15269. /** Changes this line's end point */
  15270. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  15271. /** Changes this line's start point */
  15272. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  15273. /** Changes this line's end point */
  15274. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  15275. /** Returns a line that is the same as this one, but with the start and end reversed, */
  15276. const Line reversed() const throw() { return Line (end, start); }
  15277. /** Applies an affine transform to the line's start and end points. */
  15278. void applyTransform (const AffineTransform& transform) throw()
  15279. {
  15280. start.applyTransform (transform);
  15281. end.applyTransform (transform);
  15282. }
  15283. /** Returns the length of the line. */
  15284. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  15285. /** Returns true if the line's start and end x co-ordinates are the same. */
  15286. bool isVertical() const throw() { return start.getX() == end.getX(); }
  15287. /** Returns true if the line's start and end y co-ordinates are the same. */
  15288. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  15289. /** Returns the line's angle.
  15290. This value is the number of radians clockwise from the 3 o'clock direction,
  15291. where the line's start point is considered to be at the centre.
  15292. */
  15293. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  15294. /** Compares two lines. */
  15295. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  15296. /** Compares two lines. */
  15297. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  15298. /** Finds the intersection between two lines.
  15299. @param line the other line
  15300. @param intersection the position of the point where the lines meet (or
  15301. where they would meet if they were infinitely long)
  15302. the intersection (if the lines intersect). If the lines
  15303. are parallel, this will just be set to the position
  15304. of one of the line's endpoints.
  15305. @returns true if the line segments intersect; false if they dont. Even if they
  15306. don't intersect, the intersection co-ordinates returned will still
  15307. be valid
  15308. */
  15309. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  15310. {
  15311. return findIntersection (start, end, line.start, line.end, intersection);
  15312. }
  15313. /** Finds the intersection between two lines.
  15314. @param line the line to intersect with
  15315. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  15316. */
  15317. const Point<ValueType> getIntersection (const Line& line) const throw()
  15318. {
  15319. Point<ValueType> p;
  15320. findIntersection (start, end, line.start, line.end, p);
  15321. return p;
  15322. }
  15323. /** Returns the location of the point which is a given distance along this line.
  15324. @param distanceFromStart the distance to move along the line from its
  15325. start point. This value can be negative or longer
  15326. than the line itself
  15327. @see getPointAlongLineProportionally
  15328. */
  15329. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  15330. {
  15331. return start + (end - start) * (distanceFromStart / getLength());
  15332. }
  15333. /** Returns a point which is a certain distance along and to the side of this line.
  15334. This effectively moves a given distance along the line, then another distance
  15335. perpendicularly to this, and returns the resulting position.
  15336. @param distanceFromStart the distance to move along the line from its
  15337. start point. This value can be negative or longer
  15338. than the line itself
  15339. @param perpendicularDistance how far to move sideways from the line. If you're
  15340. looking along the line from its start towards its
  15341. end, then a positive value here will move to the
  15342. right, negative value move to the left.
  15343. */
  15344. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  15345. ValueType perpendicularDistance) const throw()
  15346. {
  15347. const Point<ValueType> delta (end - start);
  15348. const double length = juce_hypot (delta.getX(), delta.getY());
  15349. if (length == 0)
  15350. return start;
  15351. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  15352. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  15353. }
  15354. /** Returns the location of the point which is a given distance along this line
  15355. proportional to the line's length.
  15356. @param proportionOfLength the distance to move along the line from its
  15357. start point, in multiples of the line's length.
  15358. So a value of 0.0 will return the line's start point
  15359. and a value of 1.0 will return its end point. (This value
  15360. can be negative or greater than 1.0).
  15361. @see getPointAlongLine
  15362. */
  15363. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  15364. {
  15365. return start + (end - start) * proportionOfLength;
  15366. }
  15367. /** Returns the smallest distance between this line segment and a given point.
  15368. So if the point is close to the line, this will return the perpendicular
  15369. distance from the line; if the point is a long way beyond one of the line's
  15370. end-point's, it'll return the straight-line distance to the nearest end-point.
  15371. pointOnLine receives the position of the point that is found.
  15372. @returns the point's distance from the line
  15373. @see getPositionAlongLineOfNearestPoint
  15374. */
  15375. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  15376. Point<ValueType>& pointOnLine) const throw()
  15377. {
  15378. const Point<ValueType> delta (end - start);
  15379. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15380. if (length > 0)
  15381. {
  15382. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  15383. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  15384. if (prop >= 0 && prop <= 1.0)
  15385. {
  15386. pointOnLine = start + delta * (ValueType) prop;
  15387. return targetPoint.getDistanceFrom (pointOnLine);
  15388. }
  15389. }
  15390. const float fromStart = targetPoint.getDistanceFrom (start);
  15391. const float fromEnd = targetPoint.getDistanceFrom (end);
  15392. if (fromStart < fromEnd)
  15393. {
  15394. pointOnLine = start;
  15395. return fromStart;
  15396. }
  15397. else
  15398. {
  15399. pointOnLine = end;
  15400. return fromEnd;
  15401. }
  15402. }
  15403. /** Finds the point on this line which is nearest to a given point, and
  15404. returns its position as a proportional position along the line.
  15405. @returns a value 0 to 1.0 which is the distance along this line from the
  15406. line's start to the point which is nearest to the point passed-in. To
  15407. turn this number into a position, use getPointAlongLineProportionally().
  15408. @see getDistanceFromPoint, getPointAlongLineProportionally
  15409. */
  15410. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  15411. {
  15412. const Point<ValueType> delta (end - start);
  15413. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15414. return length <= 0 ? 0
  15415. : jlimit ((ValueType) 0, (ValueType) 1,
  15416. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  15417. + (point.getY() - start.getY()) * delta.getY()) / length));
  15418. }
  15419. /** Finds the point on this line which is nearest to a given point.
  15420. @see getDistanceFromPoint, findNearestProportionalPositionTo
  15421. */
  15422. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  15423. {
  15424. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  15425. }
  15426. /** Returns true if the given point lies above this line.
  15427. The return value is true if the point's y coordinate is less than the y
  15428. coordinate of this line at the given x (assuming the line extends infinitely
  15429. in both directions).
  15430. */
  15431. bool isPointAbove (const Point<ValueType>& point) const throw()
  15432. {
  15433. return start.getX() != end.getX()
  15434. && point.getY() < ((end.getY() - start.getY())
  15435. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  15436. }
  15437. /** Returns a shortened copy of this line.
  15438. This will chop off part of the start of this line by a certain amount, (leaving the
  15439. end-point the same), and return the new line.
  15440. */
  15441. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  15442. {
  15443. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  15444. }
  15445. /** Returns a shortened copy of this line.
  15446. This will chop off part of the end of this line by a certain amount, (leaving the
  15447. start-point the same), and return the new line.
  15448. */
  15449. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  15450. {
  15451. const ValueType length = getLength();
  15452. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  15453. }
  15454. juce_UseDebuggingNewOperator
  15455. private:
  15456. Point<ValueType> start, end;
  15457. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  15458. const Point<ValueType>& p3, const Point<ValueType>& p4,
  15459. Point<ValueType>& intersection) throw()
  15460. {
  15461. if (p2 == p3)
  15462. {
  15463. intersection = p2;
  15464. return true;
  15465. }
  15466. const Point<ValueType> d1 (p2 - p1);
  15467. const Point<ValueType> d2 (p4 - p3);
  15468. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  15469. if (divisor == 0)
  15470. {
  15471. if (! (d1.isOrigin() || d2.isOrigin()))
  15472. {
  15473. if (d1.getY() == 0 && d2.getY() != 0)
  15474. {
  15475. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  15476. intersection = p1.withX (p3.getX() + along * d2.getX());
  15477. return along >= 0 && along <= (ValueType) 1;
  15478. }
  15479. else if (d2.getY() == 0 && d1.getY() != 0)
  15480. {
  15481. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  15482. intersection = p3.withX (p1.getX() + along * d1.getX());
  15483. return along >= 0 && along <= (ValueType) 1;
  15484. }
  15485. else if (d1.getX() == 0 && d2.getX() != 0)
  15486. {
  15487. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  15488. intersection = p1.withY (p3.getY() + along * d2.getY());
  15489. return along >= 0 && along <= (ValueType) 1;
  15490. }
  15491. else if (d2.getX() == 0 && d1.getX() != 0)
  15492. {
  15493. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  15494. intersection = p3.withY (p1.getY() + along * d1.getY());
  15495. return along >= 0 && along <= (ValueType) 1;
  15496. }
  15497. }
  15498. intersection = (p2 + p3) / (ValueType) 2;
  15499. return false;
  15500. }
  15501. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  15502. intersection = p1 + d1 * along1;
  15503. if (along1 < 0 || along1 > (ValueType) 1)
  15504. return false;
  15505. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  15506. return along2 >= 0 && along2 <= (ValueType) 1;
  15507. }
  15508. };
  15509. #endif // __JUCE_LINE_JUCEHEADER__
  15510. /*** End of inlined file: juce_Line.h ***/
  15511. /*** Start of inlined file: juce_Rectangle.h ***/
  15512. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  15513. #define __JUCE_RECTANGLE_JUCEHEADER__
  15514. class RectangleList;
  15515. /**
  15516. Manages a rectangle and allows geometric operations to be performed on it.
  15517. @see RectangleList, Path, Line, Point
  15518. */
  15519. template <typename ValueType>
  15520. class Rectangle
  15521. {
  15522. public:
  15523. /** Creates a rectangle of zero size.
  15524. The default co-ordinates will be (0, 0, 0, 0).
  15525. */
  15526. Rectangle() throw()
  15527. : x (0), y (0), w (0), h (0)
  15528. {
  15529. }
  15530. /** Creates a copy of another rectangle. */
  15531. Rectangle (const Rectangle& other) throw()
  15532. : x (other.x), y (other.y),
  15533. w (other.w), h (other.h)
  15534. {
  15535. }
  15536. /** Creates a rectangle with a given position and size. */
  15537. Rectangle (const ValueType initialX, const ValueType initialY,
  15538. const ValueType width, const ValueType height) throw()
  15539. : x (initialX), y (initialY),
  15540. w (width), h (height)
  15541. {
  15542. }
  15543. /** Creates a rectangle with a given size, and a position of (0, 0). */
  15544. Rectangle (const ValueType width, const ValueType height) throw()
  15545. : x (0), y (0), w (width), h (height)
  15546. {
  15547. }
  15548. /** Creates a Rectangle from the positions of two opposite corners. */
  15549. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  15550. : x (jmin (corner1.getX(), corner2.getX())),
  15551. y (jmin (corner1.getY(), corner2.getY())),
  15552. w (corner1.getX() - corner2.getX()),
  15553. h (corner1.getY() - corner2.getY())
  15554. {
  15555. if (w < 0) w = -w;
  15556. if (h < 0) h = -h;
  15557. }
  15558. Rectangle& operator= (const Rectangle& other) throw()
  15559. {
  15560. x = other.x; y = other.y;
  15561. w = other.w; h = other.h;
  15562. return *this;
  15563. }
  15564. /** Destructor. */
  15565. ~Rectangle() throw() {}
  15566. /** Returns true if the rectangle's width and height are both zero or less */
  15567. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  15568. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  15569. inline ValueType getX() const throw() { return x; }
  15570. /** Returns the y co-ordinate of the rectangle's top edge. */
  15571. inline ValueType getY() const throw() { return y; }
  15572. /** Returns the width of the rectangle. */
  15573. inline ValueType getWidth() const throw() { return w; }
  15574. /** Returns the height of the rectangle. */
  15575. inline ValueType getHeight() const throw() { return h; }
  15576. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  15577. inline ValueType getRight() const throw() { return x + w; }
  15578. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  15579. inline ValueType getBottom() const throw() { return y + h; }
  15580. /** Returns the x co-ordinate of the rectangle's centre. */
  15581. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  15582. /** Returns the y co-ordinate of the rectangle's centre. */
  15583. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  15584. /** Returns the centre point of the rectangle. */
  15585. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  15586. /** Returns the aspect ratio of the rectangle's width / height.
  15587. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  15588. it returns height / width. */
  15589. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  15590. /** Returns the rectangle's top-left position as a Point. */
  15591. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  15592. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15593. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  15594. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15595. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15596. /** Returns a rectangle with the same size as this one, but a new position. */
  15597. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  15598. /** Returns the rectangle's top-left position as a Point. */
  15599. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  15600. /** Returns the rectangle's top-right position as a Point. */
  15601. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  15602. /** Returns the rectangle's bottom-left position as a Point. */
  15603. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  15604. /** Returns the rectangle's bottom-right position as a Point. */
  15605. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  15606. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  15607. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  15608. /** Returns a rectangle with the same position as this one, but a new size. */
  15609. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  15610. /** Changes all the rectangle's co-ordinates. */
  15611. void setBounds (const ValueType newX, const ValueType newY,
  15612. const ValueType newWidth, const ValueType newHeight) throw()
  15613. {
  15614. x = newX; y = newY; w = newWidth; h = newHeight;
  15615. }
  15616. /** Changes the rectangle's X coordinate */
  15617. void setX (const ValueType newX) throw() { x = newX; }
  15618. /** Changes the rectangle's Y coordinate */
  15619. void setY (const ValueType newY) throw() { y = newY; }
  15620. /** Changes the rectangle's width */
  15621. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  15622. /** Changes the rectangle's height */
  15623. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  15624. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  15625. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  15626. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  15627. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  15628. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  15629. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  15630. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  15631. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  15632. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  15633. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  15634. */
  15635. void setLeft (const ValueType newLeft) throw()
  15636. {
  15637. w = jmax (ValueType(), x + w - newLeft);
  15638. x = newLeft;
  15639. }
  15640. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  15641. If the y is moved to be below the current bottom edge, the height will be set to zero.
  15642. */
  15643. void setTop (const ValueType newTop) throw()
  15644. {
  15645. h = jmax (ValueType(), y + h - newTop);
  15646. y = newTop;
  15647. }
  15648. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  15649. If the new right is below the current X value, the X will be pushed down to match it.
  15650. @see getRight
  15651. */
  15652. void setRight (const ValueType newRight) throw()
  15653. {
  15654. x = jmin (x, newRight);
  15655. w = newRight - x;
  15656. }
  15657. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  15658. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  15659. @see getBottom
  15660. */
  15661. void setBottom (const ValueType newBottom) throw()
  15662. {
  15663. y = jmin (y, newBottom);
  15664. h = newBottom - y;
  15665. }
  15666. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  15667. void translate (const ValueType deltaX,
  15668. const ValueType deltaY) throw()
  15669. {
  15670. x += deltaX;
  15671. y += deltaY;
  15672. }
  15673. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15674. const Rectangle translated (const ValueType deltaX,
  15675. const ValueType deltaY) const throw()
  15676. {
  15677. return Rectangle (x + deltaX, y + deltaY, w, h);
  15678. }
  15679. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15680. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  15681. {
  15682. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  15683. }
  15684. /** Moves this rectangle by a given amount. */
  15685. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  15686. {
  15687. x += deltaPosition.getX(); y += deltaPosition.getY();
  15688. return *this;
  15689. }
  15690. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15691. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  15692. {
  15693. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  15694. }
  15695. /** Moves this rectangle by a given amount. */
  15696. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  15697. {
  15698. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  15699. return *this;
  15700. }
  15701. /** Expands the rectangle by a given amount.
  15702. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15703. @see expanded, reduce, reduced
  15704. */
  15705. void expand (const ValueType deltaX,
  15706. const ValueType deltaY) throw()
  15707. {
  15708. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15709. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15710. setBounds (x - deltaX, y - deltaY, nw, nh);
  15711. }
  15712. /** Returns a rectangle that is larger than this one by a given amount.
  15713. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15714. @see expand, reduce, reduced
  15715. */
  15716. const Rectangle expanded (const ValueType deltaX,
  15717. const ValueType deltaY) const throw()
  15718. {
  15719. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15720. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15721. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  15722. }
  15723. /** Shrinks the rectangle by a given amount.
  15724. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15725. @see reduced, expand, expanded
  15726. */
  15727. void reduce (const ValueType deltaX,
  15728. const ValueType deltaY) throw()
  15729. {
  15730. expand (-deltaX, -deltaY);
  15731. }
  15732. /** Returns a rectangle that is smaller than this one by a given amount.
  15733. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15734. @see reduce, expand, expanded
  15735. */
  15736. const Rectangle reduced (const ValueType deltaX,
  15737. const ValueType deltaY) const throw()
  15738. {
  15739. return expanded (-deltaX, -deltaY);
  15740. }
  15741. /** Removes a strip from the top of this rectangle, reducing this rectangle
  15742. by the specified amount and returning the section that was removed.
  15743. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15744. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  15745. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  15746. that value.
  15747. */
  15748. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  15749. {
  15750. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  15751. y += r.h; h -= r.h;
  15752. return r;
  15753. }
  15754. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  15755. by the specified amount and returning the section that was removed.
  15756. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15757. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  15758. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  15759. that value.
  15760. */
  15761. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  15762. {
  15763. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  15764. x += r.w; w -= r.w;
  15765. return r;
  15766. }
  15767. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  15768. by the specified amount and returning the section that was removed.
  15769. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15770. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  15771. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  15772. that value.
  15773. */
  15774. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  15775. {
  15776. amountToRemove = jmin (amountToRemove, w);
  15777. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  15778. w -= amountToRemove;
  15779. return r;
  15780. }
  15781. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  15782. by the specified amount and returning the section that was removed.
  15783. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15784. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  15785. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  15786. that value.
  15787. */
  15788. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  15789. {
  15790. amountToRemove = jmin (amountToRemove, h);
  15791. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  15792. h -= amountToRemove;
  15793. return r;
  15794. }
  15795. /** Returns true if the two rectangles are identical. */
  15796. bool operator== (const Rectangle& other) const throw()
  15797. {
  15798. return x == other.x && y == other.y
  15799. && w == other.w && h == other.h;
  15800. }
  15801. /** Returns true if the two rectangles are not identical. */
  15802. bool operator!= (const Rectangle& other) const throw()
  15803. {
  15804. return x != other.x || y != other.y
  15805. || w != other.w || h != other.h;
  15806. }
  15807. /** Returns true if this co-ordinate is inside the rectangle. */
  15808. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  15809. {
  15810. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  15811. }
  15812. /** Returns true if this co-ordinate is inside the rectangle. */
  15813. bool contains (const Point<ValueType>& point) const throw()
  15814. {
  15815. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  15816. }
  15817. /** Returns true if this other rectangle is completely inside this one. */
  15818. bool contains (const Rectangle& other) const throw()
  15819. {
  15820. return x <= other.x && y <= other.y
  15821. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  15822. }
  15823. /** Returns the nearest point to the specified point that lies within this rectangle. */
  15824. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  15825. {
  15826. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  15827. jlimit (y, y + h, point.getY()));
  15828. }
  15829. /** Returns true if any part of another rectangle overlaps this one. */
  15830. bool intersects (const Rectangle& other) const throw()
  15831. {
  15832. return x + w > other.x
  15833. && y + h > other.y
  15834. && x < other.x + other.w
  15835. && y < other.y + other.h
  15836. && w > ValueType() && h > ValueType();
  15837. }
  15838. /** Returns the region that is the overlap between this and another rectangle.
  15839. If the two rectangles don't overlap, the rectangle returned will be empty.
  15840. */
  15841. const Rectangle getIntersection (const Rectangle& other) const throw()
  15842. {
  15843. const ValueType nx = jmax (x, other.x);
  15844. const ValueType ny = jmax (y, other.y);
  15845. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  15846. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  15847. if (nw >= ValueType() && nh >= ValueType())
  15848. return Rectangle (nx, ny, nw, nh);
  15849. return Rectangle();
  15850. }
  15851. /** Clips a rectangle so that it lies only within this one.
  15852. This is a non-static version of intersectRectangles().
  15853. Returns false if the two regions didn't overlap.
  15854. */
  15855. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  15856. {
  15857. const int maxX = jmax (otherX, x);
  15858. otherW = jmin (otherX + otherW, x + w) - maxX;
  15859. if (otherW > 0)
  15860. {
  15861. const int maxY = jmax (otherY, y);
  15862. otherH = jmin (otherY + otherH, y + h) - maxY;
  15863. if (otherH > 0)
  15864. {
  15865. otherX = maxX; otherY = maxY;
  15866. return true;
  15867. }
  15868. }
  15869. return false;
  15870. }
  15871. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  15872. If either this or the other rectangle are empty, they will not be counted as
  15873. part of the resulting region.
  15874. */
  15875. const Rectangle getUnion (const Rectangle& other) const throw()
  15876. {
  15877. if (other.isEmpty()) return *this;
  15878. if (isEmpty()) return other;
  15879. const ValueType newX = jmin (x, other.x);
  15880. const ValueType newY = jmin (y, other.y);
  15881. return Rectangle (newX, newY,
  15882. jmax (x + w, other.x + other.w) - newX,
  15883. jmax (y + h, other.y + other.h) - newY);
  15884. }
  15885. /** If this rectangle merged with another one results in a simple rectangle, this
  15886. will set this rectangle to the result, and return true.
  15887. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15888. or if they form a complex region.
  15889. */
  15890. bool enlargeIfAdjacent (const Rectangle& other) throw()
  15891. {
  15892. if (x == other.x && getRight() == other.getRight()
  15893. && (other.getBottom() >= y && other.y <= getBottom()))
  15894. {
  15895. const ValueType newY = jmin (y, other.y);
  15896. h = jmax (getBottom(), other.getBottom()) - newY;
  15897. y = newY;
  15898. return true;
  15899. }
  15900. else if (y == other.y && getBottom() == other.getBottom()
  15901. && (other.getRight() >= x && other.x <= getRight()))
  15902. {
  15903. const ValueType newX = jmin (x, other.x);
  15904. w = jmax (getRight(), other.getRight()) - newX;
  15905. x = newX;
  15906. return true;
  15907. }
  15908. return false;
  15909. }
  15910. /** If after removing another rectangle from this one the result is a simple rectangle,
  15911. this will set this object's bounds to be the result, and return true.
  15912. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15913. or if removing the other one would form a complex region.
  15914. */
  15915. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  15916. {
  15917. int inside = 0;
  15918. const int otherR = other.getRight();
  15919. if (x >= other.x && x < otherR) inside = 1;
  15920. const int otherB = other.getBottom();
  15921. if (y >= other.y && y < otherB) inside |= 2;
  15922. const int r = x + w;
  15923. if (r >= other.x && r < otherR) inside |= 4;
  15924. const int b = y + h;
  15925. if (b >= other.y && b < otherB) inside |= 8;
  15926. switch (inside)
  15927. {
  15928. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  15929. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  15930. case 2 + 4 + 8: w = other.x - x; return true;
  15931. case 1 + 4 + 8: h = other.y - y; return true;
  15932. }
  15933. return false;
  15934. }
  15935. /** Returns the smallest rectangle that can contain the shape created by applying
  15936. a transform to this rectangle.
  15937. This should only be used on floating point rectangles.
  15938. */
  15939. const Rectangle<ValueType> transformed (const AffineTransform& transform) const throw()
  15940. {
  15941. float x1 = x, y1 = y;
  15942. float x2 = x + w, y2 = y;
  15943. float x3 = x, y3 = y + h;
  15944. float x4 = x2, y4 = y3;
  15945. transform.transformPoints (x1, y1, x2, y2);
  15946. transform.transformPoints (x3, y3, x4, y4);
  15947. const float rx = jmin (x1, x2, x3, x4);
  15948. const float ry = jmin (y1, y2, y3, y4);
  15949. return Rectangle (rx, ry,
  15950. jmax (x1, x2, x3, x4) - rx,
  15951. jmax (y1, y2, y3, y4) - ry);
  15952. }
  15953. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  15954. This is only relevent for floating-point rectangles, of course.
  15955. @see toFloat()
  15956. */
  15957. const Rectangle<int> getSmallestIntegerContainer() const throw()
  15958. {
  15959. const int x1 = (int) std::floor (static_cast<float> (x));
  15960. const int y1 = (int) std::floor (static_cast<float> (y));
  15961. const int x2 = (int) std::floor (static_cast<float> (x + w + 0.9999f));
  15962. const int y2 = (int) std::floor (static_cast<float> (y + h + 0.9999f));
  15963. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  15964. }
  15965. /** Returns the smallest Rectangle that can contain a set of points. */
  15966. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  15967. {
  15968. if (numPoints == 0)
  15969. return Rectangle();
  15970. ValueType minX (points[0].getX());
  15971. ValueType maxX (minX);
  15972. ValueType minY (points[0].getY());
  15973. ValueType maxY (minY);
  15974. for (int i = 1; i < numPoints; ++i)
  15975. {
  15976. minX = jmin (minX, points[i].getX());
  15977. maxX = jmax (maxX, points[i].getX());
  15978. minY = jmin (minY, points[i].getY());
  15979. maxY = jmax (maxY, points[i].getY());
  15980. }
  15981. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  15982. }
  15983. /** Casts this rectangle to a Rectangle<float>.
  15984. Obviously this is mainly useful for rectangles that use integer types.
  15985. @see getSmallestIntegerContainer
  15986. */
  15987. const Rectangle<float> toFloat() const throw()
  15988. {
  15989. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  15990. static_cast<float> (w), static_cast<float> (h));
  15991. }
  15992. /** Static utility to intersect two sets of rectangular co-ordinates.
  15993. Returns false if the two regions didn't overlap.
  15994. @see intersectRectangle
  15995. */
  15996. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  15997. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  15998. {
  15999. const ValueType x = jmax (x1, x2);
  16000. w1 = jmin (x1 + w1, x2 + w2) - x;
  16001. if (w1 > 0)
  16002. {
  16003. const ValueType y = jmax (y1, y2);
  16004. h1 = jmin (y1 + h1, y2 + h2) - y;
  16005. if (h1 > 0)
  16006. {
  16007. x1 = x; y1 = y;
  16008. return true;
  16009. }
  16010. }
  16011. return false;
  16012. }
  16013. /** Creates a string describing this rectangle.
  16014. The string will be of the form "x y width height", e.g. "100 100 400 200".
  16015. Coupled with the fromString() method, this is very handy for things like
  16016. storing rectangles (particularly component positions) in XML attributes.
  16017. @see fromString
  16018. */
  16019. const String toString() const
  16020. {
  16021. String s;
  16022. s.preallocateStorage (16);
  16023. s << x << ' ' << y << ' ' << w << ' ' << h;
  16024. return s;
  16025. }
  16026. /** Parses a string containing a rectangle's details.
  16027. The string should contain 4 integer tokens, in the form "x y width height". They
  16028. can be comma or whitespace separated.
  16029. This method is intended to go with the toString() method, to form an easy way
  16030. of saving/loading rectangles as strings.
  16031. @see toString
  16032. */
  16033. static const Rectangle fromString (const String& stringVersion)
  16034. {
  16035. StringArray toks;
  16036. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  16037. return Rectangle (toks[0].trim().getIntValue(),
  16038. toks[1].trim().getIntValue(),
  16039. toks[2].trim().getIntValue(),
  16040. toks[3].trim().getIntValue());
  16041. }
  16042. juce_UseDebuggingNewOperator
  16043. private:
  16044. friend class RectangleList;
  16045. ValueType x, y, w, h;
  16046. };
  16047. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  16048. /*** End of inlined file: juce_Rectangle.h ***/
  16049. /*** Start of inlined file: juce_Justification.h ***/
  16050. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  16051. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  16052. /**
  16053. Represents a type of justification to be used when positioning graphical items.
  16054. e.g. it indicates whether something should be placed top-left, top-right,
  16055. centred, etc.
  16056. It is used in various places wherever this kind of information is needed.
  16057. */
  16058. class JUCE_API Justification
  16059. {
  16060. public:
  16061. /** Creates a Justification object using a combination of flags. */
  16062. inline Justification (int flags_) throw() : flags (flags_) {}
  16063. /** Creates a copy of another Justification object. */
  16064. Justification (const Justification& other) throw();
  16065. /** Copies another Justification object. */
  16066. Justification& operator= (const Justification& other) throw();
  16067. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  16068. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  16069. /** Returns the raw flags that are set for this Justification object. */
  16070. inline int getFlags() const throw() { return flags; }
  16071. /** Tests a set of flags for this object.
  16072. @returns true if any of the flags passed in are set on this object.
  16073. */
  16074. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  16075. /** Returns just the flags from this object that deal with vertical layout. */
  16076. int getOnlyVerticalFlags() const throw();
  16077. /** Returns just the flags from this object that deal with horizontal layout. */
  16078. int getOnlyHorizontalFlags() const throw();
  16079. /** Adjusts the position of a rectangle to fit it into a space.
  16080. The (x, y) position of the rectangle will be updated to position it inside the
  16081. given space according to the justification flags.
  16082. */
  16083. void applyToRectangle (int& x, int& y, int w, int h,
  16084. int spaceX, int spaceY, int spaceW, int spaceH) const throw();
  16085. /** Flag values that can be combined and used in the constructor. */
  16086. enum
  16087. {
  16088. /** Indicates that the item should be aligned against the left edge of the available space. */
  16089. left = 1,
  16090. /** Indicates that the item should be aligned against the right edge of the available space. */
  16091. right = 2,
  16092. /** Indicates that the item should be placed in the centre between the left and right
  16093. sides of the available space. */
  16094. horizontallyCentred = 4,
  16095. /** Indicates that the item should be aligned against the top edge of the available space. */
  16096. top = 8,
  16097. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  16098. bottom = 16,
  16099. /** Indicates that the item should be placed in the centre between the top and bottom
  16100. sides of the available space. */
  16101. verticallyCentred = 32,
  16102. /** Indicates that lines of text should be spread out to fill the maximum width
  16103. available, so that both margins are aligned vertically.
  16104. */
  16105. horizontallyJustified = 64,
  16106. /** Indicates that the item should be centred vertically and horizontally.
  16107. This is equivalent to (horizontallyCentred | verticallyCentred)
  16108. */
  16109. centred = 36,
  16110. /** Indicates that the item should be centred vertically but placed on the left hand side.
  16111. This is equivalent to (left | verticallyCentred)
  16112. */
  16113. centredLeft = 33,
  16114. /** Indicates that the item should be centred vertically but placed on the right hand side.
  16115. This is equivalent to (right | verticallyCentred)
  16116. */
  16117. centredRight = 34,
  16118. /** Indicates that the item should be centred horizontally and placed at the top.
  16119. This is equivalent to (horizontallyCentred | top)
  16120. */
  16121. centredTop = 12,
  16122. /** Indicates that the item should be centred horizontally and placed at the bottom.
  16123. This is equivalent to (horizontallyCentred | bottom)
  16124. */
  16125. centredBottom = 20,
  16126. /** Indicates that the item should be placed in the top-left corner.
  16127. This is equivalent to (left | top)
  16128. */
  16129. topLeft = 9,
  16130. /** Indicates that the item should be placed in the top-right corner.
  16131. This is equivalent to (right | top)
  16132. */
  16133. topRight = 10,
  16134. /** Indicates that the item should be placed in the bottom-left corner.
  16135. This is equivalent to (left | bottom)
  16136. */
  16137. bottomLeft = 17,
  16138. /** Indicates that the item should be placed in the bottom-left corner.
  16139. This is equivalent to (right | bottom)
  16140. */
  16141. bottomRight = 18
  16142. };
  16143. private:
  16144. int flags;
  16145. };
  16146. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  16147. /*** End of inlined file: juce_Justification.h ***/
  16148. class Image;
  16149. /**
  16150. A path is a sequence of lines and curves that may either form a closed shape
  16151. or be open-ended.
  16152. To use a path, you can create an empty one, then add lines and curves to it
  16153. to create shapes, then it can be rendered by a Graphics context or used
  16154. for geometric operations.
  16155. e.g. @code
  16156. Path myPath;
  16157. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  16158. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  16159. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  16160. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  16161. // add an ellipse as well, which will form a second sub-path within the path..
  16162. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  16163. // double the width of the whole thing..
  16164. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  16165. // and draw it to a graphics context with a 5-pixel thick outline.
  16166. g.strokePath (myPath, PathStrokeType (5.0f));
  16167. @endcode
  16168. A path object can actually contain multiple sub-paths, which may themselves
  16169. be open or closed.
  16170. @see PathFlatteningIterator, PathStrokeType, Graphics
  16171. */
  16172. class JUCE_API Path
  16173. {
  16174. public:
  16175. /** Creates an empty path. */
  16176. Path();
  16177. /** Creates a copy of another path. */
  16178. Path (const Path& other);
  16179. /** Destructor. */
  16180. ~Path();
  16181. /** Copies this path from another one. */
  16182. Path& operator= (const Path& other);
  16183. bool operator== (const Path& other) const throw();
  16184. bool operator!= (const Path& other) const throw();
  16185. /** Returns true if the path doesn't contain any lines or curves. */
  16186. bool isEmpty() const throw();
  16187. /** Returns the smallest rectangle that contains all points within the path.
  16188. */
  16189. const Rectangle<float> getBounds() const throw();
  16190. /** Returns the smallest rectangle that contains all points within the path
  16191. after it's been transformed with the given tranasform matrix.
  16192. */
  16193. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  16194. /** Checks whether a point lies within the path.
  16195. This is only relevent for closed paths (see closeSubPath()), and
  16196. may produce false results if used on a path which has open sub-paths.
  16197. The path's winding rule is taken into account by this method.
  16198. The tolerence parameter is passed to the PathFlatteningIterator that
  16199. is used to trace the path - for more info about it, see the notes for
  16200. the PathFlatteningIterator constructor.
  16201. @see closeSubPath, setUsingNonZeroWinding
  16202. */
  16203. bool contains (float x, float y,
  16204. float tolerence = 10.0f) const;
  16205. /** Checks whether a point lies within the path.
  16206. This is only relevent for closed paths (see closeSubPath()), and
  16207. may produce false results if used on a path which has open sub-paths.
  16208. The path's winding rule is taken into account by this method.
  16209. The tolerence parameter is passed to the PathFlatteningIterator that
  16210. is used to trace the path - for more info about it, see the notes for
  16211. the PathFlatteningIterator constructor.
  16212. @see closeSubPath, setUsingNonZeroWinding
  16213. */
  16214. bool contains (const Point<float>& point,
  16215. float tolerence = 10.0f) const;
  16216. /** Checks whether a line crosses the path.
  16217. This will return positive if the line crosses any of the paths constituent
  16218. lines or curves. It doesn't take into account whether the line is inside
  16219. or outside the path, or whether the path is open or closed.
  16220. The tolerence parameter is passed to the PathFlatteningIterator that
  16221. is used to trace the path - for more info about it, see the notes for
  16222. the PathFlatteningIterator constructor.
  16223. */
  16224. bool intersectsLine (const Line<float>& line,
  16225. float tolerence = 10.0f);
  16226. /** Cuts off parts of a line to keep the parts that are either inside or
  16227. outside this path.
  16228. Note that this isn't smart enough to cope with situations where the
  16229. line would need to be cut into multiple pieces to correctly clip against
  16230. a re-entrant shape.
  16231. @param line the line to clip
  16232. @param keepSectionOutsidePath if true, it's the section outside the path
  16233. that will be kept; if false its the section inside
  16234. the path
  16235. */
  16236. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  16237. /** Returns the length of the path.
  16238. @see getPointAlongPath
  16239. */
  16240. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  16241. /** Returns a point that is the specified distance along the path.
  16242. If the distance is greater than the total length of the path, this will return the
  16243. end point.
  16244. @see getLength
  16245. */
  16246. const Point<float> getPointAlongPath (float distanceFromStart,
  16247. const AffineTransform& transform = AffineTransform::identity) const;
  16248. /** Finds the point along the path which is nearest to a given position.
  16249. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  16250. of the path.
  16251. */
  16252. float getNearestPoint (const Point<float>& targetPoint,
  16253. Point<float>& pointOnPath,
  16254. const AffineTransform& transform = AffineTransform::identity) const;
  16255. /** Removes all lines and curves, resetting the path completely. */
  16256. void clear() throw();
  16257. /** Begins a new subpath with a given starting position.
  16258. This will move the path's current position to the co-ordinates passed in and
  16259. make it ready to draw lines or curves starting from this position.
  16260. After adding whatever lines and curves are needed, you can either
  16261. close the current sub-path using closeSubPath() or call startNewSubPath()
  16262. to move to a new sub-path, leaving the old one open-ended.
  16263. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16264. */
  16265. void startNewSubPath (float startX, float startY);
  16266. /** Begins a new subpath with a given starting position.
  16267. This will move the path's current position to the co-ordinates passed in and
  16268. make it ready to draw lines or curves starting from this position.
  16269. After adding whatever lines and curves are needed, you can either
  16270. close the current sub-path using closeSubPath() or call startNewSubPath()
  16271. to move to a new sub-path, leaving the old one open-ended.
  16272. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16273. */
  16274. void startNewSubPath (const Point<float>& start);
  16275. /** Closes a the current sub-path with a line back to its start-point.
  16276. When creating a closed shape such as a triangle, don't use 3 lineTo()
  16277. calls - instead use two lineTo() calls, followed by a closeSubPath()
  16278. to join the final point back to the start.
  16279. This ensures that closes shapes are recognised as such, and this is
  16280. important for tasks like drawing strokes, which needs to know whether to
  16281. draw end-caps or not.
  16282. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  16283. */
  16284. void closeSubPath();
  16285. /** Adds a line from the shape's last position to a new end-point.
  16286. This will connect the end-point of the last line or curve that was added
  16287. to a new point, using a straight line.
  16288. See the class description for an example of how to add lines and curves to a path.
  16289. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16290. */
  16291. void lineTo (float endX, float endY);
  16292. /** Adds a line from the shape's last position to a new end-point.
  16293. This will connect the end-point of the last line or curve that was added
  16294. to a new point, using a straight line.
  16295. See the class description for an example of how to add lines and curves to a path.
  16296. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16297. */
  16298. void lineTo (const Point<float>& end);
  16299. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16300. This will connect the end-point of the last line or curve that was added
  16301. to a new point, using a quadratic spline with one control-point.
  16302. See the class description for an example of how to add lines and curves to a path.
  16303. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16304. */
  16305. void quadraticTo (float controlPointX,
  16306. float controlPointY,
  16307. float endPointX,
  16308. float endPointY);
  16309. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16310. This will connect the end-point of the last line or curve that was added
  16311. to a new point, using a quadratic spline with one control-point.
  16312. See the class description for an example of how to add lines and curves to a path.
  16313. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16314. */
  16315. void quadraticTo (const Point<float>& controlPoint,
  16316. const Point<float>& endPoint);
  16317. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16318. This will connect the end-point of the last line or curve that was added
  16319. to a new point, using a cubic spline with two control-points.
  16320. See the class description for an example of how to add lines and curves to a path.
  16321. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16322. */
  16323. void cubicTo (float controlPoint1X,
  16324. float controlPoint1Y,
  16325. float controlPoint2X,
  16326. float controlPoint2Y,
  16327. float endPointX,
  16328. float endPointY);
  16329. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16330. This will connect the end-point of the last line or curve that was added
  16331. to a new point, using a cubic spline with two control-points.
  16332. See the class description for an example of how to add lines and curves to a path.
  16333. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16334. */
  16335. void cubicTo (const Point<float>& controlPoint1,
  16336. const Point<float>& controlPoint2,
  16337. const Point<float>& endPoint);
  16338. /** Returns the last point that was added to the path by one of the drawing methods.
  16339. */
  16340. const Point<float> getCurrentPosition() const;
  16341. /** Adds a rectangle to the path.
  16342. The rectangle is added as a new sub-path. (Any currently open paths will be
  16343. left open).
  16344. @see addRoundedRectangle, addTriangle
  16345. */
  16346. void addRectangle (float x, float y, float width, float height);
  16347. /** Adds a rectangle to the path.
  16348. The rectangle is added as a new sub-path. (Any currently open paths will be
  16349. left open).
  16350. @see addRoundedRectangle, addTriangle
  16351. */
  16352. void addRectangle (const Rectangle<int>& rectangle);
  16353. /** Adds a rectangle with rounded corners to the path.
  16354. The rectangle is added as a new sub-path. (Any currently open paths will be
  16355. left open).
  16356. @see addRectangle, addTriangle
  16357. */
  16358. void addRoundedRectangle (float x, float y, float width, float height,
  16359. float cornerSize);
  16360. /** Adds a rectangle with rounded corners to the path.
  16361. The rectangle is added as a new sub-path. (Any currently open paths will be
  16362. left open).
  16363. @see addRectangle, addTriangle
  16364. */
  16365. void addRoundedRectangle (float x, float y, float width, float height,
  16366. float cornerSizeX,
  16367. float cornerSizeY);
  16368. /** Adds a triangle to the path.
  16369. The triangle is added as a new closed sub-path. (Any currently open paths will be
  16370. left open).
  16371. Note that whether the vertices are specified in clockwise or anticlockwise
  16372. order will affect how the triangle is filled when it overlaps other
  16373. shapes (the winding order setting will affect this of course).
  16374. */
  16375. void addTriangle (float x1, float y1,
  16376. float x2, float y2,
  16377. float x3, float y3);
  16378. /** Adds a quadrilateral to the path.
  16379. The quad is added as a new closed sub-path. (Any currently open paths will be
  16380. left open).
  16381. Note that whether the vertices are specified in clockwise or anticlockwise
  16382. order will affect how the quad is filled when it overlaps other
  16383. shapes (the winding order setting will affect this of course).
  16384. */
  16385. void addQuadrilateral (float x1, float y1,
  16386. float x2, float y2,
  16387. float x3, float y3,
  16388. float x4, float y4);
  16389. /** Adds an ellipse to the path.
  16390. The shape is added as a new sub-path. (Any currently open paths will be
  16391. left open).
  16392. @see addArc
  16393. */
  16394. void addEllipse (float x, float y, float width, float height);
  16395. /** Adds an elliptical arc to the current path.
  16396. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16397. or anti-clockwise according to whether the end angle is greater than the start. This means
  16398. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16399. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16400. @param y the top edge of the rectangle in which the elliptical outline fits
  16401. @param width the width of the rectangle in which the elliptical outline fits
  16402. @param height the height of the rectangle in which the elliptical outline fits
  16403. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16404. top-centre of the ellipse)
  16405. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16406. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16407. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16408. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16409. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16410. it will be added to the current sub-path, continuing from the current postition
  16411. @see addCentredArc, arcTo, addPieSegment, addEllipse
  16412. */
  16413. void addArc (float x, float y, float width, float height,
  16414. float fromRadians,
  16415. float toRadians,
  16416. bool startAsNewSubPath = false);
  16417. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  16418. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16419. or anti-clockwise according to whether the end angle is greater than the start. This means
  16420. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16421. @param centreX the centre x of the ellipse
  16422. @param centreY the centre y of the ellipse
  16423. @param radiusX the horizontal radius of the ellipse
  16424. @param radiusY the vertical radius of the ellipse
  16425. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  16426. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16427. top-centre of the ellipse)
  16428. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16429. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16430. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16431. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16432. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16433. it will be added to the current sub-path, continuing from the current postition
  16434. @see addArc, arcTo
  16435. */
  16436. void addCentredArc (float centreX, float centreY,
  16437. float radiusX, float radiusY,
  16438. float rotationOfEllipse,
  16439. float fromRadians,
  16440. float toRadians,
  16441. bool startAsNewSubPath = false);
  16442. /** Adds a "pie-chart" shape to the path.
  16443. The shape is added as a new sub-path. (Any currently open paths will be
  16444. left open).
  16445. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16446. or anti-clockwise according to whether the end angle is greater than the start. This means
  16447. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16448. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16449. @param y the top edge of the rectangle in which the elliptical outline fits
  16450. @param width the width of the rectangle in which the elliptical outline fits
  16451. @param height the height of the rectangle in which the elliptical outline fits
  16452. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16453. top-centre of the ellipse)
  16454. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16455. top-centre of the ellipse)
  16456. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  16457. ellipse at its centre, where this value indicates the inner ellipse's size with
  16458. respect to the outer one.
  16459. @see addArc
  16460. */
  16461. void addPieSegment (float x, float y,
  16462. float width, float height,
  16463. float fromRadians,
  16464. float toRadians,
  16465. float innerCircleProportionalSize);
  16466. /** Adds a line with a specified thickness.
  16467. The line is added as a new closed sub-path. (Any currently open paths will be
  16468. left open).
  16469. @see addArrow
  16470. */
  16471. void addLineSegment (const Line<float>& line, float lineThickness);
  16472. /** Adds a line with an arrowhead on the end.
  16473. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  16474. @see PathStrokeType::createStrokeWithArrowheads
  16475. */
  16476. void addArrow (const Line<float>& line,
  16477. float lineThickness,
  16478. float arrowheadWidth,
  16479. float arrowheadLength);
  16480. /** Adds a polygon shape to the path.
  16481. @see addStar
  16482. */
  16483. void addPolygon (const Point<float>& centre,
  16484. int numberOfSides,
  16485. float radius,
  16486. float startAngle = 0.0f);
  16487. /** Adds a star shape to the path.
  16488. @see addPolygon
  16489. */
  16490. void addStar (const Point<float>& centre,
  16491. int numberOfPoints,
  16492. float innerRadius,
  16493. float outerRadius,
  16494. float startAngle = 0.0f);
  16495. /** Adds a speech-bubble shape to the path.
  16496. @param bodyX the left of the main body area of the bubble
  16497. @param bodyY the top of the main body area of the bubble
  16498. @param bodyW the width of the main body area of the bubble
  16499. @param bodyH the height of the main body area of the bubble
  16500. @param cornerSize the amount by which to round off the corners of the main body rectangle
  16501. @param arrowTipX the x position that the tip of the arrow should connect to
  16502. @param arrowTipY the y position that the tip of the arrow should connect to
  16503. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  16504. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  16505. arrow's base should be - this is a proportional distance between 0 and 1.0
  16506. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  16507. */
  16508. void addBubble (float bodyX, float bodyY,
  16509. float bodyW, float bodyH,
  16510. float cornerSize,
  16511. float arrowTipX,
  16512. float arrowTipY,
  16513. int whichSide,
  16514. float arrowPositionAlongEdgeProportional,
  16515. float arrowWidth);
  16516. /** Adds another path to this one.
  16517. The new path is added as a new sub-path. (Any currently open paths in this
  16518. path will be left open).
  16519. @param pathToAppend the path to add
  16520. */
  16521. void addPath (const Path& pathToAppend);
  16522. /** Adds another path to this one, transforming it on the way in.
  16523. The new path is added as a new sub-path, its points being transformed by the given
  16524. matrix before being added.
  16525. @param pathToAppend the path to add
  16526. @param transformToApply an optional transform to apply to the incoming vertices
  16527. */
  16528. void addPath (const Path& pathToAppend,
  16529. const AffineTransform& transformToApply);
  16530. /** Swaps the contents of this path with another one.
  16531. The internal data of the two paths is swapped over, so this is much faster than
  16532. copying it to a temp variable and back.
  16533. */
  16534. void swapWithPath (Path& other) throw();
  16535. /** Applies a 2D transform to all the vertices in the path.
  16536. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  16537. */
  16538. void applyTransform (const AffineTransform& transform) throw();
  16539. /** Rescales this path to make it fit neatly into a given space.
  16540. This is effectively a quick way of calling
  16541. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  16542. @param x the x position of the rectangle to fit the path inside
  16543. @param y the y position of the rectangle to fit the path inside
  16544. @param width the width of the rectangle to fit the path inside
  16545. @param height the height of the rectangle to fit the path inside
  16546. @param preserveProportions if true, it will fit the path into the space without altering its
  16547. horizontal/vertical scale ratio; if false, it will distort the
  16548. path to fill the specified ratio both horizontally and vertically
  16549. @see applyTransform, getTransformToScaleToFit
  16550. */
  16551. void scaleToFit (float x, float y, float width, float height,
  16552. bool preserveProportions) throw();
  16553. /** Returns a transform that can be used to rescale the path to fit into a given space.
  16554. @param x the x position of the rectangle to fit the path inside
  16555. @param y the y position of the rectangle to fit the path inside
  16556. @param width the width of the rectangle to fit the path inside
  16557. @param height the height of the rectangle to fit the path inside
  16558. @param preserveProportions if true, it will fit the path into the space without altering its
  16559. horizontal/vertical scale ratio; if false, it will distort the
  16560. path to fill the specified ratio both horizontally and vertically
  16561. @param justificationType if the proportions are preseved, the resultant path may be smaller
  16562. than the available rectangle, so this describes how it should be
  16563. positioned within the space.
  16564. @returns an appropriate transformation
  16565. @see applyTransform, scaleToFit
  16566. */
  16567. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  16568. bool preserveProportions,
  16569. const Justification& justificationType = Justification::centred) const;
  16570. /** Creates a version of this path where all sharp corners have been replaced by curves.
  16571. Wherever two lines meet at an angle, this will replace the corner with a curve
  16572. of the given radius.
  16573. */
  16574. const Path createPathWithRoundedCorners (float cornerRadius) const;
  16575. /** Changes the winding-rule to be used when filling the path.
  16576. If set to true (which is the default), then the path uses a non-zero-winding rule
  16577. to determine which points are inside the path. If set to false, it uses an
  16578. alternate-winding rule.
  16579. The winding-rule comes into play when areas of the shape overlap other
  16580. areas, and determines whether the overlapping regions are considered to be
  16581. inside or outside.
  16582. Changing this value just sets a flag - it doesn't affect the contents of the
  16583. path.
  16584. @see isUsingNonZeroWinding
  16585. */
  16586. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  16587. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  16588. The default for a new path is true.
  16589. @see setUsingNonZeroWinding
  16590. */
  16591. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  16592. /** Iterates the lines and curves that a path contains.
  16593. @see Path, PathFlatteningIterator
  16594. */
  16595. class JUCE_API Iterator
  16596. {
  16597. public:
  16598. Iterator (const Path& path);
  16599. ~Iterator();
  16600. /** Moves onto the next element in the path.
  16601. If this returns false, there are no more elements. If it returns true,
  16602. the elementType variable will be set to the type of the current element,
  16603. and some of the x and y variables will be filled in with values.
  16604. */
  16605. bool next();
  16606. enum PathElementType
  16607. {
  16608. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  16609. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  16610. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  16611. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  16612. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  16613. };
  16614. PathElementType elementType;
  16615. float x1, y1, x2, y2, x3, y3;
  16616. private:
  16617. const Path& path;
  16618. size_t index;
  16619. Iterator (const Iterator&);
  16620. Iterator& operator= (const Iterator&);
  16621. };
  16622. /** Loads a stored path from a data stream.
  16623. The data in the stream must have been written using writePathToStream().
  16624. Note that this will append the stored path to whatever is currently in
  16625. this path, so you might need to call clear() beforehand.
  16626. @see loadPathFromData, writePathToStream
  16627. */
  16628. void loadPathFromStream (InputStream& source);
  16629. /** Loads a stored path from a block of data.
  16630. This is similar to loadPathFromStream(), but just reads from a block
  16631. of data. Useful if you're including stored shapes in your code as a
  16632. block of static data.
  16633. @see loadPathFromStream, writePathToStream
  16634. */
  16635. void loadPathFromData (const void* data, int numberOfBytes);
  16636. /** Stores the path by writing it out to a stream.
  16637. After writing out a path, you can reload it using loadPathFromStream().
  16638. @see loadPathFromStream, loadPathFromData
  16639. */
  16640. void writePathToStream (OutputStream& destination) const;
  16641. /** Creates a string containing a textual representation of this path.
  16642. @see restoreFromString
  16643. */
  16644. const String toString() const;
  16645. /** Restores this path from a string that was created with the toString() method.
  16646. @see toString()
  16647. */
  16648. void restoreFromString (const String& stringVersion);
  16649. juce_UseDebuggingNewOperator
  16650. private:
  16651. friend class PathFlatteningIterator;
  16652. friend class Path::Iterator;
  16653. ArrayAllocationBase <float, DummyCriticalSection> data;
  16654. size_t numElements;
  16655. float pathXMin, pathXMax, pathYMin, pathYMax;
  16656. bool useNonZeroWinding;
  16657. static const float lineMarker;
  16658. static const float moveMarker;
  16659. static const float quadMarker;
  16660. static const float cubicMarker;
  16661. static const float closeSubPathMarker;
  16662. };
  16663. #endif // __JUCE_PATH_JUCEHEADER__
  16664. /*** End of inlined file: juce_Path.h ***/
  16665. class Font;
  16666. /** A typeface represents a size-independent font.
  16667. This base class is abstract, but calling createSystemTypefaceFor() will return
  16668. a platform-specific subclass that can be used.
  16669. The CustomTypeface subclass allow you to build your own typeface, and to
  16670. load and save it in the Juce typeface format.
  16671. Normally you should never need to deal directly with Typeface objects - the Font
  16672. class does everything you typically need for rendering text.
  16673. @see CustomTypeface, Font
  16674. */
  16675. class JUCE_API Typeface : public ReferenceCountedObject
  16676. {
  16677. public:
  16678. /** A handy typedef for a pointer to a typeface. */
  16679. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  16680. /** Returns the name of the typeface.
  16681. @see Font::getTypefaceName
  16682. */
  16683. const String getName() const throw() { return name; }
  16684. /** Creates a new system typeface. */
  16685. static const Ptr createSystemTypefaceFor (const Font& font);
  16686. /** Destructor. */
  16687. virtual ~Typeface();
  16688. /** Returns the ascent of the font, as a proportion of its height.
  16689. The height is considered to always be normalised as 1.0, so this will be a
  16690. value less that 1.0, indicating the proportion of the font that lies above
  16691. its baseline.
  16692. */
  16693. virtual float getAscent() const = 0;
  16694. /** Returns the descent of the font, as a proportion of its height.
  16695. The height is considered to always be normalised as 1.0, so this will be a
  16696. value less that 1.0, indicating the proportion of the font that lies below
  16697. its baseline.
  16698. */
  16699. virtual float getDescent() const = 0;
  16700. /** Measures the width of a line of text.
  16701. The distance returned is based on the font having an normalised height of 1.0.
  16702. You should never need to call this directly! Use Font::getStringWidth() instead!
  16703. */
  16704. virtual float getStringWidth (const String& text) = 0;
  16705. /** Converts a line of text into its glyph numbers and their positions.
  16706. The distances returned are based on the font having an normalised height of 1.0.
  16707. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  16708. */
  16709. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  16710. /** Returns the outline for a glyph.
  16711. The path returned will be normalised to a font height of 1.0.
  16712. */
  16713. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  16714. juce_UseDebuggingNewOperator
  16715. protected:
  16716. String name;
  16717. explicit Typeface (const String& name) throw();
  16718. private:
  16719. Typeface (const Typeface&);
  16720. Typeface& operator= (const Typeface&);
  16721. };
  16722. /** A typeface that can be populated with custom glyphs.
  16723. You can create a CustomTypeface if you need one that contains your own glyphs,
  16724. or if you need to load a typeface from a Juce-formatted binary stream.
  16725. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  16726. to copy glyphs into this face.
  16727. @see Typeface, Font
  16728. */
  16729. class JUCE_API CustomTypeface : public Typeface
  16730. {
  16731. public:
  16732. /** Creates a new, empty typeface. */
  16733. CustomTypeface();
  16734. /** Loads a typeface from a previously saved stream.
  16735. The stream must have been created by writeToStream().
  16736. @see writeToStream
  16737. */
  16738. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  16739. /** Destructor. */
  16740. ~CustomTypeface();
  16741. /** Resets this typeface, deleting all its glyphs and settings. */
  16742. void clear();
  16743. /** Sets the vital statistics for the typeface.
  16744. @param name the typeface's name
  16745. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  16746. the value that will be returned by Typeface::getAscent(). The
  16747. descent is assumed to be (1.0 - ascent)
  16748. @param isBold should be true if the typeface is bold
  16749. @param isItalic should be true if the typeface is italic
  16750. @param defaultCharacter the character to be used as a replacement if there's
  16751. no glyph available for the character that's being drawn
  16752. */
  16753. void setCharacteristics (const String& name, float ascent,
  16754. bool isBold, bool isItalic,
  16755. juce_wchar defaultCharacter) throw();
  16756. /** Adds a glyph to the typeface.
  16757. The path that is passed in is normalised so that the font height is 1.0, and its
  16758. origin is the anchor point of the character on its baseline.
  16759. The width is the nominal width of the character, and any extra kerning values that
  16760. are specified will be added to this width.
  16761. */
  16762. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  16763. /** Specifies an extra kerning amount to be used between a pair of characters.
  16764. The amount will be added to the nominal width of the first character when laying out a string.
  16765. */
  16766. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  16767. /** Adds a range of glyphs from another typeface.
  16768. This will attempt to pull in the paths and kerning information from another typeface and
  16769. add it to this one.
  16770. */
  16771. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  16772. /** Saves this typeface as a Juce-formatted font file.
  16773. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  16774. constructor.
  16775. */
  16776. bool writeToStream (OutputStream& outputStream);
  16777. // The following methods implement the basic Typeface behaviour.
  16778. float getAscent() const;
  16779. float getDescent() const;
  16780. float getStringWidth (const String& text);
  16781. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  16782. bool getOutlineForGlyph (int glyphNumber, Path& path);
  16783. int getGlyphForCharacter (juce_wchar character);
  16784. juce_UseDebuggingNewOperator
  16785. protected:
  16786. juce_wchar defaultCharacter;
  16787. float ascent;
  16788. bool isBold, isItalic;
  16789. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  16790. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  16791. particular character and there's no corresponding glyph, they'll call this
  16792. method so that a subclass can try to add that glyph, returning true if it
  16793. manages to do so.
  16794. */
  16795. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  16796. private:
  16797. class GlyphInfo;
  16798. friend class OwnedArray<GlyphInfo>;
  16799. OwnedArray <GlyphInfo> glyphs;
  16800. short lookupTable [128];
  16801. CustomTypeface (const CustomTypeface&);
  16802. CustomTypeface& operator= (const CustomTypeface&);
  16803. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  16804. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  16805. };
  16806. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  16807. /*** End of inlined file: juce_Typeface.h ***/
  16808. class LowLevelGraphicsContext;
  16809. /**
  16810. Represents a particular font, including its size, style, etc.
  16811. Apart from the typeface to be used, a Font object also dictates whether
  16812. the font is bold, italic, underlined, how big it is, and its kerning and
  16813. horizontal scale factor.
  16814. @see Typeface
  16815. */
  16816. class JUCE_API Font
  16817. {
  16818. public:
  16819. /** A combination of these values is used by the constructor to specify the
  16820. style of font to use.
  16821. */
  16822. enum FontStyleFlags
  16823. {
  16824. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  16825. bold = 1, /**< boldens the font. @see setStyleFlags */
  16826. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  16827. underlined = 4 /**< underlines the font. @see setStyleFlags */
  16828. };
  16829. /** Creates a sans-serif font in a given size.
  16830. @param fontHeight the height in pixels (can be fractional)
  16831. @param styleFlags the style to use - this can be a combination of the
  16832. Font::bold, Font::italic and Font::underlined, or
  16833. just Font::plain for the normal style.
  16834. @see FontStyleFlags, getDefaultSansSerifFontName
  16835. */
  16836. Font (float fontHeight,
  16837. int styleFlags = plain) throw();
  16838. /** Creates a font with a given typeface and parameters.
  16839. @param typefaceName the name of the typeface to use
  16840. @param fontHeight the height in pixels (can be fractional)
  16841. @param styleFlags the style to use - this can be a combination of the
  16842. Font::bold, Font::italic and Font::underlined, or
  16843. just Font::plain for the normal style.
  16844. @see FontStyleFlags, getDefaultSansSerifFontName
  16845. */
  16846. Font (const String& typefaceName,
  16847. float fontHeight,
  16848. int styleFlags) throw();
  16849. /** Creates a copy of another Font object. */
  16850. Font (const Font& other) throw();
  16851. /** Creates a font for a typeface. */
  16852. Font (const Typeface::Ptr& typeface) throw();
  16853. /** Creates a basic sans-serif font at a default height.
  16854. You should use one of the other constructors for creating a font that you're planning
  16855. on drawing with - this constructor is here to help initialise objects before changing
  16856. the font's settings later.
  16857. */
  16858. Font() throw();
  16859. /** Copies this font from another one. */
  16860. Font& operator= (const Font& other) throw();
  16861. bool operator== (const Font& other) const throw();
  16862. bool operator!= (const Font& other) const throw();
  16863. /** Destructor. */
  16864. ~Font() throw();
  16865. /** Changes the name of the typeface family.
  16866. e.g. "Arial", "Courier", etc.
  16867. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16868. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16869. but are generic names that are used to represent the various default fonts.
  16870. If you need to know the exact typeface name being used, you can call
  16871. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16872. If a suitable font isn't found on the machine, it'll just use a default instead.
  16873. */
  16874. void setTypefaceName (const String& faceName) throw();
  16875. /** Returns the name of the typeface family that this font uses.
  16876. e.g. "Arial", "Courier", etc.
  16877. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16878. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16879. but are generic names that are used to represent the various default fonts.
  16880. If you need to know the exact typeface name being used, you can call
  16881. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16882. */
  16883. const String& getTypefaceName() const throw() { return font->typefaceName; }
  16884. /** Returns a typeface name that represents the default sans-serif font.
  16885. This is also the typeface that will be used when a font is created without
  16886. specifying any typeface details.
  16887. Note that this method just returns a generic placeholder string that means "the default
  16888. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  16889. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16890. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  16891. */
  16892. static const String getDefaultSansSerifFontName() throw();
  16893. /** Returns a typeface name that represents the default sans-serif font.
  16894. Note that this method just returns a generic placeholder string that means "the default
  16895. serif font" - it's not the actual name of this font. To get the actual name, use
  16896. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16897. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  16898. */
  16899. static const String getDefaultSerifFontName() throw();
  16900. /** Returns a typeface name that represents the default sans-serif font.
  16901. Note that this method just returns a generic placeholder string that means "the default
  16902. monospaced font" - it's not the actual name of this font. To get the actual name, use
  16903. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16904. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  16905. */
  16906. static const String getDefaultMonospacedFontName() throw();
  16907. /** Returns the typeface names of the default fonts on the current platform. */
  16908. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed);
  16909. /** Returns the total height of this font.
  16910. This is the maximum height, from the top of the ascent to the bottom of the
  16911. descenders.
  16912. @see setHeight, setHeightWithoutChangingWidth, getAscent
  16913. */
  16914. float getHeight() const throw() { return font->height; }
  16915. /** Changes the font's height.
  16916. @see getHeight, setHeightWithoutChangingWidth
  16917. */
  16918. void setHeight (float newHeight) throw();
  16919. /** Changes the font's height without changing its width.
  16920. This alters the horizontal scale to compensate for the change in height.
  16921. */
  16922. void setHeightWithoutChangingWidth (float newHeight) throw();
  16923. /** Returns the height of the font above its baseline.
  16924. This is the maximum height from the baseline to the top.
  16925. @see getHeight, getDescent
  16926. */
  16927. float getAscent() const throw();
  16928. /** Returns the amount that the font descends below its baseline.
  16929. This is calculated as (getHeight() - getAscent()).
  16930. @see getAscent, getHeight
  16931. */
  16932. float getDescent() const throw();
  16933. /** Returns the font's style flags.
  16934. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  16935. enum, to describe whether the font is bold, italic, etc.
  16936. @see FontStyleFlags
  16937. */
  16938. int getStyleFlags() const throw() { return font->styleFlags; }
  16939. /** Changes the font's style.
  16940. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  16941. enum, to set the font's properties
  16942. @see FontStyleFlags
  16943. */
  16944. void setStyleFlags (int newFlags) throw();
  16945. /** Makes the font bold or non-bold. */
  16946. void setBold (bool shouldBeBold) throw();
  16947. /** Returns true if the font is bold. */
  16948. bool isBold() const throw();
  16949. /** Makes the font italic or non-italic. */
  16950. void setItalic (bool shouldBeItalic) throw();
  16951. /** Returns true if the font is italic. */
  16952. bool isItalic() const throw();
  16953. /** Makes the font underlined or non-underlined. */
  16954. void setUnderline (bool shouldBeUnderlined) throw();
  16955. /** Returns true if the font is underlined. */
  16956. bool isUnderlined() const throw();
  16957. /** Changes the font's horizontal scale factor.
  16958. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  16959. narrower, greater than 1.0 will be stretched out.
  16960. */
  16961. void setHorizontalScale (float scaleFactor) throw();
  16962. /** Returns the font's horizontal scale.
  16963. A value of 1.0 is the normal scale, less than this will be narrower, greater
  16964. than 1.0 will be stretched out.
  16965. @see setHorizontalScale
  16966. */
  16967. float getHorizontalScale() const throw() { return font->horizontalScale; }
  16968. /** Changes the font's kerning.
  16969. @param extraKerning a multiple of the font's height that will be added
  16970. to space between the characters. So a value of zero is
  16971. normal spacing, positive values spread the letters out,
  16972. negative values make them closer together.
  16973. */
  16974. void setExtraKerningFactor (float extraKerning) throw();
  16975. /** Returns the font's kerning.
  16976. This is the extra space added between adjacent characters, as a proportion
  16977. of the font's height.
  16978. A value of zero is normal spacing, positive values will spread the letters
  16979. out more, and negative values make them closer together.
  16980. */
  16981. float getExtraKerningFactor() const throw() { return font->kerning; }
  16982. /** Changes all the font's characteristics with one call. */
  16983. void setSizeAndStyle (float newHeight,
  16984. int newStyleFlags,
  16985. float newHorizontalScale,
  16986. float newKerningAmount) throw();
  16987. /** Returns the total width of a string as it would be drawn using this font.
  16988. For a more accurate floating-point result, use getStringWidthFloat().
  16989. */
  16990. int getStringWidth (const String& text) const throw();
  16991. /** Returns the total width of a string as it would be drawn using this font.
  16992. @see getStringWidth
  16993. */
  16994. float getStringWidthFloat (const String& text) const throw();
  16995. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  16996. An extra x offset is added at the end of the run, to indicate where the right hand
  16997. edge of the last character is.
  16998. */
  16999. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  17000. /** Returns the typeface used by this font.
  17001. Note that the object returned may go out of scope if this font is deleted
  17002. or has its style changed.
  17003. */
  17004. Typeface* getTypeface() const throw();
  17005. /** Creates an array of Font objects to represent all the fonts on the system.
  17006. If you just need the names of the typefaces, you can also use
  17007. findAllTypefaceNames() instead.
  17008. @param results the array to which new Font objects will be added.
  17009. */
  17010. static void findFonts (Array<Font>& results) throw();
  17011. /** Returns a list of all the available typeface names.
  17012. The names returned can be passed into setTypefaceName().
  17013. You can use this instead of findFonts() if you only need their names, and not
  17014. font objects.
  17015. */
  17016. static const StringArray findAllTypefaceNames();
  17017. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  17018. in the requested typeface.
  17019. */
  17020. static const String getFallbackFontName() throw();
  17021. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  17022. available in whatever font you're trying to use.
  17023. */
  17024. static void setFallbackFontName (const String& name) throw();
  17025. /** Creates a string to describe this font.
  17026. The string will contain information to describe the font's typeface, size, and
  17027. style. To recreate the font from this string, use fromString().
  17028. */
  17029. const String toString() const;
  17030. /** Recreates a font from its stringified encoding.
  17031. This method takes a string that was created by toString(), and recreates the
  17032. original font.
  17033. */
  17034. static const Font fromString (const String& fontDescription);
  17035. juce_UseDebuggingNewOperator
  17036. private:
  17037. friend class FontGlyphAlphaMap;
  17038. friend class TypefaceCache;
  17039. class SharedFontInternal : public ReferenceCountedObject
  17040. {
  17041. public:
  17042. SharedFontInternal (const String& typefaceName, float height, float horizontalScale,
  17043. float kerning, float ascent, int styleFlags,
  17044. Typeface* typeface) throw();
  17045. SharedFontInternal (const SharedFontInternal& other) throw();
  17046. String typefaceName;
  17047. float height, horizontalScale, kerning, ascent;
  17048. int styleFlags;
  17049. Typeface::Ptr typeface;
  17050. };
  17051. ReferenceCountedObjectPtr <SharedFontInternal> font;
  17052. void dupeInternalIfShared() throw();
  17053. };
  17054. #endif // __JUCE_FONT_JUCEHEADER__
  17055. /*** End of inlined file: juce_Font.h ***/
  17056. /*** Start of inlined file: juce_PathStrokeType.h ***/
  17057. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17058. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17059. /**
  17060. Describes a type of stroke used to render a solid outline along a path.
  17061. A PathStrokeType object can be used directly to create the shape of an outline
  17062. around a path, and is used by Graphics::strokePath to specify the type of
  17063. stroke to draw.
  17064. @see Path, Graphics::strokePath
  17065. */
  17066. class JUCE_API PathStrokeType
  17067. {
  17068. public:
  17069. /** The type of shape to use for the corners between two adjacent line segments. */
  17070. enum JointStyle
  17071. {
  17072. mitered, /**< Indicates that corners should be drawn with sharp joints.
  17073. Note that for angles that curve back on themselves, drawing a
  17074. mitre could require extending the point too far away from the
  17075. path, so a mitre limit is imposed and any corners that exceed it
  17076. are drawn as bevelled instead. */
  17077. curved, /**< Indicates that corners should be drawn as rounded-off. */
  17078. beveled /**< Indicates that corners should be drawn with a line flattening their
  17079. outside edge. */
  17080. };
  17081. /** The type shape to use for the ends of lines. */
  17082. enum EndCapStyle
  17083. {
  17084. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  17085. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  17086. the thickness of the stroke. */
  17087. rounded /**< Ends of lines are rounded-off with a circular shape. */
  17088. };
  17089. /** Creates a stroke type.
  17090. @param strokeThickness the width of the line to use
  17091. @param jointStyle the type of joints to use for corners
  17092. @param endStyle the type of end-caps to use for the ends of open paths.
  17093. */
  17094. PathStrokeType (float strokeThickness,
  17095. JointStyle jointStyle = mitered,
  17096. EndCapStyle endStyle = butt) throw();
  17097. /** Createes a copy of another stroke type. */
  17098. PathStrokeType (const PathStrokeType& other) throw();
  17099. /** Copies another stroke onto this one. */
  17100. PathStrokeType& operator= (const PathStrokeType& other) throw();
  17101. /** Destructor. */
  17102. ~PathStrokeType() throw();
  17103. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  17104. @param destPath the resultant stroked outline shape will be copied into this path.
  17105. Note that it's ok for the source and destination Paths to be
  17106. the same object, so you can easily turn a path into a stroked version
  17107. of itself.
  17108. @param sourcePath the path to use as the source
  17109. @param transform an optional transform to apply to the points from the source path
  17110. as they are being used
  17111. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17112. a higher resolution, which improved the quality if you'll later want
  17113. to enlarge the stroked path
  17114. @see createDashedStroke
  17115. */
  17116. void createStrokedPath (Path& destPath,
  17117. const Path& sourcePath,
  17118. const AffineTransform& transform = AffineTransform::identity,
  17119. float extraAccuracy = 1.0f) const;
  17120. /** Applies this stroke type to a path, creating a dashed line.
  17121. This is similar to createStrokedPath, but uses the array passed in to
  17122. break the stroke up into a series of dashes.
  17123. @param destPath the resultant stroked outline shape will be copied into this path.
  17124. Note that it's ok for the source and destination Paths to be
  17125. the same object, so you can easily turn a path into a stroked version
  17126. of itself.
  17127. @param sourcePath the path to use as the source
  17128. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  17129. a line of length 2, then skip a length of 3, then add a line of length 4,
  17130. skip 5, and keep repeating this pattern.
  17131. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  17132. an even number, otherwise the pattern will get out of step as it
  17133. repeats.
  17134. @param transform an optional transform to apply to the points from the source path
  17135. as they are being used
  17136. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17137. a higher resolution, which improved the quality if you'll later want
  17138. to enlarge the stroked path
  17139. */
  17140. void createDashedStroke (Path& destPath,
  17141. const Path& sourcePath,
  17142. const float* dashLengths,
  17143. int numDashLengths,
  17144. const AffineTransform& transform = AffineTransform::identity,
  17145. float extraAccuracy = 1.0f) const;
  17146. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  17147. @param destPath the resultant stroked outline shape will be copied into this path.
  17148. Note that it's ok for the source and destination Paths to be
  17149. the same object, so you can easily turn a path into a stroked version
  17150. of itself.
  17151. @param sourcePath the path to use as the source
  17152. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  17153. @param arrowheadStartLength the length of the arrowhead at the start of the path
  17154. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  17155. @param arrowheadEndLength the length of the arrowhead at the end of the path
  17156. @param transform an optional transform to apply to the points from the source path
  17157. as they are being used
  17158. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17159. a higher resolution, which improved the quality if you'll later want
  17160. to enlarge the stroked path
  17161. @see createDashedStroke
  17162. */
  17163. void createStrokeWithArrowheads (Path& destPath,
  17164. const Path& sourcePath,
  17165. float arrowheadStartWidth, float arrowheadStartLength,
  17166. float arrowheadEndWidth, float arrowheadEndLength,
  17167. const AffineTransform& transform = AffineTransform::identity,
  17168. float extraAccuracy = 1.0f) const;
  17169. /** Returns the stroke thickness. */
  17170. float getStrokeThickness() const throw() { return thickness; }
  17171. /** Sets the stroke thickness. */
  17172. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  17173. /** Returns the joint style. */
  17174. JointStyle getJointStyle() const throw() { return jointStyle; }
  17175. /** Sets the joint style. */
  17176. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  17177. /** Returns the end-cap style. */
  17178. EndCapStyle getEndStyle() const throw() { return endStyle; }
  17179. /** Sets the end-cap style. */
  17180. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  17181. juce_UseDebuggingNewOperator
  17182. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  17183. bool operator== (const PathStrokeType& other) const throw();
  17184. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  17185. bool operator!= (const PathStrokeType& other) const throw();
  17186. private:
  17187. float thickness;
  17188. JointStyle jointStyle;
  17189. EndCapStyle endStyle;
  17190. };
  17191. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17192. /*** End of inlined file: juce_PathStrokeType.h ***/
  17193. /*** Start of inlined file: juce_Colours.h ***/
  17194. #ifndef __JUCE_COLOURS_JUCEHEADER__
  17195. #define __JUCE_COLOURS_JUCEHEADER__
  17196. /*** Start of inlined file: juce_Colour.h ***/
  17197. #ifndef __JUCE_COLOUR_JUCEHEADER__
  17198. #define __JUCE_COLOUR_JUCEHEADER__
  17199. /*** Start of inlined file: juce_PixelFormats.h ***/
  17200. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  17201. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  17202. #if JUCE_MSVC
  17203. #pragma pack (push, 1)
  17204. #define PACKED
  17205. #elif JUCE_GCC
  17206. #define PACKED __attribute__((packed))
  17207. #else
  17208. #define PACKED
  17209. #endif
  17210. class PixelRGB;
  17211. class PixelAlpha;
  17212. /**
  17213. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  17214. operations with it.
  17215. This is used internally by the imaging classes.
  17216. @see PixelRGB
  17217. */
  17218. class JUCE_API PixelARGB
  17219. {
  17220. public:
  17221. /** Creates a pixel without defining its colour. */
  17222. PixelARGB() throw() {}
  17223. ~PixelARGB() throw() {}
  17224. /** Creates a pixel from a 32-bit argb value.
  17225. */
  17226. PixelARGB (const uint32 argb_) throw()
  17227. : argb (argb_)
  17228. {
  17229. }
  17230. forcedinline uint32 getARGB() const throw() { return argb; }
  17231. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  17232. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  17233. forcedinline uint8 getAlpha() const throw() { return components.a; }
  17234. forcedinline uint8 getRed() const throw() { return components.r; }
  17235. forcedinline uint8 getGreen() const throw() { return components.g; }
  17236. forcedinline uint8 getBlue() const throw() { return components.b; }
  17237. /** Blends another pixel onto this one.
  17238. This takes into account the opacity of the pixel being overlaid, and blends
  17239. it accordingly.
  17240. */
  17241. forcedinline void blend (const PixelARGB& src) throw()
  17242. {
  17243. uint32 sargb = src.getARGB();
  17244. const uint32 alpha = 0x100 - (sargb >> 24);
  17245. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17246. sargb += 0xff00ff00 & (getAG() * alpha);
  17247. argb = sargb;
  17248. }
  17249. /** Blends another pixel onto this one.
  17250. This takes into account the opacity of the pixel being overlaid, and blends
  17251. it accordingly.
  17252. */
  17253. forcedinline void blend (const PixelAlpha& src) throw();
  17254. /** Blends another pixel onto this one.
  17255. This takes into account the opacity of the pixel being overlaid, and blends
  17256. it accordingly.
  17257. */
  17258. forcedinline void blend (const PixelRGB& src) throw();
  17259. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17260. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17261. being used, so this can blend semi-transparently from a PixelRGB argument.
  17262. */
  17263. template <class Pixel>
  17264. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17265. {
  17266. ++extraAlpha;
  17267. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  17268. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  17269. const uint32 alpha = 0x100 - (sargb >> 24);
  17270. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17271. sargb += 0xff00ff00 & (getAG() * alpha);
  17272. argb = sargb;
  17273. }
  17274. /** Blends another pixel with this one, creating a colour that is somewhere
  17275. between the two, as specified by the amount.
  17276. */
  17277. template <class Pixel>
  17278. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17279. {
  17280. uint32 drb = getRB();
  17281. drb += (((src.getRB() - drb) * amount) >> 8);
  17282. drb &= 0x00ff00ff;
  17283. uint32 dag = getAG();
  17284. dag += (((src.getAG() - dag) * amount) >> 8);
  17285. dag &= 0x00ff00ff;
  17286. dag <<= 8;
  17287. dag |= drb;
  17288. argb = dag;
  17289. }
  17290. /** Copies another pixel colour over this one.
  17291. This doesn't blend it - this colour is simply replaced by the other one.
  17292. */
  17293. template <class Pixel>
  17294. forcedinline void set (const Pixel& src) throw()
  17295. {
  17296. argb = src.getARGB();
  17297. }
  17298. /** Replaces the colour's alpha value with another one. */
  17299. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17300. {
  17301. components.a = newAlpha;
  17302. }
  17303. /** Multiplies the colour's alpha value with another one. */
  17304. forcedinline void multiplyAlpha (int multiplier) throw()
  17305. {
  17306. ++multiplier;
  17307. argb = ((multiplier * getAG()) & 0xff00ff00)
  17308. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  17309. }
  17310. forcedinline void multiplyAlpha (const float multiplier) throw()
  17311. {
  17312. multiplyAlpha ((int) (multiplier * 256.0f));
  17313. }
  17314. /** Sets the pixel's colour from individual components. */
  17315. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  17316. {
  17317. components.b = b;
  17318. components.g = g;
  17319. components.r = r;
  17320. components.a = a;
  17321. }
  17322. /** Premultiplies the pixel's RGB values by its alpha. */
  17323. forcedinline void premultiply() throw()
  17324. {
  17325. const uint32 alpha = components.a;
  17326. if (alpha < 0xff)
  17327. {
  17328. if (alpha == 0)
  17329. {
  17330. components.b = 0;
  17331. components.g = 0;
  17332. components.r = 0;
  17333. }
  17334. else
  17335. {
  17336. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  17337. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  17338. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  17339. }
  17340. }
  17341. }
  17342. /** Unpremultiplies the pixel's RGB values. */
  17343. forcedinline void unpremultiply() throw()
  17344. {
  17345. const uint32 alpha = components.a;
  17346. if (alpha < 0xff)
  17347. {
  17348. if (alpha == 0)
  17349. {
  17350. components.b = 0;
  17351. components.g = 0;
  17352. components.r = 0;
  17353. }
  17354. else
  17355. {
  17356. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  17357. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  17358. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  17359. }
  17360. }
  17361. }
  17362. forcedinline void desaturate() throw()
  17363. {
  17364. if (components.a < 0xff && components.a > 0)
  17365. {
  17366. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  17367. components.r = components.g = components.b
  17368. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  17369. }
  17370. else
  17371. {
  17372. components.r = components.g = components.b
  17373. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  17374. }
  17375. }
  17376. /** The indexes of the different components in the byte layout of this type of colour. */
  17377. #if JUCE_BIG_ENDIAN
  17378. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  17379. #else
  17380. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  17381. #endif
  17382. private:
  17383. union
  17384. {
  17385. uint32 argb;
  17386. struct
  17387. {
  17388. #if JUCE_BIG_ENDIAN
  17389. uint8 a : 8, r : 8, g : 8, b : 8;
  17390. #else
  17391. uint8 b, g, r, a;
  17392. #endif
  17393. } PACKED components;
  17394. };
  17395. } PACKED;
  17396. /**
  17397. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  17398. This is used internally by the imaging classes.
  17399. @see PixelARGB
  17400. */
  17401. class JUCE_API PixelRGB
  17402. {
  17403. public:
  17404. /** Creates a pixel without defining its colour. */
  17405. PixelRGB() throw() {}
  17406. ~PixelRGB() throw() {}
  17407. /** Creates a pixel from a 32-bit argb value.
  17408. (The argb format is that used by PixelARGB)
  17409. */
  17410. PixelRGB (const uint32 argb) throw()
  17411. {
  17412. r = (uint8) (argb >> 16);
  17413. g = (uint8) (argb >> 8);
  17414. b = (uint8) (argb);
  17415. }
  17416. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  17417. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  17418. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  17419. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  17420. forcedinline uint8 getRed() const throw() { return r; }
  17421. forcedinline uint8 getGreen() const throw() { return g; }
  17422. forcedinline uint8 getBlue() const throw() { return b; }
  17423. /** Blends another pixel onto this one.
  17424. This takes into account the opacity of the pixel being overlaid, and blends
  17425. it accordingly.
  17426. */
  17427. forcedinline void blend (const PixelARGB& src) throw()
  17428. {
  17429. uint32 sargb = src.getARGB();
  17430. const uint32 alpha = 0x100 - (sargb >> 24);
  17431. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17432. sargb += 0x0000ff00 & (g * alpha);
  17433. r = (uint8) (sargb >> 16);
  17434. g = (uint8) (sargb >> 8);
  17435. b = (uint8) sargb;
  17436. }
  17437. forcedinline void blend (const PixelRGB& src) throw()
  17438. {
  17439. set (src);
  17440. }
  17441. forcedinline void blend (const PixelAlpha& src) throw();
  17442. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17443. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17444. being used, so this can blend semi-transparently from a PixelRGB argument.
  17445. */
  17446. template <class Pixel>
  17447. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17448. {
  17449. ++extraAlpha;
  17450. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  17451. const uint32 sag = extraAlpha * src.getAG();
  17452. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  17453. const uint32 alpha = 0x100 - (sargb >> 24);
  17454. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17455. sargb += 0x0000ff00 & (g * alpha);
  17456. b = (uint8) sargb;
  17457. g = (uint8) (sargb >> 8);
  17458. r = (uint8) (sargb >> 16);
  17459. }
  17460. /** Blends another pixel with this one, creating a colour that is somewhere
  17461. between the two, as specified by the amount.
  17462. */
  17463. template <class Pixel>
  17464. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17465. {
  17466. uint32 drb = getRB();
  17467. drb += (((src.getRB() - drb) * amount) >> 8);
  17468. uint32 dag = getAG();
  17469. dag += (((src.getAG() - dag) * amount) >> 8);
  17470. b = (uint8) drb;
  17471. g = (uint8) dag;
  17472. r = (uint8) (drb >> 16);
  17473. }
  17474. /** Copies another pixel colour over this one.
  17475. This doesn't blend it - this colour is simply replaced by the other one.
  17476. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  17477. is thrown away.
  17478. */
  17479. template <class Pixel>
  17480. forcedinline void set (const Pixel& src) throw()
  17481. {
  17482. b = src.getBlue();
  17483. g = src.getGreen();
  17484. r = src.getRed();
  17485. }
  17486. /** This method is included for compatibility with the PixelARGB class. */
  17487. forcedinline void setAlpha (const uint8) throw() {}
  17488. /** Multiplies the colour's alpha value with another one. */
  17489. forcedinline void multiplyAlpha (int) throw() {}
  17490. /** Sets the pixel's colour from individual components. */
  17491. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  17492. {
  17493. r = r_;
  17494. g = g_;
  17495. b = b_;
  17496. }
  17497. /** Premultiplies the pixel's RGB values by its alpha. */
  17498. forcedinline void premultiply() throw() {}
  17499. /** Unpremultiplies the pixel's RGB values. */
  17500. forcedinline void unpremultiply() throw() {}
  17501. forcedinline void desaturate() throw()
  17502. {
  17503. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  17504. }
  17505. /** The indexes of the different components in the byte layout of this type of colour. */
  17506. #if JUCE_MAC
  17507. enum { indexR = 0, indexG = 1, indexB = 2 };
  17508. #else
  17509. enum { indexR = 2, indexG = 1, indexB = 0 };
  17510. #endif
  17511. private:
  17512. #if JUCE_MAC
  17513. uint8 r, g, b;
  17514. #else
  17515. uint8 b, g, r;
  17516. #endif
  17517. } PACKED;
  17518. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  17519. {
  17520. set (src);
  17521. }
  17522. /**
  17523. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  17524. This is used internally by the imaging classes.
  17525. @see PixelARGB, PixelRGB
  17526. */
  17527. class JUCE_API PixelAlpha
  17528. {
  17529. public:
  17530. /** Creates a pixel without defining its colour. */
  17531. PixelAlpha() throw() {}
  17532. ~PixelAlpha() throw() {}
  17533. /** Creates a pixel from a 32-bit argb value.
  17534. (The argb format is that used by PixelARGB)
  17535. */
  17536. PixelAlpha (const uint32 argb) throw()
  17537. {
  17538. a = (uint8) (argb >> 24);
  17539. }
  17540. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  17541. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  17542. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  17543. forcedinline uint8 getAlpha() const throw() { return a; }
  17544. forcedinline uint8 getRed() const throw() { return 0; }
  17545. forcedinline uint8 getGreen() const throw() { return 0; }
  17546. forcedinline uint8 getBlue() const throw() { return 0; }
  17547. /** Blends another pixel onto this one.
  17548. This takes into account the opacity of the pixel being overlaid, and blends
  17549. it accordingly.
  17550. */
  17551. template <class Pixel>
  17552. forcedinline void blend (const Pixel& src) throw()
  17553. {
  17554. const int srcA = src.getAlpha();
  17555. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  17556. }
  17557. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17558. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17559. being used, so this can blend semi-transparently from a PixelRGB argument.
  17560. */
  17561. template <class Pixel>
  17562. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17563. {
  17564. ++extraAlpha;
  17565. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  17566. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  17567. }
  17568. /** Blends another pixel with this one, creating a colour that is somewhere
  17569. between the two, as specified by the amount.
  17570. */
  17571. template <class Pixel>
  17572. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17573. {
  17574. a += ((src,getAlpha() - a) * amount) >> 8;
  17575. }
  17576. /** Copies another pixel colour over this one.
  17577. This doesn't blend it - this colour is simply replaced by the other one.
  17578. */
  17579. template <class Pixel>
  17580. forcedinline void set (const Pixel& src) throw()
  17581. {
  17582. a = src.getAlpha();
  17583. }
  17584. /** Replaces the colour's alpha value with another one. */
  17585. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17586. {
  17587. a = newAlpha;
  17588. }
  17589. /** Multiplies the colour's alpha value with another one. */
  17590. forcedinline void multiplyAlpha (int multiplier) throw()
  17591. {
  17592. ++multiplier;
  17593. a = (uint8) ((a * multiplier) >> 8);
  17594. }
  17595. forcedinline void multiplyAlpha (const float multiplier) throw()
  17596. {
  17597. a = (uint8) (a * multiplier);
  17598. }
  17599. /** Sets the pixel's colour from individual components. */
  17600. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  17601. {
  17602. a = a_;
  17603. }
  17604. /** Premultiplies the pixel's RGB values by its alpha. */
  17605. forcedinline void premultiply() throw()
  17606. {
  17607. }
  17608. /** Unpremultiplies the pixel's RGB values. */
  17609. forcedinline void unpremultiply() throw()
  17610. {
  17611. }
  17612. forcedinline void desaturate() throw()
  17613. {
  17614. }
  17615. /** The indexes of the different components in the byte layout of this type of colour. */
  17616. enum { indexA = 0 };
  17617. private:
  17618. uint8 a : 8;
  17619. } PACKED;
  17620. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  17621. {
  17622. blend (PixelARGB (src.getARGB()));
  17623. }
  17624. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  17625. {
  17626. uint32 sargb = src.getARGB();
  17627. const uint32 alpha = 0x100 - (sargb >> 24);
  17628. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17629. sargb += 0xff00ff00 & (getAG() * alpha);
  17630. argb = sargb;
  17631. }
  17632. #if JUCE_MSVC
  17633. #pragma pack (pop)
  17634. #endif
  17635. #undef PACKED
  17636. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  17637. /*** End of inlined file: juce_PixelFormats.h ***/
  17638. /**
  17639. Represents a colour, also including a transparency value.
  17640. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  17641. */
  17642. class JUCE_API Colour
  17643. {
  17644. public:
  17645. /** Creates a transparent black colour. */
  17646. Colour() throw();
  17647. /** Creates a copy of another Colour object. */
  17648. Colour (const Colour& other) throw();
  17649. /** Creates a colour from a 32-bit ARGB value.
  17650. The format of this number is:
  17651. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  17652. All components in the range 0x00 to 0xff.
  17653. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17654. @see getPixelARGB
  17655. */
  17656. explicit Colour (uint32 argb) throw();
  17657. /** Creates an opaque colour using 8-bit red, green and blue values */
  17658. Colour (uint8 red,
  17659. uint8 green,
  17660. uint8 blue) throw();
  17661. /** Creates an opaque colour using 8-bit red, green and blue values */
  17662. static const Colour fromRGB (uint8 red,
  17663. uint8 green,
  17664. uint8 blue) throw();
  17665. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17666. Colour (uint8 red,
  17667. uint8 green,
  17668. uint8 blue,
  17669. uint8 alpha) throw();
  17670. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17671. static const Colour fromRGBA (uint8 red,
  17672. uint8 green,
  17673. uint8 blue,
  17674. uint8 alpha) throw();
  17675. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  17676. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  17677. Values outside the valid range will be clipped.
  17678. */
  17679. Colour (uint8 red,
  17680. uint8 green,
  17681. uint8 blue,
  17682. float alpha) throw();
  17683. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  17684. static const Colour fromRGBAFloat (uint8 red,
  17685. uint8 green,
  17686. uint8 blue,
  17687. float alpha) throw();
  17688. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17689. The floating point values must be between 0.0 and 1.0.
  17690. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17691. Values outside the valid range will be clipped.
  17692. */
  17693. Colour (float hue,
  17694. float saturation,
  17695. float brightness,
  17696. uint8 alpha) throw();
  17697. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  17698. All values must be between 0.0 and 1.0.
  17699. Numbers outside the valid range will be clipped.
  17700. */
  17701. Colour (float hue,
  17702. float saturation,
  17703. float brightness,
  17704. float alpha) throw();
  17705. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17706. The floating point values must be between 0.0 and 1.0.
  17707. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17708. Values outside the valid range will be clipped.
  17709. */
  17710. static const Colour fromHSV (float hue,
  17711. float saturation,
  17712. float brightness,
  17713. float alpha) throw();
  17714. /** Destructor. */
  17715. ~Colour() throw();
  17716. /** Copies another Colour object. */
  17717. Colour& operator= (const Colour& other) throw();
  17718. /** Compares two colours. */
  17719. bool operator== (const Colour& other) const throw();
  17720. /** Compares two colours. */
  17721. bool operator!= (const Colour& other) const throw();
  17722. /** Returns the red component of this colour.
  17723. @returns a value between 0x00 and 0xff.
  17724. */
  17725. uint8 getRed() const throw() { return argb.getRed(); }
  17726. /** Returns the green component of this colour.
  17727. @returns a value between 0x00 and 0xff.
  17728. */
  17729. uint8 getGreen() const throw() { return argb.getGreen(); }
  17730. /** Returns the blue component of this colour.
  17731. @returns a value between 0x00 and 0xff.
  17732. */
  17733. uint8 getBlue() const throw() { return argb.getBlue(); }
  17734. /** Returns the red component of this colour as a floating point value.
  17735. @returns a value between 0.0 and 1.0
  17736. */
  17737. float getFloatRed() const throw();
  17738. /** Returns the green component of this colour as a floating point value.
  17739. @returns a value between 0.0 and 1.0
  17740. */
  17741. float getFloatGreen() const throw();
  17742. /** Returns the blue component of this colour as a floating point value.
  17743. @returns a value between 0.0 and 1.0
  17744. */
  17745. float getFloatBlue() const throw();
  17746. /** Returns a premultiplied ARGB pixel object that represents this colour.
  17747. */
  17748. const PixelARGB getPixelARGB() const throw();
  17749. /** Returns a 32-bit integer that represents this colour.
  17750. The format of this number is:
  17751. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  17752. */
  17753. uint32 getARGB() const throw();
  17754. /** Returns the colour's alpha (opacity).
  17755. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  17756. */
  17757. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  17758. /** Returns the colour's alpha (opacity) as a floating point value.
  17759. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  17760. */
  17761. float getFloatAlpha() const throw();
  17762. /** Returns true if this colour is completely opaque.
  17763. Equivalent to (getAlpha() == 0xff).
  17764. */
  17765. bool isOpaque() const throw();
  17766. /** Returns true if this colour is completely transparent.
  17767. Equivalent to (getAlpha() == 0x00).
  17768. */
  17769. bool isTransparent() const throw();
  17770. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17771. const Colour withAlpha (uint8 newAlpha) const throw();
  17772. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17773. const Colour withAlpha (float newAlpha) const throw();
  17774. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  17775. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  17776. */
  17777. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  17778. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  17779. If the foreground colour is semi-transparent, it is blended onto this colour
  17780. accordingly.
  17781. */
  17782. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  17783. /** Returns a colour that lies somewhere between this one and another.
  17784. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  17785. is 1.0, the result is 100% of the other colour.
  17786. */
  17787. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  17788. /** Returns the colour's hue component.
  17789. The value returned is in the range 0.0 to 1.0
  17790. */
  17791. float getHue() const throw();
  17792. /** Returns the colour's saturation component.
  17793. The value returned is in the range 0.0 to 1.0
  17794. */
  17795. float getSaturation() const throw();
  17796. /** Returns the colour's brightness component.
  17797. The value returned is in the range 0.0 to 1.0
  17798. */
  17799. float getBrightness() const throw();
  17800. /** Returns the colour's hue, saturation and brightness components all at once.
  17801. The values returned are in the range 0.0 to 1.0
  17802. */
  17803. void getHSB (float& hue,
  17804. float& saturation,
  17805. float& brightness) const throw();
  17806. /** Returns a copy of this colour with a different hue. */
  17807. const Colour withHue (float newHue) const throw();
  17808. /** Returns a copy of this colour with a different saturation. */
  17809. const Colour withSaturation (float newSaturation) const throw();
  17810. /** Returns a copy of this colour with a different brightness.
  17811. @see brighter, darker, withMultipliedBrightness
  17812. */
  17813. const Colour withBrightness (float newBrightness) const throw();
  17814. /** Returns a copy of this colour with it hue rotated.
  17815. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  17816. @see brighter, darker, withMultipliedBrightness
  17817. */
  17818. const Colour withRotatedHue (float amountToRotate) const throw();
  17819. /** Returns a copy of this colour with its saturation multiplied by the given value.
  17820. The new colour's saturation is (this->getSaturation() * multiplier)
  17821. (the result is clipped to legal limits).
  17822. */
  17823. const Colour withMultipliedSaturation (float multiplier) const throw();
  17824. /** Returns a copy of this colour with its brightness multiplied by the given value.
  17825. The new colour's saturation is (this->getBrightness() * multiplier)
  17826. (the result is clipped to legal limits).
  17827. */
  17828. const Colour withMultipliedBrightness (float amount) const throw();
  17829. /** Returns a brighter version of this colour.
  17830. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  17831. unchanged, and higher values make it brighter
  17832. @see withMultipliedBrightness
  17833. */
  17834. const Colour brighter (float amountBrighter = 0.4f) const throw();
  17835. /** Returns a darker version of this colour.
  17836. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  17837. unchanged, and higher values make it darker
  17838. @see withMultipliedBrightness
  17839. */
  17840. const Colour darker (float amountDarker = 0.4f) const throw();
  17841. /** Returns a colour that will be clearly visible against this colour.
  17842. The amount parameter indicates how contrasting the new colour should
  17843. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  17844. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  17845. return white; Colours::white.contrasting (1.0f) will return black, etc.
  17846. */
  17847. const Colour contrasting (float amount = 1.0f) const throw();
  17848. /** Returns a colour that contrasts against two colours.
  17849. Looks for a colour that contrasts with both of the colours passed-in.
  17850. Handy for things like choosing a highlight colour in text editors, etc.
  17851. */
  17852. static const Colour contrasting (const Colour& colour1,
  17853. const Colour& colour2) throw();
  17854. /** Returns an opaque shade of grey.
  17855. @param brightness the level of grey to return - 0 is black, 1.0 is white
  17856. */
  17857. static const Colour greyLevel (float brightness) throw();
  17858. /** Returns a stringified version of this colour.
  17859. The string can be turned back into a colour using the fromString() method.
  17860. */
  17861. const String toString() const;
  17862. /** Reads the colour from a string that was created with toString().
  17863. */
  17864. static const Colour fromString (const String& encodedColourString);
  17865. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  17866. const String toDisplayString (bool includeAlphaValue) const;
  17867. juce_UseDebuggingNewOperator
  17868. private:
  17869. PixelARGB argb;
  17870. };
  17871. #endif // __JUCE_COLOUR_JUCEHEADER__
  17872. /*** End of inlined file: juce_Colour.h ***/
  17873. /**
  17874. Contains a set of predefined named colours (mostly standard HTML colours)
  17875. @see Colour, Colours::greyLevel
  17876. */
  17877. class Colours
  17878. {
  17879. public:
  17880. static JUCE_API const Colour
  17881. transparentBlack, /**< ARGB = 0x00000000 */
  17882. transparentWhite, /**< ARGB = 0x00ffffff */
  17883. black, /**< ARGB = 0xff000000 */
  17884. white, /**< ARGB = 0xffffffff */
  17885. blue, /**< ARGB = 0xff0000ff */
  17886. grey, /**< ARGB = 0xff808080 */
  17887. green, /**< ARGB = 0xff008000 */
  17888. red, /**< ARGB = 0xffff0000 */
  17889. yellow, /**< ARGB = 0xffffff00 */
  17890. aliceblue, antiquewhite, aqua, aquamarine,
  17891. azure, beige, bisque, blanchedalmond,
  17892. blueviolet, brown, burlywood, cadetblue,
  17893. chartreuse, chocolate, coral, cornflowerblue,
  17894. cornsilk, crimson, cyan, darkblue,
  17895. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  17896. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  17897. darkorchid, darkred, darksalmon, darkseagreen,
  17898. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  17899. deeppink, deepskyblue, dimgrey, dodgerblue,
  17900. firebrick, floralwhite, forestgreen, fuchsia,
  17901. gainsboro, gold, goldenrod, greenyellow,
  17902. honeydew, hotpink, indianred, indigo,
  17903. ivory, khaki, lavender, lavenderblush,
  17904. lemonchiffon, lightblue, lightcoral, lightcyan,
  17905. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  17906. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  17907. lightsteelblue, lightyellow, lime, limegreen,
  17908. linen, magenta, maroon, mediumaquamarine,
  17909. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  17910. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  17911. midnightblue, mintcream, mistyrose, navajowhite,
  17912. navy, oldlace, olive, olivedrab,
  17913. orange, orangered, orchid, palegoldenrod,
  17914. palegreen, paleturquoise, palevioletred, papayawhip,
  17915. peachpuff, peru, pink, plum,
  17916. powderblue, purple, rosybrown, royalblue,
  17917. saddlebrown, salmon, sandybrown, seagreen,
  17918. seashell, sienna, silver, skyblue,
  17919. slateblue, slategrey, snow, springgreen,
  17920. steelblue, tan, teal, thistle,
  17921. tomato, turquoise, violet, wheat,
  17922. whitesmoke, yellowgreen;
  17923. /** Attempts to look up a string in the list of known colour names, and return
  17924. the appropriate colour.
  17925. A non-case-sensitive search is made of the list of predefined colours, and
  17926. if a match is found, that colour is returned. If no match is found, the
  17927. colour passed in as the defaultColour parameter is returned.
  17928. */
  17929. static JUCE_API const Colour findColourForName (const String& colourName,
  17930. const Colour& defaultColour);
  17931. private:
  17932. // this isn't a class you should ever instantiate - it's just here for the
  17933. // static values in it.
  17934. Colours();
  17935. Colours (const Colours&);
  17936. Colours& operator= (const Colours&);
  17937. };
  17938. #endif // __JUCE_COLOURS_JUCEHEADER__
  17939. /*** End of inlined file: juce_Colours.h ***/
  17940. /*** Start of inlined file: juce_ColourGradient.h ***/
  17941. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  17942. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  17943. /**
  17944. Describes the layout and colours that should be used to paint a colour gradient.
  17945. @see Graphics::setGradientFill
  17946. */
  17947. class JUCE_API ColourGradient
  17948. {
  17949. public:
  17950. /** Creates a gradient object.
  17951. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  17952. colour2 should be. In between them there's a gradient.
  17953. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  17954. its centre.
  17955. The alpha transparencies of the colours are used, so note that
  17956. if you blend from transparent to a solid colour, the RGB of the transparent
  17957. colour will become visible in parts of the gradient. e.g. blending
  17958. from Colour::transparentBlack to Colours::white will produce a
  17959. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  17960. will be white all the way across.
  17961. @see ColourGradient
  17962. */
  17963. ColourGradient (const Colour& colour1, float x1, float y1,
  17964. const Colour& colour2, float x2, float y2,
  17965. bool isRadial);
  17966. /** Creates an uninitialised gradient.
  17967. If you use this constructor instead of the other one, be sure to set all the
  17968. object's public member variables before using it!
  17969. */
  17970. ColourGradient() throw();
  17971. /** Destructor */
  17972. ~ColourGradient();
  17973. /** Removes any colours that have been added.
  17974. This will also remove any start and end colours, so the gradient won't work. You'll
  17975. need to add more colours with addColour().
  17976. */
  17977. void clearColours();
  17978. /** Adds a colour at a point along the length of the gradient.
  17979. This allows the gradient to go through a spectrum of colours, instead of just a
  17980. start and end colour.
  17981. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  17982. of the distance along the line between the two points
  17983. at which the colour should occur.
  17984. @param colour the colour that should be used at this point
  17985. @returns the index at which the new point was added
  17986. */
  17987. int addColour (double proportionAlongGradient,
  17988. const Colour& colour);
  17989. /** Removes one of the colours from the gradient. */
  17990. void removeColour (int index);
  17991. /** Multiplies the alpha value of all the colours by the given scale factor */
  17992. void multiplyOpacity (float multiplier) throw();
  17993. /** Returns the number of colour-stops that have been added. */
  17994. int getNumColours() const throw();
  17995. /** Returns the position along the length of the gradient of the colour with this index.
  17996. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17997. */
  17998. double getColourPosition (int index) const throw();
  17999. /** Returns the colour that was added with a given index.
  18000. The index is from 0 to getNumColours() - 1.
  18001. */
  18002. const Colour getColour (int index) const throw();
  18003. /** Changes the colour at a given index.
  18004. The index is from 0 to getNumColours() - 1.
  18005. */
  18006. void setColour (int index, const Colour& newColour) throw();
  18007. /** Returns the an interpolated colour at any position along the gradient.
  18008. @param position the position along the gradient, between 0 and 1
  18009. */
  18010. const Colour getColourAtPosition (double position) const throw();
  18011. /** Creates a set of interpolated premultiplied ARGB values.
  18012. This will resize the HeapBlock, fill it with the colours, and will return the number of
  18013. colours that it added.
  18014. */
  18015. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  18016. /** Returns true if all colours are opaque. */
  18017. bool isOpaque() const throw();
  18018. /** Returns true if all colours are completely transparent. */
  18019. bool isInvisible() const throw();
  18020. Point<float> point1, point2;
  18021. /** If true, the gradient should be filled circularly, centred around
  18022. point1, with point2 defining a point on the circumference.
  18023. If false, the gradient is linear between the two points.
  18024. */
  18025. bool isRadial;
  18026. bool operator== (const ColourGradient& other) const throw();
  18027. bool operator!= (const ColourGradient& other) const throw();
  18028. juce_UseDebuggingNewOperator
  18029. private:
  18030. struct ColourPoint
  18031. {
  18032. ColourPoint() throw() {}
  18033. ColourPoint (const double position_, const Colour& colour_) throw()
  18034. : position (position_), colour (colour_)
  18035. {}
  18036. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  18037. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  18038. double position;
  18039. Colour colour;
  18040. };
  18041. Array <ColourPoint> colours;
  18042. };
  18043. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  18044. /*** End of inlined file: juce_ColourGradient.h ***/
  18045. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  18046. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  18047. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  18048. /**
  18049. Defines the method used to postion some kind of rectangular object within
  18050. a rectangular viewport.
  18051. Although similar to Justification, this is more specific, and has some extra
  18052. options.
  18053. */
  18054. class JUCE_API RectanglePlacement
  18055. {
  18056. public:
  18057. /** Creates a RectanglePlacement object using a combination of flags. */
  18058. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  18059. /** Creates a copy of another RectanglePlacement object. */
  18060. RectanglePlacement (const RectanglePlacement& other) throw();
  18061. /** Copies another RectanglePlacement object. */
  18062. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  18063. /** Flag values that can be combined and used in the constructor. */
  18064. enum
  18065. {
  18066. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  18067. xLeft = 1,
  18068. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  18069. xRight = 2,
  18070. /** Indicates that the source should be placed in the centre between the left and right
  18071. sides of the available space. */
  18072. xMid = 4,
  18073. /** Indicates that the source's top edge should be aligned with the top edge of the
  18074. destination rectangle. */
  18075. yTop = 8,
  18076. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  18077. destination rectangle. */
  18078. yBottom = 16,
  18079. /** Indicates that the source should be placed in the centre between the top and bottom
  18080. sides of the available space. */
  18081. yMid = 32,
  18082. /** If this flag is set, then the source rectangle will be resized to completely fill
  18083. the destination rectangle, and all other flags are ignored.
  18084. */
  18085. stretchToFit = 64,
  18086. /** If this flag is set, then the source rectangle will be resized so that it is the
  18087. minimum size to completely fill the destination rectangle, without changing its
  18088. aspect ratio. This means that some of the source rectangle may fall outside
  18089. the destination.
  18090. If this flag is not set, the source will be given the maximum size at which none
  18091. of it falls outside the destination rectangle.
  18092. */
  18093. fillDestination = 128,
  18094. /** Indicates that the source rectangle can be reduced in size if required, but should
  18095. never be made larger than its original size.
  18096. */
  18097. onlyReduceInSize = 256,
  18098. /** Indicates that the source rectangle can be enlarged if required, but should
  18099. never be made smaller than its original size.
  18100. */
  18101. onlyIncreaseInSize = 512,
  18102. /** Indicates that the source rectangle's size should be left unchanged.
  18103. */
  18104. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  18105. /** A shorthand value that is equivalent to (xMid | yMid). */
  18106. centred = 4 + 32
  18107. };
  18108. /** Returns the raw flags that are set for this object. */
  18109. inline int getFlags() const throw() { return flags; }
  18110. /** Tests a set of flags for this object.
  18111. @returns true if any of the flags passed in are set on this object.
  18112. */
  18113. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  18114. /** Adjusts the position and size of a rectangle to fit it into a space.
  18115. The source rectangle co-ordinates will be adjusted so that they fit into
  18116. the destination rectangle based on this object's flags.
  18117. */
  18118. void applyTo (double& sourceX,
  18119. double& sourceY,
  18120. double& sourceW,
  18121. double& sourceH,
  18122. double destinationX,
  18123. double destinationY,
  18124. double destinationW,
  18125. double destinationH) const throw();
  18126. /** Returns the transform that should be applied to these source co-ordinates to fit them
  18127. into the destination rectangle using the current flags.
  18128. */
  18129. const AffineTransform getTransformToFit (float sourceX,
  18130. float sourceY,
  18131. float sourceW,
  18132. float sourceH,
  18133. float destinationX,
  18134. float destinationY,
  18135. float destinationW,
  18136. float destinationH) const throw();
  18137. private:
  18138. int flags;
  18139. };
  18140. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  18141. /*** End of inlined file: juce_RectanglePlacement.h ***/
  18142. class LowLevelGraphicsContext;
  18143. class Image;
  18144. class FillType;
  18145. class RectangleList;
  18146. /**
  18147. A graphics context, used for drawing a component or image.
  18148. When a Component needs painting, a Graphics context is passed to its
  18149. Component::paint() method, and this you then call methods within this
  18150. object to actually draw the component's content.
  18151. A Graphics can also be created from an image, to allow drawing directly onto
  18152. that image.
  18153. @see Component::paint
  18154. */
  18155. class JUCE_API Graphics
  18156. {
  18157. public:
  18158. /** Creates a Graphics object to draw directly onto the given image.
  18159. The graphics object that is created will be set up to draw onto the image,
  18160. with the context's clipping area being the entire size of the image, and its
  18161. origin being the image's origin. To draw into a subsection of an image, use the
  18162. reduceClipRegion() and setOrigin() methods.
  18163. Obviously you shouldn't delete the image before this context is deleted.
  18164. */
  18165. explicit Graphics (const Image& imageToDrawOnto);
  18166. /** Destructor. */
  18167. ~Graphics();
  18168. /** Changes the current drawing colour.
  18169. This sets the colour that will now be used for drawing operations - it also
  18170. sets the opacity to that of the colour passed-in.
  18171. If a brush is being used when this method is called, the brush will be deselected,
  18172. and any subsequent drawing will be done with a solid colour brush instead.
  18173. @see setOpacity
  18174. */
  18175. void setColour (const Colour& newColour);
  18176. /** Changes the opacity to use with the current colour.
  18177. If a solid colour is being used for drawing, this changes its opacity
  18178. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  18179. If a gradient is being used, this will have no effect on it.
  18180. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  18181. */
  18182. void setOpacity (const float newOpacity);
  18183. /** Sets the context to use a gradient for its fill pattern.
  18184. */
  18185. void setGradientFill (const ColourGradient& gradient);
  18186. /** Sets the context to use a tiled image pattern for filling.
  18187. Make sure that you don't delete this image while it's still being used by
  18188. this context!
  18189. */
  18190. void setTiledImageFill (const Image& imageToUse,
  18191. int anchorX, int anchorY,
  18192. float opacity);
  18193. /** Changes the current fill settings.
  18194. @see setColour, setGradientFill, setTiledImageFill
  18195. */
  18196. void setFillType (const FillType& newFill);
  18197. /** Changes the font to use for subsequent text-drawing functions.
  18198. Note there's also a setFont (float, int) method to quickly change the size and
  18199. style of the current font.
  18200. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  18201. */
  18202. void setFont (const Font& newFont);
  18203. /** Changes the size and style of the currently-selected font.
  18204. This is a convenient shortcut that changes the context's current font to a
  18205. different size or style. The typeface won't be changed.
  18206. @see Font
  18207. */
  18208. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  18209. /** Returns the currently selected font. */
  18210. const Font getCurrentFont() const;
  18211. /** Draws a one-line text string.
  18212. This will use the current colour (or brush) to fill the text. The font is the last
  18213. one specified by setFont().
  18214. @param text the string to draw
  18215. @param startX the position to draw the left-hand edge of the text
  18216. @param baselineY the position of the text's baseline
  18217. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  18218. */
  18219. void drawSingleLineText (const String& text,
  18220. int startX, int baselineY) const;
  18221. /** Draws text across multiple lines.
  18222. This will break the text onto a new line where there's a new-line or
  18223. carriage-return character, or at a word-boundary when the text becomes wider
  18224. than the size specified by the maximumLineWidth parameter.
  18225. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  18226. */
  18227. void drawMultiLineText (const String& text,
  18228. int startX, int baselineY,
  18229. int maximumLineWidth) const;
  18230. /** Renders a string of text as a vector path.
  18231. This allows a string to be transformed with an arbitrary AffineTransform and
  18232. rendered using the current colour/brush. It's much slower than the normal text methods
  18233. but more accurate.
  18234. @see setFont
  18235. */
  18236. void drawTextAsPath (const String& text,
  18237. const AffineTransform& transform) const;
  18238. /** Draws a line of text within a specified rectangle.
  18239. The text will be positioned within the rectangle based on the justification
  18240. flags passed-in. If the string is too long to fit inside the rectangle, it will
  18241. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  18242. flag is true).
  18243. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  18244. */
  18245. void drawText (const String& text,
  18246. int x, int y, int width, int height,
  18247. const Justification& justificationType,
  18248. bool useEllipsesIfTooBig) const;
  18249. /** Tries to draw a text string inside a given space.
  18250. This does its best to make the given text readable within the specified rectangle,
  18251. so it useful for labelling things.
  18252. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  18253. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  18254. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  18255. it's been truncated.
  18256. A Justification parameter lets you specify how the text is laid out within the rectangle,
  18257. both horizontally and vertically.
  18258. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  18259. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  18260. can set this value to 1.0f.
  18261. @see GlyphArrangement::addFittedText
  18262. */
  18263. void drawFittedText (const String& text,
  18264. int x, int y, int width, int height,
  18265. const Justification& justificationFlags,
  18266. int maximumNumberOfLines,
  18267. float minimumHorizontalScale = 0.7f) const;
  18268. /** Fills the context's entire clip region with the current colour or brush.
  18269. (See also the fillAll (const Colour&) method which is a quick way of filling
  18270. it with a given colour).
  18271. */
  18272. void fillAll() const;
  18273. /** Fills the context's entire clip region with a given colour.
  18274. This leaves the context's current colour and brush unchanged, it just
  18275. uses the specified colour temporarily.
  18276. */
  18277. void fillAll (const Colour& colourToUse) const;
  18278. /** Fills a rectangle with the current colour or brush.
  18279. @see drawRect, fillRoundedRectangle
  18280. */
  18281. void fillRect (int x, int y, int width, int height) const;
  18282. /** Fills a rectangle with the current colour or brush. */
  18283. void fillRect (const Rectangle<int>& rectangle) const;
  18284. /** Fills a rectangle with the current colour or brush.
  18285. This uses sub-pixel positioning so is slower than the fillRect method which
  18286. takes integer co-ordinates.
  18287. */
  18288. void fillRect (float x, float y, float width, float height) const;
  18289. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18290. @see drawRoundedRectangle, Path::addRoundedRectangle
  18291. */
  18292. void fillRoundedRectangle (float x, float y, float width, float height,
  18293. float cornerSize) const;
  18294. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18295. @see drawRoundedRectangle, Path::addRoundedRectangle
  18296. */
  18297. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  18298. float cornerSize) const;
  18299. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  18300. */
  18301. void fillCheckerBoard (const Rectangle<int>& area,
  18302. int checkWidth, int checkHeight,
  18303. const Colour& colour1, const Colour& colour2) const;
  18304. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18305. The lines are drawn inside the given rectangle, and greater line thicknesses
  18306. extend inwards.
  18307. @see fillRect
  18308. */
  18309. void drawRect (int x, int y, int width, int height,
  18310. int lineThickness = 1) const;
  18311. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18312. The lines are drawn inside the given rectangle, and greater line thicknesses
  18313. extend inwards.
  18314. @see fillRect
  18315. */
  18316. void drawRect (float x, float y, float width, float height,
  18317. float lineThickness = 1.0f) const;
  18318. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18319. The lines are drawn inside the given rectangle, and greater line thicknesses
  18320. extend inwards.
  18321. @see fillRect
  18322. */
  18323. void drawRect (const Rectangle<int>& rectangle,
  18324. int lineThickness = 1) const;
  18325. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18326. @see fillRoundedRectangle, Path::addRoundedRectangle
  18327. */
  18328. void drawRoundedRectangle (float x, float y, float width, float height,
  18329. float cornerSize, float lineThickness) const;
  18330. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18331. @see fillRoundedRectangle, Path::addRoundedRectangle
  18332. */
  18333. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  18334. float cornerSize, float lineThickness) const;
  18335. /** Draws a 3D raised (or indented) bevel using two colours.
  18336. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  18337. extend inwards.
  18338. The top-left colour is used for the top- and left-hand edges of the
  18339. bevel; the bottom-right colour is used for the bottom- and right-hand
  18340. edges.
  18341. If useGradient is true, then the bevel fades out to make it look more curved
  18342. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  18343. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  18344. the centre edges are sharp and it fades towards the outside.
  18345. */
  18346. void drawBevel (int x, int y, int width, int height,
  18347. int bevelThickness,
  18348. const Colour& topLeftColour = Colours::white,
  18349. const Colour& bottomRightColour = Colours::black,
  18350. bool useGradient = true,
  18351. bool sharpEdgeOnOutside = true) const;
  18352. /** Draws a pixel using the current colour or brush.
  18353. */
  18354. void setPixel (int x, int y) const;
  18355. /** Fills an ellipse with the current colour or brush.
  18356. The ellipse is drawn to fit inside the given rectangle.
  18357. @see drawEllipse, Path::addEllipse
  18358. */
  18359. void fillEllipse (float x, float y, float width, float height) const;
  18360. /** Draws an elliptical stroke using the current colour or brush.
  18361. @see fillEllipse, Path::addEllipse
  18362. */
  18363. void drawEllipse (float x, float y, float width, float height,
  18364. float lineThickness) const;
  18365. /** Draws a line between two points.
  18366. The line is 1 pixel wide and drawn with the current colour or brush.
  18367. */
  18368. void drawLine (float startX, float startY, float endX, float endY) const;
  18369. /** Draws a line between two points with a given thickness.
  18370. @see Path::addLineSegment
  18371. */
  18372. void drawLine (float startX, float startY, float endX, float endY,
  18373. float lineThickness) const;
  18374. /** Draws a line between two points.
  18375. The line is 1 pixel wide and drawn with the current colour or brush.
  18376. */
  18377. void drawLine (const Line<float>& line) const;
  18378. /** Draws a line between two points with a given thickness.
  18379. @see Path::addLineSegment
  18380. */
  18381. void drawLine (const Line<float>& line, float lineThickness) const;
  18382. /** Draws a dashed line using a custom set of dash-lengths.
  18383. @param startX the line's start x co-ordinate
  18384. @param startY the line's start y co-ordinate
  18385. @param endX the line's end x co-ordinate
  18386. @param endY the line's end y co-ordinate
  18387. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  18388. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  18389. draw 6 pixels, skip 7 pixels, and then repeat.
  18390. @param numDashLengths the number of elements in the array (this must be an even number).
  18391. @param lineThickness the thickness of the line to draw
  18392. @see PathStrokeType::createDashedStroke
  18393. */
  18394. void drawDashedLine (float startX, float startY,
  18395. float endX, float endY,
  18396. const float* dashLengths, int numDashLengths,
  18397. float lineThickness = 1.0f) const;
  18398. /** Draws a vertical line of pixels at a given x position.
  18399. The x position is an integer, but the top and bottom of the line can be sub-pixel
  18400. positions, and these will be anti-aliased if necessary.
  18401. */
  18402. void drawVerticalLine (int x, float top, float bottom) const;
  18403. /** Draws a horizontal line of pixels at a given y position.
  18404. The y position is an integer, but the left and right ends of the line can be sub-pixel
  18405. positions, and these will be anti-aliased if necessary.
  18406. */
  18407. void drawHorizontalLine (int y, float left, float right) const;
  18408. /** Fills a path using the currently selected colour or brush.
  18409. */
  18410. void fillPath (const Path& path,
  18411. const AffineTransform& transform = AffineTransform::identity) const;
  18412. /** Draws a path's outline using the currently selected colour or brush.
  18413. */
  18414. void strokePath (const Path& path,
  18415. const PathStrokeType& strokeType,
  18416. const AffineTransform& transform = AffineTransform::identity) const;
  18417. /** Draws a line with an arrowhead at its end.
  18418. @param line the line to draw
  18419. @param lineThickness the thickness of the line
  18420. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  18421. @param arrowheadLength the length of the arrow head (along the length of the line)
  18422. */
  18423. void drawArrow (const Line<float>& line,
  18424. float lineThickness,
  18425. float arrowheadWidth,
  18426. float arrowheadLength) const;
  18427. /** Types of rendering quality that can be specified when drawing images.
  18428. @see blendImage, Graphics::setImageResamplingQuality
  18429. */
  18430. enum ResamplingQuality
  18431. {
  18432. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  18433. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  18434. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  18435. };
  18436. /** Changes the quality that will be used when resampling images.
  18437. By default a Graphics object will be set to mediumRenderingQuality.
  18438. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  18439. */
  18440. void setImageResamplingQuality (const ResamplingQuality newQuality);
  18441. /** Draws an image.
  18442. This will draw the whole of an image, positioning its top-left corner at the
  18443. given co-ordinates, and keeping its size the same. This is the simplest image
  18444. drawing method - the others give more control over the scaling and clipping
  18445. of the images.
  18446. Images are composited using the context's current opacity, so if you
  18447. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18448. (or setColour() with an opaque colour) before drawing images.
  18449. */
  18450. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  18451. bool fillAlphaChannelWithCurrentBrush = false) const;
  18452. /** Draws part of an image, rescaling it to fit in a given target region.
  18453. The specified area of the source image is rescaled and drawn to fill the
  18454. specifed destination rectangle.
  18455. Images are composited using the context's current opacity, so if you
  18456. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18457. (or setColour() with an opaque colour) before drawing images.
  18458. @param imageToDraw the image to overlay
  18459. @param destX the left of the destination rectangle
  18460. @param destY the top of the destination rectangle
  18461. @param destWidth the width of the destination rectangle
  18462. @param destHeight the height of the destination rectangle
  18463. @param sourceX the left of the rectangle to copy from the source image
  18464. @param sourceY the top of the rectangle to copy from the source image
  18465. @param sourceWidth the width of the rectangle to copy from the source image
  18466. @param sourceHeight the height of the rectangle to copy from the source image
  18467. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  18468. the source image's alpha channel is used as a mask with
  18469. which to fill the destination using the current colour
  18470. or brush. (If the source is has no alpha channel, then
  18471. it will just fill the target with a solid rectangle)
  18472. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  18473. */
  18474. void drawImage (const Image& imageToDraw,
  18475. int destX, int destY, int destWidth, int destHeight,
  18476. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  18477. bool fillAlphaChannelWithCurrentBrush = false) const;
  18478. /** Draws an image, having applied an affine transform to it.
  18479. This lets you throw the image around in some wacky ways, rotate it, shear,
  18480. scale it, etc.
  18481. Images are composited using the context's current opacity, so if you
  18482. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18483. (or setColour() with an opaque colour) before drawing images.
  18484. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  18485. are ignored and it is filled with the current brush, masked by its alpha channel.
  18486. If you want to render only a subsection of an image, use Image::getClippedImage() to
  18487. create the section that you need.
  18488. @see setImageResamplingQuality, drawImage
  18489. */
  18490. void drawImageTransformed (const Image& imageToDraw,
  18491. const AffineTransform& transform,
  18492. bool fillAlphaChannelWithCurrentBrush = false) const;
  18493. /** Draws an image to fit within a designated rectangle.
  18494. If the image is too big or too small for the space, it will be rescaled
  18495. to fit as nicely as it can do without affecting its aspect ratio. It will
  18496. then be placed within the target rectangle according to the justification flags
  18497. specified.
  18498. @param imageToDraw the source image to draw
  18499. @param destX top-left of the target rectangle to fit it into
  18500. @param destY top-left of the target rectangle to fit it into
  18501. @param destWidth size of the target rectangle to fit the image into
  18502. @param destHeight size of the target rectangle to fit the image into
  18503. @param placementWithinTarget this specifies how the image should be positioned
  18504. within the target rectangle - see the RectanglePlacement
  18505. class for more details about this.
  18506. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  18507. alpha channel will be used as a mask with which to
  18508. draw with the current brush or colour. This is
  18509. similar to fillAlphaMap(), and see also drawImage()
  18510. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  18511. */
  18512. void drawImageWithin (const Image& imageToDraw,
  18513. int destX, int destY, int destWidth, int destHeight,
  18514. const RectanglePlacement& placementWithinTarget,
  18515. bool fillAlphaChannelWithCurrentBrush = false) const;
  18516. /** Returns the position of the bounding box for the current clipping region.
  18517. @see getClipRegion, clipRegionIntersects
  18518. */
  18519. const Rectangle<int> getClipBounds() const;
  18520. /** Checks whether a rectangle overlaps the context's clipping region.
  18521. If this returns false, no part of the given area can be drawn onto, so this
  18522. method can be used to optimise a component's paint() method, by letting it
  18523. avoid drawing complex objects that aren't within the region being repainted.
  18524. */
  18525. bool clipRegionIntersects (const Rectangle<int>& area) const;
  18526. /** Intersects the current clipping region with another region.
  18527. @returns true if the resulting clipping region is non-zero in size
  18528. @see setOrigin, clipRegionIntersects
  18529. */
  18530. bool reduceClipRegion (int x, int y, int width, int height);
  18531. /** Intersects the current clipping region with a rectangle list region.
  18532. @returns true if the resulting clipping region is non-zero in size
  18533. @see setOrigin, clipRegionIntersects
  18534. */
  18535. bool reduceClipRegion (const RectangleList& clipRegion);
  18536. /** Intersects the current clipping region with a path.
  18537. @returns true if the resulting clipping region is non-zero in size
  18538. @see reduceClipRegion
  18539. */
  18540. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  18541. /** Intersects the current clipping region with an image's alpha-channel.
  18542. The current clipping path is intersected with the area covered by this image's
  18543. alpha-channel, after the image has been transformed by the specified matrix.
  18544. @param image the image whose alpha-channel should be used. If the image doesn't
  18545. have an alpha-channel, it is treated as entirely opaque.
  18546. @param transform a matrix to apply to the image
  18547. @returns true if the resulting clipping region is non-zero in size
  18548. @see reduceClipRegion
  18549. */
  18550. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  18551. /** Excludes a rectangle to stop it being drawn into. */
  18552. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  18553. /** Returns true if no drawing can be done because the clip region is zero. */
  18554. bool isClipEmpty() const;
  18555. /** Saves the current graphics state on an internal stack.
  18556. To restore the state, use restoreState().
  18557. */
  18558. void saveState();
  18559. /** Restores a graphics state that was previously saved with saveState().
  18560. */
  18561. void restoreState();
  18562. /** Moves the position of the context's origin.
  18563. This changes the position that the context considers to be (0, 0) to
  18564. the specified position.
  18565. So if you call setOrigin (100, 100), then the position that was previously
  18566. referred to as (100, 100) will subsequently be considered to be (0, 0).
  18567. @see reduceClipRegion
  18568. */
  18569. void setOrigin (int newOriginX, int newOriginY);
  18570. /** Resets the current colour, brush, and font to default settings. */
  18571. void resetToDefaultState();
  18572. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  18573. bool isVectorDevice() const;
  18574. juce_UseDebuggingNewOperator
  18575. /** Create a graphics that uses a given low-level renderer.
  18576. For internal use only.
  18577. NB. The context will NOT be deleted by this object when it is deleted.
  18578. */
  18579. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  18580. /** @internal */
  18581. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  18582. private:
  18583. LowLevelGraphicsContext* const context;
  18584. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  18585. bool saveStatePending;
  18586. void saveStateIfPending();
  18587. Graphics (const Graphics&);
  18588. Graphics& operator= (const Graphics& other);
  18589. };
  18590. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  18591. /*** End of inlined file: juce_Graphics.h ***/
  18592. /**
  18593. A graphical effect filter that can be applied to components.
  18594. An ImageEffectFilter can be applied to the image that a component
  18595. paints before it hits the screen.
  18596. This is used for adding effects like shadows, blurs, etc.
  18597. @see Component::setComponentEffect
  18598. */
  18599. class JUCE_API ImageEffectFilter
  18600. {
  18601. public:
  18602. /** Overridden to render the effect.
  18603. The implementation of this method must use the image that is passed in
  18604. as its source, and should render its output to the graphics context passed in.
  18605. @param sourceImage the image that the source component has just rendered with
  18606. its paint() method. The image may or may not have an alpha
  18607. channel, depending on whether the component is opaque.
  18608. @param destContext the graphics context to use to draw the resultant image.
  18609. */
  18610. virtual void applyEffect (Image& sourceImage,
  18611. Graphics& destContext) = 0;
  18612. /** Destructor. */
  18613. virtual ~ImageEffectFilter() {}
  18614. };
  18615. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18616. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  18617. /*** Start of inlined file: juce_Image.h ***/
  18618. #ifndef __JUCE_IMAGE_JUCEHEADER__
  18619. #define __JUCE_IMAGE_JUCEHEADER__
  18620. /**
  18621. Holds a fixed-size bitmap.
  18622. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  18623. To draw into an image, create a Graphics object for it.
  18624. e.g. @code
  18625. // create a transparent 500x500 image..
  18626. Image myImage (Image::RGB, 500, 500, true);
  18627. Graphics g (myImage);
  18628. g.setColour (Colours::red);
  18629. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  18630. @endcode
  18631. Other useful ways to create an image are with the ImageCache class, or the
  18632. ImageFileFormat, which provides a way to load common image files.
  18633. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  18634. */
  18635. class JUCE_API Image
  18636. {
  18637. public:
  18638. /**
  18639. */
  18640. enum PixelFormat
  18641. {
  18642. UnknownFormat,
  18643. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  18644. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  18645. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  18646. };
  18647. /**
  18648. */
  18649. enum ImageType
  18650. {
  18651. SoftwareImage = 0,
  18652. NativeImage
  18653. };
  18654. /** Creates a null image. */
  18655. Image();
  18656. /** Creates an image with a specified size and format.
  18657. @param format the number of colour channels in the image
  18658. @param imageWidth the desired width of the image, in pixels - this value must be
  18659. greater than zero (otherwise a width of 1 will be used)
  18660. @param imageHeight the desired width of the image, in pixels - this value must be
  18661. greater than zero (otherwise a height of 1 will be used)
  18662. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  18663. or transparent black (if it's ARGB). If false, the image may contain
  18664. junk initially, so you need to make sure you overwrite it thoroughly.
  18665. @param type the type of image - this lets you specify whether you want a purely
  18666. memory-based image, or one that may be managed by the OS if possible.
  18667. */
  18668. Image (PixelFormat format,
  18669. int imageWidth,
  18670. int imageHeight,
  18671. bool clearImage,
  18672. ImageType type = NativeImage);
  18673. /** Creates a shared reference to another image.
  18674. This won't create a duplicate of the image - when Image objects are copied, they simply
  18675. point to the same shared image data. To make sure that an Image object has its own unique,
  18676. unshared internal data, call duplicateIfShared().
  18677. */
  18678. Image (const Image& other);
  18679. /** Makes this image refer to the same underlying image as another object.
  18680. This won't create a duplicate of the image - when Image objects are copied, they simply
  18681. point to the same shared image data. To make sure that an Image object has its own unique,
  18682. unshared internal data, call duplicateIfShared().
  18683. */
  18684. Image& operator= (const Image&);
  18685. /** Destructor. */
  18686. ~Image();
  18687. /** Returns true if the two images are referring to the same internal, shared image. */
  18688. bool operator== (const Image& other) const throw() { return image == other.image; }
  18689. /** Returns true if the two images are not referring to the same internal, shared image. */
  18690. bool operator!= (const Image& other) const throw() { return image != other.image; }
  18691. /** Returns true if this image isn't null.
  18692. If you create an Image with the default constructor, it has no size or content, and is null
  18693. until you reassign it to an Image which contains some actual data.
  18694. The isNull() method is the opposite of isValid().
  18695. @see isNull
  18696. */
  18697. inline bool isValid() const throw() { return image != 0; }
  18698. /** Returns true if this image is not valid.
  18699. If you create an Image with the default constructor, it has no size or content, and is null
  18700. until you reassign it to an Image which contains some actual data.
  18701. The isNull() method is the opposite of isValid().
  18702. @see isValid
  18703. */
  18704. inline bool isNull() const throw() { return image == 0; }
  18705. /** A null Image object that can be used when you need to return an invalid image.
  18706. This object is the equivalient to an Image created with the default constructor.
  18707. */
  18708. static const Image null;
  18709. /** Returns the image's width (in pixels). */
  18710. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  18711. /** Returns the image's height (in pixels). */
  18712. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  18713. /** Returns a rectangle with the same size as this image.
  18714. The rectangle's origin is always (0, 0).
  18715. */
  18716. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  18717. /** Returns the image's pixel format. */
  18718. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  18719. /** True if the image's format is ARGB. */
  18720. bool isARGB() const throw() { return getFormat() == ARGB; }
  18721. /** True if the image's format is RGB. */
  18722. bool isRGB() const throw() { return getFormat() == RGB; }
  18723. /** True if the image's format is a single-channel alpha map. */
  18724. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  18725. /** True if the image contains an alpha-channel. */
  18726. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  18727. /** Clears a section of the image with a given colour.
  18728. This won't do any alpha-blending - it just sets all pixels in the image to
  18729. the given colour (which may be non-opaque if the image has an alpha channel).
  18730. */
  18731. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  18732. /** Returns a rescaled version of this image.
  18733. A new image is returned which is a copy of this one, rescaled to the given size.
  18734. Note that if the new size is identical to the existing image, this will just return
  18735. a reference to the original image, and won't actually create a duplicate.
  18736. */
  18737. const Image rescaled (int newWidth, int newHeight,
  18738. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  18739. /** Returns a version of this image with a different image format.
  18740. A new image is returned which has been converted to the specified format.
  18741. Note that if the new format is no different to the current one, this will just return
  18742. a reference to the original image, and won't actually create a copy.
  18743. */
  18744. const Image convertedToFormat (PixelFormat newFormat) const;
  18745. /** Makes sure that no other Image objects share the same underlying data as this one.
  18746. If no other Image objects refer to the same shared data as this one, this method has no
  18747. effect. But if there are other references to the data, this will create a new copy of
  18748. the data internally.
  18749. Call this if you want to draw onto the image, but want to make sure that this doesn't
  18750. affect any other code that may be sharing the same data.
  18751. @see getReferenceCount
  18752. */
  18753. void duplicateIfShared();
  18754. /** Returns an image which refers to a subsection of this image.
  18755. This will not make a copy of the original - the new image will keep a reference to it, so that
  18756. if the original image is changed, the contents of the subsection will also change. Likewise if you
  18757. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  18758. you use operator= to make the original Image object refer to something else, the subsection image
  18759. won't pick up this change, it'll remain pointing at the original.
  18760. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  18761. image than the area you asked for, or even a null image if the area was out-of-bounds.
  18762. */
  18763. const Image getClippedImage (const Rectangle<int>& area) const;
  18764. /** Returns the colour of one of the pixels in the image.
  18765. If the co-ordinates given are beyond the image's boundaries, this will
  18766. return Colours::transparentBlack.
  18767. @see setPixelAt, Image::BitmapData::getPixelColour
  18768. */
  18769. const Colour getPixelAt (int x, int y) const;
  18770. /** Sets the colour of one of the image's pixels.
  18771. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  18772. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  18773. with the given one. The colour's opacity will be ignored if this image doesn't have
  18774. an alpha-channel.
  18775. @see getPixelAt, Image::BitmapData::setPixelColour
  18776. */
  18777. void setPixelAt (int x, int y, const Colour& colour);
  18778. /** Changes the opacity of a pixel.
  18779. This only has an effect if the image has an alpha channel and if the
  18780. given co-ordinates are inside the image's boundary.
  18781. The multiplier must be in the range 0 to 1.0, and the current alpha
  18782. at the given co-ordinates will be multiplied by this value.
  18783. @see setPixelAt
  18784. */
  18785. void multiplyAlphaAt (int x, int y, float multiplier);
  18786. /** Changes the overall opacity of the image.
  18787. This will multiply the alpha value of each pixel in the image by the given
  18788. amount (limiting the resulting alpha values between 0 and 255). This allows
  18789. you to make an image more or less transparent.
  18790. If the image doesn't have an alpha channel, this won't have any effect.
  18791. */
  18792. void multiplyAllAlphas (float amountToMultiplyBy);
  18793. /** Changes all the colours to be shades of grey, based on their current luminosity.
  18794. */
  18795. void desaturate();
  18796. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  18797. You should only use this class as a last resort - messing about with the internals of
  18798. an image is only recommended for people who really know what they're doing!
  18799. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  18800. hanging around while the image is being used elsewhere.
  18801. Depending on the way the image class is implemented, this may create a temporary buffer
  18802. which is copied back to the image when the object is deleted, or it may just get a pointer
  18803. directly into the image's raw data.
  18804. You can use the stride and data values in this class directly, but don't alter them!
  18805. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  18806. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  18807. */
  18808. class BitmapData
  18809. {
  18810. public:
  18811. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  18812. BitmapData (const Image& image, int x, int y, int w, int h);
  18813. BitmapData (const Image& image, bool needsToBeWritable);
  18814. ~BitmapData();
  18815. /** Returns a pointer to the start of a line in the image.
  18816. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  18817. sure it's not out-of-range.
  18818. */
  18819. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  18820. /** Returns a pointer to a pixel in the image.
  18821. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  18822. not out-of-range.
  18823. */
  18824. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  18825. /** Returns the colour of a given pixel.
  18826. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18827. repsonsibility to make sure they're within the image's size.
  18828. */
  18829. const Colour getPixelColour (int x, int y) const throw();
  18830. /** Sets the colour of a given pixel.
  18831. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18832. repsonsibility to make sure they're within the image's size.
  18833. */
  18834. void setPixelColour (int x, int y, const Colour& colour) const throw();
  18835. uint8* data;
  18836. const PixelFormat pixelFormat;
  18837. int lineStride, pixelStride, width, height;
  18838. private:
  18839. BitmapData (const BitmapData&);
  18840. BitmapData& operator= (const BitmapData&);
  18841. };
  18842. /** Copies some pixel values to a rectangle of the image.
  18843. The format of the pixel data must match that of the image itself, and the
  18844. rectangle supplied must be within the image's bounds.
  18845. */
  18846. void setPixelData (int destX, int destY, int destW, int destH,
  18847. const uint8* sourcePixelData, int sourceLineStride);
  18848. /** Copies a section of the image to somewhere else within itself. */
  18849. void moveImageSection (int destX, int destY,
  18850. int sourceX, int sourceY,
  18851. int width, int height);
  18852. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  18853. of the image.
  18854. @param result the list that will have the area added to it
  18855. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  18856. above this level will be considered opaque
  18857. */
  18858. void createSolidAreaMask (RectangleList& result,
  18859. float alphaThreshold = 0.5f) const;
  18860. /** Returns a user-specified data item that was set with setTag().
  18861. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18862. image. The value is shared between all Image object that are referring to the
  18863. same underlying image data object.
  18864. */
  18865. const var getTag() const;
  18866. /** Attaches a user-specified data item to this image, which can be retrieved using getTag().
  18867. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18868. image. The value is shared between all Image object that are referring to the
  18869. same underlying image data object.
  18870. Note that if this Image is null, this method will fail to store the data.
  18871. */
  18872. void setTag (const var& newTag);
  18873. /** Creates a context suitable for drawing onto this image.
  18874. Don't call this method directly! It's used internally by the Graphics class.
  18875. */
  18876. LowLevelGraphicsContext* createLowLevelContext() const;
  18877. /** Returns the number of Image objects which are currently referring to the same internal
  18878. shared image data.
  18879. @see duplicateIfShared
  18880. */
  18881. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  18882. /** This is a base class for task-specific types of image.
  18883. Don't use this class directly! It's used internally by the Image class.
  18884. */
  18885. class SharedImage : public ReferenceCountedObject
  18886. {
  18887. public:
  18888. SharedImage (PixelFormat format, int width, int height);
  18889. ~SharedImage();
  18890. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  18891. virtual SharedImage* clone() = 0;
  18892. virtual ImageType getType() const = 0;
  18893. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  18894. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  18895. const PixelFormat getPixelFormat() const throw() { return format; }
  18896. int getWidth() const throw() { return width; }
  18897. int getHeight() const throw() { return height; }
  18898. int getPixelStride() const throw() { return pixelStride; }
  18899. int getLineStride() const throw() { return lineStride; }
  18900. uint8* getPixelData (int x, int y) const throw();
  18901. protected:
  18902. friend class Image;
  18903. friend class Image::BitmapData;
  18904. const PixelFormat format;
  18905. const int width, height;
  18906. int pixelStride, lineStride;
  18907. uint8* imageData;
  18908. var userTag;
  18909. SharedImage (const SharedImage&);
  18910. SharedImage& operator= (const SharedImage&);
  18911. };
  18912. /** @internal */
  18913. SharedImage* getSharedImage() const throw() { return image; }
  18914. /** @internal */
  18915. explicit Image (SharedImage* instance);
  18916. juce_UseDebuggingNewOperator
  18917. private:
  18918. ReferenceCountedObjectPtr<SharedImage> image;
  18919. };
  18920. #endif // __JUCE_IMAGE_JUCEHEADER__
  18921. /*** End of inlined file: juce_Image.h ***/
  18922. /*** Start of inlined file: juce_RectangleList.h ***/
  18923. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  18924. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  18925. /**
  18926. Maintains a set of rectangles as a complex region.
  18927. This class allows a set of rectangles to be treated as a solid shape, and can
  18928. add and remove rectangular sections of it, and simplify overlapping or
  18929. adjacent rectangles.
  18930. @see Rectangle
  18931. */
  18932. class JUCE_API RectangleList
  18933. {
  18934. public:
  18935. /** Creates an empty RectangleList */
  18936. RectangleList() throw();
  18937. /** Creates a copy of another list */
  18938. RectangleList (const RectangleList& other);
  18939. /** Creates a list containing just one rectangle. */
  18940. RectangleList (const Rectangle<int>& rect);
  18941. /** Copies this list from another one. */
  18942. RectangleList& operator= (const RectangleList& other);
  18943. /** Destructor. */
  18944. ~RectangleList();
  18945. /** Returns true if the region is empty. */
  18946. bool isEmpty() const throw();
  18947. /** Returns the number of rectangles in the list. */
  18948. int getNumRectangles() const throw() { return rects.size(); }
  18949. /** Returns one of the rectangles at a particular index.
  18950. @returns the rectangle at the index, or an empty rectangle if the
  18951. index is out-of-range.
  18952. */
  18953. const Rectangle<int> getRectangle (int index) const throw();
  18954. /** Removes all rectangles to leave an empty region. */
  18955. void clear();
  18956. /** Merges a new rectangle into the list.
  18957. The rectangle being added will first be clipped to remove any parts of it
  18958. that overlap existing rectangles in the list.
  18959. */
  18960. void add (int x, int y, int width, int height);
  18961. /** Merges a new rectangle into the list.
  18962. The rectangle being added will first be clipped to remove any parts of it
  18963. that overlap existing rectangles in the list, and adjacent rectangles will be
  18964. merged into it.
  18965. */
  18966. void add (const Rectangle<int>& rect);
  18967. /** Dumbly adds a rectangle to the list without checking for overlaps.
  18968. This simply adds the rectangle to the end, it doesn't merge it or remove
  18969. any overlapping bits.
  18970. */
  18971. void addWithoutMerging (const Rectangle<int>& rect);
  18972. /** Merges another rectangle list into this one.
  18973. Any overlaps between the two lists will be clipped, so that the result is
  18974. the union of both lists.
  18975. */
  18976. void add (const RectangleList& other);
  18977. /** Removes a rectangular region from the list.
  18978. Any rectangles in the list which overlap this will be clipped and subdivided
  18979. if necessary.
  18980. */
  18981. void subtract (const Rectangle<int>& rect);
  18982. /** Removes all areas in another RectangleList from this one.
  18983. Any rectangles in the list which overlap this will be clipped and subdivided
  18984. if necessary.
  18985. @returns true if the resulting list is non-empty.
  18986. */
  18987. bool subtract (const RectangleList& otherList);
  18988. /** Removes any areas of the region that lie outside a given rectangle.
  18989. Any rectangles in the list which overlap this will be clipped and subdivided
  18990. if necessary.
  18991. Returns true if the resulting region is not empty, false if it is empty.
  18992. @see getIntersectionWith
  18993. */
  18994. bool clipTo (const Rectangle<int>& rect);
  18995. /** Removes any areas of the region that lie outside a given rectangle list.
  18996. Any rectangles in this object which overlap the specified list will be clipped
  18997. and subdivided if necessary.
  18998. Returns true if the resulting region is not empty, false if it is empty.
  18999. @see getIntersectionWith
  19000. */
  19001. bool clipTo (const RectangleList& other);
  19002. /** Creates a region which is the result of clipping this one to a given rectangle.
  19003. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  19004. resulting region into the list whose reference is passed-in.
  19005. Returns true if the resulting region is not empty, false if it is empty.
  19006. @see clipTo
  19007. */
  19008. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  19009. /** Swaps the contents of this and another list.
  19010. This swaps their internal pointers, so is hugely faster than using copy-by-value
  19011. to swap them.
  19012. */
  19013. void swapWith (RectangleList& otherList) throw();
  19014. /** Checks whether the region contains a given point.
  19015. @returns true if the point lies within one of the rectangles in the list
  19016. */
  19017. bool containsPoint (int x, int y) const throw();
  19018. /** Checks whether the region contains the whole of a given rectangle.
  19019. @returns true all parts of the rectangle passed in lie within the region
  19020. defined by this object
  19021. @see intersectsRectangle, containsPoint
  19022. */
  19023. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  19024. /** Checks whether the region contains any part of a given rectangle.
  19025. @returns true if any part of the rectangle passed in lies within the region
  19026. defined by this object
  19027. @see containsRectangle
  19028. */
  19029. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  19030. /** Checks whether this region intersects any part of another one.
  19031. @see intersectsRectangle
  19032. */
  19033. bool intersects (const RectangleList& other) const throw();
  19034. /** Returns the smallest rectangle that can enclose the whole of this region. */
  19035. const Rectangle<int> getBounds() const throw();
  19036. /** Optimises the list into a minimum number of constituent rectangles.
  19037. This will try to combine any adjacent rectangles into larger ones where
  19038. possible, to simplify lists that might have been fragmented by repeated
  19039. add/subtract calls.
  19040. */
  19041. void consolidate();
  19042. /** Adds an x and y value to all the co-ordinates. */
  19043. void offsetAll (int dx, int dy) throw();
  19044. /** Creates a Path object to represent this region. */
  19045. const Path toPath() const;
  19046. /** An iterator for accessing all the rectangles in a RectangleList. */
  19047. class Iterator
  19048. {
  19049. public:
  19050. Iterator (const RectangleList& list) throw();
  19051. ~Iterator();
  19052. /** Advances to the next rectangle, and returns true if it's not finished.
  19053. Call this before using getRectangle() to find the rectangle that was returned.
  19054. */
  19055. bool next() throw();
  19056. /** Returns the current rectangle. */
  19057. const Rectangle<int>* getRectangle() const throw() { return current; }
  19058. juce_UseDebuggingNewOperator
  19059. private:
  19060. const Rectangle<int>* current;
  19061. const RectangleList& owner;
  19062. int index;
  19063. Iterator (const Iterator&);
  19064. Iterator& operator= (const Iterator&);
  19065. };
  19066. juce_UseDebuggingNewOperator
  19067. private:
  19068. friend class Iterator;
  19069. Array <Rectangle<int> > rects;
  19070. };
  19071. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  19072. /*** End of inlined file: juce_RectangleList.h ***/
  19073. /*** Start of inlined file: juce_BorderSize.h ***/
  19074. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  19075. #define __JUCE_BORDERSIZE_JUCEHEADER__
  19076. /**
  19077. Specifies a set of gaps to be left around the sides of a rectangle.
  19078. This is basically the size of the spaces at the top, bottom, left and right of
  19079. a rectangle. It's used by various component classes to specify borders.
  19080. @see Rectangle
  19081. */
  19082. class JUCE_API BorderSize
  19083. {
  19084. public:
  19085. /** Creates a null border.
  19086. All sizes are left as 0.
  19087. */
  19088. BorderSize() throw();
  19089. /** Creates a copy of another border. */
  19090. BorderSize (const BorderSize& other) throw();
  19091. /** Creates a border with the given gaps. */
  19092. BorderSize (int topGap,
  19093. int leftGap,
  19094. int bottomGap,
  19095. int rightGap) throw();
  19096. /** Creates a border with the given gap on all sides. */
  19097. explicit BorderSize (int allGaps) throw();
  19098. /** Destructor. */
  19099. ~BorderSize() throw();
  19100. /** Returns the gap that should be left at the top of the region. */
  19101. int getTop() const throw() { return top; }
  19102. /** Returns the gap that should be left at the top of the region. */
  19103. int getLeft() const throw() { return left; }
  19104. /** Returns the gap that should be left at the top of the region. */
  19105. int getBottom() const throw() { return bottom; }
  19106. /** Returns the gap that should be left at the top of the region. */
  19107. int getRight() const throw() { return right; }
  19108. /** Returns the sum of the top and bottom gaps. */
  19109. int getTopAndBottom() const throw() { return top + bottom; }
  19110. /** Returns the sum of the left and right gaps. */
  19111. int getLeftAndRight() const throw() { return left + right; }
  19112. /** Changes the top gap. */
  19113. void setTop (int newTopGap) throw();
  19114. /** Changes the left gap. */
  19115. void setLeft (int newLeftGap) throw();
  19116. /** Changes the bottom gap. */
  19117. void setBottom (int newBottomGap) throw();
  19118. /** Changes the right gap. */
  19119. void setRight (int newRightGap) throw();
  19120. /** Returns a rectangle with these borders removed from it. */
  19121. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  19122. /** Removes this border from a given rectangle. */
  19123. void subtractFrom (Rectangle<int>& rectangle) const throw();
  19124. /** Returns a rectangle with these borders added around it. */
  19125. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  19126. /** Adds this border around a given rectangle. */
  19127. void addTo (Rectangle<int>& original) const throw();
  19128. bool operator== (const BorderSize& other) const throw();
  19129. bool operator!= (const BorderSize& other) const throw();
  19130. juce_UseDebuggingNewOperator
  19131. private:
  19132. int top, left, bottom, right;
  19133. };
  19134. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  19135. /*** End of inlined file: juce_BorderSize.h ***/
  19136. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  19137. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19138. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19139. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  19140. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19141. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19142. /**
  19143. Classes derived from this will be automatically deleted when the application exits.
  19144. After JUCEApplication::shutdown() has been called, any objects derived from
  19145. DeletedAtShutdown which are still in existence will be deleted in the reverse
  19146. order to that in which they were created.
  19147. So if you've got a singleton and don't want to have to explicitly delete it, just
  19148. inherit from this and it'll be taken care of.
  19149. */
  19150. class JUCE_API DeletedAtShutdown
  19151. {
  19152. protected:
  19153. /** Creates a DeletedAtShutdown object. */
  19154. DeletedAtShutdown();
  19155. /** Destructor.
  19156. It's ok to delete these objects explicitly - it's only the ones left
  19157. dangling at the end that will be deleted automatically.
  19158. */
  19159. virtual ~DeletedAtShutdown();
  19160. public:
  19161. /** Deletes all extant objects.
  19162. This shouldn't be used by applications, as it's called automatically
  19163. in the shutdown code of the JUCEApplication class.
  19164. */
  19165. static void deleteAll();
  19166. private:
  19167. DeletedAtShutdown (const DeletedAtShutdown&);
  19168. DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  19169. static CriticalSection& getLock();
  19170. static Array <DeletedAtShutdown*>& getObjects();
  19171. };
  19172. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19173. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  19174. /**
  19175. Manages the system's stack of modal components.
  19176. Normally you'll just use the Component methods to invoke modal states in components,
  19177. and won't have to deal with this class directly, but this is the singleton object that's
  19178. used internally to manage the stack.
  19179. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  19180. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  19181. */
  19182. class JUCE_API ModalComponentManager : public AsyncUpdater,
  19183. public DeletedAtShutdown
  19184. {
  19185. public:
  19186. /** Receives callbacks when a modal component is dismissed.
  19187. You can register a callback using Component::enterModalState() or
  19188. ModalComponentManager::attachCallback().
  19189. */
  19190. class Callback
  19191. {
  19192. public:
  19193. /** */
  19194. Callback() {}
  19195. /** Destructor. */
  19196. virtual ~Callback() {}
  19197. /** Called to indicate that a modal component has been dismissed.
  19198. You can register a callback using Component::enterModalState() or
  19199. ModalComponentManager::attachCallback().
  19200. The returnValue parameter is the value that was passed to Component::exitModalState()
  19201. when the component was dismissed.
  19202. The callback object will be deleted shortly after this method is called.
  19203. */
  19204. virtual void modalStateFinished (int returnValue) = 0;
  19205. };
  19206. /** Returns the number of components currently being shown modally.
  19207. @see getModalComponent
  19208. */
  19209. int getNumModalComponents() const;
  19210. /** Returns one of the components being shown modally.
  19211. An index of 0 is the most recently-shown, topmost component.
  19212. */
  19213. Component* getModalComponent (int index) const;
  19214. /** Returns true if the specified component is in a modal state. */
  19215. bool isModal (Component* component) const;
  19216. /** Returns true if the specified component is currently the topmost modal component. */
  19217. bool isFrontModalComponent (Component* component) const;
  19218. /** Adds a new callback that will be called when the specified modal component is dismissed.
  19219. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  19220. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  19221. called.
  19222. Each component can have any number of callbacks associated with it, and this one is added
  19223. to that list.
  19224. The object that is passed in will be deleted by the manager when it's no longer needed. If
  19225. the given component is not currently modal, the callback object is deleted immediately and
  19226. no action is taken.
  19227. */
  19228. void attachCallback (Component* component, Callback* callback);
  19229. /** Runs the event loop until the currently topmost modal component is dismissed, and
  19230. returns the exit code for that component.
  19231. */
  19232. int runEventLoopForCurrentComponent();
  19233. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  19234. protected:
  19235. /** Creates a ModalComponentManager.
  19236. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  19237. */
  19238. ModalComponentManager();
  19239. /** Destructor. */
  19240. ~ModalComponentManager();
  19241. /** @internal */
  19242. void handleAsyncUpdate();
  19243. private:
  19244. class ModalItem;
  19245. class ReturnValueRetriever;
  19246. friend class Component;
  19247. friend class OwnedArray <ModalItem>;
  19248. OwnedArray <ModalItem> stack;
  19249. void startModal (Component* component, Callback* callback);
  19250. void endModal (Component* component, int returnValue);
  19251. void endModal (Component* component);
  19252. };
  19253. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19254. /*** End of inlined file: juce_ModalComponentManager.h ***/
  19255. class LookAndFeel;
  19256. class MouseInputSource;
  19257. class MouseInputSourceInternal;
  19258. class ComponentPeer;
  19259. /**
  19260. The base class for all JUCE user-interface objects.
  19261. */
  19262. class JUCE_API Component : public MouseListener,
  19263. public MessageListener
  19264. {
  19265. public:
  19266. /** Creates a component.
  19267. To get it to actually appear, you'll also need to:
  19268. - Either add it to a parent component or use the addToDesktop() method to
  19269. make it a desktop window
  19270. - Set its size and position to something sensible
  19271. - Use setVisible() to make it visible
  19272. And for it to serve any useful purpose, you'll need to write a
  19273. subclass of Component or use one of the other types of component from
  19274. the library.
  19275. */
  19276. Component();
  19277. /** Destructor.
  19278. Note that when a component is deleted, any child components it contain are NOT
  19279. automatically deleted. It's your responsibilty to manage their lifespan - you
  19280. may want to use helper methods like deleteAllChildren(), or less haphazard
  19281. approaches like using ScopedPointers or normal object aggregation to manage them.
  19282. If the component being deleted is currently the child of another one, then during
  19283. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  19284. callback. Any ComponentListener objects that have registered with it will also have their
  19285. ComponentListener::componentBeingDeleted() methods called.
  19286. */
  19287. virtual ~Component();
  19288. /** Creates a component, setting its name at the same time.
  19289. @see getName, setName
  19290. */
  19291. explicit Component (const String& componentName);
  19292. /** Returns the name of this component.
  19293. @see setName
  19294. */
  19295. const String& getName() const throw() { return componentName_; }
  19296. /** Sets the name of this component.
  19297. When the name changes, all registered ComponentListeners will receive a
  19298. ComponentListener::componentNameChanged() callback.
  19299. @see getName
  19300. */
  19301. virtual void setName (const String& newName);
  19302. /** Checks whether this Component object has been deleted.
  19303. This will check whether this object is still a valid component, or whether
  19304. it's been deleted.
  19305. It's safe to call this on null or dangling pointers, but note that there is a
  19306. small risk if another new (but different) component has been created at the
  19307. same memory address which this one occupied, this methods can return a
  19308. false positive.
  19309. */
  19310. bool isValidComponent() const;
  19311. /** Makes the component visible or invisible.
  19312. This method will show or hide the component.
  19313. Note that components default to being non-visible when first created.
  19314. Also note that visible components won't be seen unless all their parent components
  19315. are also visible.
  19316. This method will call visibilityChanged() and also componentVisibilityChanged()
  19317. for any component listeners that are interested in this component.
  19318. @param shouldBeVisible whether to show or hide the component
  19319. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  19320. */
  19321. virtual void setVisible (bool shouldBeVisible);
  19322. /** Tests whether the component is visible or not.
  19323. this doesn't necessarily tell you whether this comp is actually on the screen
  19324. because this depends on whether all the parent components are also visible - use
  19325. isShowing() to find this out.
  19326. @see isShowing, setVisible
  19327. */
  19328. bool isVisible() const throw() { return flags.visibleFlag; }
  19329. /** Called when this component's visiblility changes.
  19330. @see setVisible, isVisible
  19331. */
  19332. virtual void visibilityChanged();
  19333. /** Tests whether this component and all its parents are visible.
  19334. @returns true only if this component and all its parents are visible.
  19335. @see isVisible
  19336. */
  19337. bool isShowing() const;
  19338. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  19339. To do this, this function will cunningly:
  19340. - take a snapshot of the component as it currently looks
  19341. - call setVisible(false) on the component
  19342. - replace it with a special component that will continue drawing the
  19343. snapshot, animating it and gradually making it more transparent
  19344. - when it's gone, the special component will also be deleted
  19345. As soon as this method returns, the component can be safely removed and deleted
  19346. leaving the proxy to do the fade-out, so it's even ok to call this in a
  19347. component's destructor.
  19348. Passing non-zero x and y values will cause the ghostly component image to
  19349. also whizz off by this distance while fading out. If the scale factor is
  19350. not 1.0, it will also zoom from the component's current size to this new size.
  19351. One thing to be careful about is that the parent component must be able to cope
  19352. with this unknown component type being added to it.
  19353. */
  19354. void fadeOutComponent (int lengthOfFadeOutInMilliseconds,
  19355. int deltaXToMove = 0,
  19356. int deltaYToMove = 0,
  19357. float scaleFactorAtEnd = 1.0f);
  19358. /** Makes this component appear as a window on the desktop.
  19359. Note that before calling this, you should make sure that the component's opacity is
  19360. set correctly using setOpaque(). If the component is non-opaque, the windowing
  19361. system will try to create a special transparent window for it, which will generally take
  19362. a lot more CPU to operate (and might not even be possible on some platforms).
  19363. If the component is inside a parent component at the time this method is called, it
  19364. will be first be removed from that parent. Likewise if a component on the desktop
  19365. is subsequently added to another component, it'll be removed from the desktop.
  19366. @param windowStyleFlags a combination of the flags specified in the
  19367. ComponentPeer::StyleFlags enum, which define the
  19368. window's characteristics.
  19369. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  19370. in which the juce component should place itself. On Windows,
  19371. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  19372. supported on all platforms, and best left as 0 unless you know
  19373. what you're doing
  19374. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  19375. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  19376. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  19377. */
  19378. virtual void addToDesktop (int windowStyleFlags,
  19379. void* nativeWindowToAttachTo = 0);
  19380. /** If the component is currently showing on the desktop, this will hide it.
  19381. You can also use setVisible() to hide a desktop window temporarily, but
  19382. removeFromDesktop() will free any system resources that are being used up.
  19383. @see addToDesktop, isOnDesktop
  19384. */
  19385. void removeFromDesktop();
  19386. /** Returns true if this component is currently showing on the desktop.
  19387. @see addToDesktop, removeFromDesktop
  19388. */
  19389. bool isOnDesktop() const throw();
  19390. /** Returns the heavyweight window that contains this component.
  19391. If this component is itself on the desktop, this will return the window
  19392. object that it is using. Otherwise, it will return the window of
  19393. its top-level parent component.
  19394. This may return 0 if there isn't a desktop component.
  19395. @see addToDesktop, isOnDesktop
  19396. */
  19397. ComponentPeer* getPeer() const;
  19398. /** For components on the desktop, this is called if the system wants to close the window.
  19399. This is a signal that either the user or the system wants the window to close. The
  19400. default implementation of this method will trigger an assertion to warn you that your
  19401. component should do something about it, but you can override this to ignore the event
  19402. if you want.
  19403. */
  19404. virtual void userTriedToCloseWindow();
  19405. /** Called for a desktop component which has just been minimised or un-minimised.
  19406. This will only be called for components on the desktop.
  19407. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  19408. */
  19409. virtual void minimisationStateChanged (bool isNowMinimised);
  19410. /** Brings the component to the front of its siblings.
  19411. If some of the component's siblings have had their 'always-on-top' flag set,
  19412. then they will still be kept in front of this one (unless of course this
  19413. one is also 'always-on-top').
  19414. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  19415. to the component (see grabKeyboardFocus() for more details)
  19416. @see toBack, toBehind, setAlwaysOnTop
  19417. */
  19418. void toFront (bool shouldAlsoGainFocus);
  19419. /** Changes this component's z-order to be at the back of all its siblings.
  19420. If the component is set to be 'always-on-top', it will only be moved to the
  19421. back of the other other 'always-on-top' components.
  19422. @see toFront, toBehind, setAlwaysOnTop
  19423. */
  19424. void toBack();
  19425. /** Changes this component's z-order so that it's just behind another component.
  19426. @see toFront, toBack
  19427. */
  19428. void toBehind (Component* other);
  19429. /** Sets whether the component should always be kept at the front of its siblings.
  19430. @see isAlwaysOnTop
  19431. */
  19432. void setAlwaysOnTop (bool shouldStayOnTop);
  19433. /** Returns true if this component is set to always stay in front of its siblings.
  19434. @see setAlwaysOnTop
  19435. */
  19436. bool isAlwaysOnTop() const throw();
  19437. /** Returns the x co-ordinate of the component's left edge.
  19438. This is a distance in pixels from the left edge of the component's parent.
  19439. @see getScreenX
  19440. */
  19441. inline int getX() const throw() { return bounds_.getX(); }
  19442. /** Returns the y co-ordinate of the top of this component.
  19443. This is a distance in pixels from the top edge of the component's parent.
  19444. @see getScreenY
  19445. */
  19446. inline int getY() const throw() { return bounds_.getY(); }
  19447. /** Returns the component's width in pixels. */
  19448. inline int getWidth() const throw() { return bounds_.getWidth(); }
  19449. /** Returns the component's height in pixels. */
  19450. inline int getHeight() const throw() { return bounds_.getHeight(); }
  19451. /** Returns the x co-ordinate of the component's right-hand edge.
  19452. This is a distance in pixels from the left edge of the component's parent.
  19453. */
  19454. int getRight() const throw() { return bounds_.getRight(); }
  19455. /** Returns the component's top-left position as a Point. */
  19456. const Point<int> getPosition() const throw() { return bounds_.getPosition(); }
  19457. /** Returns the y co-ordinate of the bottom edge of this component.
  19458. This is a distance in pixels from the top edge of the component's parent.
  19459. */
  19460. int getBottom() const throw() { return bounds_.getBottom(); }
  19461. /** Returns this component's bounding box.
  19462. The rectangle returned is relative to the top-left of the component's parent.
  19463. */
  19464. const Rectangle<int>& getBounds() const throw() { return bounds_; }
  19465. /** Returns the component's bounds, relative to its own origin.
  19466. This is like getBounds(), but returns the rectangle in local co-ordinates, In practice, it'll
  19467. return a rectangle with position (0, 0), and the same size as this component.
  19468. */
  19469. const Rectangle<int> getLocalBounds() const throw();
  19470. /** Returns the region of this component that's not obscured by other, opaque components.
  19471. The RectangleList that is returned represents the area of this component
  19472. which isn't covered by opaque child components.
  19473. If includeSiblings is true, it will also take into account any siblings
  19474. that may be overlapping the component.
  19475. */
  19476. void getVisibleArea (RectangleList& result,
  19477. bool includeSiblings) const;
  19478. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  19479. @see getX, relativePositionToGlobal
  19480. */
  19481. int getScreenX() const;
  19482. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  19483. @see getY, relativePositionToGlobal
  19484. */
  19485. int getScreenY() const;
  19486. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  19487. @see getScreenBounds
  19488. */
  19489. const Point<int> getScreenPosition() const;
  19490. /** Returns the bounds of this component, relative to the screen's top-left.
  19491. @see getScreenPosition
  19492. */
  19493. const Rectangle<int> getScreenBounds() const;
  19494. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  19495. @see globalPositionToRelative, relativePositionToOtherComponent
  19496. */
  19497. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) const;
  19498. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  19499. @see relativePositionToGlobal, relativePositionToOtherComponent
  19500. */
  19501. const Point<int> globalPositionToRelative (const Point<int>& screenPosition) const;
  19502. /** Converts a position relative to this component's top-left into a position
  19503. relative to another component's top-left.
  19504. @see relativePositionToGlobal, globalPositionToRelative
  19505. */
  19506. const Point<int> relativePositionToOtherComponent (const Component* targetComponent,
  19507. const Point<int>& positionRelativeToThis) const;
  19508. /** Moves the component to a new position.
  19509. Changes the component's top-left position (without changing its size).
  19510. The position is relative to the top-left of the component's parent.
  19511. If the component actually moves, this method will make a synchronous call to moved().
  19512. @see setBounds, ComponentListener::componentMovedOrResized
  19513. */
  19514. void setTopLeftPosition (int x, int y);
  19515. /** Moves the component to a new position.
  19516. Changes the position of the component's top-right corner (keeping it the same size).
  19517. The position is relative to the top-left of the component's parent.
  19518. If the component actually moves, this method will make a synchronous call to moved().
  19519. */
  19520. void setTopRightPosition (int x, int y);
  19521. /** Changes the size of the component.
  19522. A synchronous call to resized() will be occur if the size actually changes.
  19523. */
  19524. void setSize (int newWidth, int newHeight);
  19525. /** Changes the component's position and size.
  19526. The co-ordinates are relative to the top-left of the component's parent, or relative
  19527. to the origin of the screen is the component is on the desktop.
  19528. If this method changes the component's top-left position, it will make a synchronous
  19529. call to moved(). If it changes the size, it will also make a call to resized().
  19530. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  19531. */
  19532. void setBounds (int x, int y, int width, int height);
  19533. /** Changes the component's position and size.
  19534. @see setBounds
  19535. */
  19536. void setBounds (const Rectangle<int>& newBounds);
  19537. /** Changes the component's position and size in terms of fractions of its parent's size.
  19538. The values are factors of the parent's size, so for example
  19539. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  19540. width and height of the parent, with its top-left position 20% of
  19541. the way across and down the parent.
  19542. */
  19543. void setBoundsRelative (float proportionalX, float proportionalY,
  19544. float proportionalWidth, float proportionalHeight);
  19545. /** Changes the component's position and size based on the amount of space to leave around it.
  19546. This will position the component within its parent, leaving the specified number of
  19547. pixels around each edge.
  19548. */
  19549. void setBoundsInset (const BorderSize& borders);
  19550. /** Positions the component within a given rectangle, keeping its proportions
  19551. unchanged.
  19552. If onlyReduceInSize is false, the component will be resized to fill as much of the
  19553. rectangle as possible without changing its aspect ratio (the component's
  19554. current size is used to determine its aspect ratio, so a zero-size component
  19555. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  19556. too big to fit inside the rectangle.
  19557. It will then be positioned within the rectangle according to the justification flags
  19558. specified.
  19559. */
  19560. void setBoundsToFit (int x, int y, int width, int height,
  19561. const Justification& justification,
  19562. bool onlyReduceInSize);
  19563. /** Changes the position of the component's centre.
  19564. Leaves the component's size unchanged, but sets the position of its centre
  19565. relative to its parent's top-left.
  19566. */
  19567. void setCentrePosition (int x, int y);
  19568. /** Changes the position of the component's centre.
  19569. Leaves the position unchanged, but positions its centre relative to its
  19570. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  19571. its parent.
  19572. */
  19573. void setCentreRelative (float x, float y);
  19574. /** Changes the component's size and centres it within its parent.
  19575. After changing the size, the component will be moved so that it's
  19576. centred within its parent. If the component is on the desktop (or has no
  19577. parent component), then it'll be centred within the main monitor area.
  19578. */
  19579. void centreWithSize (int width, int height);
  19580. /** Returns a proportion of the component's width.
  19581. This is a handy equivalent of (getWidth() * proportion).
  19582. */
  19583. int proportionOfWidth (float proportion) const throw();
  19584. /** Returns a proportion of the component's height.
  19585. This is a handy equivalent of (getHeight() * proportion).
  19586. */
  19587. int proportionOfHeight (float proportion) const throw();
  19588. /** Returns the width of the component's parent.
  19589. If the component has no parent (i.e. if it's on the desktop), this will return
  19590. the width of the screen.
  19591. */
  19592. int getParentWidth() const throw();
  19593. /** Returns the height of the component's parent.
  19594. If the component has no parent (i.e. if it's on the desktop), this will return
  19595. the height of the screen.
  19596. */
  19597. int getParentHeight() const throw();
  19598. /** Returns the screen co-ordinates of the monitor that contains this component.
  19599. If there's only one monitor, this will return its size - if there are multiple
  19600. monitors, it will return the area of the monitor that contains the component's
  19601. centre.
  19602. */
  19603. const Rectangle<int> getParentMonitorArea() const;
  19604. /** Returns the number of child components that this component contains.
  19605. @see getChildComponent, getIndexOfChildComponent
  19606. */
  19607. int getNumChildComponents() const throw();
  19608. /** Returns one of this component's child components, by it index.
  19609. The component with index 0 is at the back of the z-order, the one at the
  19610. front will have index (getNumChildComponents() - 1).
  19611. If the index is out-of-range, this will return a null pointer.
  19612. @see getNumChildComponents, getIndexOfChildComponent
  19613. */
  19614. Component* getChildComponent (int index) const throw();
  19615. /** Returns the index of this component in the list of child components.
  19616. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  19617. values are further towards the front.
  19618. Returns -1 if the component passed-in is not a child of this component.
  19619. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  19620. */
  19621. int getIndexOfChildComponent (const Component* child) const throw();
  19622. /** Adds a child component to this one.
  19623. Adding a child component does not mean that the component will own or delete the child - it's
  19624. your responsibility to delete the component. Note that it's safe to delete a component
  19625. without first removing it from its parent - doing so will automatically remove it and
  19626. send out the appropriate notifications before the deletion completes.
  19627. If the child is already a child of this component, then no action will be taken, and its
  19628. z-order will be left unchanged.
  19629. @param child the new component to add. If the component passed-in is already
  19630. the child of another component, it'll first be removed from it current parent.
  19631. @param zOrder The index in the child-list at which this component should be inserted.
  19632. A value of -1 will insert it in front of the others, 0 is the back.
  19633. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  19634. */
  19635. void addChildComponent (Component* child, int zOrder = -1);
  19636. /** Adds a child component to this one, and also makes the child visible if it isn't.
  19637. Quite a useful function, this is just the same as calling addChildComponent()
  19638. followed by setVisible (true) on the child. See addChildComponent() for more details.
  19639. */
  19640. void addAndMakeVisible (Component* child, int zOrder = -1);
  19641. /** Removes one of this component's child-components.
  19642. If the child passed-in isn't actually a child of this component (either because
  19643. it's invalid or is the child of a different parent), then no action is taken.
  19644. Note that removing a child will not delete it! But it's ok to delete a component
  19645. without first removing it - doing so will automatically remove it and send out the
  19646. appropriate notifications before the deletion completes.
  19647. @see addChildComponent, ComponentListener::componentChildrenChanged
  19648. */
  19649. void removeChildComponent (Component* childToRemove);
  19650. /** Removes one of this component's child-components by index.
  19651. This will return a pointer to the component that was removed, or null if
  19652. the index was out-of-range.
  19653. Note that removing a child will not delete it! But it's ok to delete a component
  19654. without first removing it - doing so will automatically remove it and send out the
  19655. appropriate notifications before the deletion completes.
  19656. @see addChildComponent, ComponentListener::componentChildrenChanged
  19657. */
  19658. Component* removeChildComponent (int childIndexToRemove);
  19659. /** Removes all this component's children.
  19660. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  19661. */
  19662. void removeAllChildren();
  19663. /** Removes all this component's children, and deletes them.
  19664. @see removeAllChildren
  19665. */
  19666. void deleteAllChildren();
  19667. /** Returns the component which this component is inside.
  19668. If this is the highest-level component or hasn't yet been added to
  19669. a parent, this will return null.
  19670. */
  19671. Component* getParentComponent() const throw() { return parentComponent_; }
  19672. /** Searches the parent components for a component of a specified class.
  19673. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  19674. component that can be dynamically cast to a MyComp, or will return 0 if none
  19675. of the parents are suitable.
  19676. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  19677. */
  19678. template <class TargetClass>
  19679. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  19680. {
  19681. (void) dummyParameter;
  19682. Component* p = parentComponent_;
  19683. while (p != 0)
  19684. {
  19685. TargetClass* target = dynamic_cast <TargetClass*> (p);
  19686. if (target != 0)
  19687. return target;
  19688. p = p->parentComponent_;
  19689. }
  19690. return 0;
  19691. }
  19692. /** Returns the highest-level component which contains this one or its parents.
  19693. This will search upwards in the parent-hierarchy from this component, until it
  19694. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  19695. not yet added to a parent), and will return that.
  19696. */
  19697. Component* getTopLevelComponent() const throw();
  19698. /** Checks whether a component is anywhere inside this component or its children.
  19699. This will recursively check through this component's children to see if the
  19700. given component is anywhere inside.
  19701. */
  19702. bool isParentOf (const Component* possibleChild) const throw();
  19703. /** Called to indicate that the component's parents have changed.
  19704. When a component is added or removed from its parent, this method will
  19705. be called on all of its children (recursively - so all children of its
  19706. children will also be called as well).
  19707. Subclasses can override this if they need to react to this in some way.
  19708. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  19709. */
  19710. virtual void parentHierarchyChanged();
  19711. /** Subclasses can use this callback to be told when children are added or removed.
  19712. @see parentHierarchyChanged
  19713. */
  19714. virtual void childrenChanged();
  19715. /** Tests whether a given point inside the component.
  19716. Overriding this method allows you to create components which only intercept
  19717. mouse-clicks within a user-defined area.
  19718. This is called to find out whether a particular x, y co-ordinate is
  19719. considered to be inside the component or not, and is used by methods such
  19720. as contains() and getComponentAt() to work out which component
  19721. the mouse is clicked on.
  19722. Components with custom shapes will probably want to override it to perform
  19723. some more complex hit-testing.
  19724. The default implementation of this method returns either true or false,
  19725. depending on the value that was set by calling setInterceptsMouseClicks() (true
  19726. is the default return value).
  19727. Note that the hit-test region is not related to the opacity with which
  19728. areas of a component are painted.
  19729. Applications should never call hitTest() directly - instead use the
  19730. contains() method, because this will also test for occlusion by the
  19731. component's parent.
  19732. Note that for components on the desktop, this method will be ignored, because it's
  19733. not always possible to implement this behaviour on all platforms.
  19734. @param x the x co-ordinate to test, relative to the left hand edge of this
  19735. component. This value is guaranteed to be greater than or equal to
  19736. zero, and less than the component's width
  19737. @param y the y co-ordinate to test, relative to the top edge of this
  19738. component. This value is guaranteed to be greater than or equal to
  19739. zero, and less than the component's height
  19740. @returns true if the click is considered to be inside the component
  19741. @see setInterceptsMouseClicks, contains
  19742. */
  19743. virtual bool hitTest (int x, int y);
  19744. /** Changes the default return value for the hitTest() method.
  19745. Setting this to false is an easy way to make a component pass its mouse-clicks
  19746. through to the components behind it.
  19747. When a component is created, the default setting for this is true.
  19748. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  19749. return false (or true for child components if allowClicksOnChildComponents
  19750. is true)
  19751. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  19752. components can be clicked on as normal but clicks on this component pass
  19753. straight through; if this is false and allowClicksOnThisComponent
  19754. is false, then neither this component nor any child components can
  19755. be clicked on
  19756. @see hitTest, getInterceptsMouseClicks
  19757. */
  19758. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  19759. bool allowClicksOnChildComponents) throw();
  19760. /** Retrieves the current state of the mouse-click interception flags.
  19761. On return, the two parameters are set to the state used in the last call to
  19762. setInterceptsMouseClicks().
  19763. @see setInterceptsMouseClicks
  19764. */
  19765. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  19766. bool& allowsClicksOnChildComponents) const throw();
  19767. /** Returns true if a given point lies within this component or one of its children.
  19768. Never override this method! Use hitTest to create custom hit regions.
  19769. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19770. @param y the y co-ordinate to test, relative to this component's top edge.
  19771. @returns true if the point is within the component's hit-test area, but only if
  19772. that part of the component isn't clipped by its parent component. Note
  19773. that this won't take into account any overlapping sibling components
  19774. which might be in the way - for that, see reallyContains()
  19775. @see hitTest, reallyContains, getComponentAt
  19776. */
  19777. virtual bool contains (int x, int y);
  19778. /** Returns true if a given point lies in this component, taking any overlapping
  19779. siblings into account.
  19780. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19781. @param y the y co-ordinate to test, relative to this component's top edge.
  19782. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  19783. component, this determines the value that will
  19784. be returned.
  19785. @see contains, getComponentAt
  19786. */
  19787. bool reallyContains (int x, int y, bool returnTrueIfWithinAChild);
  19788. /** Returns the component at a certain point within this one.
  19789. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19790. @param y the y co-ordinate to test, relative to this component's top edge.
  19791. @returns the component that is at this position - which may be 0, this component,
  19792. or one of its children. Note that overlapping siblings that might actually
  19793. be in the way are not taken into account by this method - to account for these,
  19794. instead call getComponentAt on the top-level parent of this component.
  19795. @see hitTest, contains, reallyContains
  19796. */
  19797. Component* getComponentAt (int x, int y);
  19798. /** Returns the component at a certain point within this one.
  19799. @param position the co-ordinates to test, relative to this component's top-left.
  19800. @returns the component that is at this position - which may be 0, this component,
  19801. or one of its children. Note that overlapping siblings that might actually
  19802. be in the way are not taken into account by this method - to account for these,
  19803. instead call getComponentAt on the top-level parent of this component.
  19804. @see hitTest, contains, reallyContains
  19805. */
  19806. Component* getComponentAt (const Point<int>& position);
  19807. /** Marks the whole component as needing to be redrawn.
  19808. Calling this will not do any repainting immediately, but will mark the component
  19809. as 'dirty'. At some point in the near future the operating system will send a paint
  19810. message, which will redraw all the dirty regions of all components.
  19811. There's no guarantee about how soon after calling repaint() the redraw will actually
  19812. happen, and other queued events may be delivered before a redraw is done.
  19813. If the setBufferedToImage() method has been used to cause this component
  19814. to use a buffer, the repaint() call will invalidate the component's buffer.
  19815. To redraw just a subsection of the component rather than the whole thing,
  19816. use the repaint (int, int, int, int) method.
  19817. @see paint
  19818. */
  19819. void repaint();
  19820. /** Marks a subsection of this component as needing to be redrawn.
  19821. Calling this will not do any repainting immediately, but will mark the given region
  19822. of the component as 'dirty'. At some point in the near future the operating system
  19823. will send a paint message, which will redraw all the dirty regions of all components.
  19824. There's no guarantee about how soon after calling repaint() the redraw will actually
  19825. happen, and other queued events may be delivered before a redraw is done.
  19826. The region that is passed in will be clipped to keep it within the bounds of this
  19827. component.
  19828. @see repaint()
  19829. */
  19830. void repaint (int x, int y, int width, int height);
  19831. /** Marks a subsection of this component as needing to be redrawn.
  19832. Calling this will not do any repainting immediately, but will mark the given region
  19833. of the component as 'dirty'. At some point in the near future the operating system
  19834. will send a paint message, which will redraw all the dirty regions of all components.
  19835. There's no guarantee about how soon after calling repaint() the redraw will actually
  19836. happen, and other queued events may be delivered before a redraw is done.
  19837. The region that is passed in will be clipped to keep it within the bounds of this
  19838. component.
  19839. @see repaint()
  19840. */
  19841. void repaint (const Rectangle<int>& area);
  19842. /** Makes the component use an internal buffer to optimise its redrawing.
  19843. Setting this flag to true will cause the component to allocate an
  19844. internal buffer into which it paints itself, so that when asked to
  19845. redraw itself, it can use this buffer rather than actually calling the
  19846. paint() method.
  19847. The buffer is kept until the repaint() method is called directly on
  19848. this component (or until it is resized), when the image is invalidated
  19849. and then redrawn the next time the component is painted.
  19850. Note that only the drawing that happens within the component's paint()
  19851. method is drawn into the buffer, it's child components are not buffered, and
  19852. nor is the paintOverChildren() method.
  19853. @see repaint, paint, createComponentSnapshot
  19854. */
  19855. void setBufferedToImage (bool shouldBeBuffered);
  19856. /** Generates a snapshot of part of this component.
  19857. This will return a new Image, the size of the rectangle specified,
  19858. containing a snapshot of the specified area of the component and all
  19859. its children.
  19860. The image may or may not have an alpha-channel, depending on whether the
  19861. image is opaque or not.
  19862. If the clipImageToComponentBounds parameter is true and the area is greater than
  19863. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  19864. then parts of the component beyond its bounds can be drawn.
  19865. @see paintEntireComponent
  19866. */
  19867. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  19868. bool clipImageToComponentBounds = true);
  19869. /** Draws this component and all its subcomponents onto the specified graphics
  19870. context.
  19871. You should very rarely have to use this method, it's simply there in case you need
  19872. to draw a component with a custom graphics context for some reason, e.g. for
  19873. creating a snapshot of the component.
  19874. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  19875. on its children in order to render the entire tree.
  19876. The graphics context may be left in an undefined state after this method returns,
  19877. so you may need to reset it if you're going to use it again.
  19878. */
  19879. void paintEntireComponent (Graphics& context);
  19880. /** Adds an effect filter to alter the component's appearance.
  19881. When a component has an effect filter set, then this is applied to the
  19882. results of its paint() method. There are a few preset effects, such as
  19883. a drop-shadow or glow, but they can be user-defined as well.
  19884. The effect that is passed in will not be deleted by the component - the
  19885. caller must take care of deleting it.
  19886. To remove an effect from a component, pass a null pointer in as the parameter.
  19887. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  19888. */
  19889. void setComponentEffect (ImageEffectFilter* newEffect);
  19890. /** Returns the current component effect.
  19891. @see setComponentEffect
  19892. */
  19893. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  19894. /** Finds the appropriate look-and-feel to use for this component.
  19895. If the component hasn't had a look-and-feel explicitly set, this will
  19896. return the parent's look-and-feel, or just the default one if there's no
  19897. parent.
  19898. @see setLookAndFeel, lookAndFeelChanged
  19899. */
  19900. LookAndFeel& getLookAndFeel() const throw();
  19901. /** Sets the look and feel to use for this component.
  19902. This will also change the look and feel for any child components that haven't
  19903. had their look set explicitly.
  19904. The object passed in will not be deleted by the component, so it's the caller's
  19905. responsibility to manage it. It may be used at any time until this component
  19906. has been deleted.
  19907. Calling this method will also invoke the sendLookAndFeelChange() method.
  19908. @see getLookAndFeel, lookAndFeelChanged
  19909. */
  19910. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  19911. /** Called to let the component react to a change in the look-and-feel setting.
  19912. When the look-and-feel is changed for a component, this will be called in
  19913. all its child components, recursively.
  19914. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  19915. an application uses a LookAndFeel class that might have changed internally.
  19916. @see sendLookAndFeelChange, getLookAndFeel
  19917. */
  19918. virtual void lookAndFeelChanged();
  19919. /** Calls the lookAndFeelChanged() method in this component and all its children.
  19920. This will recurse through the children and their children, calling lookAndFeelChanged()
  19921. on them all.
  19922. @see lookAndFeelChanged
  19923. */
  19924. void sendLookAndFeelChange();
  19925. /** Indicates whether any parts of the component might be transparent.
  19926. Components that always paint all of their contents with solid colour and
  19927. thus completely cover any components behind them should use this method
  19928. to tell the repaint system that they are opaque.
  19929. This information is used to optimise drawing, because it means that
  19930. objects underneath opaque windows don't need to be painted.
  19931. By default, components are considered transparent, unless this is used to
  19932. make it otherwise.
  19933. @see isOpaque, getVisibleArea
  19934. */
  19935. void setOpaque (bool shouldBeOpaque);
  19936. /** Returns true if no parts of this component are transparent.
  19937. @returns the value that was set by setOpaque, (the default being false)
  19938. @see setOpaque
  19939. */
  19940. bool isOpaque() const throw();
  19941. /** Indicates whether the component should be brought to the front when clicked.
  19942. Setting this flag to true will cause the component to be brought to the front
  19943. when the mouse is clicked somewhere inside it or its child components.
  19944. Note that a top-level desktop window might still be brought to the front by the
  19945. operating system when it's clicked, depending on how the OS works.
  19946. By default this is set to false.
  19947. @see setMouseClickGrabsKeyboardFocus
  19948. */
  19949. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  19950. /** Indicates whether the component should be brought to the front when clicked-on.
  19951. @see setBroughtToFrontOnMouseClick
  19952. */
  19953. bool isBroughtToFrontOnMouseClick() const throw();
  19954. // Keyboard focus methods
  19955. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  19956. By default components aren't actually interested in gaining the
  19957. focus, but this method can be used to turn this on.
  19958. See the grabKeyboardFocus() method for details about the way a component
  19959. is chosen to receive the focus.
  19960. @see grabKeyboardFocus, getWantsKeyboardFocus
  19961. */
  19962. void setWantsKeyboardFocus (bool wantsFocus) throw();
  19963. /** Returns true if the component is interested in getting keyboard focus.
  19964. This returns the flag set by setWantsKeyboardFocus(). The default
  19965. setting is false.
  19966. @see setWantsKeyboardFocus
  19967. */
  19968. bool getWantsKeyboardFocus() const throw();
  19969. /** Chooses whether a click on this component automatically grabs the focus.
  19970. By default this is set to true, but you might want a component which can
  19971. be focused, but where you don't want the user to be able to affect it directly
  19972. by clicking.
  19973. */
  19974. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  19975. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  19976. See setMouseClickGrabsKeyboardFocus() for more info.
  19977. */
  19978. bool getMouseClickGrabsKeyboardFocus() const throw();
  19979. /** Tries to give keyboard focus to this component.
  19980. When the user clicks on a component or its grabKeyboardFocus()
  19981. method is called, the following procedure is used to work out which
  19982. component should get it:
  19983. - if the component that was clicked on actually wants focus (as indicated
  19984. by calling getWantsKeyboardFocus), it gets it.
  19985. - if the component itself doesn't want focus, it will try to pass it
  19986. on to whichever of its children is the default component, as determined by
  19987. KeyboardFocusTraverser::getDefaultComponent()
  19988. - if none of its children want focus at all, it will pass it up to its
  19989. parent instead, unless it's a top-level component without a parent,
  19990. in which case it just takes the focus itself.
  19991. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  19992. getCurrentlyFocusedComponent, focusGained, focusLost,
  19993. keyPressed, keyStateChanged
  19994. */
  19995. void grabKeyboardFocus();
  19996. /** Returns true if this component currently has the keyboard focus.
  19997. @param trueIfChildIsFocused if this is true, then the method returns true if
  19998. either this component or any of its children (recursively)
  19999. have the focus. If false, the method only returns true if
  20000. this component has the focus.
  20001. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  20002. focusGained, focusLost
  20003. */
  20004. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  20005. /** Returns the component that currently has the keyboard focus.
  20006. @returns the focused component, or null if nothing is focused.
  20007. */
  20008. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  20009. /** Tries to move the keyboard focus to one of this component's siblings.
  20010. This will try to move focus to either the next or previous component. (This
  20011. is the method that is used when shifting focus by pressing the tab key).
  20012. Components for which getWantsKeyboardFocus() returns false are not looked at.
  20013. @param moveToNext if true, the focus will move forwards; if false, it will
  20014. move backwards
  20015. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  20016. */
  20017. void moveKeyboardFocusToSibling (bool moveToNext);
  20018. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  20019. which focus should be passed from this component.
  20020. The default implementation of this method will return a default
  20021. KeyboardFocusTraverser if this component is a focus container (as determined
  20022. by the setFocusContainer() method). If the component isn't a focus
  20023. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  20024. If you overrride this to return a custom KeyboardFocusTraverser, then
  20025. this component and all its sub-components will use the new object to
  20026. make their focusing decisions.
  20027. The method should return a new object, which the caller is required to
  20028. delete when no longer needed.
  20029. */
  20030. virtual KeyboardFocusTraverser* createFocusTraverser();
  20031. /** Returns the focus order of this component, if one has been specified.
  20032. By default components don't have a focus order - in that case, this
  20033. will return 0. Lower numbers indicate that the component will be
  20034. earlier in the focus traversal order.
  20035. To change the order, call setExplicitFocusOrder().
  20036. The focus order may be used by the KeyboardFocusTraverser class as part of
  20037. its algorithm for deciding the order in which components should be traversed.
  20038. See the KeyboardFocusTraverser class for more details on this.
  20039. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  20040. */
  20041. int getExplicitFocusOrder() const;
  20042. /** Sets the index used in determining the order in which focusable components
  20043. should be traversed.
  20044. A value of 0 or less is taken to mean that no explicit order is wanted, and
  20045. that traversal should use other factors, like the component's position.
  20046. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  20047. */
  20048. void setExplicitFocusOrder (int newFocusOrderIndex);
  20049. /** Indicates whether this component is a parent for components that can have
  20050. their focus traversed.
  20051. This flag is used by the default implementation of the createFocusTraverser()
  20052. method, which uses the flag to find the first parent component (of the currently
  20053. focused one) which wants to be a focus container.
  20054. So using this method to set the flag to 'true' causes this component to
  20055. act as the top level within which focus is passed around.
  20056. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  20057. */
  20058. void setFocusContainer (bool shouldBeFocusContainer) throw();
  20059. /** Returns true if this component has been marked as a focus container.
  20060. See setFocusContainer() for more details.
  20061. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  20062. */
  20063. bool isFocusContainer() const throw();
  20064. /** Returns true if the component (and all its parents) are enabled.
  20065. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  20066. what difference this makes to the component depends on the type. E.g. buttons
  20067. and sliders will choose to draw themselves differently, etc.
  20068. Note that if one of this component's parents is disabled, this will always
  20069. return false, even if this component itself is enabled.
  20070. @see setEnabled, enablementChanged
  20071. */
  20072. bool isEnabled() const throw();
  20073. /** Enables or disables this component.
  20074. Disabling a component will also cause all of its child components to become
  20075. disabled.
  20076. Similarly, enabling a component which is inside a disabled parent
  20077. component won't make any difference until the parent is re-enabled.
  20078. @see isEnabled, enablementChanged
  20079. */
  20080. void setEnabled (bool shouldBeEnabled);
  20081. /** Callback to indicate that this component has been enabled or disabled.
  20082. This can be triggered by one of the component's parent components
  20083. being enabled or disabled, as well as changes to the component itself.
  20084. The default implementation of this method does nothing; your class may
  20085. wish to repaint itself or something when this happens.
  20086. @see setEnabled, isEnabled
  20087. */
  20088. virtual void enablementChanged();
  20089. /** Changes the mouse cursor shape to use when the mouse is over this component.
  20090. Note that the cursor set by this method can be overridden by the getMouseCursor
  20091. method.
  20092. @see MouseCursor
  20093. */
  20094. void setMouseCursor (const MouseCursor& cursorType);
  20095. /** Returns the mouse cursor shape to use when the mouse is over this component.
  20096. The default implementation will return the cursor that was set by setCursor()
  20097. but can be overridden for more specialised purposes, e.g. returning different
  20098. cursors depending on the mouse position.
  20099. @see MouseCursor
  20100. */
  20101. virtual const MouseCursor getMouseCursor();
  20102. /** Forces the current mouse cursor to be updated.
  20103. If you're overriding the getMouseCursor() method to control which cursor is
  20104. displayed, then this will only be checked each time the user moves the mouse. So
  20105. if you want to force the system to check that the cursor being displayed is
  20106. up-to-date (even if the mouse is just sitting there), call this method.
  20107. This isn't needed if you're only using setMouseCursor().
  20108. */
  20109. void updateMouseCursor() const;
  20110. /** Components can override this method to draw their content.
  20111. The paint() method gets called when a region of a component needs redrawing,
  20112. either because the component's repaint() method has been called, or because
  20113. something has happened on the screen that means a section of a window needs
  20114. to be redrawn.
  20115. Any child components will draw themselves over whatever this method draws. If
  20116. you need to paint over the top of your child components, you can also implement
  20117. the paintOverChildren() method to do this.
  20118. If you want to cause a component to redraw itself, this is done asynchronously -
  20119. calling the repaint() method marks a region of the component as "dirty", and the
  20120. paint() method will automatically be called sometime later, by the message thread,
  20121. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  20122. you never redraw something synchronously.
  20123. You should never need to call this method directly - to take a snapshot of the
  20124. component you could use createComponentSnapshot() or paintEntireComponent().
  20125. @param g the graphics context that must be used to do the drawing operations.
  20126. @see repaint, paintOverChildren, Graphics
  20127. */
  20128. virtual void paint (Graphics& g);
  20129. /** Components can override this method to draw over the top of their children.
  20130. For most drawing operations, it's better to use the normal paint() method,
  20131. but if you need to overlay something on top of the children, this can be
  20132. used.
  20133. @see paint, Graphics
  20134. */
  20135. virtual void paintOverChildren (Graphics& g);
  20136. /** Called when the mouse moves inside this component.
  20137. If the mouse button isn't pressed and the mouse moves over a component,
  20138. this will be called to let the component react to this.
  20139. A component will always get a mouseEnter callback before a mouseMove.
  20140. @param e details about the position and status of the mouse event
  20141. @see mouseEnter, mouseExit, mouseDrag, contains
  20142. */
  20143. virtual void mouseMove (const MouseEvent& e);
  20144. /** Called when the mouse first enters this component.
  20145. If the mouse button isn't pressed and the mouse moves into a component,
  20146. this will be called to let the component react to this.
  20147. When the mouse button is pressed and held down while being moved in
  20148. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  20149. mouseDrag messages are sent to the component that the mouse was originally
  20150. clicked on, until the button is released.
  20151. If you're writing a component that needs to repaint itself when the mouse
  20152. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  20153. method.
  20154. @param e details about the position and status of the mouse event
  20155. @see mouseExit, mouseDrag, mouseMove, contains
  20156. */
  20157. virtual void mouseEnter (const MouseEvent& e);
  20158. /** Called when the mouse moves out of this component.
  20159. This will be called when the mouse moves off the edge of this
  20160. component.
  20161. If the mouse button was pressed, and it was then dragged off the
  20162. edge of the component and released, then this callback will happen
  20163. when the button is released, after the mouseUp callback.
  20164. If you're writing a component that needs to repaint itself when the mouse
  20165. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  20166. method.
  20167. @param e details about the position and status of the mouse event
  20168. @see mouseEnter, mouseDrag, mouseMove, contains
  20169. */
  20170. virtual void mouseExit (const MouseEvent& e);
  20171. /** Called when a mouse button is pressed while it's over this component.
  20172. The MouseEvent object passed in contains lots of methods for finding out
  20173. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  20174. were held down at the time.
  20175. Once a button is held down, the mouseDrag method will be called when the
  20176. mouse moves, until the button is released.
  20177. @param e details about the position and status of the mouse event
  20178. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  20179. */
  20180. virtual void mouseDown (const MouseEvent& e);
  20181. /** Called when the mouse is moved while a button is held down.
  20182. When a mouse button is pressed inside a component, that component
  20183. receives mouseDrag callbacks each time the mouse moves, even if the
  20184. mouse strays outside the component's bounds.
  20185. If you want to be able to drag things off the edge of a component
  20186. and have the component scroll when you get to the edges, the
  20187. beginDragAutoRepeat() method might be useful.
  20188. @param e details about the position and status of the mouse event
  20189. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  20190. */
  20191. virtual void mouseDrag (const MouseEvent& e);
  20192. /** Called when a mouse button is released.
  20193. A mouseUp callback is sent to the component in which a button was pressed
  20194. even if the mouse is actually over a different component when the
  20195. button is released.
  20196. The MouseEvent object passed in contains lots of methods for finding out
  20197. which buttons were down just before they were released.
  20198. @param e details about the position and status of the mouse event
  20199. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  20200. */
  20201. virtual void mouseUp (const MouseEvent& e);
  20202. /** Called when a mouse button has been double-clicked in this component.
  20203. The MouseEvent object passed in contains lots of methods for finding out
  20204. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  20205. were held down at the time.
  20206. For altering the time limit used to detect double-clicks,
  20207. see MouseEvent::setDoubleClickTimeout.
  20208. @param e details about the position and status of the mouse event
  20209. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  20210. MouseEvent::getDoubleClickTimeout
  20211. */
  20212. virtual void mouseDoubleClick (const MouseEvent& e);
  20213. /** Called when the mouse-wheel is moved.
  20214. This callback is sent to the component that the mouse is over when the
  20215. wheel is moved.
  20216. If not overridden, the component will forward this message to its parent, so
  20217. that parent components can collect mouse-wheel messages that happen to
  20218. child components which aren't interested in them.
  20219. @param e details about the position and status of the mouse event
  20220. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  20221. value means the wheel has been pushed to the right, negative means it
  20222. was pushed to the left
  20223. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  20224. value means the wheel has been pushed upwards, negative means it
  20225. was pushed downwards
  20226. */
  20227. virtual void mouseWheelMove (const MouseEvent& e,
  20228. float wheelIncrementX,
  20229. float wheelIncrementY);
  20230. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  20231. next mouse-drag operation.
  20232. This allows you to make sure that mouseDrag() events sent continuously, even
  20233. when the mouse isn't moving. This can be useful for things like auto-scrolling
  20234. components when the mouse is near an edge.
  20235. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  20236. minimum interval between consecutive mouse drag callbacks. The callbacks
  20237. will continue until the mouse is released, and then the interval will be reset,
  20238. so you need to make sure it's called every time you begin a drag event. If it
  20239. is called when the mouse isn't actually being pressed, it will apply to the next
  20240. mouse-drag operation that happens.
  20241. Passing an interval of 0 or less will cancel the auto-repeat.
  20242. @see mouseDrag
  20243. */
  20244. static void beginDragAutoRepeat (int millisecondIntervalBetweenCallbacks);
  20245. /** Causes automatic repaints when the mouse enters or exits this component.
  20246. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  20247. on the component, it will trigger a repaint.
  20248. This is handy for things like buttons that need to draw themselves differently when
  20249. the mouse moves over them, and it avoids having to override all the different mouse
  20250. callbacks and call repaint().
  20251. @see mouseEnter, mouseExit, mouseDown, mouseUp
  20252. */
  20253. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  20254. /** Registers a listener to be told when mouse events occur in this component.
  20255. If you need to get informed about mouse events in a component but can't or
  20256. don't want to override its methods, you can attach any number of listeners
  20257. to the component, and these will get told about the events in addition to
  20258. the component's own callbacks being called.
  20259. Note that a MouseListener can also be attached to more than one component.
  20260. @param newListener the listener to register
  20261. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  20262. for events that happen to any child component
  20263. within this component, including deeply-nested
  20264. child components. If false, it will only be
  20265. told about events that this component handles.
  20266. @see MouseListener, removeMouseListener
  20267. */
  20268. void addMouseListener (MouseListener* newListener,
  20269. bool wantsEventsForAllNestedChildComponents);
  20270. /** Deregisters a mouse listener.
  20271. @see addMouseListener, MouseListener
  20272. */
  20273. void removeMouseListener (MouseListener* listenerToRemove);
  20274. /** Adds a listener that wants to hear about keypresses that this component receives.
  20275. The listeners that are registered with a component are called by its keyPressed() or
  20276. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  20277. If you add an object as a key listener, be careful to remove it when the object
  20278. is deleted, or the component will be left with a dangling pointer.
  20279. @see keyPressed, keyStateChanged, removeKeyListener
  20280. */
  20281. void addKeyListener (KeyListener* newListener);
  20282. /** Removes a previously-registered key listener.
  20283. @see addKeyListener
  20284. */
  20285. void removeKeyListener (KeyListener* listenerToRemove);
  20286. /** Called when a key is pressed.
  20287. When a key is pressed, the component that has the keyboard focus will have this
  20288. method called. Remember that a component will only be given the focus if its
  20289. setWantsKeyboardFocus() method has been used to enable this.
  20290. If your implementation returns true, the event will be consumed and not passed
  20291. on to any other listeners. If it returns false, the key will be passed to any
  20292. KeyListeners that have been registered with this component. As soon as one of these
  20293. returns true, the process will stop, but if they all return false, the event will
  20294. be passed upwards to this component's parent, and so on.
  20295. The default implementation of this method does nothing and returns false.
  20296. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  20297. */
  20298. virtual bool keyPressed (const KeyPress& key);
  20299. /** Called when a key is pressed or released.
  20300. Whenever a key on the keyboard is pressed or released (including modifier keys
  20301. like shift and ctrl), this method will be called on the component that currently
  20302. has the keyboard focus. Remember that a component will only be given the focus if
  20303. its setWantsKeyboardFocus() method has been used to enable this.
  20304. If your implementation returns true, the event will be consumed and not passed
  20305. on to any other listeners. If it returns false, then any KeyListeners that have
  20306. been registered with this component will have their keyStateChanged methods called.
  20307. As soon as one of these returns true, the process will stop, but if they all return
  20308. false, the event will be passed upwards to this component's parent, and so on.
  20309. The default implementation of this method does nothing and returns false.
  20310. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  20311. method.
  20312. @param isKeyDown true if a key has been pressed; false if it has been released
  20313. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  20314. */
  20315. virtual bool keyStateChanged (bool isKeyDown);
  20316. /** Called when a modifier key is pressed or released.
  20317. Whenever the shift, control, alt or command keys are pressed or released,
  20318. this method will be called on the component that currently has the keyboard focus.
  20319. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  20320. method has been used to enable this.
  20321. The default implementation of this method actually calls its parent's modifierKeysChanged
  20322. method, so that focused components which aren't interested in this will give their
  20323. parents a chance to act on the event instead.
  20324. @see keyStateChanged, ModifierKeys
  20325. */
  20326. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  20327. /** Enumeration used by the focusChanged() and focusLost() methods. */
  20328. enum FocusChangeType
  20329. {
  20330. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  20331. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  20332. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  20333. };
  20334. /** Called to indicate that this component has just acquired the keyboard focus.
  20335. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20336. */
  20337. virtual void focusGained (FocusChangeType cause);
  20338. /** Called to indicate that this component has just lost the keyboard focus.
  20339. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20340. */
  20341. virtual void focusLost (FocusChangeType cause);
  20342. /** Called to indicate that one of this component's children has been focused or unfocused.
  20343. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  20344. changed. It happens when focus moves from one of this component's children (at any depth)
  20345. to a component that isn't contained in this one, (or vice-versa).
  20346. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20347. */
  20348. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  20349. /** Returns true if the mouse is currently over this component.
  20350. If the mouse isn't over the component, this will return false, even if the
  20351. mouse is currently being dragged - so you can use this in your mouseDrag
  20352. method to find out whether it's really over the component or not.
  20353. Note that when the mouse button is being held down, then the only component
  20354. for which this method will return true is the one that was originally
  20355. clicked on.
  20356. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  20357. */
  20358. bool isMouseOver() const throw();
  20359. /** Returns true if the mouse button is currently held down in this component.
  20360. Note that this is a test to see whether the mouse is being pressed in this
  20361. component, so it'll return false if called on component A when the mouse
  20362. is actually being dragged in component B.
  20363. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  20364. */
  20365. bool isMouseButtonDown() const throw();
  20366. /** True if the mouse is over this component, or if it's being dragged in this component.
  20367. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  20368. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  20369. */
  20370. bool isMouseOverOrDragging() const throw();
  20371. /** Returns true if a mouse button is currently down.
  20372. Unlike isMouseButtonDown, this will test the current state of the
  20373. buttons without regard to which component (if any) it has been
  20374. pressed in.
  20375. @see isMouseButtonDown, ModifierKeys
  20376. */
  20377. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  20378. /** Returns the mouse's current position, relative to this component.
  20379. The co-ordinates are relative to the component's top-left corner.
  20380. */
  20381. const Point<int> getMouseXYRelative() const;
  20382. /** Called when this component's size has been changed.
  20383. A component can implement this method to do things such as laying out its
  20384. child components when its width or height changes.
  20385. The method is called synchronously as a result of the setBounds or setSize
  20386. methods, so repeatedly changing a components size will repeatedly call its
  20387. resized method (unlike things like repainting, where multiple calls to repaint
  20388. are coalesced together).
  20389. If the component is a top-level window on the desktop, its size could also
  20390. be changed by operating-system factors beyond the application's control.
  20391. @see moved, setSize
  20392. */
  20393. virtual void resized();
  20394. /** Called when this component's position has been changed.
  20395. This is called when the position relative to its parent changes, not when
  20396. its absolute position on the screen changes (so it won't be called for
  20397. all child components when a parent component is moved).
  20398. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  20399. or any of the other repositioning methods, and like resized(), it will be
  20400. called each time those methods are called.
  20401. If the component is a top-level window on the desktop, its position could also
  20402. be changed by operating-system factors beyond the application's control.
  20403. @see resized, setBounds
  20404. */
  20405. virtual void moved();
  20406. /** Called when one of this component's children is moved or resized.
  20407. If the parent wants to know about changes to its immediate children (not
  20408. to children of its children), this is the method to override.
  20409. @see moved, resized, parentSizeChanged
  20410. */
  20411. virtual void childBoundsChanged (Component* child);
  20412. /** Called when this component's immediate parent has been resized.
  20413. If the component is a top-level window, this indicates that the screen size
  20414. has changed.
  20415. @see childBoundsChanged, moved, resized
  20416. */
  20417. virtual void parentSizeChanged();
  20418. /** Called when this component has been moved to the front of its siblings.
  20419. The component may have been brought to the front by the toFront() method, or
  20420. by the operating system if it's a top-level window.
  20421. @see toFront
  20422. */
  20423. virtual void broughtToFront();
  20424. /** Adds a listener to be told about changes to the component hierarchy or position.
  20425. Component listeners get called when this component's size, position or children
  20426. change - see the ComponentListener class for more details.
  20427. @param newListener the listener to register - if this is already registered, it
  20428. will be ignored.
  20429. @see ComponentListener, removeComponentListener
  20430. */
  20431. void addComponentListener (ComponentListener* newListener);
  20432. /** Removes a component listener.
  20433. @see addComponentListener
  20434. */
  20435. void removeComponentListener (ComponentListener* listenerToRemove);
  20436. /** Dispatches a numbered message to this component.
  20437. This is a quick and cheap way of allowing simple asynchronous messages to
  20438. be sent to components. It's also safe, because if the component that you
  20439. send the message to is a null or dangling pointer, this won't cause an error.
  20440. The command ID is later delivered to the component's handleCommandMessage() method by
  20441. the application's message queue.
  20442. @see handleCommandMessage
  20443. */
  20444. void postCommandMessage (int commandId);
  20445. /** Called to handle a command that was sent by postCommandMessage().
  20446. This is called by the message thread when a command message arrives, and
  20447. the component can override this method to process it in any way it needs to.
  20448. @see postCommandMessage
  20449. */
  20450. virtual void handleCommandMessage (int commandId);
  20451. /** Runs a component modally, waiting until the loop terminates.
  20452. This method first makes the component visible, brings it to the front and
  20453. gives it the keyboard focus.
  20454. It then runs a loop, dispatching messages from the system message queue, but
  20455. blocking all mouse or keyboard messages from reaching any components other
  20456. than this one and its children.
  20457. This loop continues until the component's exitModalState() method is called (or
  20458. the component is deleted), and then this method returns, returning the value
  20459. passed into exitModalState().
  20460. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  20461. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  20462. */
  20463. int runModalLoop();
  20464. /** Puts the component into a modal state.
  20465. This makes the component modal, so that messages are blocked from reaching
  20466. any components other than this one and its children, but unlike runModalLoop(),
  20467. this method returns immediately.
  20468. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  20469. get the focus, which is usually what you'll want it to do. If not, it will leave
  20470. the focus unchanged.
  20471. The callback is an optional object which will receive a callback when the modal
  20472. component loses its modal status, either by being hidden or when exitModalState()
  20473. is called. If you pass an object in here, the system will take care of deleting it
  20474. later, after making the callback
  20475. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  20476. */
  20477. void enterModalState (bool takeKeyboardFocus = true,
  20478. ModalComponentManager::Callback* callback = 0);
  20479. /** Ends a component's modal state.
  20480. If this component is currently modal, this will turn of its modalness, and return
  20481. a value to the runModalLoop() method that might have be running its modal loop.
  20482. @see runModalLoop, enterModalState, isCurrentlyModal
  20483. */
  20484. void exitModalState (int returnValue);
  20485. /** Returns true if this component is the modal one.
  20486. It's possible to have nested modal components, e.g. a pop-up dialog box
  20487. that launches another pop-up, but this will only return true for
  20488. the one at the top of the stack.
  20489. @see getCurrentlyModalComponent
  20490. */
  20491. bool isCurrentlyModal() const throw();
  20492. /** Returns the number of components that are currently in a modal state.
  20493. @see getCurrentlyModalComponent
  20494. */
  20495. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  20496. /** Returns one of the components that are currently modal.
  20497. The index specifies which of the possible modal components to return. The order
  20498. of the components in this list is the reverse of the order in which they became
  20499. modal - so the component at index 0 is always the active component, and the others
  20500. are progressively earlier ones that are themselves now blocked by later ones.
  20501. @returns the modal component, or null if no components are modal (or if the
  20502. index is out of range)
  20503. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  20504. */
  20505. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  20506. /** Checks whether there's a modal component somewhere that's stopping this one
  20507. from receiving messages.
  20508. If there is a modal component, its canModalEventBeSentToComponent() method
  20509. will be called to see if it will still allow this component to receive events.
  20510. @see runModalLoop, getCurrentlyModalComponent
  20511. */
  20512. bool isCurrentlyBlockedByAnotherModalComponent() const;
  20513. /** When a component is modal, this callback allows it to choose which other
  20514. components can still receive events.
  20515. When a modal component is active and the user clicks on a non-modal component,
  20516. this method is called on the modal component, and if it returns true, the
  20517. event is allowed to reach its target. If it returns false, the event is blocked
  20518. and the inputAttemptWhenModal() callback is made.
  20519. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  20520. implementation just returns false in all cases.
  20521. */
  20522. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  20523. /** Called when the user tries to click on a component that is blocked by another
  20524. modal component.
  20525. When a component is modal and the user clicks on one of the other components,
  20526. the modal component will receive this callback.
  20527. The default implementation of this method will play a beep, and bring the currently
  20528. modal component to the front, but it can be overridden to do other tasks.
  20529. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  20530. */
  20531. virtual void inputAttemptWhenModal();
  20532. /** Returns the set of properties that belong to this component.
  20533. Each component has a NamedValueSet object which you can use to attach arbitrary
  20534. items of data to it.
  20535. */
  20536. NamedValueSet& getProperties() throw() { return properties; }
  20537. /** Returns the set of properties that belong to this component.
  20538. Each component has a NamedValueSet object which you can use to attach arbitrary
  20539. items of data to it.
  20540. */
  20541. const NamedValueSet& getProperties() const throw() { return properties; }
  20542. /** Looks for a colour that has been registered with the given colour ID number.
  20543. If a colour has been set for this ID number using setColour(), then it is
  20544. returned. If none has been set, the method will try calling the component's
  20545. LookAndFeel class's findColour() method. If none has been registered with the
  20546. look-and-feel either, it will just return black.
  20547. The colour IDs for various purposes are stored as enums in the components that
  20548. they are relevent to - for an example, see Slider::ColourIds,
  20549. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  20550. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20551. */
  20552. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  20553. /** Registers a colour to be used for a particular purpose.
  20554. Changing a colour will cause a synchronous callback to the colourChanged()
  20555. method, which your component can override if it needs to do something when
  20556. colours are altered.
  20557. For more details about colour IDs, see the comments for findColour().
  20558. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20559. */
  20560. void setColour (int colourId, const Colour& colour);
  20561. /** If a colour has been set with setColour(), this will remove it.
  20562. This allows you to make a colour revert to its default state.
  20563. */
  20564. void removeColour (int colourId);
  20565. /** Returns true if the specified colour ID has been explicitly set for this
  20566. component using the setColour() method.
  20567. */
  20568. bool isColourSpecified (int colourId) const;
  20569. /** This looks for any colours that have been specified for this component,
  20570. and copies them to the specified target component.
  20571. */
  20572. void copyAllExplicitColoursTo (Component& target) const;
  20573. /** This method is called when a colour is changed by the setColour() method.
  20574. @see setColour, findColour
  20575. */
  20576. virtual void colourChanged();
  20577. /** Returns the underlying native window handle for this component.
  20578. This is platform-dependent and strictly for power-users only!
  20579. */
  20580. void* getWindowHandle() const;
  20581. /** When created, each component is given a number to uniquely identify it.
  20582. The number is incremented each time a new component is created, so it's a more
  20583. unique way of identifying a component than using its memory location (which
  20584. may be reused after the component is deleted, of course).
  20585. */
  20586. uint32 getComponentUID() const throw() { return componentUID; }
  20587. /** Holds a pointer to some type of Component, which automatically becomes null if
  20588. the component is deleted.
  20589. If you're using a component which may be deleted by another event that's outside
  20590. of your control, use a SafePointer instead of a normal pointer to refer to it,
  20591. and you can test whether it's null before using it to see if something has deleted
  20592. it.
  20593. The ComponentType typedef must be Component, or some subclass of Component.
  20594. Note that this class isn't thread-safe, and assumes that all the code that uses
  20595. it is running on the message thread.
  20596. */
  20597. template <class ComponentType>
  20598. class SafePointer : private ComponentListener
  20599. {
  20600. public:
  20601. /** Creates a null SafePointer. */
  20602. SafePointer() : comp (0) {}
  20603. /** Creates a SafePointer that points at the given component. */
  20604. SafePointer (ComponentType* const component) : comp (component) { attach(); }
  20605. /** Creates a copy of another SafePointer. */
  20606. SafePointer (const SafePointer& other) : comp (other.comp) { attach(); }
  20607. /** Destructor. */
  20608. ~SafePointer() { detach(); }
  20609. /** Copies another pointer to this one. */
  20610. SafePointer& operator= (const SafePointer& other) { return operator= (other.comp); }
  20611. /** Copies another pointer to this one. */
  20612. SafePointer& operator= (ComponentType* const newComponent)
  20613. {
  20614. detach();
  20615. comp = newComponent;
  20616. attach();
  20617. return *this;
  20618. }
  20619. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20620. operator ComponentType*() const throw() { return comp; }
  20621. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20622. ComponentType* getComponent() const throw() { return comp; }
  20623. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20624. ComponentType* operator->() throw() { jassert (comp != 0); return comp; }
  20625. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20626. const ComponentType* operator->() const throw() { jassert (comp != 0); return comp; }
  20627. juce_UseDebuggingNewOperator
  20628. private:
  20629. ComponentType* comp;
  20630. void attach() { if (comp != 0) comp->addComponentListener (this); }
  20631. void detach() { if (comp != 0) comp->removeComponentListener (this); }
  20632. void componentBeingDeleted (Component&) { comp = 0; }
  20633. };
  20634. /** A class to keep an eye on one or two components and check for them being deleted.
  20635. This is designed for use with the ListenerList::callChecked() methods, to allow
  20636. the list iterator to stop cleanly if the component is deleted by a listener callback
  20637. while the list is still being iterated.
  20638. */
  20639. class BailOutChecker
  20640. {
  20641. public:
  20642. /** Creates a checker that watches either one or two components.
  20643. component1 must be a valid component; component2 can be null if you only need
  20644. to check on one component.
  20645. */
  20646. BailOutChecker (Component* component1,
  20647. Component* component2 = 0);
  20648. /** Returns true if either of the two components have been deleted since this
  20649. object was created. */
  20650. bool shouldBailOut() const throw();
  20651. private:
  20652. typedef SafePointer<Component> SafeComponentPtr;
  20653. SafeComponentPtr safePointer1, safePointer2;
  20654. Component* const component2;
  20655. BailOutChecker (const BailOutChecker&);
  20656. BailOutChecker& operator= (const BailOutChecker&);
  20657. };
  20658. juce_UseDebuggingNewOperator
  20659. private:
  20660. friend class ComponentPeer;
  20661. friend class InternalDragRepeater;
  20662. friend class MouseInputSource;
  20663. friend class MouseInputSourceInternal;
  20664. static Component* currentlyFocusedComponent;
  20665. String componentName_;
  20666. Component* parentComponent_;
  20667. uint32 componentUID;
  20668. Rectangle<int> bounds_;
  20669. int numDeepMouseListeners;
  20670. Array <Component*> childComponentList_;
  20671. LookAndFeel* lookAndFeel_;
  20672. MouseCursor cursor_;
  20673. ImageEffectFilter* effect_;
  20674. Image bufferedImage_;
  20675. Array <MouseListener*>* mouseListeners_;
  20676. Array <KeyListener*>* keyListeners_;
  20677. ListenerList <ComponentListener> componentListeners;
  20678. NamedValueSet properties;
  20679. struct ComponentFlags
  20680. {
  20681. bool hasHeavyweightPeerFlag : 1;
  20682. bool visibleFlag : 1;
  20683. bool opaqueFlag : 1;
  20684. bool ignoresMouseClicksFlag : 1;
  20685. bool allowChildMouseClicksFlag : 1;
  20686. bool wantsFocusFlag : 1;
  20687. bool isFocusContainerFlag : 1;
  20688. bool dontFocusOnMouseClickFlag : 1;
  20689. bool alwaysOnTopFlag : 1;
  20690. bool bufferToImageFlag : 1;
  20691. bool bringToFrontOnClickFlag : 1;
  20692. bool repaintOnMouseActivityFlag : 1;
  20693. bool draggingFlag : 1;
  20694. bool mouseOverFlag : 1;
  20695. bool mouseInsideFlag : 1;
  20696. bool currentlyModalFlag : 1;
  20697. bool isDisabledFlag : 1;
  20698. bool childCompFocusedFlag : 1;
  20699. #if JUCE_DEBUG
  20700. bool isInsidePaintCall : 1;
  20701. #endif
  20702. };
  20703. union
  20704. {
  20705. uint32 componentFlags_;
  20706. ComponentFlags flags;
  20707. };
  20708. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20709. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20710. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20711. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  20712. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20713. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20714. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  20715. void internalBroughtToFront();
  20716. void internalFocusGain (const FocusChangeType cause);
  20717. void internalFocusLoss (const FocusChangeType cause);
  20718. void internalChildFocusChange (FocusChangeType cause);
  20719. void internalModalInputAttempt();
  20720. void internalModifierKeysChanged();
  20721. void internalChildrenChanged();
  20722. void internalHierarchyChanged();
  20723. void renderComponent (Graphics& context);
  20724. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  20725. void repaintParent();
  20726. void sendFakeMouseMove() const;
  20727. void takeKeyboardFocus (const FocusChangeType cause);
  20728. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  20729. static void giveAwayFocus();
  20730. void sendEnablementChangeMessage();
  20731. static void* runModalLoopCallback (void*);
  20732. static void bringModalComponentToFront();
  20733. void subtractObscuredRegions (RectangleList& result, const Point<int>& delta,
  20734. const Rectangle<int>& clipRect,
  20735. const Component* const compToAvoid) const;
  20736. void clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  20737. int deltaX, int deltaY) const;
  20738. // how much of the component is not off the edges of its parents
  20739. const Rectangle<int> getUnclippedArea() const;
  20740. void sendVisibilityChangeMessage();
  20741. const Rectangle<int> getParentOrMainMonitorBounds() const;
  20742. // This is included here just to cause a compile error if your code is still handling
  20743. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  20744. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  20745. // implement its methods instead of this Component method).
  20746. virtual void filesDropped (const StringArray&, int, int) {}
  20747. // components aren't allowed to have copy constructors, as this would mess up parent
  20748. // hierarchies. You might need to give your subclasses a private dummy constructor like
  20749. // this one to avoid compiler warnings.
  20750. Component (const Component&);
  20751. Component& operator= (const Component&);
  20752. protected:
  20753. /** @internal */
  20754. virtual void internalRepaint (int x, int y, int w, int h);
  20755. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  20756. /** Overridden from the MessageListener parent class.
  20757. You can override this if you really need to, but be sure to pass your unwanted messages up
  20758. to this base class implementation, as the Component class needs to send itself messages
  20759. to work properly.
  20760. */
  20761. void handleMessage (const Message&);
  20762. };
  20763. #endif // __JUCE_COMPONENT_JUCEHEADER__
  20764. /*** End of inlined file: juce_Component.h ***/
  20765. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  20766. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20767. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20768. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  20769. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20770. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20771. /** A type used to hold the unique ID for an application command.
  20772. This is a numeric type, so it can be stored as an integer.
  20773. @see ApplicationCommandInfo, ApplicationCommandManager,
  20774. ApplicationCommandTarget, KeyPressMappingSet
  20775. */
  20776. typedef int CommandID;
  20777. /** A set of general-purpose application command IDs.
  20778. Because these commands are likely to be used in most apps, they're defined
  20779. here to help different apps to use the same numeric values for them.
  20780. Of course you don't have to use these, but some of them are used internally by
  20781. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  20782. @see ApplicationCommandInfo, ApplicationCommandManager,
  20783. ApplicationCommandTarget, KeyPressMappingSet
  20784. */
  20785. namespace StandardApplicationCommandIDs
  20786. {
  20787. /** This command ID should be used to send a "Quit the App" command.
  20788. This command is recognised by the JUCEApplication class, so if it is invoked
  20789. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  20790. object will catch it and call JUCEApplication::systemRequestedQuit().
  20791. */
  20792. static const CommandID quit = 0x1001;
  20793. /** The command ID that should be used to send a "Delete" command. */
  20794. static const CommandID del = 0x1002;
  20795. /** The command ID that should be used to send a "Cut" command. */
  20796. static const CommandID cut = 0x1003;
  20797. /** The command ID that should be used to send a "Copy to clipboard" command. */
  20798. static const CommandID copy = 0x1004;
  20799. /** The command ID that should be used to send a "Paste from clipboard" command. */
  20800. static const CommandID paste = 0x1005;
  20801. /** The command ID that should be used to send a "Select all" command. */
  20802. static const CommandID selectAll = 0x1006;
  20803. /** The command ID that should be used to send a "Deselect all" command. */
  20804. static const CommandID deselectAll = 0x1007;
  20805. }
  20806. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20807. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  20808. /**
  20809. Holds information describing an application command.
  20810. This object is used to pass information about a particular command, such as its
  20811. name, description and other usage flags.
  20812. When an ApplicationCommandTarget is asked to provide information about the commands
  20813. it can perform, this is the structure gets filled-in to describe each one.
  20814. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  20815. ApplicationCommandManager
  20816. */
  20817. struct JUCE_API ApplicationCommandInfo
  20818. {
  20819. explicit ApplicationCommandInfo (CommandID commandID) throw();
  20820. /** Sets a number of the structures values at once.
  20821. The meanings of each of the parameters is described below, in the appropriate
  20822. member variable's description.
  20823. */
  20824. void setInfo (const String& shortName,
  20825. const String& description,
  20826. const String& categoryName,
  20827. int flags) throw();
  20828. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  20829. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  20830. is false, the bit is set.
  20831. */
  20832. void setActive (bool isActive) throw();
  20833. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  20834. */
  20835. void setTicked (bool isTicked) throw();
  20836. /** Handy method for adding a keypress to the defaultKeypresses array.
  20837. This is just so you can write things like:
  20838. @code
  20839. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  20840. @endcode
  20841. instead of
  20842. @code
  20843. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  20844. @endcode
  20845. */
  20846. void addDefaultKeypress (int keyCode,
  20847. const ModifierKeys& modifiers) throw();
  20848. /** The command's unique ID number.
  20849. */
  20850. CommandID commandID;
  20851. /** A short name to describe the command.
  20852. This should be suitable for use in menus, on buttons that trigger the command, etc.
  20853. You can use the setInfo() method to quickly set this and some of the command's
  20854. other properties.
  20855. */
  20856. String shortName;
  20857. /** A longer description of the command.
  20858. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  20859. pop-up tooltip describing what the command does.
  20860. You can use the setInfo() method to quickly set this and some of the command's
  20861. other properties.
  20862. */
  20863. String description;
  20864. /** A named category that the command fits into.
  20865. You can give your commands any category you like, and these will be displayed in
  20866. contexts such as the KeyMappingEditorComponent, where the category is used to group
  20867. commands together.
  20868. You can use the setInfo() method to quickly set this and some of the command's
  20869. other properties.
  20870. */
  20871. String categoryName;
  20872. /** A list of zero or more keypresses that should be used as the default keys for
  20873. this command.
  20874. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  20875. this list to initialise the default set of key-to-command mappings.
  20876. @see addDefaultKeypress
  20877. */
  20878. Array <KeyPress> defaultKeypresses;
  20879. /** Flags describing the ways in which this command should be used.
  20880. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  20881. variable.
  20882. */
  20883. enum CommandFlags
  20884. {
  20885. /** Indicates that the command can't currently be performed.
  20886. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  20887. not currently permissable to perform the command. If the flag is set, then
  20888. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  20889. command or show themselves as not being enabled.
  20890. @see ApplicationCommandInfo::setActive
  20891. */
  20892. isDisabled = 1 << 0,
  20893. /** Indicates that the command should have a tick next to it on a menu.
  20894. If your command is shown on a menu and this is set, it'll show a tick next to
  20895. it. Other components such as buttons may also use this flag to indicate that it
  20896. is a value that can be toggled, and is currently in the 'on' state.
  20897. @see ApplicationCommandInfo::setTicked
  20898. */
  20899. isTicked = 1 << 1,
  20900. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  20901. it will call the command twice, once on key-down and again on key-up.
  20902. @see ApplicationCommandTarget::InvocationInfo
  20903. */
  20904. wantsKeyUpDownCallbacks = 1 << 2,
  20905. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  20906. command in its list.
  20907. */
  20908. hiddenFromKeyEditor = 1 << 3,
  20909. /** If this flag is present, then a KeyMappingEditorComponent will display the
  20910. command in its list, but won't allow the assigned keypress to be changed.
  20911. */
  20912. readOnlyInKeyEditor = 1 << 4,
  20913. /** If this flag is present and the command is invoked from a keypress, then any
  20914. buttons or menus that are also connected to the command will not flash to
  20915. indicate that they've been triggered.
  20916. */
  20917. dontTriggerVisualFeedback = 1 << 5
  20918. };
  20919. /** A bitwise-OR of the values specified in the CommandFlags enum.
  20920. You can use the setInfo() method to quickly set this and some of the command's
  20921. other properties.
  20922. */
  20923. int flags;
  20924. };
  20925. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20926. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  20927. /**
  20928. A command target publishes a list of command IDs that it can perform.
  20929. An ApplicationCommandManager despatches commands to targets, which must be
  20930. able to provide information about what commands they can handle.
  20931. To create a target, you'll need to inherit from this class, implementing all of
  20932. its pure virtual methods.
  20933. For info about how a target is chosen to receive a command, see
  20934. ApplicationCommandManager::getFirstCommandTarget().
  20935. @see ApplicationCommandManager, ApplicationCommandInfo
  20936. */
  20937. class JUCE_API ApplicationCommandTarget
  20938. {
  20939. public:
  20940. /** Creates a command target. */
  20941. ApplicationCommandTarget();
  20942. /** Destructor. */
  20943. virtual ~ApplicationCommandTarget();
  20944. /**
  20945. */
  20946. struct JUCE_API InvocationInfo
  20947. {
  20948. InvocationInfo (const CommandID commandID) throw();
  20949. /** The UID of the command that should be performed. */
  20950. CommandID commandID;
  20951. /** The command's flags.
  20952. See ApplicationCommandInfo for a description of these flag values.
  20953. */
  20954. int commandFlags;
  20955. /** The types of context in which the command might be called. */
  20956. enum InvocationMethod
  20957. {
  20958. direct = 0, /**< The command is being invoked directly by a piece of code. */
  20959. fromKeyPress, /**< The command is being invoked by a key-press. */
  20960. fromMenu, /**< The command is being invoked by a menu selection. */
  20961. fromButton /**< The command is being invoked by a button click. */
  20962. };
  20963. /** The type of event that triggered this command. */
  20964. InvocationMethod invocationMethod;
  20965. /** If triggered by a keypress or menu, this will be the component that had the
  20966. keyboard focus at the time.
  20967. If triggered by a button, it may be set to that component, or it may be null.
  20968. */
  20969. Component* originatingComponent;
  20970. /** The keypress that was used to invoke it.
  20971. Note that this will be an invalid keypress if the command was invoked
  20972. by some other means than a keyboard shortcut.
  20973. */
  20974. KeyPress keyPress;
  20975. /** True if the callback is being invoked when the key is pressed,
  20976. false if the key is being released.
  20977. @see KeyPressMappingSet::addCommand()
  20978. */
  20979. bool isKeyDown;
  20980. /** If the key is being released, this indicates how long it had been held
  20981. down for.
  20982. (Only relevant if isKeyDown is false.)
  20983. */
  20984. int millisecsSinceKeyPressed;
  20985. };
  20986. /** This must return the next target to try after this one.
  20987. When a command is being sent, and the first target can't handle
  20988. that command, this method is used to determine the next target that should
  20989. be tried.
  20990. It may return 0 if it doesn't know of another target.
  20991. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  20992. method to return a parent component that might want to handle it.
  20993. @see invoke
  20994. */
  20995. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  20996. /** This must return a complete list of commands that this target can handle.
  20997. Your target should add all the command IDs that it handles to the array that is
  20998. passed-in.
  20999. */
  21000. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  21001. /** This must provide details about one of the commands that this target can perform.
  21002. This will be called with one of the command IDs that the target provided in its
  21003. getAllCommands() methods.
  21004. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  21005. suitable information about the command. (The commandID field will already have been filled-in
  21006. by the caller).
  21007. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  21008. set all the fields at once.
  21009. If the command is currently inactive for some reason, this method must use
  21010. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  21011. bit of the ApplicationCommandInfo::flags field).
  21012. Any default key-presses for the command should be appended to the
  21013. ApplicationCommandInfo::defaultKeypresses field.
  21014. Note that if you change something that affects the status of the commands
  21015. that would be returned by this method (e.g. something that makes some commands
  21016. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  21017. to cause the manager to refresh its status.
  21018. */
  21019. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  21020. /** This must actually perform the specified command.
  21021. If this target is able to perform the command specified by the commandID field of the
  21022. InvocationInfo structure, then it should do so, and must return true.
  21023. If it can't handle this command, it should return false, which tells the caller to pass
  21024. the command on to the next target in line.
  21025. @see invoke, ApplicationCommandManager::invoke
  21026. */
  21027. virtual bool perform (const InvocationInfo& info) = 0;
  21028. /** Makes this target invoke a command.
  21029. Your code can call this method to invoke a command on this target, but normally
  21030. you'd call it indirectly via ApplicationCommandManager::invoke() or
  21031. ApplicationCommandManager::invokeDirectly().
  21032. If this target can perform the given command, it will call its perform() method to
  21033. do so. If not, then getNextCommandTarget() will be used to determine the next target
  21034. to try, and the command will be passed along to it.
  21035. @param invocationInfo this must be correctly filled-in, describing the context for
  21036. the invocation.
  21037. @param asynchronously if false, the command will be performed before this method returns.
  21038. If true, a message will be posted so that the command will be performed
  21039. later on the message thread, and this method will return immediately.
  21040. @see perform, ApplicationCommandManager::invoke
  21041. */
  21042. bool invoke (const InvocationInfo& invocationInfo,
  21043. const bool asynchronously);
  21044. /** Invokes a given command directly on this target.
  21045. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  21046. structure.
  21047. */
  21048. bool invokeDirectly (const CommandID commandID,
  21049. const bool asynchronously);
  21050. /** Searches this target and all subsequent ones for the first one that can handle
  21051. the specified command.
  21052. This will use getNextCommandTarget() to determine the chain of targets to try
  21053. after this one.
  21054. */
  21055. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  21056. /** Checks whether this command can currently be performed by this target.
  21057. This will return true only if a call to getCommandInfo() doesn't set the
  21058. isDisabled flag to indicate that the command is inactive.
  21059. */
  21060. bool isCommandActive (const CommandID commandID);
  21061. /** If this object is a Component, this method will seach upwards in its current
  21062. UI hierarchy for the next parent component that implements the
  21063. ApplicationCommandTarget class.
  21064. If your target is a Component, this is a very handy method to use in your
  21065. getNextCommandTarget() implementation.
  21066. */
  21067. ApplicationCommandTarget* findFirstTargetParentComponent();
  21068. juce_UseDebuggingNewOperator
  21069. private:
  21070. // (for async invocation of commands)
  21071. class CommandTargetMessageInvoker : public MessageListener
  21072. {
  21073. public:
  21074. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  21075. ~CommandTargetMessageInvoker();
  21076. void handleMessage (const Message& message);
  21077. private:
  21078. ApplicationCommandTarget* const owner;
  21079. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  21080. CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  21081. };
  21082. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  21083. friend class CommandTargetMessageInvoker;
  21084. bool tryToInvoke (const InvocationInfo& info, const bool async);
  21085. ApplicationCommandTarget (const ApplicationCommandTarget&);
  21086. ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  21087. };
  21088. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21089. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  21090. /*** Start of inlined file: juce_ActionListener.h ***/
  21091. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  21092. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  21093. /**
  21094. Receives callbacks to indicate that some kind of event has occurred.
  21095. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  21096. about something that's happened.
  21097. @see ActionListenerList, ActionBroadcaster, ChangeListener
  21098. */
  21099. class JUCE_API ActionListener
  21100. {
  21101. public:
  21102. /** Destructor. */
  21103. virtual ~ActionListener() {}
  21104. /** Overridden by your subclass to receive the callback.
  21105. @param message the string that was specified when the event was triggered
  21106. by a call to ActionListenerList::sendActionMessage()
  21107. */
  21108. virtual void actionListenerCallback (const String& message) = 0;
  21109. };
  21110. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  21111. /*** End of inlined file: juce_ActionListener.h ***/
  21112. /**
  21113. An instance of this class is used to specify initialisation and shutdown
  21114. code for the application.
  21115. An application that wants to run in the JUCE framework needs to declare a
  21116. subclass of JUCEApplication and implement its various pure virtual methods.
  21117. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  21118. to declare an instance of this class and generate a suitable platform-specific
  21119. main() function.
  21120. e.g. @code
  21121. class MyJUCEApp : public JUCEApplication
  21122. {
  21123. // NEVER put objects inside a JUCEApplication class - only use pointers to
  21124. // objects, which you must create in the initialise() method.
  21125. MyApplicationWindow* myMainWindow;
  21126. public:
  21127. MyJUCEApp()
  21128. : myMainWindow (0)
  21129. {
  21130. // never create any Juce objects in the constructor - do all your initialisation
  21131. // in the initialise() method.
  21132. }
  21133. ~MyJUCEApp()
  21134. {
  21135. // all your shutdown code must have already been done in the shutdown() method -
  21136. // nothing should happen in this destructor.
  21137. }
  21138. void initialise (const String& commandLine)
  21139. {
  21140. myMainWindow = new MyApplicationWindow();
  21141. myMainWindow->setBounds (100, 100, 400, 500);
  21142. myMainWindow->setVisible (true);
  21143. }
  21144. void shutdown()
  21145. {
  21146. delete myMainWindow;
  21147. }
  21148. const String getApplicationName()
  21149. {
  21150. return "Super JUCE-o-matic";
  21151. }
  21152. const String getApplicationVersion()
  21153. {
  21154. return "1.0";
  21155. }
  21156. };
  21157. // this creates wrapper code to actually launch the app properly.
  21158. START_JUCE_APPLICATION (MyJUCEApp)
  21159. @endcode
  21160. Because this object will be created before Juce has properly initialised, you must
  21161. NEVER add any member variable objects that will be automatically constructed. Likewise
  21162. don't put ANY code in the constructor that could call Juce functions. Any objects that
  21163. you want to add to the class must be pointers, which you should instantiate during the
  21164. initialise() method, and delete in the shutdown() method.
  21165. @see MessageManager, DeletedAtShutdown
  21166. */
  21167. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  21168. private ActionListener
  21169. {
  21170. protected:
  21171. /** Constructs a JUCE app object.
  21172. If subclasses implement a constructor or destructor, they shouldn't call any
  21173. JUCE code in there - put your startup/shutdown code in initialise() and
  21174. shutdown() instead.
  21175. */
  21176. JUCEApplication();
  21177. public:
  21178. /** Destructor.
  21179. If subclasses implement a constructor or destructor, they shouldn't call any
  21180. JUCE code in there - put your startup/shutdown code in initialise() and
  21181. shutdown() instead.
  21182. */
  21183. virtual ~JUCEApplication();
  21184. /** Returns the global instance of the application object being run. */
  21185. static JUCEApplication* getInstance() throw();
  21186. /** Called when the application starts.
  21187. This will be called once to let the application do whatever initialisation
  21188. it needs, create its windows, etc.
  21189. After the method returns, the normal event-dispatch loop will be run,
  21190. until the quit() method is called, at which point the shutdown()
  21191. method will be called to let the application clear up anything it needs
  21192. to delete.
  21193. If during the initialise() method, the application decides not to start-up
  21194. after all, it can just call the quit() method and the event loop won't be run.
  21195. @param commandLineParameters the line passed in does not include the
  21196. name of the executable, just the parameter list.
  21197. @see shutdown, quit
  21198. */
  21199. virtual void initialise (const String& commandLineParameters) = 0;
  21200. /** Returns true if the application hasn't yet completed its initialise() method
  21201. and entered the main event loop.
  21202. This is handy for things like splash screens to know when the app's up-and-running
  21203. properly.
  21204. */
  21205. bool isInitialising() const throw();
  21206. /* Called to allow the application to clear up before exiting.
  21207. After JUCEApplication::quit() has been called, the event-dispatch loop will
  21208. terminate, and this method will get called to allow the app to sort itself
  21209. out.
  21210. Be careful that nothing happens in this method that might rely on messages
  21211. being sent, or any kind of window activity, because the message loop is no
  21212. longer running at this point.
  21213. @see DeletedAtShutdown
  21214. */
  21215. virtual void shutdown() = 0;
  21216. /** Returns the application's name.
  21217. An application must implement this to name itself.
  21218. */
  21219. virtual const String getApplicationName() = 0;
  21220. /** Returns the application's version number.
  21221. An application can implement this to give itself a version.
  21222. (The default implementation of this just returns an empty string).
  21223. */
  21224. virtual const String getApplicationVersion();
  21225. /** Checks whether multiple instances of the app are allowed.
  21226. If you application class returns true for this, more than one instance is
  21227. permitted to run (except on the Mac where this isn't possible).
  21228. If it's false, the second instance won't start, but it you will still get a
  21229. callback to anotherInstanceStarted() to tell you about this - which
  21230. gives you a chance to react to what the user was trying to do.
  21231. */
  21232. virtual bool moreThanOneInstanceAllowed();
  21233. /** Indicates that the user has tried to start up another instance of the app.
  21234. This will get called even if moreThanOneInstanceAllowed() is false.
  21235. */
  21236. virtual void anotherInstanceStarted (const String& commandLine);
  21237. /** Called when the operating system is trying to close the application.
  21238. The default implementation of this method is to call quit(), but it may
  21239. be overloaded to ignore the request or do some other special behaviour
  21240. instead. For example, you might want to offer the user the chance to save
  21241. their changes before quitting, and give them the chance to cancel.
  21242. If you want to send a quit signal to your app, this is the correct method
  21243. to call, because it means that requests that come from the system get handled
  21244. in the same way as those from your own application code. So e.g. you'd
  21245. call this method from a "quit" item on a menu bar.
  21246. */
  21247. virtual void systemRequestedQuit();
  21248. /** If any unhandled exceptions make it through to the message dispatch loop, this
  21249. callback will be triggered, in case you want to log them or do some other
  21250. type of error-handling.
  21251. If the type of exception is derived from the std::exception class, the pointer
  21252. passed-in will be valid. If the exception is of unknown type, this pointer
  21253. will be null.
  21254. */
  21255. virtual void unhandledException (const std::exception* e,
  21256. const String& sourceFilename,
  21257. int lineNumber);
  21258. /** Signals that the main message loop should stop and the application should terminate.
  21259. This isn't synchronous, it just posts a quit message to the main queue, and
  21260. when this message arrives, the message loop will stop, the shutdown() method
  21261. will be called, and the app will exit.
  21262. Note that this will cause an unconditional quit to happen, so if you need an
  21263. extra level before this, e.g. to give the user the chance to save their work
  21264. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  21265. method - see that method's help for more info.
  21266. @see MessageManager, DeletedAtShutdown
  21267. */
  21268. static void quit();
  21269. /** Sets the value that should be returned as the application's exit code when the
  21270. app quits.
  21271. This is the value that's returned by the main() function. Normally you'd leave this
  21272. as 0 unless you want to indicate an error code.
  21273. @see getApplicationReturnValue
  21274. */
  21275. void setApplicationReturnValue (int newReturnValue) throw();
  21276. /** Returns the value that has been set as the application's exit code.
  21277. @see setApplicationReturnValue
  21278. */
  21279. int getApplicationReturnValue() const throw() { return appReturnValue; }
  21280. /** Returns the application's command line params.
  21281. */
  21282. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  21283. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  21284. /** @internal */
  21285. static int main (const String& commandLine, JUCEApplication* newApp);
  21286. /** @internal */
  21287. static int main (int argc, const char* argv[], JUCEApplication* newApp);
  21288. /** @internal */
  21289. static void sendUnhandledException (const std::exception* e,
  21290. const char* sourceFile,
  21291. int lineNumber);
  21292. /** @internal */
  21293. ApplicationCommandTarget* getNextCommandTarget();
  21294. /** @internal */
  21295. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  21296. /** @internal */
  21297. void getAllCommands (Array <CommandID>& commands);
  21298. /** @internal */
  21299. bool perform (const InvocationInfo& info);
  21300. /** @internal */
  21301. void actionListenerCallback (const String& message);
  21302. /** @internal */
  21303. bool initialiseApp (const String& commandLine);
  21304. /** @internal */
  21305. int shutdownApp();
  21306. private:
  21307. String commandLineParameters;
  21308. int appReturnValue;
  21309. bool stillInitialising;
  21310. ScopedPointer<InterProcessLock> appLock;
  21311. static JUCEApplication* appInstance;
  21312. JUCEApplication (const JUCEApplication&);
  21313. JUCEApplication& operator= (const JUCEApplication&);
  21314. };
  21315. #endif // __JUCE_APPLICATION_JUCEHEADER__
  21316. /*** End of inlined file: juce_Application.h ***/
  21317. #endif
  21318. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  21319. #endif
  21320. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  21321. #endif
  21322. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21323. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  21324. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21325. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21326. /*** Start of inlined file: juce_Desktop.h ***/
  21327. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  21328. #define __JUCE_DESKTOP_JUCEHEADER__
  21329. /*** Start of inlined file: juce_Timer.h ***/
  21330. #ifndef __JUCE_TIMER_JUCEHEADER__
  21331. #define __JUCE_TIMER_JUCEHEADER__
  21332. class InternalTimerThread;
  21333. /**
  21334. Repeatedly calls a user-defined method at a specified time interval.
  21335. A Timer's timerCallback() method will be repeatedly called at a given
  21336. interval. Initially when a Timer object is created, they will do nothing
  21337. until the startTimer() method is called, then the message thread will
  21338. start calling it back until stopTimer() is called.
  21339. The time interval isn't guaranteed to be precise to any more than maybe
  21340. 10-20ms, and the intervals may end up being much longer than requested if the
  21341. system is busy. Because it's the message thread that is doing the callbacks,
  21342. any messages that take a significant amount of time to process will block
  21343. all the timers for that period.
  21344. If you need to have a single callback that is shared by multiple timers with
  21345. different frequencies, then the MultiTimer class allows you to do that - its
  21346. structure is very similar to the Timer class, but contains multiple timers
  21347. internally, each one identified by an ID number.
  21348. @see MultiTimer
  21349. */
  21350. class JUCE_API Timer
  21351. {
  21352. protected:
  21353. /** Creates a Timer.
  21354. When created, the timer is stopped, so use startTimer() to get it going.
  21355. */
  21356. Timer() throw();
  21357. /** Creates a copy of another timer.
  21358. Note that this timer won't be started, even if the one you're copying
  21359. is running.
  21360. */
  21361. Timer (const Timer& other) throw();
  21362. public:
  21363. /** Destructor. */
  21364. virtual ~Timer();
  21365. /** The user-defined callback routine that actually gets called periodically.
  21366. It's perfectly ok to call startTimer() or stopTimer() from within this
  21367. callback to change the subsequent intervals.
  21368. */
  21369. virtual void timerCallback() = 0;
  21370. /** Starts the timer and sets the length of interval required.
  21371. If the timer is already started, this will reset it, so the
  21372. time between calling this method and the next timer callback
  21373. will not be less than the interval length passed in.
  21374. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  21375. rounded up to 1)
  21376. */
  21377. void startTimer (int intervalInMilliseconds) throw();
  21378. /** Stops the timer.
  21379. No more callbacks will be made after this method returns.
  21380. If this is called from a different thread, any callbacks that may
  21381. be currently executing may be allowed to finish before the method
  21382. returns.
  21383. */
  21384. void stopTimer() throw();
  21385. /** Checks if the timer has been started.
  21386. @returns true if the timer is running.
  21387. */
  21388. bool isTimerRunning() const throw() { return periodMs > 0; }
  21389. /** Returns the timer's interval.
  21390. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  21391. */
  21392. int getTimerInterval() const throw() { return periodMs; }
  21393. private:
  21394. friend class InternalTimerThread;
  21395. int countdownMs, periodMs;
  21396. Timer* previous;
  21397. Timer* next;
  21398. Timer& operator= (const Timer&);
  21399. };
  21400. #endif // __JUCE_TIMER_JUCEHEADER__
  21401. /*** End of inlined file: juce_Timer.h ***/
  21402. class MouseInputSource;
  21403. class MouseInputSourceInternal;
  21404. class MouseListener;
  21405. /**
  21406. Classes can implement this interface and register themselves with the Desktop class
  21407. to receive callbacks when the currently focused component changes.
  21408. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  21409. */
  21410. class JUCE_API FocusChangeListener
  21411. {
  21412. public:
  21413. /** Destructor. */
  21414. virtual ~FocusChangeListener() {}
  21415. /** Callback to indicate that the currently focused component has changed. */
  21416. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  21417. };
  21418. /**
  21419. Describes and controls aspects of the computer's desktop.
  21420. */
  21421. class JUCE_API Desktop : private DeletedAtShutdown,
  21422. private Timer,
  21423. private AsyncUpdater
  21424. {
  21425. public:
  21426. /** There's only one dektop object, and this method will return it.
  21427. */
  21428. static Desktop& JUCE_CALLTYPE getInstance();
  21429. /** Returns a list of the positions of all the monitors available.
  21430. The first rectangle in the list will be the main monitor area.
  21431. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21432. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21433. */
  21434. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  21435. /** Returns the position and size of the main monitor.
  21436. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21437. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21438. */
  21439. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  21440. /** Returns the position and size of the monitor which contains this co-ordinate.
  21441. If none of the monitors contains the point, this will just return the
  21442. main monitor.
  21443. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21444. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21445. */
  21446. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  21447. /** Returns the mouse position.
  21448. The co-ordinates are relative to the top-left of the main monitor.
  21449. */
  21450. static const Point<int> getMousePosition();
  21451. /** Makes the mouse pointer jump to a given location.
  21452. The co-ordinates are relative to the top-left of the main monitor.
  21453. */
  21454. static void setMousePosition (const Point<int>& newPosition);
  21455. /** Returns the last position at which a mouse button was pressed.
  21456. */
  21457. static const Point<int> getLastMouseDownPosition() throw();
  21458. /** Returns the number of times the mouse button has been clicked since the
  21459. app started.
  21460. Each mouse-down event increments this number by 1.
  21461. */
  21462. static int getMouseButtonClickCounter() throw();
  21463. /** This lets you prevent the screensaver from becoming active.
  21464. Handy if you're running some sort of presentation app where having a screensaver
  21465. appear would be annoying.
  21466. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  21467. won't enable a screensaver unless the user has actually set one up).
  21468. The disablement will only happen while the Juce application is the foreground
  21469. process - if another task is running in front of it, then the screensaver will
  21470. be unaffected.
  21471. @see isScreenSaverEnabled
  21472. */
  21473. static void setScreenSaverEnabled (bool isEnabled);
  21474. /** Returns true if the screensaver has not been turned off.
  21475. This will return the last value passed into setScreenSaverEnabled(). Note that
  21476. it won't tell you whether the user is actually using a screen saver, just
  21477. whether this app is deliberately preventing one from running.
  21478. @see setScreenSaverEnabled
  21479. */
  21480. static bool isScreenSaverEnabled();
  21481. /** Registers a MouseListener that will receive all mouse events that occur on
  21482. any component.
  21483. @see removeGlobalMouseListener
  21484. */
  21485. void addGlobalMouseListener (MouseListener* listener);
  21486. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  21487. method.
  21488. @see addGlobalMouseListener
  21489. */
  21490. void removeGlobalMouseListener (MouseListener* listener);
  21491. /** Registers a MouseListener that will receive a callback whenever the focused
  21492. component changes.
  21493. */
  21494. void addFocusChangeListener (FocusChangeListener* listener);
  21495. /** Unregisters a listener that was added with addFocusChangeListener(). */
  21496. void removeFocusChangeListener (FocusChangeListener* listener);
  21497. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  21498. The component must already be on the desktop for this method to work. It will
  21499. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  21500. etc will be hidden.
  21501. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  21502. the component that's currently being used will be resized back to the size
  21503. and position it was in before being put into this mode.
  21504. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  21505. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  21506. to hide as much on-screen paraphenalia as possible.
  21507. */
  21508. void setKioskModeComponent (Component* componentToUse,
  21509. bool allowMenusAndBars = true);
  21510. /** Returns the component that is currently being used in kiosk-mode.
  21511. This is the component that was last set by setKioskModeComponent(). If none
  21512. has been set, this returns 0.
  21513. */
  21514. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  21515. /** Returns the number of components that are currently active as top-level
  21516. desktop windows.
  21517. @see getComponent, Component::addToDesktop
  21518. */
  21519. int getNumComponents() const throw();
  21520. /** Returns one of the top-level desktop window components.
  21521. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  21522. index is out-of-range.
  21523. @see getNumComponents, Component::addToDesktop
  21524. */
  21525. Component* getComponent (int index) const throw();
  21526. /** Finds the component at a given screen location.
  21527. This will drill down into top-level windows to find the child component at
  21528. the given position.
  21529. Returns 0 if the co-ordinates are inside a non-Juce window.
  21530. */
  21531. Component* findComponentAt (const Point<int>& screenPosition) const;
  21532. /** Returns the number of MouseInputSource objects the system has at its disposal.
  21533. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21534. system, there could be one input source per potential finger.
  21535. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  21536. @see getMouseSource
  21537. */
  21538. int getNumMouseSources() const throw() { return mouseSources.size(); }
  21539. /** Returns one of the system's MouseInputSource objects.
  21540. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  21541. a null pointer.
  21542. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21543. system, there could be one input source per potential finger.
  21544. */
  21545. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  21546. /** Returns the main mouse input device that the system is using.
  21547. @see getNumMouseSources()
  21548. */
  21549. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  21550. /** Returns the number of mouse-sources that are currently being dragged.
  21551. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  21552. juce component has the button down on it. In a multi-touch system, this could
  21553. be any number from 0 to the number of simultaneous touches that can be detected.
  21554. */
  21555. int getNumDraggingMouseSources() const throw();
  21556. /** Returns one of the mouse sources that's currently being dragged.
  21557. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  21558. out of range, or if no mice or fingers are down, this will return a null pointer.
  21559. */
  21560. MouseInputSource* getDraggingMouseSource (int index) const throw();
  21561. juce_UseDebuggingNewOperator
  21562. /** Tells this object to refresh its idea of what the screen resolution is.
  21563. (Called internally by the native code).
  21564. */
  21565. void refreshMonitorSizes();
  21566. /** True if the OS supports semitransparent windows */
  21567. static bool canUseSemiTransparentWindows() throw();
  21568. private:
  21569. static Desktop* instance;
  21570. friend class Component;
  21571. friend class ComponentPeer;
  21572. friend class MouseInputSource;
  21573. friend class MouseInputSourceInternal;
  21574. friend class DeletedAtShutdown;
  21575. friend class TopLevelWindowManager;
  21576. OwnedArray <MouseInputSource> mouseSources;
  21577. void createMouseInputSources();
  21578. ListenerList <MouseListener> mouseListeners;
  21579. ListenerList <FocusChangeListener> focusListeners;
  21580. Array <Component*> desktopComponents;
  21581. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  21582. Point<int> lastFakeMouseMove;
  21583. void sendMouseMove();
  21584. int mouseClickCounter;
  21585. void incrementMouseClickCounter() throw();
  21586. Component* kioskModeComponent;
  21587. Rectangle<int> kioskComponentOriginalBounds;
  21588. void timerCallback();
  21589. void resetTimer();
  21590. int getNumDisplayMonitors() const throw();
  21591. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  21592. void addDesktopComponent (Component* c);
  21593. void removeDesktopComponent (Component* c);
  21594. void componentBroughtToFront (Component* c);
  21595. void triggerFocusCallback();
  21596. void handleAsyncUpdate();
  21597. Desktop();
  21598. ~Desktop();
  21599. Desktop (const Desktop&);
  21600. Desktop& operator= (const Desktop&);
  21601. };
  21602. #endif // __JUCE_DESKTOP_JUCEHEADER__
  21603. /*** End of inlined file: juce_Desktop.h ***/
  21604. class KeyPressMappingSet;
  21605. class ApplicationCommandManagerListener;
  21606. /**
  21607. One of these objects holds a list of all the commands your app can perform,
  21608. and despatches these commands when needed.
  21609. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  21610. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  21611. to invoke automatically, which means you don't have to handle the result of a menu
  21612. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  21613. which can choose which events they want to handle.
  21614. This architecture also allows for nested ApplicationCommandTargets, so that for example
  21615. you could have two different objects, one inside the other, both of which can respond to
  21616. a "delete" command. Depending on which one has focus, the command will be sent to the
  21617. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  21618. method.
  21619. To set up your app to use commands, you'll need to do the following:
  21620. - Create a global ApplicationCommandManager to hold the list of all possible
  21621. commands. (This will also manage a set of key-mappings for them).
  21622. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  21623. This allows the object to provide a list of commands that it can perform, and
  21624. to handle them.
  21625. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  21626. or ApplicationCommandManager::registerCommand().
  21627. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  21628. method to access the key-mapper object, which you will need to register as a key-listener
  21629. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  21630. about setting this up.
  21631. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  21632. cause these commands to be invoked automatically.
  21633. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  21634. When a command is invoked, the ApplicationCommandManager will try to choose the best
  21635. ApplicationCommandTarget to receive the specified command. To do this it will use the
  21636. current keyboard focus to see which component might be interested, and will search the
  21637. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  21638. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  21639. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  21640. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  21641. point if the command still hasn't been performed, it will be passed to the current
  21642. JUCEApplication object (which is itself an ApplicationCommandTarget).
  21643. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  21644. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  21645. the object yourself.
  21646. @see ApplicationCommandTarget, ApplicationCommandInfo
  21647. */
  21648. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  21649. private FocusChangeListener
  21650. {
  21651. public:
  21652. /** Creates an ApplicationCommandManager.
  21653. Once created, you'll need to register all your app's commands with it, using
  21654. ApplicationCommandManager::registerAllCommandsForTarget() or
  21655. ApplicationCommandManager::registerCommand().
  21656. */
  21657. ApplicationCommandManager();
  21658. /** Destructor.
  21659. Make sure that you don't delete this if pointers to it are still being used by
  21660. objects such as PopupMenus or Buttons.
  21661. */
  21662. virtual ~ApplicationCommandManager();
  21663. /** Clears the current list of all commands.
  21664. Note that this will also clear the contents of the KeyPressMappingSet.
  21665. */
  21666. void clearCommands();
  21667. /** Adds a command to the list of registered commands.
  21668. @see registerAllCommandsForTarget
  21669. */
  21670. void registerCommand (const ApplicationCommandInfo& newCommand);
  21671. /** Adds all the commands that this target publishes to the manager's list.
  21672. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  21673. to get details about all the commands that this target can do, and will call
  21674. registerCommand() to add each one to the manger's list.
  21675. @see registerCommand
  21676. */
  21677. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  21678. /** Removes the command with a specified ID.
  21679. Note that this will also remove any key mappings that are mapped to the command.
  21680. */
  21681. void removeCommand (CommandID commandID);
  21682. /** This should be called to tell the manager that one of its registered commands may have changed
  21683. its active status.
  21684. Because the command manager only finds out whether a command is active or inactive by querying
  21685. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  21686. allows things like buttons to update their enablement, etc.
  21687. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  21688. for any registered listeners.
  21689. */
  21690. void commandStatusChanged();
  21691. /** Returns the number of commands that have been registered.
  21692. @see registerCommand
  21693. */
  21694. int getNumCommands() const throw() { return commands.size(); }
  21695. /** Returns the details about one of the registered commands.
  21696. The index is between 0 and (getNumCommands() - 1).
  21697. */
  21698. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  21699. /** Returns the details about a given command ID.
  21700. This will search the list of registered commands for one with the given command
  21701. ID number, and return its associated info. If no matching command is found, this
  21702. will return 0.
  21703. */
  21704. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  21705. /** Returns the name field for a command.
  21706. An empty string is returned if no command with this ID has been registered.
  21707. @see getDescriptionOfCommand
  21708. */
  21709. const String getNameOfCommand (CommandID commandID) const throw();
  21710. /** Returns the description field for a command.
  21711. An empty string is returned if no command with this ID has been registered. If the
  21712. command has no description, this will return its short name field instead.
  21713. @see getNameOfCommand
  21714. */
  21715. const String getDescriptionOfCommand (CommandID commandID) const throw();
  21716. /** Returns the list of categories.
  21717. This will go through all registered commands, and return a list of all the distict
  21718. categoryName values from their ApplicationCommandInfo structure.
  21719. @see getCommandsInCategory()
  21720. */
  21721. const StringArray getCommandCategories() const throw();
  21722. /** Returns a list of all the command UIDs in a particular category.
  21723. @see getCommandCategories()
  21724. */
  21725. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  21726. /** Returns the manager's internal set of key mappings.
  21727. This object can be used to edit the keypresses. To actually link this object up
  21728. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  21729. class.
  21730. @see KeyPressMappingSet
  21731. */
  21732. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  21733. /** Invokes the given command directly, sending it to the default target.
  21734. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  21735. structure.
  21736. */
  21737. bool invokeDirectly (CommandID commandID, bool asynchronously);
  21738. /** Sends a command to the default target.
  21739. This will choose a target using getFirstCommandTarget(), and send the specified command
  21740. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  21741. first target can't handle the command, it will be passed on to targets further down the
  21742. chain (see ApplicationCommandTarget::invoke() for more info).
  21743. @param invocationInfo this must be correctly filled-in, describing the context for
  21744. the invocation.
  21745. @param asynchronously if false, the command will be performed before this method returns.
  21746. If true, a message will be posted so that the command will be performed
  21747. later on the message thread, and this method will return immediately.
  21748. @see ApplicationCommandTarget::invoke
  21749. */
  21750. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  21751. bool asynchronously);
  21752. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  21753. Whenever the manager needs to know which target a command should be sent to, it calls
  21754. this method to determine the first one to try.
  21755. By default, this method will return the target that was set by calling setFirstCommandTarget().
  21756. If no target is set, it will return the result of findDefaultComponentTarget().
  21757. If you need to make sure all commands go via your own custom target, then you can
  21758. either use setFirstCommandTarget() to specify a single target, or override this method
  21759. if you need more complex logic to choose one.
  21760. It may return 0 if no targets are available.
  21761. @see getTargetForCommand, invoke, invokeDirectly
  21762. */
  21763. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  21764. /** Sets a target to be returned by getFirstCommandTarget().
  21765. If this is set to 0, then getFirstCommandTarget() will by default return the
  21766. result of findDefaultComponentTarget().
  21767. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  21768. deleting the target object.
  21769. */
  21770. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  21771. /** Tries to find the best target to use to perform a given command.
  21772. This will call getFirstCommandTarget() to find the preferred target, and will
  21773. check whether that target can handle the given command. If it can't, then it'll use
  21774. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  21775. so on until no more are available.
  21776. If no targets are found that can perform the command, this method will return 0.
  21777. If a target is found, then it will get the target to fill-in the upToDateInfo
  21778. structure with the latest info about that command, so that the caller can see
  21779. whether the command is disabled, ticked, etc.
  21780. */
  21781. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  21782. ApplicationCommandInfo& upToDateInfo);
  21783. /** Registers a listener that will be called when various events occur. */
  21784. void addListener (ApplicationCommandManagerListener* listener) throw();
  21785. /** Deregisters a previously-added listener. */
  21786. void removeListener (ApplicationCommandManagerListener* listener) throw();
  21787. /** Looks for a suitable command target based on which Components have the keyboard focus.
  21788. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  21789. but is exposed here in case it's useful.
  21790. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  21791. windows, etc., and using the findTargetForComponent() method.
  21792. */
  21793. static ApplicationCommandTarget* findDefaultComponentTarget();
  21794. /** Examines this component and all its parents in turn, looking for the first one
  21795. which is a ApplicationCommandTarget.
  21796. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  21797. that class.
  21798. */
  21799. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  21800. juce_UseDebuggingNewOperator
  21801. private:
  21802. OwnedArray <ApplicationCommandInfo> commands;
  21803. ListenerList <ApplicationCommandManagerListener> listeners;
  21804. ScopedPointer <KeyPressMappingSet> keyMappings;
  21805. ApplicationCommandTarget* firstTarget;
  21806. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  21807. void handleAsyncUpdate();
  21808. void globalFocusChanged (Component*);
  21809. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  21810. // version of this method.
  21811. virtual short getFirstCommandTarget() { return 0; }
  21812. ApplicationCommandManager (const ApplicationCommandManager&);
  21813. ApplicationCommandManager& operator= (const ApplicationCommandManager&);
  21814. };
  21815. /**
  21816. A listener that receives callbacks from an ApplicationCommandManager when
  21817. commands are invoked or the command list is changed.
  21818. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  21819. */
  21820. class JUCE_API ApplicationCommandManagerListener
  21821. {
  21822. public:
  21823. /** Destructor. */
  21824. virtual ~ApplicationCommandManagerListener() {}
  21825. /** Called when an app command is about to be invoked. */
  21826. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  21827. /** Called when commands are registered or deregistered from the
  21828. command manager, or when commands are made active or inactive.
  21829. Note that if you're using this to watch for changes to whether a command is disabled,
  21830. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  21831. whenever the status of your command might have changed.
  21832. */
  21833. virtual void applicationCommandListChanged() = 0;
  21834. };
  21835. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21836. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  21837. #endif
  21838. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21839. #endif
  21840. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21841. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  21842. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21843. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21844. /*** Start of inlined file: juce_PropertiesFile.h ***/
  21845. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  21846. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  21847. /** Wrapper on a file that stores a list of key/value data pairs.
  21848. Useful for storing application settings, etc. See the PropertySet class for
  21849. the interfaces that read and write values.
  21850. Not designed for very large amounts of data, as it keeps all the values in
  21851. memory and writes them out to disk lazily when they are changed.
  21852. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  21853. with it, and these will be signalled when a value changes.
  21854. @see PropertySet
  21855. */
  21856. class JUCE_API PropertiesFile : public PropertySet,
  21857. public ChangeBroadcaster,
  21858. private Timer
  21859. {
  21860. public:
  21861. enum FileFormatOptions
  21862. {
  21863. ignoreCaseOfKeyNames = 1,
  21864. storeAsBinary = 2,
  21865. storeAsCompressedBinary = 4,
  21866. storeAsXML = 8
  21867. };
  21868. /**
  21869. Creates a PropertiesFile object.
  21870. @param file the file to use
  21871. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  21872. is changed, the object will wait for this amount
  21873. of time and then save the file. If zero, the file
  21874. will be written to disk immediately on being changed
  21875. (which might be slow, as it'll re-write synchronously
  21876. each time a value-change method is called). If it is
  21877. less than zero, the file won't be saved until
  21878. save() or saveIfNeeded() are explicitly called.
  21879. @param optionFlags a combination of the flags in the FileFormatOptions
  21880. enum, which specify the type of file to save, and other
  21881. options.
  21882. @param processLock an optional InterprocessLock object that will be used to
  21883. prevent multiple threads or processes from writing to the file
  21884. at the same time. The PropertiesFile will keep a pointer to
  21885. this object but will not take ownership of it - the caller is
  21886. responsible for making sure that the lock doesn't get deleted
  21887. before the PropertiesFile has been deleted.
  21888. */
  21889. PropertiesFile (const File& file,
  21890. int millisecondsBeforeSaving,
  21891. int optionFlags,
  21892. InterProcessLock* processLock = 0);
  21893. /** Destructor.
  21894. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  21895. */
  21896. ~PropertiesFile();
  21897. /** Returns true if this file was created from a valid (or non-existent) file.
  21898. If the file failed to load correctly because it was corrupt or had insufficient
  21899. access, this will be false.
  21900. */
  21901. bool isValidFile() const throw() { return loadedOk; }
  21902. /** This will flush all the values to disk if they've changed since the last
  21903. time they were saved.
  21904. Returns false if it fails to write to the file for some reason (maybe because
  21905. it's read-only or the directory doesn't exist or something).
  21906. @see save
  21907. */
  21908. bool saveIfNeeded();
  21909. /** This will force a write-to-disk of the current values, regardless of whether
  21910. anything has changed since the last save.
  21911. Returns false if it fails to write to the file for some reason (maybe because
  21912. it's read-only or the directory doesn't exist or something).
  21913. @see saveIfNeeded
  21914. */
  21915. bool save();
  21916. /** Returns true if the properties have been altered since the last time they were saved.
  21917. The file is flagged as needing to be saved when you change a value, but you can
  21918. explicitly set this flag with setNeedsToBeSaved().
  21919. */
  21920. bool needsToBeSaved() const;
  21921. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  21922. @see needsToBeSaved
  21923. */
  21924. void setNeedsToBeSaved (bool needsToBeSaved);
  21925. /** Returns the file that's being used. */
  21926. const File getFile() const { return file; }
  21927. /** Handy utility to create a properties file in whatever the standard OS-specific
  21928. location is for these things.
  21929. This uses getDefaultAppSettingsFile() to decide what file to create, then
  21930. creates a PropertiesFile object with the specified properties. See
  21931. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  21932. what the parameters do.
  21933. @see getDefaultAppSettingsFile
  21934. */
  21935. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  21936. const String& fileNameSuffix,
  21937. const String& folderName,
  21938. bool commonToAllUsers,
  21939. int millisecondsBeforeSaving,
  21940. int propertiesFileOptions,
  21941. InterProcessLock* processLock = 0);
  21942. /** Handy utility to choose a file in the standard OS-dependent location for application
  21943. settings files.
  21944. So on a Mac, this will return a file called:
  21945. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  21946. On Windows it'll return something like:
  21947. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  21948. On Linux it'll return
  21949. ~/.[folderName]/[applicationName].[fileNameSuffix]
  21950. If you pass an empty string as the folder name, it'll use the app name for this (or
  21951. omit the folder name on the Mac).
  21952. If commonToAllUsers is true, then this will return the same file for all users of the
  21953. computer, regardless of the current user. If it is false, the file will be specific to
  21954. only the current user. Use this to choose whether you're saving settings that are common
  21955. or user-specific.
  21956. */
  21957. static const File getDefaultAppSettingsFile (const String& applicationName,
  21958. const String& fileNameSuffix,
  21959. const String& folderName,
  21960. bool commonToAllUsers);
  21961. juce_UseDebuggingNewOperator
  21962. protected:
  21963. virtual void propertyChanged();
  21964. private:
  21965. File file;
  21966. int timerInterval;
  21967. const int options;
  21968. bool loadedOk, needsWriting;
  21969. InterProcessLock* processLock;
  21970. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  21971. InterProcessLock::ScopedLockType* createProcessLock() const;
  21972. void timerCallback();
  21973. PropertiesFile (const PropertiesFile&);
  21974. PropertiesFile& operator= (const PropertiesFile&);
  21975. };
  21976. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  21977. /*** End of inlined file: juce_PropertiesFile.h ***/
  21978. /**
  21979. Manages a collection of properties.
  21980. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  21981. as a singleton.
  21982. It holds two different PropertiesFile objects internally, one for user-specific
  21983. settings (stored in your user directory), and one for settings that are common to
  21984. all users (stored in a folder accessible to all users).
  21985. The class manages the creation of these files on-demand, allowing access via the
  21986. getUserSettings() and getCommonSettings() methods. It also has a few handy
  21987. methods like testWriteAccess() to check that the files can be saved.
  21988. If you're using one of these as a singleton, then your app's start-up code should
  21989. first of all call setStorageParameters() to tell it the parameters to use to create
  21990. the properties files.
  21991. @see PropertiesFile
  21992. */
  21993. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  21994. {
  21995. public:
  21996. /**
  21997. Creates an ApplicationProperties object.
  21998. Before using it, you must call setStorageParameters() to give it the info
  21999. it needs to create the property files.
  22000. */
  22001. ApplicationProperties() throw();
  22002. /** Destructor.
  22003. */
  22004. ~ApplicationProperties();
  22005. juce_DeclareSingleton (ApplicationProperties, false)
  22006. /** Gives the object the information it needs to create the appropriate properties files.
  22007. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  22008. info about how these parameters are used.
  22009. */
  22010. void setStorageParameters (const String& applicationName,
  22011. const String& fileNameSuffix,
  22012. const String& folderName,
  22013. int millisecondsBeforeSaving,
  22014. int propertiesFileOptions) throw();
  22015. /** Tests whether the files can be successfully written to, and can show
  22016. an error message if not.
  22017. Returns true if none of the tests fail.
  22018. @param testUserSettings if true, the user settings file will be tested
  22019. @param testCommonSettings if true, the common settings file will be tested
  22020. @param showWarningDialogOnFailure if true, the method will show a helpful error
  22021. message box if either of the tests fail
  22022. */
  22023. bool testWriteAccess (bool testUserSettings,
  22024. bool testCommonSettings,
  22025. bool showWarningDialogOnFailure);
  22026. /** Returns the user settings file.
  22027. The first time this is called, it will create and load the properties file.
  22028. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  22029. the common settings are used as a second-chance place to look. This is done via the
  22030. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  22031. to the fallback for the user settings.
  22032. @see getCommonSettings
  22033. */
  22034. PropertiesFile* getUserSettings() throw();
  22035. /** Returns the common settings file.
  22036. The first time this is called, it will create and load the properties file.
  22037. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  22038. read-only (e.g. because the user doesn't have permission to write
  22039. to shared files), then this will return the user settings instead,
  22040. (like getUserSettings() would do). This is handy if you'd like to
  22041. write a value to the common settings, but if that's no possible,
  22042. then you'd rather write to the user settings than none at all.
  22043. If returnUserPropsIfReadOnly is false, this method will always return
  22044. the common settings, even if any changes to them can't be saved.
  22045. @see getUserSettings
  22046. */
  22047. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly) throw();
  22048. /** Saves both files if they need to be saved.
  22049. @see PropertiesFile::saveIfNeeded
  22050. */
  22051. bool saveIfNeeded();
  22052. /** Flushes and closes both files if they are open.
  22053. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  22054. and closes both files. They will then be re-opened the next time getUserSettings()
  22055. or getCommonSettings() is called.
  22056. */
  22057. void closeFiles();
  22058. juce_UseDebuggingNewOperator
  22059. private:
  22060. ScopedPointer <PropertiesFile> userProps, commonProps;
  22061. String appName, fileSuffix, folderName;
  22062. int msBeforeSaving, options;
  22063. int commonSettingsAreReadOnly;
  22064. ApplicationProperties (const ApplicationProperties&);
  22065. ApplicationProperties& operator= (const ApplicationProperties&);
  22066. void openFiles() throw();
  22067. };
  22068. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  22069. /*** End of inlined file: juce_ApplicationProperties.h ***/
  22070. #endif
  22071. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22072. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  22073. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22074. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22075. /*** Start of inlined file: juce_AudioFormat.h ***/
  22076. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  22077. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  22078. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  22079. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22080. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22081. class AudioFormat;
  22082. /**
  22083. Reads samples from an audio file stream.
  22084. A subclass that reads a specific type of audio format will be created by
  22085. an AudioFormat object.
  22086. @see AudioFormat, AudioFormatWriter
  22087. */
  22088. class JUCE_API AudioFormatReader
  22089. {
  22090. protected:
  22091. /** Creates an AudioFormatReader object.
  22092. @param sourceStream the stream to read from - this will be deleted
  22093. by this object when it is no longer needed. (Some
  22094. specialised readers might not use this parameter and
  22095. can leave it as 0).
  22096. @param formatName the description that will be returned by the getFormatName()
  22097. method
  22098. */
  22099. AudioFormatReader (InputStream* sourceStream,
  22100. const String& formatName);
  22101. public:
  22102. /** Destructor. */
  22103. virtual ~AudioFormatReader();
  22104. /** Returns a description of what type of format this is.
  22105. E.g. "AIFF"
  22106. */
  22107. const String getFormatName() const throw() { return formatName; }
  22108. /** Reads samples from the stream.
  22109. @param destSamples an array of buffers into which the sample data for each
  22110. channel will be written.
  22111. If the format is fixed-point, each channel will be written
  22112. as an array of 32-bit signed integers using the full
  22113. range -0x80000000 to 0x7fffffff, regardless of the source's
  22114. bit-depth. If it is a floating-point format, you should cast
  22115. the resulting array to a (float**) to get the values (in the
  22116. range -1.0 to 1.0 or beyond)
  22117. If the format is stereo, then destSamples[0] is the left channel
  22118. data, and destSamples[1] is the right channel.
  22119. The numDestChannels parameter indicates how many pointers this array
  22120. contains, but some of these pointers can be null if you don't want to
  22121. read data for some of the channels
  22122. @param numDestChannels the number of array elements in the destChannels array
  22123. @param startSampleInSource the position in the audio file or stream at which the samples
  22124. should be read, as a number of samples from the start of the
  22125. stream. It's ok for this to be beyond the start or end of the
  22126. available data - any samples that are out-of-range will be returned
  22127. as zeros.
  22128. @param numSamplesToRead the number of samples to read. If this is greater than the number
  22129. of samples that the file or stream contains. the result will be padded
  22130. with zeros
  22131. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  22132. for some of the channels that you pass in, then they should be filled with
  22133. copies of valid source channels.
  22134. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  22135. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  22136. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  22137. was false, then only the first channel would be filled with the file's contents, and
  22138. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  22139. from a stereo file, then the last 3 would all end up with copies of the same data.
  22140. @returns true if the operation succeeded, false if there was an error. Note
  22141. that reading sections of data beyond the extent of the stream isn't an
  22142. error - the reader should just return zeros for these regions
  22143. @see readMaxLevels
  22144. */
  22145. bool read (int** destSamples,
  22146. int numDestChannels,
  22147. int64 startSampleInSource,
  22148. int numSamplesToRead,
  22149. bool fillLeftoverChannelsWithCopies);
  22150. /** Finds the highest and lowest sample levels from a section of the audio stream.
  22151. This will read a block of samples from the stream, and measure the
  22152. highest and lowest sample levels from the channels in that section, returning
  22153. these as normalised floating-point levels.
  22154. @param startSample the offset into the audio stream to start reading from. It's
  22155. ok for this to be beyond the start or end of the stream.
  22156. @param numSamples how many samples to read
  22157. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  22158. @param highestLeft on return, this is the highest absolute sample from the left channel
  22159. @param lowestRight on return, this is the lowest absolute sample from the right
  22160. channel (if there is one)
  22161. @param highestRight on return, this is the highest absolute sample from the right
  22162. channel (if there is one)
  22163. @see read
  22164. */
  22165. virtual void readMaxLevels (int64 startSample,
  22166. int64 numSamples,
  22167. float& lowestLeft,
  22168. float& highestLeft,
  22169. float& lowestRight,
  22170. float& highestRight);
  22171. /** Scans the source looking for a sample whose magnitude is in a specified range.
  22172. This will read from the source, either forwards or backwards between two sample
  22173. positions, until it finds a sample whose magnitude lies between two specified levels.
  22174. If it finds a suitable sample, it returns its position; if not, it will return -1.
  22175. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  22176. points when you're searching for a continuous range of samples
  22177. @param startSample the first sample to look at
  22178. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  22179. the search will go backwards
  22180. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  22181. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  22182. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  22183. of this many consecutive samples, all of which lie
  22184. within the target range. When it finds such a sequence,
  22185. it returns the position of the first in-range sample
  22186. it found (i.e. the earliest one if scanning forwards, the
  22187. latest one if scanning backwards)
  22188. */
  22189. int64 searchForLevel (int64 startSample,
  22190. int64 numSamplesToSearch,
  22191. double magnitudeRangeMinimum,
  22192. double magnitudeRangeMaximum,
  22193. int minimumConsecutiveSamples);
  22194. /** The sample-rate of the stream. */
  22195. double sampleRate;
  22196. /** The number of bits per sample, e.g. 16, 24, 32. */
  22197. unsigned int bitsPerSample;
  22198. /** The total number of samples in the audio stream. */
  22199. int64 lengthInSamples;
  22200. /** The total number of channels in the audio stream. */
  22201. unsigned int numChannels;
  22202. /** Indicates whether the data is floating-point or fixed. */
  22203. bool usesFloatingPointData;
  22204. /** A set of metadata values that the reader has pulled out of the stream.
  22205. Exactly what these values are depends on the format, so you can
  22206. check out the format implementation code to see what kind of stuff
  22207. they understand.
  22208. */
  22209. StringPairArray metadataValues;
  22210. /** The input stream, for use by subclasses. */
  22211. InputStream* input;
  22212. /** Subclasses must implement this method to perform the low-level read operation.
  22213. Callers should use read() instead of calling this directly.
  22214. @param destSamples the array of destination buffers to fill. Some of these
  22215. pointers may be null
  22216. @param numDestChannels the number of items in the destSamples array. This
  22217. value is guaranteed not to be greater than the number of
  22218. channels that this reader object contains
  22219. @param startOffsetInDestBuffer the number of samples from the start of the
  22220. dest data at which to begin writing
  22221. @param startSampleInFile the number of samples into the source data at which
  22222. to begin reading. This value is guaranteed to be >= 0.
  22223. @param numSamples the number of samples to read
  22224. */
  22225. virtual bool readSamples (int** destSamples,
  22226. int numDestChannels,
  22227. int startOffsetInDestBuffer,
  22228. int64 startSampleInFile,
  22229. int numSamples) = 0;
  22230. juce_UseDebuggingNewOperator
  22231. private:
  22232. String formatName;
  22233. AudioFormatReader (const AudioFormatReader&);
  22234. AudioFormatReader& operator= (const AudioFormatReader&);
  22235. };
  22236. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22237. /*** End of inlined file: juce_AudioFormatReader.h ***/
  22238. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  22239. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22240. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22241. /*** Start of inlined file: juce_AudioSource.h ***/
  22242. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22243. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  22244. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  22245. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22246. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22247. class AudioFormatReader;
  22248. class AudioFormatWriter;
  22249. /**
  22250. A multi-channel buffer of 32-bit floating point audio samples.
  22251. */
  22252. class JUCE_API AudioSampleBuffer
  22253. {
  22254. public:
  22255. /** Creates a buffer with a specified number of channels and samples.
  22256. The contents of the buffer will initially be undefined, so use clear() to
  22257. set all the samples to zero.
  22258. The buffer will allocate its memory internally, and this will be released
  22259. when the buffer is deleted.
  22260. */
  22261. AudioSampleBuffer (int numChannels,
  22262. int numSamples) throw();
  22263. /** Creates a buffer using a pre-allocated block of memory.
  22264. Note that if the buffer is resized or its number of channels is changed, it
  22265. will re-allocate memory internally and copy the existing data to this new area,
  22266. so it will then stop directly addressing this memory.
  22267. @param dataToReferTo a pre-allocated array containing pointers to the data
  22268. for each channel that should be used by this buffer. The
  22269. buffer will only refer to this memory, it won't try to delete
  22270. it when the buffer is deleted or resized.
  22271. @param numChannels the number of channels to use - this must correspond to the
  22272. number of elements in the array passed in
  22273. @param numSamples the number of samples to use - this must correspond to the
  22274. size of the arrays passed in
  22275. */
  22276. AudioSampleBuffer (float** dataToReferTo,
  22277. int numChannels,
  22278. int numSamples) throw();
  22279. /** Copies another buffer.
  22280. This buffer will make its own copy of the other's data, unless the buffer was created
  22281. using an external data buffer, in which case boths buffers will just point to the same
  22282. shared block of data.
  22283. */
  22284. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  22285. /** Copies another buffer onto this one.
  22286. This buffer's size will be changed to that of the other buffer.
  22287. */
  22288. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  22289. /** Destructor.
  22290. This will free any memory allocated by the buffer.
  22291. */
  22292. virtual ~AudioSampleBuffer() throw();
  22293. /** Returns the number of channels of audio data that this buffer contains.
  22294. @see getSampleData
  22295. */
  22296. int getNumChannels() const throw() { return numChannels; }
  22297. /** Returns the number of samples allocated in each of the buffer's channels.
  22298. @see getSampleData
  22299. */
  22300. int getNumSamples() const throw() { return size; }
  22301. /** Returns a pointer one of the buffer's channels.
  22302. For speed, this doesn't check whether the channel number is out of range,
  22303. so be careful when using it!
  22304. */
  22305. float* getSampleData (const int channelNumber) const throw()
  22306. {
  22307. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  22308. return channels [channelNumber];
  22309. }
  22310. /** Returns a pointer to a sample in one of the buffer's channels.
  22311. For speed, this doesn't check whether the channel and sample number
  22312. are out-of-range, so be careful when using it!
  22313. */
  22314. float* getSampleData (const int channelNumber,
  22315. const int sampleOffset) const throw()
  22316. {
  22317. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  22318. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  22319. return channels [channelNumber] + sampleOffset;
  22320. }
  22321. /** Returns an array of pointers to the channels in the buffer.
  22322. Don't modify any of the pointers that are returned, and bear in mind that
  22323. these will become invalid if the buffer is resized.
  22324. */
  22325. float** getArrayOfChannels() const throw() { return channels; }
  22326. /** Chages the buffer's size or number of channels.
  22327. This can expand or contract the buffer's length, and add or remove channels.
  22328. If keepExistingContent is true, it will try to preserve as much of the
  22329. old data as it can in the new buffer.
  22330. If clearExtraSpace is true, then any extra channels or space that is
  22331. allocated will be also be cleared. If false, then this space is left
  22332. uninitialised.
  22333. If avoidReallocating is true, then changing the buffer's size won't reduce the
  22334. amount of memory that is currently allocated (but it will still increase it if
  22335. the new size is bigger than the amount it currently has). If this is false, then
  22336. a new allocation will be done so that the buffer uses takes up the minimum amount
  22337. of memory that it needs.
  22338. */
  22339. void setSize (int newNumChannels,
  22340. int newNumSamples,
  22341. bool keepExistingContent = false,
  22342. bool clearExtraSpace = false,
  22343. bool avoidReallocating = false) throw();
  22344. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  22345. There's also a constructor that lets you specify arrays like this, but this
  22346. lets you change the channels dynamically.
  22347. Note that if the buffer is resized or its number of channels is changed, it
  22348. will re-allocate memory internally and copy the existing data to this new area,
  22349. so it will then stop directly addressing this memory.
  22350. @param dataToReferTo a pre-allocated array containing pointers to the data
  22351. for each channel that should be used by this buffer. The
  22352. buffer will only refer to this memory, it won't try to delete
  22353. it when the buffer is deleted or resized.
  22354. @param numChannels the number of channels to use - this must correspond to the
  22355. number of elements in the array passed in
  22356. @param numSamples the number of samples to use - this must correspond to the
  22357. size of the arrays passed in
  22358. */
  22359. void setDataToReferTo (float** dataToReferTo,
  22360. int numChannels,
  22361. int numSamples) throw();
  22362. /** Clears all the samples in all channels. */
  22363. void clear() throw();
  22364. /** Clears a specified region of all the channels.
  22365. For speed, this doesn't check whether the channel and sample number
  22366. are in-range, so be careful!
  22367. */
  22368. void clear (int startSample,
  22369. int numSamples) throw();
  22370. /** Clears a specified region of just one channel.
  22371. For speed, this doesn't check whether the channel and sample number
  22372. are in-range, so be careful!
  22373. */
  22374. void clear (int channel,
  22375. int startSample,
  22376. int numSamples) throw();
  22377. /** Applies a gain multiple to a region of one channel.
  22378. For speed, this doesn't check whether the channel and sample number
  22379. are in-range, so be careful!
  22380. */
  22381. void applyGain (int channel,
  22382. int startSample,
  22383. int numSamples,
  22384. float gain) throw();
  22385. /** Applies a gain multiple to a region of all the channels.
  22386. For speed, this doesn't check whether the sample numbers
  22387. are in-range, so be careful!
  22388. */
  22389. void applyGain (int startSample,
  22390. int numSamples,
  22391. float gain) throw();
  22392. /** Applies a range of gains to a region of a channel.
  22393. The gain that is applied to each sample will vary from
  22394. startGain on the first sample to endGain on the last Sample,
  22395. so it can be used to do basic fades.
  22396. For speed, this doesn't check whether the sample numbers
  22397. are in-range, so be careful!
  22398. */
  22399. void applyGainRamp (int channel,
  22400. int startSample,
  22401. int numSamples,
  22402. float startGain,
  22403. float endGain) throw();
  22404. /** Adds samples from another buffer to this one.
  22405. @param destChannel the channel within this buffer to add the samples to
  22406. @param destStartSample the start sample within this buffer's channel
  22407. @param source the source buffer to add from
  22408. @param sourceChannel the channel within the source buffer to read from
  22409. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22410. @param numSamples the number of samples to process
  22411. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22412. added to this buffer's samples
  22413. @see copyFrom
  22414. */
  22415. void addFrom (int destChannel,
  22416. int destStartSample,
  22417. const AudioSampleBuffer& source,
  22418. int sourceChannel,
  22419. int sourceStartSample,
  22420. int numSamples,
  22421. float gainToApplyToSource = 1.0f) throw();
  22422. /** Adds samples from an array of floats to one of the channels.
  22423. @param destChannel the channel within this buffer to add the samples to
  22424. @param destStartSample the start sample within this buffer's channel
  22425. @param source the source data to use
  22426. @param numSamples the number of samples to process
  22427. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22428. added to this buffer's samples
  22429. @see copyFrom
  22430. */
  22431. void addFrom (int destChannel,
  22432. int destStartSample,
  22433. const float* source,
  22434. int numSamples,
  22435. float gainToApplyToSource = 1.0f) throw();
  22436. /** Adds samples from an array of floats, applying a gain ramp to them.
  22437. @param destChannel the channel within this buffer to add the samples to
  22438. @param destStartSample the start sample within this buffer's channel
  22439. @param source the source data to use
  22440. @param numSamples the number of samples to process
  22441. @param startGain the gain to apply to the first sample (this is multiplied with
  22442. the source samples before they are added to this buffer)
  22443. @param endGain the gain to apply to the final sample. The gain is linearly
  22444. interpolated between the first and last samples.
  22445. */
  22446. void addFromWithRamp (int destChannel,
  22447. int destStartSample,
  22448. const float* source,
  22449. int numSamples,
  22450. float startGain,
  22451. float endGain) throw();
  22452. /** Copies samples from another buffer to this one.
  22453. @param destChannel the channel within this buffer to copy the samples to
  22454. @param destStartSample the start sample within this buffer's channel
  22455. @param source the source buffer to read from
  22456. @param sourceChannel the channel within the source buffer to read from
  22457. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22458. @param numSamples the number of samples to process
  22459. @see addFrom
  22460. */
  22461. void copyFrom (int destChannel,
  22462. int destStartSample,
  22463. const AudioSampleBuffer& source,
  22464. int sourceChannel,
  22465. int sourceStartSample,
  22466. int numSamples) throw();
  22467. /** Copies samples from an array of floats into one of the channels.
  22468. @param destChannel the channel within this buffer to copy the samples to
  22469. @param destStartSample the start sample within this buffer's channel
  22470. @param source the source buffer to read from
  22471. @param numSamples the number of samples to process
  22472. @see addFrom
  22473. */
  22474. void copyFrom (int destChannel,
  22475. int destStartSample,
  22476. const float* source,
  22477. int numSamples) throw();
  22478. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  22479. @param destChannel the channel within this buffer to copy the samples to
  22480. @param destStartSample the start sample within this buffer's channel
  22481. @param source the source buffer to read from
  22482. @param numSamples the number of samples to process
  22483. @param gain the gain to apply
  22484. @see addFrom
  22485. */
  22486. void copyFrom (int destChannel,
  22487. int destStartSample,
  22488. const float* source,
  22489. int numSamples,
  22490. float gain) throw();
  22491. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  22492. @param destChannel the channel within this buffer to copy the samples to
  22493. @param destStartSample the start sample within this buffer's channel
  22494. @param source the source buffer to read from
  22495. @param numSamples the number of samples to process
  22496. @param startGain the gain to apply to the first sample (this is multiplied with
  22497. the source samples before they are copied to this buffer)
  22498. @param endGain the gain to apply to the final sample. The gain is linearly
  22499. interpolated between the first and last samples.
  22500. @see addFrom
  22501. */
  22502. void copyFromWithRamp (int destChannel,
  22503. int destStartSample,
  22504. const float* source,
  22505. int numSamples,
  22506. float startGain,
  22507. float endGain) throw();
  22508. /** Finds the highest and lowest sample values in a given range.
  22509. @param channel the channel to read from
  22510. @param startSample the start sample within the channel
  22511. @param numSamples the number of samples to check
  22512. @param minVal on return, the lowest value that was found
  22513. @param maxVal on return, the highest value that was found
  22514. */
  22515. void findMinMax (int channel,
  22516. int startSample,
  22517. int numSamples,
  22518. float& minVal,
  22519. float& maxVal) const throw();
  22520. /** Finds the highest absolute sample value within a region of a channel.
  22521. */
  22522. float getMagnitude (int channel,
  22523. int startSample,
  22524. int numSamples) const throw();
  22525. /** Finds the highest absolute sample value within a region on all channels.
  22526. */
  22527. float getMagnitude (int startSample,
  22528. int numSamples) const throw();
  22529. /** Returns the root mean squared level for a region of a channel.
  22530. */
  22531. float getRMSLevel (int channel,
  22532. int startSample,
  22533. int numSamples) const throw();
  22534. /** Fills a section of the buffer using an AudioReader as its source.
  22535. This will convert the reader's fixed- or floating-point data to
  22536. the buffer's floating-point format, and will try to intelligently
  22537. cope with mismatches between the number of channels in the reader
  22538. and the buffer.
  22539. @see writeToAudioWriter
  22540. */
  22541. void readFromAudioReader (AudioFormatReader* reader,
  22542. int startSample,
  22543. int numSamples,
  22544. int readerStartSample,
  22545. bool useReaderLeftChan,
  22546. bool useReaderRightChan);
  22547. /** Writes a section of this buffer to an audio writer.
  22548. This saves you having to mess about with channels or floating/fixed
  22549. point conversion.
  22550. @see readFromAudioReader
  22551. */
  22552. void writeToAudioWriter (AudioFormatWriter* writer,
  22553. int startSample,
  22554. int numSamples) const;
  22555. juce_UseDebuggingNewOperator
  22556. private:
  22557. int numChannels, size;
  22558. size_t allocatedBytes;
  22559. float** channels;
  22560. HeapBlock <char> allocatedData;
  22561. float* preallocatedChannelSpace [32];
  22562. void allocateData();
  22563. void allocateChannels (float** dataToReferTo);
  22564. };
  22565. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22566. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  22567. /**
  22568. Used by AudioSource::getNextAudioBlock().
  22569. */
  22570. struct JUCE_API AudioSourceChannelInfo
  22571. {
  22572. /** The destination buffer to fill with audio data.
  22573. When the AudioSource::getNextAudioBlock() method is called, the active section
  22574. of this buffer should be filled with whatever output the source produces.
  22575. Only the samples specified by the startSample and numSamples members of this structure
  22576. should be affected by the call.
  22577. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22578. method can be treated as the input if the source is performing some kind of filter operation,
  22579. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22580. a handy way of doing this.
  22581. The number of channels in the buffer could be anything, so the AudioSource
  22582. must cope with this in whatever way is appropriate for its function.
  22583. */
  22584. AudioSampleBuffer* buffer;
  22585. /** The first sample in the buffer from which the callback is expected
  22586. to write data. */
  22587. int startSample;
  22588. /** The number of samples in the buffer which the callback is expected to
  22589. fill with data. */
  22590. int numSamples;
  22591. /** Convenient method to clear the buffer if the source is not producing any data. */
  22592. void clearActiveBufferRegion() const
  22593. {
  22594. if (buffer != 0)
  22595. buffer->clear (startSample, numSamples);
  22596. }
  22597. };
  22598. /**
  22599. Base class for objects that can produce a continuous stream of audio.
  22600. @see AudioFormatReaderSource, ResamplingAudioSource
  22601. */
  22602. class JUCE_API AudioSource
  22603. {
  22604. protected:
  22605. /** Creates an AudioSource. */
  22606. AudioSource() throw() {}
  22607. public:
  22608. /** Destructor. */
  22609. virtual ~AudioSource() {}
  22610. /** Tells the source to prepare for playing.
  22611. The source can use this opportunity to initialise anything it needs to.
  22612. Note that this method could be called more than once in succession without
  22613. a matching call to releaseResources(), so make sure your code is robust and
  22614. can handle that kind of situation.
  22615. @param samplesPerBlockExpected the number of samples that the source
  22616. will be expected to supply each time its
  22617. getNextAudioBlock() method is called. This
  22618. number may vary slightly, because it will be dependent
  22619. on audio hardware callbacks, and these aren't
  22620. guaranteed to always use a constant block size, so
  22621. the source should be able to cope with small variations.
  22622. @param sampleRate the sample rate that the output will be used at - this
  22623. is needed by sources such as tone generators.
  22624. @see releaseResources, getNextAudioBlock
  22625. */
  22626. virtual void prepareToPlay (int samplesPerBlockExpected,
  22627. double sampleRate) = 0;
  22628. /** Allows the source to release anything it no longer needs after playback has stopped.
  22629. This will be called when the source is no longer going to have its getNextAudioBlock()
  22630. method called, so it should release any spare memory, etc. that it might have
  22631. allocated during the prepareToPlay() call.
  22632. Note that there's no guarantee that prepareToPlay() will actually have been called before
  22633. releaseResources(), and it may be called more than once in succession, so make sure your
  22634. code is robust and doesn't make any assumptions about when it will be called.
  22635. @see prepareToPlay, getNextAudioBlock
  22636. */
  22637. virtual void releaseResources() = 0;
  22638. /** Called repeatedly to fetch subsequent blocks of audio data.
  22639. After calling the prepareToPlay() method, this callback will be made each
  22640. time the audio playback hardware (or whatever other destination the audio
  22641. data is going to) needs another block of data.
  22642. It will generally be called on a high-priority system thread, or possibly even
  22643. an interrupt, so be careful not to do too much work here, as that will cause
  22644. audio glitches!
  22645. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  22646. */
  22647. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  22648. };
  22649. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  22650. /*** End of inlined file: juce_AudioSource.h ***/
  22651. /**
  22652. Writes samples to an audio file stream.
  22653. A subclass that writes a specific type of audio format will be created by
  22654. an AudioFormat object.
  22655. After creating one of these with the AudioFormat::createWriterFor() method
  22656. you can call its write() method to store the samples, and then delete it.
  22657. @see AudioFormat, AudioFormatReader
  22658. */
  22659. class JUCE_API AudioFormatWriter
  22660. {
  22661. protected:
  22662. /** Creates an AudioFormatWriter object.
  22663. @param destStream the stream to write to - this will be deleted
  22664. by this object when it is no longer needed
  22665. @param formatName the description that will be returned by the getFormatName()
  22666. method
  22667. @param sampleRate the sample rate to use - the base class just stores
  22668. this value, it doesn't do anything with it
  22669. @param numberOfChannels the number of channels to write - the base class just stores
  22670. this value, it doesn't do anything with it
  22671. @param bitsPerSample the bit depth of the stream - the base class just stores
  22672. this value, it doesn't do anything with it
  22673. */
  22674. AudioFormatWriter (OutputStream* destStream,
  22675. const String& formatName,
  22676. double sampleRate,
  22677. unsigned int numberOfChannels,
  22678. unsigned int bitsPerSample);
  22679. public:
  22680. /** Destructor. */
  22681. virtual ~AudioFormatWriter();
  22682. /** Returns a description of what type of format this is.
  22683. E.g. "AIFF file"
  22684. */
  22685. const String getFormatName() const throw() { return formatName; }
  22686. /** Writes a set of samples to the audio stream.
  22687. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  22688. can use AudioSampleBuffer::writeToAudioWriter().
  22689. @param samplesToWrite an array of arrays containing the sample data for
  22690. each channel to write. This is a zero-terminated
  22691. array of arrays, and can contain a different number
  22692. of channels than the actual stream uses, and the
  22693. writer should do its best to cope with this.
  22694. If the format is fixed-point, each channel will be formatted
  22695. as an array of signed integers using the full 32-bit
  22696. range -0x80000000 to 0x7fffffff, regardless of the source's
  22697. bit-depth. If it is a floating-point format, you should treat
  22698. the arrays as arrays of floats, and just cast it to an (int**)
  22699. to pass it into the method.
  22700. @param numSamples the number of samples to write
  22701. */
  22702. virtual bool write (const int** samplesToWrite,
  22703. int numSamples) = 0;
  22704. /** Reads a section of samples from an AudioFormatReader, and writes these to
  22705. the output.
  22706. This will take care of any floating-point conversion that's required to convert
  22707. between the two formats. It won't deal with sample-rate conversion, though.
  22708. If numSamplesToRead < 0, it will write the entire length of the reader.
  22709. @returns false if it can't read or write properly during the operation
  22710. */
  22711. bool writeFromAudioReader (AudioFormatReader& reader,
  22712. int64 startSample,
  22713. int64 numSamplesToRead);
  22714. /** Reads some samples from an AudioSource, and writes these to the output.
  22715. The source must already have been initialised with the AudioSource::prepareToPlay() method
  22716. @param source the source to read from
  22717. @param numSamplesToRead total number of samples to read and write
  22718. @param samplesPerBlock the maximum number of samples to fetch from the source
  22719. @returns false if it can't read or write properly during the operation
  22720. */
  22721. bool writeFromAudioSource (AudioSource& source,
  22722. int numSamplesToRead,
  22723. int samplesPerBlock = 2048);
  22724. /** Returns the sample rate being used. */
  22725. double getSampleRate() const throw() { return sampleRate; }
  22726. /** Returns the number of channels being written. */
  22727. int getNumChannels() const throw() { return numChannels; }
  22728. /** Returns the bit-depth of the data being written. */
  22729. int getBitsPerSample() const throw() { return bitsPerSample; }
  22730. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  22731. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  22732. juce_UseDebuggingNewOperator
  22733. protected:
  22734. /** The sample rate of the stream. */
  22735. double sampleRate;
  22736. /** The number of channels being written to the stream. */
  22737. unsigned int numChannels;
  22738. /** The bit depth of the file. */
  22739. unsigned int bitsPerSample;
  22740. /** True if it's a floating-point format, false if it's fixed-point. */
  22741. bool usesFloatingPointData;
  22742. /** The output stream for Use by subclasses. */
  22743. OutputStream* output;
  22744. private:
  22745. String formatName;
  22746. AudioFormatWriter (const AudioFormatWriter&);
  22747. AudioFormatWriter& operator= (const AudioFormatWriter&);
  22748. };
  22749. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22750. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  22751. /**
  22752. Subclasses of AudioFormat are used to read and write different audio
  22753. file formats.
  22754. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  22755. */
  22756. class JUCE_API AudioFormat
  22757. {
  22758. public:
  22759. /** Destructor. */
  22760. virtual ~AudioFormat();
  22761. /** Returns the name of this format.
  22762. e.g. "WAV file" or "AIFF file"
  22763. */
  22764. const String& getFormatName() const;
  22765. /** Returns all the file extensions that might apply to a file of this format.
  22766. The first item will be the one that's preferred when creating a new file.
  22767. So for a wav file this might just return ".wav"; for an AIFF file it might
  22768. return two items, ".aif" and ".aiff"
  22769. */
  22770. const StringArray& getFileExtensions() const;
  22771. /** Returns true if this the given file can be read by this format.
  22772. Subclasses shouldn't do too much work here, just check the extension or
  22773. file type. The base class implementation just checks the file's extension
  22774. against one of the ones that was registered in the constructor.
  22775. */
  22776. virtual bool canHandleFile (const File& fileToTest);
  22777. /** Returns a set of sample rates that the format can read and write. */
  22778. virtual const Array <int> getPossibleSampleRates() = 0;
  22779. /** Returns a set of bit depths that the format can read and write. */
  22780. virtual const Array <int> getPossibleBitDepths() = 0;
  22781. /** Returns true if the format can do 2-channel audio. */
  22782. virtual bool canDoStereo() = 0;
  22783. /** Returns true if the format can do 1-channel audio. */
  22784. virtual bool canDoMono() = 0;
  22785. /** Returns true if the format uses compressed data. */
  22786. virtual bool isCompressed();
  22787. /** Returns a list of different qualities that can be used when writing.
  22788. Non-compressed formats will just return an empty array, but for something
  22789. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  22790. When calling createWriterFor(), an index from this array is passed in to
  22791. tell the format which option is required.
  22792. */
  22793. virtual const StringArray getQualityOptions();
  22794. /** Tries to create an object that can read from a stream containing audio
  22795. data in this format.
  22796. The reader object that is returned can be used to read from the stream, and
  22797. should then be deleted by the caller.
  22798. @param sourceStream the stream to read from - the AudioFormatReader object
  22799. that is returned will delete this stream when it no longer
  22800. needs it.
  22801. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  22802. should delete the stream object that was passed-in. (If a valid
  22803. reader is returned, it will always be in charge of deleting the
  22804. stream, so this parameter is ignored)
  22805. @see AudioFormatReader
  22806. */
  22807. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22808. const bool deleteStreamIfOpeningFails) = 0;
  22809. /** Tries to create an object that can write to a stream with this audio format.
  22810. The writer object that is returned can be used to write to the stream, and
  22811. should then be deleted by the caller.
  22812. If the stream can't be created for some reason (e.g. the parameters passed in
  22813. here aren't suitable), this will return 0.
  22814. @param streamToWriteTo the stream that the data will go to - this will be
  22815. deleted by the AudioFormatWriter object when it's no longer
  22816. needed. If no AudioFormatWriter can be created by this method,
  22817. the stream will NOT be deleted, so that the caller can re-use it
  22818. to try to open a different format, etc
  22819. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  22820. returned by getPossibleSampleRates()
  22821. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  22822. the choice will depend on the results of canDoMono() and
  22823. canDoStereo()
  22824. @param bitsPerSample the bits per sample to use - this must be one of the values
  22825. returned by getPossibleBitDepths()
  22826. @param metadataValues a set of metadata values that the writer should try to write
  22827. to the stream. Exactly what these are depends on the format,
  22828. and the subclass doesn't actually have to do anything with
  22829. them if it doesn't want to. Have a look at the specific format
  22830. implementation classes to see possible values that can be
  22831. used
  22832. @param qualityOptionIndex the index of one of compression qualities returned by the
  22833. getQualityOptions() method. If there aren't any quality options
  22834. for this format, just pass 0 in this parameter, as it'll be
  22835. ignored
  22836. @see AudioFormatWriter
  22837. */
  22838. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22839. double sampleRateToUse,
  22840. unsigned int numberOfChannels,
  22841. int bitsPerSample,
  22842. const StringPairArray& metadataValues,
  22843. int qualityOptionIndex) = 0;
  22844. protected:
  22845. /** Creates an AudioFormat object.
  22846. @param formatName this sets the value that will be returned by getFormatName()
  22847. @param fileExtensions a zero-terminated list of file extensions - this is what will
  22848. be returned by getFileExtension()
  22849. */
  22850. AudioFormat (const String& formatName,
  22851. const StringArray& fileExtensions);
  22852. private:
  22853. String formatName;
  22854. StringArray fileExtensions;
  22855. };
  22856. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  22857. /*** End of inlined file: juce_AudioFormat.h ***/
  22858. /**
  22859. Reads and Writes AIFF format audio files.
  22860. @see AudioFormat
  22861. */
  22862. class JUCE_API AiffAudioFormat : public AudioFormat
  22863. {
  22864. public:
  22865. /** Creates an format object. */
  22866. AiffAudioFormat();
  22867. /** Destructor. */
  22868. ~AiffAudioFormat();
  22869. const Array <int> getPossibleSampleRates();
  22870. const Array <int> getPossibleBitDepths();
  22871. bool canDoStereo();
  22872. bool canDoMono();
  22873. #if JUCE_MAC
  22874. bool canHandleFile (const File& fileToTest);
  22875. #endif
  22876. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22877. const bool deleteStreamIfOpeningFails);
  22878. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22879. double sampleRateToUse,
  22880. unsigned int numberOfChannels,
  22881. int bitsPerSample,
  22882. const StringPairArray& metadataValues,
  22883. int qualityOptionIndex);
  22884. juce_UseDebuggingNewOperator
  22885. };
  22886. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22887. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  22888. #endif
  22889. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22890. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  22891. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22892. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22893. #if JUCE_USE_CDBURNER || DOXYGEN
  22894. /**
  22895. */
  22896. class AudioCDBurner : public ChangeBroadcaster
  22897. {
  22898. public:
  22899. /** Returns a list of available optical drives.
  22900. Use openDevice() to open one of the items from this list.
  22901. */
  22902. static const StringArray findAvailableDevices();
  22903. /** Tries to open one of the optical drives.
  22904. The deviceIndex is an index into the array returned by findAvailableDevices().
  22905. */
  22906. static AudioCDBurner* openDevice (const int deviceIndex);
  22907. /** Destructor. */
  22908. ~AudioCDBurner();
  22909. enum DiskState
  22910. {
  22911. unknown, /**< An error condition, if the device isn't responding. */
  22912. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  22913. may seem to be permanently open. */
  22914. noDisc, /**< The drive has no disk in it. */
  22915. writableDiskPresent, /**< The drive contains a writeable disk. */
  22916. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  22917. };
  22918. /** Returns the current status of the device.
  22919. To get informed when the drive's status changes, attach a ChangeListener to
  22920. the AudioCDBurner.
  22921. */
  22922. DiskState getDiskState() const;
  22923. /** Returns true if there's a writable disk in the drive. */
  22924. bool isDiskPresent() const;
  22925. /** Sends an eject signal to the drive.
  22926. The eject will happen asynchronously, so you can use getDiskState() and
  22927. waitUntilStateChange() to monitor its progress.
  22928. */
  22929. bool openTray();
  22930. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  22931. @returns the device's new state
  22932. */
  22933. DiskState waitUntilStateChange (int timeOutMilliseconds);
  22934. /** Returns the set of possible write speeds that the device can handle.
  22935. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  22936. Note that if there's no media present in the drive, this value may be unavailable!
  22937. @see setWriteSpeed, getWriteSpeed
  22938. */
  22939. const Array<int> getAvailableWriteSpeeds() const;
  22940. /** Tries to enable or disable buffer underrun safety on devices that support it.
  22941. @returns true if it's now enabled. If the device doesn't support it, this
  22942. will always return false.
  22943. */
  22944. bool setBufferUnderrunProtection (const bool shouldBeEnabled);
  22945. /** Returns the number of free blocks on the disk.
  22946. There are 75 blocks per second, at 44100Hz.
  22947. */
  22948. int getNumAvailableAudioBlocks() const;
  22949. /** Adds a track to be written.
  22950. The source passed-in here will be kept by this object, and it will
  22951. be used and deleted at some point in the future, either during the
  22952. burn() method or when this AudioCDBurner object is deleted. Your caller
  22953. method shouldn't keep a reference to it or use it again after passing
  22954. it in here.
  22955. */
  22956. bool addAudioTrack (AudioSource* source, int numSamples);
  22957. /** Receives progress callbacks during a cd-burn operation.
  22958. @see AudioCDBurner::burn()
  22959. */
  22960. class BurnProgressListener
  22961. {
  22962. public:
  22963. BurnProgressListener() throw() {}
  22964. virtual ~BurnProgressListener() {}
  22965. /** Called at intervals to report on the progress of the AudioCDBurner.
  22966. To cancel the burn, return true from this method.
  22967. */
  22968. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  22969. };
  22970. /** Runs the burn process.
  22971. This method will block until the operation is complete.
  22972. @param listener the object to receive callbacks about progress
  22973. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  22974. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  22975. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  22976. 0 or less to mean the fastest speed.
  22977. */
  22978. const String burn (BurnProgressListener* listener,
  22979. bool ejectDiscAfterwards,
  22980. bool performFakeBurnForTesting,
  22981. int writeSpeed);
  22982. /** If a burn operation is currently in progress, this tells it to stop
  22983. as soon as possible.
  22984. It's also possible to stop the burn process by returning true from
  22985. BurnProgressListener::audioCDBurnProgress()
  22986. */
  22987. void abortBurn();
  22988. juce_UseDebuggingNewOperator
  22989. private:
  22990. AudioCDBurner (const int deviceIndex);
  22991. class Pimpl;
  22992. friend class ScopedPointer<Pimpl>;
  22993. ScopedPointer<Pimpl> pimpl;
  22994. };
  22995. #endif
  22996. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22997. /*** End of inlined file: juce_AudioCDBurner.h ***/
  22998. #endif
  22999. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  23000. /*** Start of inlined file: juce_AudioCDReader.h ***/
  23001. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  23002. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  23003. #if JUCE_USE_CDREADER || DOXYGEN
  23004. #if JUCE_MAC
  23005. #endif
  23006. /**
  23007. A type of AudioFormatReader that reads from an audio CD.
  23008. One of these can be used to read a CD as if it's one big audio stream. Use the
  23009. getPositionOfTrackStart() method to find where the individual tracks are
  23010. within the stream.
  23011. @see AudioFormatReader
  23012. */
  23013. class JUCE_API AudioCDReader : public AudioFormatReader
  23014. {
  23015. public:
  23016. /** Returns a list of names of Audio CDs currently available for reading.
  23017. If there's a CD drive but no CD in it, this might return an empty list, or
  23018. possibly a device that can be opened but which has no tracks, depending
  23019. on the platform.
  23020. @see createReaderForCD
  23021. */
  23022. static const StringArray getAvailableCDNames();
  23023. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  23024. @param index the index of one of the available CDs - use getAvailableCDNames()
  23025. to find out how many there are.
  23026. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  23027. caller will be responsible for deleting the object returned.
  23028. */
  23029. static AudioCDReader* createReaderForCD (const int index);
  23030. /** Destructor. */
  23031. ~AudioCDReader();
  23032. /** Implementation of the AudioFormatReader method. */
  23033. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  23034. int64 startSampleInFile, int numSamples);
  23035. /** Checks whether the CD has been removed from the drive.
  23036. */
  23037. bool isCDStillPresent() const;
  23038. /** Returns the total number of tracks (audio + data).
  23039. */
  23040. int getNumTracks() const;
  23041. /** Finds the sample offset of the start of a track.
  23042. @param trackNum the track number, where 0 is the first track.
  23043. */
  23044. int getPositionOfTrackStart (int trackNum) const;
  23045. /** Returns true if a given track is an audio track.
  23046. @param trackNum the track number, where 0 is the first track.
  23047. */
  23048. bool isTrackAudio (int trackNum) const;
  23049. /** Refreshes the object's table of contents.
  23050. If the disc has been ejected and a different one put in since this
  23051. object was created, this will cause it to update its idea of how many tracks
  23052. there are, etc.
  23053. */
  23054. void refreshTrackLengths();
  23055. /** Enables scanning for indexes within tracks.
  23056. @see getLastIndex
  23057. */
  23058. void enableIndexScanning (bool enabled);
  23059. /** Returns the index number found during the last read() call.
  23060. Index scanning is turned off by default - turn it on with enableIndexScanning().
  23061. Then when the read() method is called, if it comes across an index within that
  23062. block, the index number is stored and returned by this method.
  23063. Some devices might not support indexes, of course.
  23064. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  23065. @see enableIndexScanning
  23066. */
  23067. int getLastIndex() const;
  23068. /** Scans a track to find the position of any indexes within it.
  23069. @param trackNumber the track to look in, where 0 is the first track on the disc
  23070. @returns an array of sample positions of any index points found (not including
  23071. the index that marks the start of the track)
  23072. */
  23073. const Array <int> findIndexesInTrack (const int trackNumber);
  23074. /** Returns the CDDB id number for the CD.
  23075. It's not a great way of identifying a disc, but it's traditional.
  23076. */
  23077. int getCDDBId();
  23078. /** Tries to eject the disk.
  23079. Of course this might not be possible, if some other process is using it.
  23080. */
  23081. void ejectDisk();
  23082. juce_UseDebuggingNewOperator
  23083. private:
  23084. #if JUCE_MAC
  23085. File volumeDir;
  23086. Array<File> tracks;
  23087. Array<int> trackStartSamples;
  23088. int currentReaderTrack;
  23089. ScopedPointer <AudioFormatReader> reader;
  23090. AudioCDReader (const File& volume);
  23091. public:
  23092. static int compareElements (const File&, const File&);
  23093. private:
  23094. #elif JUCE_WINDOWS
  23095. int numTracks;
  23096. int trackStarts[100];
  23097. bool audioTracks [100];
  23098. void* handle;
  23099. bool indexingEnabled;
  23100. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  23101. MemoryBlock buffer;
  23102. AudioCDReader (void* handle);
  23103. int getIndexAt (int samplePos);
  23104. #elif JUCE_LINUX
  23105. AudioCDReader();
  23106. #endif
  23107. AudioCDReader (const AudioCDReader&);
  23108. AudioCDReader& operator= (const AudioCDReader&);
  23109. };
  23110. #endif
  23111. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  23112. /*** End of inlined file: juce_AudioCDReader.h ***/
  23113. #endif
  23114. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  23115. #endif
  23116. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23117. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  23118. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23119. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23120. /**
  23121. A class for keeping a list of available audio formats, and for deciding which
  23122. one to use to open a given file.
  23123. You can either use this class as a singleton object, or create instances of it
  23124. yourself. Once created, use its registerFormat() method to tell it which
  23125. formats it should use.
  23126. @see AudioFormat
  23127. */
  23128. class JUCE_API AudioFormatManager
  23129. {
  23130. public:
  23131. /** Creates an empty format manager.
  23132. Before it'll be any use, you'll need to call registerFormat() with all the
  23133. formats you want it to be able to recognise.
  23134. */
  23135. AudioFormatManager();
  23136. /** Destructor. */
  23137. ~AudioFormatManager();
  23138. juce_DeclareSingleton (AudioFormatManager, false);
  23139. /** Adds a format to the manager's list of available file types.
  23140. The object passed-in will be deleted by this object, so don't keep a pointer
  23141. to it!
  23142. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  23143. return this one when called.
  23144. */
  23145. void registerFormat (AudioFormat* newFormat,
  23146. bool makeThisTheDefaultFormat);
  23147. /** Handy method to make it easy to register the formats that come with Juce.
  23148. Currently, this will add WAV and AIFF to the list.
  23149. */
  23150. void registerBasicFormats();
  23151. /** Clears the list of known formats. */
  23152. void clearFormats();
  23153. /** Returns the number of currently registered file formats. */
  23154. int getNumKnownFormats() const;
  23155. /** Returns one of the registered file formats. */
  23156. AudioFormat* getKnownFormat (int index) const;
  23157. /** Looks for which of the known formats is listed as being for a given file
  23158. extension.
  23159. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  23160. */
  23161. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  23162. /** Returns the format which has been set as the default one.
  23163. You can set a format as being the default when it is registered. It's useful
  23164. when you want to write to a file, because the best format may change between
  23165. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  23166. If none has been set as the default, this method will just return the first
  23167. one in the list.
  23168. */
  23169. AudioFormat* getDefaultFormat() const;
  23170. /** Returns a set of wildcards for file-matching that contains the extensions for
  23171. all known formats.
  23172. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  23173. */
  23174. const String getWildcardForAllFormats() const;
  23175. /** Searches through the known formats to try to create a suitable reader for
  23176. this file.
  23177. If none of the registered formats can open the file, it'll return 0. If it
  23178. returns a reader, it's the caller's responsibility to delete the reader.
  23179. */
  23180. AudioFormatReader* createReaderFor (const File& audioFile);
  23181. /** Searches through the known formats to try to create a suitable reader for
  23182. this stream.
  23183. The stream object that is passed-in will be deleted by this method or by the
  23184. reader that is returned, so the caller should not keep any references to it.
  23185. The stream that is passed-in must be capable of being repositioned so
  23186. that all the formats can have a go at opening it.
  23187. If none of the registered formats can open the stream, it'll return 0. If it
  23188. returns a reader, it's the caller's responsibility to delete the reader.
  23189. */
  23190. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  23191. juce_UseDebuggingNewOperator
  23192. private:
  23193. OwnedArray<AudioFormat> knownFormats;
  23194. int defaultFormatIndex;
  23195. };
  23196. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23197. /*** End of inlined file: juce_AudioFormatManager.h ***/
  23198. #endif
  23199. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23200. #endif
  23201. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  23202. #endif
  23203. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23204. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  23205. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23206. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23207. /**
  23208. This class is used to wrap an AudioFormatReader and only read from a
  23209. subsection of the file.
  23210. So if you have a reader which can read a 1000 sample file, you could wrap it
  23211. in one of these to only access, e.g. samples 100 to 200, and any samples
  23212. outside that will come back as 0. Accessing sample 0 from this reader will
  23213. actually read the first sample from the other's subsection, which might
  23214. be at a non-zero position.
  23215. @see AudioFormatReader
  23216. */
  23217. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  23218. {
  23219. public:
  23220. /** Creates a AudioSubsectionReader for a given data source.
  23221. @param sourceReader the source reader from which we'll be taking data
  23222. @param subsectionStartSample the sample within the source reader which will be
  23223. mapped onto sample 0 for this reader.
  23224. @param subsectionLength the number of samples from the source that will
  23225. make up the subsection. If this reader is asked for
  23226. any samples beyond this region, it will return zero.
  23227. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  23228. this object is deleted.
  23229. */
  23230. AudioSubsectionReader (AudioFormatReader* sourceReader,
  23231. int64 subsectionStartSample,
  23232. int64 subsectionLength,
  23233. bool deleteSourceWhenDeleted);
  23234. /** Destructor. */
  23235. ~AudioSubsectionReader();
  23236. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  23237. int64 startSampleInFile, int numSamples);
  23238. void readMaxLevels (int64 startSample,
  23239. int64 numSamples,
  23240. float& lowestLeft,
  23241. float& highestLeft,
  23242. float& lowestRight,
  23243. float& highestRight);
  23244. juce_UseDebuggingNewOperator
  23245. private:
  23246. AudioFormatReader* const source;
  23247. int64 startSample, length;
  23248. const bool deleteSourceWhenDeleted;
  23249. AudioSubsectionReader (const AudioSubsectionReader&);
  23250. AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  23251. };
  23252. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23253. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  23254. #endif
  23255. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23256. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  23257. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23258. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23259. class AudioThumbnailCache;
  23260. /**
  23261. Makes it easy to quickly draw scaled views of the waveform shape of an
  23262. audio file.
  23263. To use this class, just create an AudioThumbNail class for the file you want
  23264. to draw, call setSource to tell it which file or resource to use, then call
  23265. drawChannel() to draw it.
  23266. The class will asynchronously scan the wavefile to create its scaled-down view,
  23267. so you should make your UI repaint itself as this data comes in. To do this, the
  23268. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  23269. listeners should repaint themselves.
  23270. The thumbnail stores an internal low-res version of the wave data, and this can
  23271. be loaded and saved to avoid having to scan the file again.
  23272. @see AudioThumbnailCache
  23273. */
  23274. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  23275. public TimeSliceClient,
  23276. private Timer
  23277. {
  23278. public:
  23279. /** Creates an audio thumbnail.
  23280. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  23281. of the audio data, this is the scale at which it should be done. (This
  23282. number is the number of original samples that will be averaged for each
  23283. low-res sample)
  23284. @param formatManagerToUse the audio format manager that is used to open the file
  23285. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  23286. thread and storage that is used to by the thumbnail, and the cache
  23287. object can be shared between multiple thumbnails
  23288. */
  23289. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  23290. AudioFormatManager& formatManagerToUse,
  23291. AudioThumbnailCache& cacheToUse);
  23292. /** Destructor. */
  23293. ~AudioThumbnail();
  23294. /** Specifies the file or stream that contains the audio file.
  23295. For a file, just call
  23296. @code
  23297. setSource (new FileInputSource (file))
  23298. @endcode
  23299. You can pass a zero in here to clear the thumbnail.
  23300. The source that is passed in will be deleted by this object when it is no
  23301. longer needed
  23302. */
  23303. void setSource (InputSource* newSource);
  23304. /** Reloads the low res thumbnail data from an input stream.
  23305. The thumb will automatically attempt to reload itself from its
  23306. AudioThumbnailCache.
  23307. */
  23308. void loadFrom (InputStream& input);
  23309. /** Saves the low res thumbnail data to an output stream.
  23310. The thumb will automatically attempt to save itself to its
  23311. AudioThumbnailCache after it finishes scanning the wave file.
  23312. */
  23313. void saveTo (OutputStream& output) const;
  23314. /** Returns the number of channels in the file.
  23315. */
  23316. int getNumChannels() const throw();
  23317. /** Returns the length of the audio file, in seconds.
  23318. */
  23319. double getTotalLength() const throw();
  23320. /** Renders the waveform shape for a channel.
  23321. The waveform will be drawn within the specified rectangle, where startTime
  23322. and endTime specify the times within the audio file that should be positioned
  23323. at the left and right edges of the rectangle.
  23324. The waveform will be scaled vertically so that a full-volume sample will fill
  23325. the rectangle vertically, but you can also specify an extra vertical scale factor
  23326. with the verticalZoomFactor parameter.
  23327. */
  23328. void drawChannel (Graphics& g,
  23329. int x, int y, int w, int h,
  23330. double startTimeSeconds,
  23331. double endTimeSeconds,
  23332. int channelNum,
  23333. float verticalZoomFactor);
  23334. /** Returns true if the low res preview is fully generated.
  23335. */
  23336. bool isFullyLoaded() const throw();
  23337. /** @internal */
  23338. bool useTimeSlice();
  23339. /** @internal */
  23340. void timerCallback();
  23341. juce_UseDebuggingNewOperator
  23342. private:
  23343. AudioFormatManager& formatManagerToUse;
  23344. AudioThumbnailCache& cache;
  23345. ScopedPointer <InputSource> source;
  23346. CriticalSection readerLock;
  23347. ScopedPointer <AudioFormatReader> reader;
  23348. MemoryBlock data, cachedLevels;
  23349. int orginalSamplesPerThumbnailSample;
  23350. int numChannelsCached, numSamplesCached;
  23351. double cachedStart, cachedTimePerPixel;
  23352. bool cacheNeedsRefilling;
  23353. void clear();
  23354. AudioFormatReader* createReader() const;
  23355. void generateSection (AudioFormatReader& reader, int64 startSample, int numSamples);
  23356. char* getChannelData (int channel) const;
  23357. void refillCache (int numSamples, double startTime, double timePerPixel);
  23358. friend class AudioThumbnailCache;
  23359. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  23360. bool initialiseFromAudioFile (AudioFormatReader& reader);
  23361. // returns true if more needs to be read
  23362. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  23363. };
  23364. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23365. /*** End of inlined file: juce_AudioThumbnail.h ***/
  23366. #endif
  23367. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23368. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  23369. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23370. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23371. struct ThumbnailCacheEntry;
  23372. /**
  23373. An instance of this class is used to manage multiple AudioThumbnail objects.
  23374. The cache runs a single background thread that is shared by all the thumbnails
  23375. that need it, and it maintains a set of low-res previews in memory, to avoid
  23376. having to re-scan audio files too often.
  23377. @see AudioThumbnail
  23378. */
  23379. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  23380. {
  23381. public:
  23382. /** Creates a cache object.
  23383. The maxNumThumbsToStore parameter lets you specify how many previews should
  23384. be kept in memory at once.
  23385. */
  23386. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  23387. /** Destructor. */
  23388. ~AudioThumbnailCache();
  23389. /** Clears out any stored thumbnails.
  23390. */
  23391. void clear();
  23392. /** Reloads the specified thumb if this cache contains the appropriate stored
  23393. data.
  23394. This is called automatically by the AudioThumbnail class, so you shouldn't
  23395. normally need to call it directly.
  23396. */
  23397. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  23398. /** Stores the cachable data from the specified thumb in this cache.
  23399. This is called automatically by the AudioThumbnail class, so you shouldn't
  23400. normally need to call it directly.
  23401. */
  23402. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  23403. juce_UseDebuggingNewOperator
  23404. private:
  23405. OwnedArray <ThumbnailCacheEntry> thumbs;
  23406. int maxNumThumbsToStore;
  23407. friend class AudioThumbnail;
  23408. void addThumbnail (AudioThumbnail* thumb);
  23409. void removeThumbnail (AudioThumbnail* thumb);
  23410. };
  23411. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23412. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  23413. #endif
  23414. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23415. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  23416. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23417. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23418. #if JUCE_USE_FLAC || defined (DOXYGEN)
  23419. /**
  23420. Reads and writes the lossless-compression FLAC audio format.
  23421. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  23422. and make sure your include search path and library search path are set up to find
  23423. the FLAC header files and static libraries.
  23424. @see AudioFormat
  23425. */
  23426. class JUCE_API FlacAudioFormat : public AudioFormat
  23427. {
  23428. public:
  23429. FlacAudioFormat();
  23430. ~FlacAudioFormat();
  23431. const Array <int> getPossibleSampleRates();
  23432. const Array <int> getPossibleBitDepths();
  23433. bool canDoStereo();
  23434. bool canDoMono();
  23435. bool isCompressed();
  23436. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23437. const bool deleteStreamIfOpeningFails);
  23438. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23439. double sampleRateToUse,
  23440. unsigned int numberOfChannels,
  23441. int bitsPerSample,
  23442. const StringPairArray& metadataValues,
  23443. int qualityOptionIndex);
  23444. juce_UseDebuggingNewOperator
  23445. };
  23446. #endif
  23447. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23448. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  23449. #endif
  23450. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23451. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  23452. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23453. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23454. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  23455. /**
  23456. Reads and writes the Ogg-Vorbis audio format.
  23457. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  23458. and make sure your include search path and library search path are set up to find
  23459. the Vorbis and Ogg header files and static libraries.
  23460. @see AudioFormat,
  23461. */
  23462. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  23463. {
  23464. public:
  23465. OggVorbisAudioFormat();
  23466. ~OggVorbisAudioFormat();
  23467. const Array <int> getPossibleSampleRates();
  23468. const Array <int> getPossibleBitDepths();
  23469. bool canDoStereo();
  23470. bool canDoMono();
  23471. bool isCompressed();
  23472. const StringArray getQualityOptions();
  23473. /** Tries to estimate the quality level of an ogg file based on its size.
  23474. If it can't read the file for some reason, this will just return 1 (medium quality),
  23475. otherwise it will return the approximate quality setting that would have been used
  23476. to create the file.
  23477. @see getQualityOptions
  23478. */
  23479. int estimateOggFileQuality (const File& source);
  23480. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23481. const bool deleteStreamIfOpeningFails);
  23482. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23483. double sampleRateToUse,
  23484. unsigned int numberOfChannels,
  23485. int bitsPerSample,
  23486. const StringPairArray& metadataValues,
  23487. int qualityOptionIndex);
  23488. juce_UseDebuggingNewOperator
  23489. };
  23490. #endif
  23491. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23492. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  23493. #endif
  23494. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23495. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  23496. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23497. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23498. #if JUCE_QUICKTIME
  23499. /**
  23500. Uses QuickTime to read the audio track a movie or media file.
  23501. As well as QuickTime movies, this should also manage to open other audio
  23502. files that quicktime can understand, like mp3, m4a, etc.
  23503. @see AudioFormat
  23504. */
  23505. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  23506. {
  23507. public:
  23508. /** Creates a format object. */
  23509. QuickTimeAudioFormat();
  23510. /** Destructor. */
  23511. ~QuickTimeAudioFormat();
  23512. const Array <int> getPossibleSampleRates();
  23513. const Array <int> getPossibleBitDepths();
  23514. bool canDoStereo();
  23515. bool canDoMono();
  23516. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23517. const bool deleteStreamIfOpeningFails);
  23518. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23519. double sampleRateToUse,
  23520. unsigned int numberOfChannels,
  23521. int bitsPerSample,
  23522. const StringPairArray& metadataValues,
  23523. int qualityOptionIndex);
  23524. juce_UseDebuggingNewOperator
  23525. };
  23526. #endif
  23527. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23528. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  23529. #endif
  23530. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23531. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  23532. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23533. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23534. /**
  23535. Reads and Writes WAV format audio files.
  23536. @see AudioFormat
  23537. */
  23538. class JUCE_API WavAudioFormat : public AudioFormat
  23539. {
  23540. public:
  23541. /** Creates a format object. */
  23542. WavAudioFormat();
  23543. /** Destructor. */
  23544. ~WavAudioFormat();
  23545. /** Metadata property name used by wav readers and writers for adding
  23546. a BWAV chunk to the file.
  23547. @see AudioFormatReader::metadataValues, createWriterFor
  23548. */
  23549. static const char* const bwavDescription;
  23550. /** Metadata property name used by wav readers and writers for adding
  23551. a BWAV chunk to the file.
  23552. @see AudioFormatReader::metadataValues, createWriterFor
  23553. */
  23554. static const char* const bwavOriginator;
  23555. /** Metadata property name used by wav readers and writers for adding
  23556. a BWAV chunk to the file.
  23557. @see AudioFormatReader::metadataValues, createWriterFor
  23558. */
  23559. static const char* const bwavOriginatorRef;
  23560. /** Metadata property name used by wav readers and writers for adding
  23561. a BWAV chunk to the file.
  23562. Date format is: yyyy-mm-dd
  23563. @see AudioFormatReader::metadataValues, createWriterFor
  23564. */
  23565. static const char* const bwavOriginationDate;
  23566. /** Metadata property name used by wav readers and writers for adding
  23567. a BWAV chunk to the file.
  23568. Time format is: hh-mm-ss
  23569. @see AudioFormatReader::metadataValues, createWriterFor
  23570. */
  23571. static const char* const bwavOriginationTime;
  23572. /** Metadata property name used by wav readers and writers for adding
  23573. a BWAV chunk to the file.
  23574. This is the number of samples from the start of an edit that the
  23575. file is supposed to begin at. Seems like an obvious mistake to
  23576. only allow a file to occur in an edit once, but that's the way
  23577. it is..
  23578. @see AudioFormatReader::metadataValues, createWriterFor
  23579. */
  23580. static const char* const bwavTimeReference;
  23581. /** Metadata property name used by wav readers and writers for adding
  23582. a BWAV chunk to the file.
  23583. This is a
  23584. @see AudioFormatReader::metadataValues, createWriterFor
  23585. */
  23586. static const char* const bwavCodingHistory;
  23587. /** Utility function to fill out the appropriate metadata for a BWAV file.
  23588. This just makes it easier than using the property names directly, and it
  23589. fills out the time and date in the right format.
  23590. */
  23591. static const StringPairArray createBWAVMetadata (const String& description,
  23592. const String& originator,
  23593. const String& originatorRef,
  23594. const Time& dateAndTime,
  23595. const int64 timeReferenceSamples,
  23596. const String& codingHistory);
  23597. const Array <int> getPossibleSampleRates();
  23598. const Array <int> getPossibleBitDepths();
  23599. bool canDoStereo();
  23600. bool canDoMono();
  23601. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23602. const bool deleteStreamIfOpeningFails);
  23603. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23604. double sampleRateToUse,
  23605. unsigned int numberOfChannels,
  23606. int bitsPerSample,
  23607. const StringPairArray& metadataValues,
  23608. int qualityOptionIndex);
  23609. /** Utility function to replace the metadata in a wav file with a new set of values.
  23610. If possible, this cheats by overwriting just the metadata region of the file, rather
  23611. than by copying the whole file again.
  23612. */
  23613. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  23614. juce_UseDebuggingNewOperator
  23615. };
  23616. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23617. /*** End of inlined file: juce_WavAudioFormat.h ***/
  23618. #endif
  23619. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23620. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  23621. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23622. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23623. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  23624. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23625. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23626. /**
  23627. A type of AudioSource which can be repositioned.
  23628. The basic AudioSource just streams continuously with no idea of a current
  23629. time or length, so the PositionableAudioSource is used for a finite stream
  23630. that has a current read position.
  23631. @see AudioSource, AudioTransportSource
  23632. */
  23633. class JUCE_API PositionableAudioSource : public AudioSource
  23634. {
  23635. protected:
  23636. /** Creates the PositionableAudioSource. */
  23637. PositionableAudioSource() throw() {}
  23638. public:
  23639. /** Destructor */
  23640. ~PositionableAudioSource() {}
  23641. /** Tells the stream to move to a new position.
  23642. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23643. should return samples from this position.
  23644. Note that this may be called on a different thread to getNextAudioBlock(),
  23645. so the subclass should make sure it's synchronised.
  23646. */
  23647. virtual void setNextReadPosition (int newPosition) = 0;
  23648. /** Returns the position from which the next block will be returned.
  23649. @see setNextReadPosition
  23650. */
  23651. virtual int getNextReadPosition() const = 0;
  23652. /** Returns the total length of the stream (in samples). */
  23653. virtual int getTotalLength() const = 0;
  23654. /** Returns true if this source is actually playing in a loop. */
  23655. virtual bool isLooping() const = 0;
  23656. };
  23657. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23658. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  23659. /**
  23660. A type of AudioSource that will read from an AudioFormatReader.
  23661. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23662. */
  23663. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23664. {
  23665. public:
  23666. /** Creates an AudioFormatReaderSource for a given reader.
  23667. @param sourceReader the reader to use as the data source
  23668. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23669. when this object is deleted; if false it will be
  23670. left up to the caller to manage its lifetime
  23671. */
  23672. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23673. const bool deleteReaderWhenThisIsDeleted);
  23674. /** Destructor. */
  23675. ~AudioFormatReaderSource();
  23676. /** Toggles loop-mode.
  23677. If set to true, it will continuously loop the input source. If false,
  23678. it will just emit silence after the source has finished.
  23679. @see isLooping
  23680. */
  23681. void setLooping (const bool shouldLoop) throw();
  23682. /** Returns whether loop-mode is turned on or not. */
  23683. bool isLooping() const { return looping; }
  23684. /** Returns the reader that's being used. */
  23685. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23686. /** Implementation of the AudioSource method. */
  23687. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23688. /** Implementation of the AudioSource method. */
  23689. void releaseResources();
  23690. /** Implementation of the AudioSource method. */
  23691. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23692. /** Implements the PositionableAudioSource method. */
  23693. void setNextReadPosition (int newPosition);
  23694. /** Implements the PositionableAudioSource method. */
  23695. int getNextReadPosition() const;
  23696. /** Implements the PositionableAudioSource method. */
  23697. int getTotalLength() const;
  23698. juce_UseDebuggingNewOperator
  23699. private:
  23700. AudioFormatReader* reader;
  23701. bool deleteReader;
  23702. int volatile nextPlayPos;
  23703. bool volatile looping;
  23704. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23705. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23706. AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23707. };
  23708. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23709. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  23710. #endif
  23711. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23712. #endif
  23713. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23714. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  23715. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23716. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23717. /*** Start of inlined file: juce_AudioIODevice.h ***/
  23718. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23719. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23720. class AudioIODevice;
  23721. /**
  23722. One of these is passed to an AudioIODevice object to stream the audio data
  23723. in and out.
  23724. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  23725. method on its own high-priority audio thread, when it needs to send or receive
  23726. the next block of data.
  23727. @see AudioIODevice, AudioDeviceManager
  23728. */
  23729. class JUCE_API AudioIODeviceCallback
  23730. {
  23731. public:
  23732. /** Destructor. */
  23733. virtual ~AudioIODeviceCallback() {}
  23734. /** Processes a block of incoming and outgoing audio data.
  23735. The subclass's implementation should use the incoming audio for whatever
  23736. purposes it needs to, and must fill all the output channels with the next
  23737. block of output data before returning.
  23738. The channel data is arranged with the same array indices as the channel name
  23739. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  23740. that aren't specified in AudioIODevice::open() will have a null pointer for their
  23741. associated channel, so remember to check for this.
  23742. @param inputChannelData a set of arrays containing the audio data for each
  23743. incoming channel - this data is valid until the function
  23744. returns. There will be one channel of data for each input
  23745. channel that was enabled when the audio device was opened
  23746. (see AudioIODevice::open())
  23747. @param numInputChannels the number of pointers to channel data in the
  23748. inputChannelData array.
  23749. @param outputChannelData a set of arrays which need to be filled with the data
  23750. that should be sent to each outgoing channel of the device.
  23751. There will be one channel of data for each output channel
  23752. that was enabled when the audio device was opened (see
  23753. AudioIODevice::open())
  23754. The initial contents of the array is undefined, so the
  23755. callback function must fill all the channels with zeros if
  23756. its output is silence. Failing to do this could cause quite
  23757. an unpleasant noise!
  23758. @param numOutputChannels the number of pointers to channel data in the
  23759. outputChannelData array.
  23760. @param numSamples the number of samples in each channel of the input and
  23761. output arrays. The number of samples will depend on the
  23762. audio device's buffer size and will usually remain constant,
  23763. although this isn't guaranteed, so make sure your code can
  23764. cope with reasonable changes in the buffer size from one
  23765. callback to the next.
  23766. */
  23767. virtual void audioDeviceIOCallback (const float** inputChannelData,
  23768. int numInputChannels,
  23769. float** outputChannelData,
  23770. int numOutputChannels,
  23771. int numSamples) = 0;
  23772. /** Called to indicate that the device is about to start calling back.
  23773. This will be called just before the audio callbacks begin, either when this
  23774. callback has just been added to an audio device, or after the device has been
  23775. restarted because of a sample-rate or block-size change.
  23776. You can use this opportunity to find out the sample rate and block size
  23777. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23778. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23779. @param device the audio IO device that will be used to drive the callback.
  23780. Note that if you're going to store this this pointer, it is
  23781. only valid until the next time that audioDeviceStopped is called.
  23782. */
  23783. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23784. /** Called to indicate that the device has stopped.
  23785. */
  23786. virtual void audioDeviceStopped() = 0;
  23787. };
  23788. /**
  23789. Base class for an audio device with synchronised input and output channels.
  23790. Subclasses of this are used to implement different protocols such as DirectSound,
  23791. ASIO, CoreAudio, etc.
  23792. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23793. documentation for that class for more info.
  23794. For an easier way of managing audio devices and their settings, have a look at the
  23795. AudioDeviceManager class.
  23796. @see AudioIODeviceType, AudioDeviceManager
  23797. */
  23798. class JUCE_API AudioIODevice
  23799. {
  23800. public:
  23801. /** Destructor. */
  23802. virtual ~AudioIODevice();
  23803. /** Returns the device's name, (as set in the constructor). */
  23804. const String& getName() const throw() { return name; }
  23805. /** Returns the type of the device.
  23806. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23807. */
  23808. const String& getTypeName() const throw() { return typeName; }
  23809. /** Returns the names of all the available output channels on this device.
  23810. To find out which of these are currently in use, call getActiveOutputChannels().
  23811. */
  23812. virtual const StringArray getOutputChannelNames() = 0;
  23813. /** Returns the names of all the available input channels on this device.
  23814. To find out which of these are currently in use, call getActiveInputChannels().
  23815. */
  23816. virtual const StringArray getInputChannelNames() = 0;
  23817. /** Returns the number of sample-rates this device supports.
  23818. To find out which rates are available on this device, use this method to
  23819. find out how many there are, and getSampleRate() to get the rates.
  23820. @see getSampleRate
  23821. */
  23822. virtual int getNumSampleRates() = 0;
  23823. /** Returns one of the sample-rates this device supports.
  23824. To find out which rates are available on this device, use getNumSampleRates() to
  23825. find out how many there are, and getSampleRate() to get the individual rates.
  23826. The sample rate is set by the open() method.
  23827. (Note that for DirectSound some rates might not work, depending on combinations
  23828. of i/o channels that are being opened).
  23829. @see getNumSampleRates
  23830. */
  23831. virtual double getSampleRate (int index) = 0;
  23832. /** Returns the number of sizes of buffer that are available.
  23833. @see getBufferSizeSamples, getDefaultBufferSize
  23834. */
  23835. virtual int getNumBufferSizesAvailable() = 0;
  23836. /** Returns one of the possible buffer-sizes.
  23837. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23838. @returns a number of samples
  23839. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23840. */
  23841. virtual int getBufferSizeSamples (int index) = 0;
  23842. /** Returns the default buffer-size to use.
  23843. @returns a number of samples
  23844. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23845. */
  23846. virtual int getDefaultBufferSize() = 0;
  23847. /** Tries to open the device ready to play.
  23848. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  23849. input channel should be enabled
  23850. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  23851. output channel should be enabled
  23852. @param sampleRate the sample rate to try to use - to find out which rates are
  23853. available, see getNumSampleRates() and getSampleRate()
  23854. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23855. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23856. @returns an error description if there's a problem, or an empty string if it succeeds in
  23857. opening the device
  23858. @see close
  23859. */
  23860. virtual const String open (const BigInteger& inputChannels,
  23861. const BigInteger& outputChannels,
  23862. double sampleRate,
  23863. int bufferSizeSamples) = 0;
  23864. /** Closes and releases the device if it's open. */
  23865. virtual void close() = 0;
  23866. /** Returns true if the device is still open.
  23867. A device might spontaneously close itself if something goes wrong, so this checks if
  23868. it's still open.
  23869. */
  23870. virtual bool isOpen() = 0;
  23871. /** Starts the device actually playing.
  23872. This must be called after the device has been opened.
  23873. @param callback the callback to use for streaming the data.
  23874. @see AudioIODeviceCallback, open
  23875. */
  23876. virtual void start (AudioIODeviceCallback* callback) = 0;
  23877. /** Stops the device playing.
  23878. Once a device has been started, this will stop it. Any pending calls to the
  23879. callback class will be flushed before this method returns.
  23880. */
  23881. virtual void stop() = 0;
  23882. /** Returns true if the device is still calling back.
  23883. The device might mysteriously stop, so this checks whether it's
  23884. still playing.
  23885. */
  23886. virtual bool isPlaying() = 0;
  23887. /** Returns the last error that happened if anything went wrong. */
  23888. virtual const String getLastError() = 0;
  23889. /** Returns the buffer size that the device is currently using.
  23890. If the device isn't actually open, this value doesn't really mean much.
  23891. */
  23892. virtual int getCurrentBufferSizeSamples() = 0;
  23893. /** Returns the sample rate that the device is currently using.
  23894. If the device isn't actually open, this value doesn't really mean much.
  23895. */
  23896. virtual double getCurrentSampleRate() = 0;
  23897. /** Returns the device's current physical bit-depth.
  23898. If the device isn't actually open, this value doesn't really mean much.
  23899. */
  23900. virtual int getCurrentBitDepth() = 0;
  23901. /** Returns a mask showing which of the available output channels are currently
  23902. enabled.
  23903. @see getOutputChannelNames
  23904. */
  23905. virtual const BigInteger getActiveOutputChannels() const = 0;
  23906. /** Returns a mask showing which of the available input channels are currently
  23907. enabled.
  23908. @see getInputChannelNames
  23909. */
  23910. virtual const BigInteger getActiveInputChannels() const = 0;
  23911. /** Returns the device's output latency.
  23912. This is the delay in samples between a callback getting a block of data, and
  23913. that data actually getting played.
  23914. */
  23915. virtual int getOutputLatencyInSamples() = 0;
  23916. /** Returns the device's input latency.
  23917. This is the delay in samples between some audio actually arriving at the soundcard,
  23918. and the callback getting passed this block of data.
  23919. */
  23920. virtual int getInputLatencyInSamples() = 0;
  23921. /** True if this device can show a pop-up control panel for editing its settings.
  23922. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23923. to display it.
  23924. */
  23925. virtual bool hasControlPanel() const;
  23926. /** Shows a device-specific control panel if there is one.
  23927. This should only be called for devices which return true from hasControlPanel().
  23928. */
  23929. virtual bool showControlPanel();
  23930. protected:
  23931. /** Creates a device, setting its name and type member variables. */
  23932. AudioIODevice (const String& deviceName,
  23933. const String& typeName);
  23934. /** @internal */
  23935. String name, typeName;
  23936. };
  23937. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23938. /*** End of inlined file: juce_AudioIODevice.h ***/
  23939. /**
  23940. Wrapper class to continuously stream audio from an audio source to an
  23941. AudioIODevice.
  23942. This object acts as an AudioIODeviceCallback, so can be attached to an
  23943. output device, and will stream audio from an AudioSource.
  23944. */
  23945. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23946. {
  23947. public:
  23948. /** Creates an empty AudioSourcePlayer. */
  23949. AudioSourcePlayer();
  23950. /** Destructor.
  23951. Make sure this object isn't still being used by an AudioIODevice before
  23952. deleting it!
  23953. */
  23954. virtual ~AudioSourcePlayer();
  23955. /** Changes the current audio source to play from.
  23956. If the source passed in is already being used, this method will do nothing.
  23957. If the source is not null, its prepareToPlay() method will be called
  23958. before it starts being used for playback.
  23959. If there's another source currently playing, its releaseResources() method
  23960. will be called after it has been swapped for the new one.
  23961. @param newSource the new source to use - this will NOT be deleted
  23962. by this object when no longer needed, so it's the
  23963. caller's responsibility to manage it.
  23964. */
  23965. void setSource (AudioSource* newSource);
  23966. /** Returns the source that's playing.
  23967. May return 0 if there's no source.
  23968. */
  23969. AudioSource* getCurrentSource() const throw() { return source; }
  23970. /** Sets a gain to apply to the audio data.
  23971. @see getGain
  23972. */
  23973. void setGain (const float newGain) throw();
  23974. /** Returns the current gain.
  23975. @see setGain
  23976. */
  23977. float getGain() const throw() { return gain; }
  23978. /** Implementation of the AudioIODeviceCallback method. */
  23979. void audioDeviceIOCallback (const float** inputChannelData,
  23980. int totalNumInputChannels,
  23981. float** outputChannelData,
  23982. int totalNumOutputChannels,
  23983. int numSamples);
  23984. /** Implementation of the AudioIODeviceCallback method. */
  23985. void audioDeviceAboutToStart (AudioIODevice* device);
  23986. /** Implementation of the AudioIODeviceCallback method. */
  23987. void audioDeviceStopped();
  23988. juce_UseDebuggingNewOperator
  23989. private:
  23990. CriticalSection readLock;
  23991. AudioSource* source;
  23992. double sampleRate;
  23993. int bufferSize;
  23994. float* channels [128];
  23995. float* outputChans [128];
  23996. const float* inputChans [128];
  23997. AudioSampleBuffer tempBuffer;
  23998. float lastGain, gain;
  23999. AudioSourcePlayer (const AudioSourcePlayer&);
  24000. AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  24001. };
  24002. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24003. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  24004. #endif
  24005. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24006. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  24007. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24008. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24009. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  24010. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24011. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24012. /**
  24013. An AudioSource which takes another source as input, and buffers it using a thread.
  24014. Create this as a wrapper around another thread, and it will read-ahead with
  24015. a background thread to smooth out playback. You can either create one of these
  24016. directly, or use it indirectly using an AudioTransportSource.
  24017. @see PositionableAudioSource, AudioTransportSource
  24018. */
  24019. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  24020. {
  24021. public:
  24022. /** Creates a BufferingAudioSource.
  24023. @param source the input source to read from
  24024. @param deleteSourceWhenDeleted if true, then the input source object will
  24025. be deleted when this object is deleted
  24026. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  24027. */
  24028. BufferingAudioSource (PositionableAudioSource* source,
  24029. const bool deleteSourceWhenDeleted,
  24030. int numberOfSamplesToBuffer);
  24031. /** Destructor.
  24032. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  24033. flag was set in the constructor.
  24034. */
  24035. ~BufferingAudioSource();
  24036. /** Implementation of the AudioSource method. */
  24037. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24038. /** Implementation of the AudioSource method. */
  24039. void releaseResources();
  24040. /** Implementation of the AudioSource method. */
  24041. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24042. /** Implements the PositionableAudioSource method. */
  24043. void setNextReadPosition (int newPosition);
  24044. /** Implements the PositionableAudioSource method. */
  24045. int getNextReadPosition() const;
  24046. /** Implements the PositionableAudioSource method. */
  24047. int getTotalLength() const { return source->getTotalLength(); }
  24048. /** Implements the PositionableAudioSource method. */
  24049. bool isLooping() const { return source->isLooping(); }
  24050. juce_UseDebuggingNewOperator
  24051. private:
  24052. PositionableAudioSource* source;
  24053. bool deleteSourceWhenDeleted;
  24054. int numberOfSamplesToBuffer;
  24055. AudioSampleBuffer buffer;
  24056. CriticalSection bufferStartPosLock;
  24057. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  24058. bool wasSourceLooping;
  24059. double volatile sampleRate;
  24060. friend class SharedBufferingAudioSourceThread;
  24061. bool readNextBufferChunk();
  24062. void readBufferSection (int start, int length, int bufferOffset);
  24063. BufferingAudioSource (const BufferingAudioSource&);
  24064. BufferingAudioSource& operator= (const BufferingAudioSource&);
  24065. };
  24066. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24067. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  24068. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  24069. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24070. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24071. /**
  24072. A type of AudioSource that takes an input source and changes its sample rate.
  24073. @see AudioSource
  24074. */
  24075. class JUCE_API ResamplingAudioSource : public AudioSource
  24076. {
  24077. public:
  24078. /** Creates a ResamplingAudioSource for a given input source.
  24079. @param inputSource the input source to read from
  24080. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24081. this object is deleted
  24082. @param numChannels the number of channels to process
  24083. */
  24084. ResamplingAudioSource (AudioSource* const inputSource,
  24085. const bool deleteInputWhenDeleted,
  24086. int numChannels = 2);
  24087. /** Destructor. */
  24088. ~ResamplingAudioSource();
  24089. /** Changes the resampling ratio.
  24090. (This value can be changed at any time, even while the source is running).
  24091. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  24092. values will speed it up; lower values will slow it
  24093. down. The ratio must be greater than 0
  24094. */
  24095. void setResamplingRatio (const double samplesInPerOutputSample);
  24096. /** Returns the current resampling ratio.
  24097. This is the value that was set by setResamplingRatio().
  24098. */
  24099. double getResamplingRatio() const throw() { return ratio; }
  24100. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24101. void releaseResources();
  24102. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24103. juce_UseDebuggingNewOperator
  24104. private:
  24105. AudioSource* const input;
  24106. const bool deleteInputWhenDeleted;
  24107. double ratio, lastRatio;
  24108. AudioSampleBuffer buffer;
  24109. int bufferPos, sampsInBuffer;
  24110. double subSampleOffset;
  24111. double coefficients[6];
  24112. CriticalSection ratioLock;
  24113. const int numChannels;
  24114. HeapBlock<float*> destBuffers, srcBuffers;
  24115. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  24116. void createLowPass (const double proportionalRate);
  24117. struct FilterState
  24118. {
  24119. double x1, x2, y1, y2;
  24120. };
  24121. HeapBlock<FilterState> filterStates;
  24122. void resetFilters();
  24123. void applyFilter (float* samples, int num, FilterState& fs);
  24124. ResamplingAudioSource (const ResamplingAudioSource&);
  24125. ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  24126. };
  24127. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24128. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  24129. /**
  24130. An AudioSource that takes a PositionableAudioSource and allows it to be
  24131. played, stopped, started, etc.
  24132. This can also be told use a buffer and background thread to read ahead, and
  24133. if can correct for different sample-rates.
  24134. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  24135. to control playback of an audio file.
  24136. @see AudioSource, AudioSourcePlayer
  24137. */
  24138. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  24139. public ChangeBroadcaster
  24140. {
  24141. public:
  24142. /** Creates an AudioTransportSource.
  24143. After creating one of these, use the setSource() method to select an input source.
  24144. */
  24145. AudioTransportSource();
  24146. /** Destructor. */
  24147. ~AudioTransportSource();
  24148. /** Sets the reader that is being used as the input source.
  24149. This will stop playback, reset the position to 0 and change to the new reader.
  24150. The source passed in will not be deleted by this object, so must be managed by
  24151. the caller.
  24152. @param newSource the new input source to use. This may be zero
  24153. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  24154. is zero, no reading ahead will be done; if it's
  24155. greater than zero, a BufferingAudioSource will be used
  24156. to do the reading-ahead
  24157. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  24158. rate of the source, and playback will be sample-rate
  24159. adjusted to maintain playback at the correct pitch. If
  24160. this is 0, no sample-rate adjustment will be performed
  24161. */
  24162. void setSource (PositionableAudioSource* const newSource,
  24163. int readAheadBufferSize = 0,
  24164. double sourceSampleRateToCorrectFor = 0.0);
  24165. /** Changes the current playback position in the source stream.
  24166. The next time the getNextAudioBlock() method is called, this
  24167. is the time from which it'll read data.
  24168. @see getPosition
  24169. */
  24170. void setPosition (double newPosition);
  24171. /** Returns the position that the next data block will be read from
  24172. This is a time in seconds.
  24173. */
  24174. double getCurrentPosition() const;
  24175. /** Returns true if the player has stopped because its input stream ran out of data.
  24176. */
  24177. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24178. /** Starts playing (if a source has been selected).
  24179. If it starts playing, this will send a message to any ChangeListeners
  24180. that are registered with this object.
  24181. */
  24182. void start();
  24183. /** Stops playing.
  24184. If it's actually playing, this will send a message to any ChangeListeners
  24185. that are registered with this object.
  24186. */
  24187. void stop();
  24188. /** Returns true if it's currently playing. */
  24189. bool isPlaying() const throw() { return playing; }
  24190. /** Changes the gain to apply to the output.
  24191. @param newGain a factor by which to multiply the outgoing samples,
  24192. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24193. */
  24194. void setGain (const float newGain) throw();
  24195. /** Returns the current gain setting.
  24196. @see setGain
  24197. */
  24198. float getGain() const throw() { return gain; }
  24199. /** Implementation of the AudioSource method. */
  24200. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24201. /** Implementation of the AudioSource method. */
  24202. void releaseResources();
  24203. /** Implementation of the AudioSource method. */
  24204. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24205. /** Implements the PositionableAudioSource method. */
  24206. void setNextReadPosition (int newPosition);
  24207. /** Implements the PositionableAudioSource method. */
  24208. int getNextReadPosition() const;
  24209. /** Implements the PositionableAudioSource method. */
  24210. int getTotalLength() const;
  24211. /** Implements the PositionableAudioSource method. */
  24212. bool isLooping() const;
  24213. juce_UseDebuggingNewOperator
  24214. private:
  24215. PositionableAudioSource* source;
  24216. ResamplingAudioSource* resamplerSource;
  24217. BufferingAudioSource* bufferingSource;
  24218. PositionableAudioSource* positionableSource;
  24219. AudioSource* masterSource;
  24220. CriticalSection callbackLock;
  24221. float volatile gain, lastGain;
  24222. bool volatile playing, stopped;
  24223. double sampleRate, sourceSampleRate;
  24224. int blockSize, readAheadBufferSize;
  24225. bool isPrepared, inputStreamEOF;
  24226. AudioTransportSource (const AudioTransportSource&);
  24227. AudioTransportSource& operator= (const AudioTransportSource&);
  24228. };
  24229. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24230. /*** End of inlined file: juce_AudioTransportSource.h ***/
  24231. #endif
  24232. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24233. #endif
  24234. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24235. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  24236. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24237. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24238. /**
  24239. An AudioSource that takes the audio from another source, and re-maps its
  24240. input and output channels to a different arrangement.
  24241. You can use this to increase or decrease the number of channels that an
  24242. audio source uses, or to re-order those channels.
  24243. Call the reset() method before using it to set up a default mapping, and then
  24244. the setInputChannelMapping() and setOutputChannelMapping() methods to
  24245. create an appropriate mapping, otherwise no channels will be connected and
  24246. it'll produce silence.
  24247. @see AudioSource
  24248. */
  24249. class ChannelRemappingAudioSource : public AudioSource
  24250. {
  24251. public:
  24252. /** Creates a remapping source that will pass on audio from the given input.
  24253. @param source the input source to use. Make sure that this doesn't
  24254. get deleted before the ChannelRemappingAudioSource object
  24255. @param deleteSourceWhenDeleted if true, the input source will be deleted
  24256. when this object is deleted, if false, the caller is
  24257. responsible for its deletion
  24258. */
  24259. ChannelRemappingAudioSource (AudioSource* const source,
  24260. const bool deleteSourceWhenDeleted);
  24261. /** Destructor. */
  24262. ~ChannelRemappingAudioSource();
  24263. /** Specifies a number of channels that this audio source must produce from its
  24264. getNextAudioBlock() callback.
  24265. */
  24266. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  24267. /** Clears any mapped channels.
  24268. After this, no channels are mapped, so this object will produce silence. Create
  24269. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  24270. */
  24271. void clearAllMappings() throw();
  24272. /** Creates an input channel mapping.
  24273. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  24274. data will be sent to destChannelIndex of our input source.
  24275. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  24276. source specified when this object was created).
  24277. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  24278. during our getNextAudioBlock() callback
  24279. */
  24280. void setInputChannelMapping (const int destChannelIndex,
  24281. const int sourceChannelIndex) throw();
  24282. /** Creates an output channel mapping.
  24283. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  24284. our input audio source will be copied to channel destChannelIndex of the final buffer.
  24285. @param sourceChannelIndex the index of an output channel coming from our input audio source
  24286. (i.e. the source specified when this object was created).
  24287. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  24288. during our getNextAudioBlock() callback
  24289. */
  24290. void setOutputChannelMapping (const int sourceChannelIndex,
  24291. const int destChannelIndex) throw();
  24292. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  24293. our input audio source.
  24294. */
  24295. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  24296. /** Returns the output channel to which channel outputChannelIndex of our input audio
  24297. source will be sent to.
  24298. */
  24299. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  24300. /** Returns an XML object to encapsulate the state of the mappings.
  24301. @see restoreFromXml
  24302. */
  24303. XmlElement* createXml() const throw();
  24304. /** Restores the mappings from an XML object created by createXML().
  24305. @see createXml
  24306. */
  24307. void restoreFromXml (const XmlElement& e) throw();
  24308. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24309. void releaseResources();
  24310. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24311. juce_UseDebuggingNewOperator
  24312. private:
  24313. int requiredNumberOfChannels;
  24314. Array <int> remappedInputs, remappedOutputs;
  24315. AudioSource* const source;
  24316. const bool deleteSourceWhenDeleted;
  24317. AudioSampleBuffer buffer;
  24318. AudioSourceChannelInfo remappedInfo;
  24319. CriticalSection lock;
  24320. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  24321. ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  24322. };
  24323. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24324. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  24325. #endif
  24326. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24327. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  24328. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24329. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24330. /*** Start of inlined file: juce_IIRFilter.h ***/
  24331. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  24332. #define __JUCE_IIRFILTER_JUCEHEADER__
  24333. /**
  24334. An IIR filter that can perform low, high, or band-pass filtering on an
  24335. audio signal.
  24336. @see IIRFilterAudioSource
  24337. */
  24338. class JUCE_API IIRFilter
  24339. {
  24340. public:
  24341. /** Creates a filter.
  24342. Initially the filter is inactive, so will have no effect on samples that
  24343. you process with it. Use the appropriate method to turn it into the type
  24344. of filter needed.
  24345. */
  24346. IIRFilter();
  24347. /** Creates a copy of another filter. */
  24348. IIRFilter (const IIRFilter& other);
  24349. /** Destructor. */
  24350. ~IIRFilter();
  24351. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  24352. Note that this clears the processing state, but the type of filter and
  24353. its coefficients aren't changed. To put a filter into an inactive state, use
  24354. the makeInactive() method.
  24355. */
  24356. void reset() throw();
  24357. /** Performs the filter operation on the given set of samples.
  24358. */
  24359. void processSamples (float* samples,
  24360. int numSamples) throw();
  24361. /** Processes a single sample, without any locking or checking.
  24362. Use this if you need fast processing of a single value, but be aware that
  24363. this isn't thread-safe in the way that processSamples() is.
  24364. */
  24365. float processSingleSampleRaw (float sample) throw();
  24366. /** Sets the filter up to act as a low-pass filter.
  24367. */
  24368. void makeLowPass (double sampleRate,
  24369. double frequency) throw();
  24370. /** Sets the filter up to act as a high-pass filter.
  24371. */
  24372. void makeHighPass (double sampleRate,
  24373. double frequency) throw();
  24374. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  24375. The gain is a scale factor that the low frequencies are multiplied by, so values
  24376. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  24377. attenuate them.
  24378. */
  24379. void makeLowShelf (double sampleRate,
  24380. double cutOffFrequency,
  24381. double Q,
  24382. float gainFactor) throw();
  24383. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  24384. The gain is a scale factor that the high frequencies are multiplied by, so values
  24385. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  24386. attenuate them.
  24387. */
  24388. void makeHighShelf (double sampleRate,
  24389. double cutOffFrequency,
  24390. double Q,
  24391. float gainFactor) throw();
  24392. /** Sets the filter up to act as a band pass filter centred around a
  24393. frequency, with a variable Q and gain.
  24394. The gain is a scale factor that the centre frequencies are multiplied by, so
  24395. values greater than 1.0 will boost the centre frequencies, values less than
  24396. 1.0 will attenuate them.
  24397. */
  24398. void makeBandPass (double sampleRate,
  24399. double centreFrequency,
  24400. double Q,
  24401. float gainFactor) throw();
  24402. /** Clears the filter's coefficients so that it becomes inactive.
  24403. */
  24404. void makeInactive() throw();
  24405. /** Makes this filter duplicate the set-up of another one.
  24406. */
  24407. void copyCoefficientsFrom (const IIRFilter& other) throw();
  24408. juce_UseDebuggingNewOperator
  24409. protected:
  24410. CriticalSection processLock;
  24411. void setCoefficients (double c1, double c2, double c3,
  24412. double c4, double c5, double c6) throw();
  24413. bool active;
  24414. float coefficients[6];
  24415. float x1, x2, y1, y2;
  24416. // (use the copyCoefficientsFrom() method instead of this operator)
  24417. IIRFilter& operator= (const IIRFilter&);
  24418. };
  24419. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  24420. /*** End of inlined file: juce_IIRFilter.h ***/
  24421. /**
  24422. An AudioSource that performs an IIR filter on another source.
  24423. */
  24424. class JUCE_API IIRFilterAudioSource : public AudioSource
  24425. {
  24426. public:
  24427. /** Creates a IIRFilterAudioSource for a given input source.
  24428. @param inputSource the input source to read from
  24429. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24430. this object is deleted
  24431. */
  24432. IIRFilterAudioSource (AudioSource* const inputSource,
  24433. const bool deleteInputWhenDeleted);
  24434. /** Destructor. */
  24435. ~IIRFilterAudioSource();
  24436. /** Changes the filter to use the same parameters as the one being passed in.
  24437. */
  24438. void setFilterParameters (const IIRFilter& newSettings);
  24439. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24440. void releaseResources();
  24441. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24442. juce_UseDebuggingNewOperator
  24443. private:
  24444. AudioSource* const input;
  24445. const bool deleteInputWhenDeleted;
  24446. OwnedArray <IIRFilter> iirFilters;
  24447. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24448. IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24449. };
  24450. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24451. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  24452. #endif
  24453. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24454. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  24455. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24456. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24457. /**
  24458. An AudioSource that mixes together the output of a set of other AudioSources.
  24459. Input sources can be added and removed while the mixer is running as long as their
  24460. prepareToPlay() and releaseResources() methods are called before and after adding
  24461. them to the mixer.
  24462. */
  24463. class JUCE_API MixerAudioSource : public AudioSource
  24464. {
  24465. public:
  24466. /** Creates a MixerAudioSource.
  24467. */
  24468. MixerAudioSource();
  24469. /** Destructor. */
  24470. ~MixerAudioSource();
  24471. /** Adds an input source to the mixer.
  24472. If the mixer is running you'll need to make sure that the input source
  24473. is ready to play by calling its prepareToPlay() method before adding it.
  24474. If the mixer is stopped, then its input sources will be automatically
  24475. prepared when the mixer's prepareToPlay() method is called.
  24476. @param newInput the source to add to the mixer
  24477. @param deleteWhenRemoved if true, then this source will be deleted when
  24478. the mixer is deleted or when removeAllInputs() is
  24479. called (unless the source is previously removed
  24480. with the removeInputSource method)
  24481. */
  24482. void addInputSource (AudioSource* newInput,
  24483. const bool deleteWhenRemoved);
  24484. /** Removes an input source.
  24485. If the mixer is running, this will remove the source but not call its
  24486. releaseResources() method, so the caller might want to do this manually.
  24487. @param input the source to remove
  24488. @param deleteSource whether to delete this source after it's been removed
  24489. */
  24490. void removeInputSource (AudioSource* input,
  24491. const bool deleteSource);
  24492. /** Removes all the input sources.
  24493. If the mixer is running, this will remove the sources but not call their
  24494. releaseResources() method, so the caller might want to do this manually.
  24495. Any sources which were added with the deleteWhenRemoved flag set will be
  24496. deleted by this method.
  24497. */
  24498. void removeAllInputs();
  24499. /** Implementation of the AudioSource method.
  24500. This will call prepareToPlay() on all its input sources.
  24501. */
  24502. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24503. /** Implementation of the AudioSource method.
  24504. This will call releaseResources() on all its input sources.
  24505. */
  24506. void releaseResources();
  24507. /** Implementation of the AudioSource method. */
  24508. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24509. juce_UseDebuggingNewOperator
  24510. private:
  24511. Array <AudioSource*> inputs;
  24512. BigInteger inputsToDelete;
  24513. CriticalSection lock;
  24514. AudioSampleBuffer tempBuffer;
  24515. double currentSampleRate;
  24516. int bufferSizeExpected;
  24517. MixerAudioSource (const MixerAudioSource&);
  24518. MixerAudioSource& operator= (const MixerAudioSource&);
  24519. };
  24520. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24521. /*** End of inlined file: juce_MixerAudioSource.h ***/
  24522. #endif
  24523. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24524. #endif
  24525. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24526. #endif
  24527. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24528. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24529. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24530. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24531. /**
  24532. A simple AudioSource that generates a sine wave.
  24533. */
  24534. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24535. {
  24536. public:
  24537. /** Creates a ToneGeneratorAudioSource. */
  24538. ToneGeneratorAudioSource();
  24539. /** Destructor. */
  24540. ~ToneGeneratorAudioSource();
  24541. /** Sets the signal's amplitude. */
  24542. void setAmplitude (const float newAmplitude);
  24543. /** Sets the signal's frequency. */
  24544. void setFrequency (const double newFrequencyHz);
  24545. /** Implementation of the AudioSource method. */
  24546. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24547. /** Implementation of the AudioSource method. */
  24548. void releaseResources();
  24549. /** Implementation of the AudioSource method. */
  24550. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24551. juce_UseDebuggingNewOperator
  24552. private:
  24553. double frequency, sampleRate;
  24554. double currentPhase, phasePerSample;
  24555. float amplitude;
  24556. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24557. ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24558. };
  24559. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24560. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24561. #endif
  24562. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24563. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  24564. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24565. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24566. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  24567. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24568. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24569. class AudioDeviceManager;
  24570. class Component;
  24571. /**
  24572. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24573. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  24574. method. Each of the objects returned can then be used to list the available
  24575. devices of that type. E.g.
  24576. @code
  24577. OwnedArray <AudioIODeviceType> types;
  24578. myAudioDeviceManager.createAudioDeviceTypes (types);
  24579. for (int i = 0; i < types.size(); ++i)
  24580. {
  24581. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24582. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24583. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24584. for (int j = 0; j < deviceNames.size(); ++j)
  24585. {
  24586. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24587. ...
  24588. }
  24589. }
  24590. @endcode
  24591. For an easier way of managing audio devices and their settings, have a look at the
  24592. AudioDeviceManager class.
  24593. @see AudioIODevice, AudioDeviceManager
  24594. */
  24595. class JUCE_API AudioIODeviceType
  24596. {
  24597. public:
  24598. /** Returns the name of this type of driver that this object manages.
  24599. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24600. */
  24601. const String& getTypeName() const throw() { return typeName; }
  24602. /** Refreshes the object's cached list of known devices.
  24603. This must be called at least once before calling getDeviceNames() or any of
  24604. the other device creation methods.
  24605. */
  24606. virtual void scanForDevices() = 0;
  24607. /** Returns the list of available devices of this type.
  24608. The scanForDevices() method must have been called to create this list.
  24609. @param wantInputNames only really used by DirectSound where devices are split up
  24610. into inputs and outputs, this indicates whether to use
  24611. the input or output name to refer to a pair of devices.
  24612. */
  24613. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  24614. /** Returns the name of the default device.
  24615. This will be one of the names from the getDeviceNames() list.
  24616. @param forInput if true, this means that a default input device should be
  24617. returned; if false, it should return the default output
  24618. */
  24619. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  24620. /** Returns the index of a given device in the list of device names.
  24621. If asInput is true, it shows the index in the inputs list, otherwise it
  24622. looks for it in the outputs list.
  24623. */
  24624. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  24625. /** Returns true if two different devices can be used for the input and output.
  24626. */
  24627. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24628. /** Creates one of the devices of this type.
  24629. The deviceName must be one of the strings returned by getDeviceNames(), and
  24630. scanForDevices() must have been called before this method is used.
  24631. */
  24632. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24633. const String& inputDeviceName) = 0;
  24634. struct DeviceSetupDetails
  24635. {
  24636. AudioDeviceManager* manager;
  24637. int minNumInputChannels, maxNumInputChannels;
  24638. int minNumOutputChannels, maxNumOutputChannels;
  24639. bool useStereoPairs;
  24640. };
  24641. /** Destructor. */
  24642. virtual ~AudioIODeviceType();
  24643. protected:
  24644. explicit AudioIODeviceType (const String& typeName);
  24645. private:
  24646. String typeName;
  24647. AudioIODeviceType (const AudioIODeviceType&);
  24648. AudioIODeviceType& operator= (const AudioIODeviceType&);
  24649. };
  24650. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24651. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  24652. /*** Start of inlined file: juce_MidiInput.h ***/
  24653. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  24654. #define __JUCE_MIDIINPUT_JUCEHEADER__
  24655. /*** Start of inlined file: juce_MidiMessage.h ***/
  24656. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  24657. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  24658. /**
  24659. Encapsulates a MIDI message.
  24660. @see MidiMessageSequence, MidiOutput, MidiInput
  24661. */
  24662. class JUCE_API MidiMessage
  24663. {
  24664. public:
  24665. /** Creates a 3-byte short midi message.
  24666. @param byte1 message byte 1
  24667. @param byte2 message byte 2
  24668. @param byte3 message byte 3
  24669. @param timeStamp the time to give the midi message - this value doesn't
  24670. use any particular units, so will be application-specific
  24671. */
  24672. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  24673. /** Creates a 2-byte short midi message.
  24674. @param byte1 message byte 1
  24675. @param byte2 message byte 2
  24676. @param timeStamp the time to give the midi message - this value doesn't
  24677. use any particular units, so will be application-specific
  24678. */
  24679. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  24680. /** Creates a 1-byte short midi message.
  24681. @param byte1 message byte 1
  24682. @param timeStamp the time to give the midi message - this value doesn't
  24683. use any particular units, so will be application-specific
  24684. */
  24685. MidiMessage (int byte1, double timeStamp = 0) throw();
  24686. /** Creates a midi message from a block of data. */
  24687. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  24688. /** Reads the next midi message from some data.
  24689. This will read as many bytes from a data stream as it needs to make a
  24690. complete message, and will return the number of bytes it used. This lets
  24691. you read a sequence of midi messages from a file or stream.
  24692. @param data the data to read from
  24693. @param maxBytesToUse the maximum number of bytes it's allowed to read
  24694. @param numBytesUsed returns the number of bytes that were actually needed
  24695. @param lastStatusByte in a sequence of midi messages, the initial byte
  24696. can be dropped from a message if it's the same as the
  24697. first byte of the previous message, so this lets you
  24698. supply the byte to use if the first byte of the message
  24699. has in fact been dropped.
  24700. @param timeStamp the time to give the midi message - this value doesn't
  24701. use any particular units, so will be application-specific
  24702. */
  24703. MidiMessage (const void* data, int maxBytesToUse,
  24704. int& numBytesUsed, uint8 lastStatusByte,
  24705. double timeStamp = 0);
  24706. /** Creates a copy of another midi message. */
  24707. MidiMessage (const MidiMessage& other);
  24708. /** Creates a copy of another midi message, with a different timestamp. */
  24709. MidiMessage (const MidiMessage& other, double newTimeStamp);
  24710. /** Destructor. */
  24711. ~MidiMessage();
  24712. /** Copies this message from another one. */
  24713. MidiMessage& operator= (const MidiMessage& other);
  24714. /** Returns a pointer to the raw midi data.
  24715. @see getRawDataSize
  24716. */
  24717. uint8* getRawData() const throw() { return data; }
  24718. /** Returns the number of bytes of data in the message.
  24719. @see getRawData
  24720. */
  24721. int getRawDataSize() const throw() { return size; }
  24722. /** Returns the timestamp associated with this message.
  24723. The exact meaning of this time and its units will vary, as messages are used in
  24724. a variety of different contexts.
  24725. If you're getting the message from a midi file, this could be a time in seconds, or
  24726. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  24727. If the message is being used in a MidiBuffer, it might indicate the number of
  24728. audio samples from the start of the buffer.
  24729. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  24730. for details of the way that it initialises this value.
  24731. @see setTimeStamp, addToTimeStamp
  24732. */
  24733. double getTimeStamp() const throw() { return timeStamp; }
  24734. /** Changes the message's associated timestamp.
  24735. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  24736. @see addToTimeStamp, getTimeStamp
  24737. */
  24738. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  24739. /** Adds a value to the message's timestamp.
  24740. The units for the timestamp will be application-specific.
  24741. */
  24742. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  24743. /** Returns the midi channel associated with the message.
  24744. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  24745. if it's a sysex)
  24746. @see isForChannel, setChannel
  24747. */
  24748. int getChannel() const throw();
  24749. /** Returns true if the message applies to the given midi channel.
  24750. @param channelNumber the channel number to look for, in the range 1 to 16
  24751. @see getChannel, setChannel
  24752. */
  24753. bool isForChannel (int channelNumber) const throw();
  24754. /** Changes the message's midi channel.
  24755. This won't do anything for non-channel messages like sysexes.
  24756. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  24757. */
  24758. void setChannel (int newChannelNumber) throw();
  24759. /** Returns true if this is a system-exclusive message.
  24760. */
  24761. bool isSysEx() const throw();
  24762. /** Returns a pointer to the sysex data inside the message.
  24763. If this event isn't a sysex event, it'll return 0.
  24764. @see getSysExDataSize
  24765. */
  24766. const uint8* getSysExData() const throw();
  24767. /** Returns the size of the sysex data.
  24768. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  24769. @see getSysExData
  24770. */
  24771. int getSysExDataSize() const throw();
  24772. /** Returns true if this message is a 'key-down' event.
  24773. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  24774. velocity 0, it will still be considered to be a note-on and the
  24775. method will return true. If returnTrueForVelocity0 is false, then
  24776. if this is a note-on event with velocity 0, it'll be regarded as
  24777. a note-off, and the method will return false
  24778. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  24779. */
  24780. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  24781. /** Creates a key-down message (using a floating-point velocity).
  24782. @param channel the midi channel, in the range 1 to 16
  24783. @param noteNumber the key number, 0 to 127
  24784. @param velocity in the range 0 to 1.0
  24785. @see isNoteOn
  24786. */
  24787. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  24788. /** Creates a key-down message (using an integer velocity).
  24789. @param channel the midi channel, in the range 1 to 16
  24790. @param noteNumber the key number, 0 to 127
  24791. @param velocity in the range 0 to 127
  24792. @see isNoteOn
  24793. */
  24794. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  24795. /** Returns true if this message is a 'key-up' event.
  24796. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  24797. for a note-on event with a velocity of 0.
  24798. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  24799. */
  24800. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  24801. /** Creates a key-up message.
  24802. @param channel the midi channel, in the range 1 to 16
  24803. @param noteNumber the key number, 0 to 127
  24804. @see isNoteOff
  24805. */
  24806. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  24807. /** Returns true if this message is a 'key-down' or 'key-up' event.
  24808. @see isNoteOn, isNoteOff
  24809. */
  24810. bool isNoteOnOrOff() const throw();
  24811. /** Returns the midi note number for note-on and note-off messages.
  24812. If the message isn't a note-on or off, the value returned will be
  24813. meaningless.
  24814. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  24815. */
  24816. int getNoteNumber() const throw();
  24817. /** Changes the midi note number of a note-on or note-off message.
  24818. If the message isn't a note on or off, this will do nothing.
  24819. */
  24820. void setNoteNumber (int newNoteNumber) throw();
  24821. /** Returns the velocity of a note-on or note-off message.
  24822. The value returned will be in the range 0 to 127.
  24823. If the message isn't a note-on or off event, it will return 0.
  24824. @see getFloatVelocity
  24825. */
  24826. uint8 getVelocity() const throw();
  24827. /** Returns the velocity of a note-on or note-off message.
  24828. The value returned will be in the range 0 to 1.0
  24829. If the message isn't a note-on or off event, it will return 0.
  24830. @see getVelocity, setVelocity
  24831. */
  24832. float getFloatVelocity() const throw();
  24833. /** Changes the velocity of a note-on or note-off message.
  24834. If the message isn't a note on or off, this will do nothing.
  24835. @param newVelocity the new velocity, in the range 0 to 1.0
  24836. @see getFloatVelocity, multiplyVelocity
  24837. */
  24838. void setVelocity (float newVelocity) throw();
  24839. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  24840. If the message isn't a note on or off, this will do nothing.
  24841. @param scaleFactor the value by which to multiply the velocity
  24842. @see setVelocity
  24843. */
  24844. void multiplyVelocity (float scaleFactor) throw();
  24845. /** Returns true if the message is a program (patch) change message.
  24846. @see getProgramChangeNumber, getGMInstrumentName
  24847. */
  24848. bool isProgramChange() const throw();
  24849. /** Returns the new program number of a program change message.
  24850. If the message isn't a program change, the value returned will be
  24851. nonsense.
  24852. @see isProgramChange, getGMInstrumentName
  24853. */
  24854. int getProgramChangeNumber() const throw();
  24855. /** Creates a program-change message.
  24856. @param channel the midi channel, in the range 1 to 16
  24857. @param programNumber the midi program number, 0 to 127
  24858. @see isProgramChange, getGMInstrumentName
  24859. */
  24860. static const MidiMessage programChange (int channel, int programNumber) throw();
  24861. /** Returns true if the message is a pitch-wheel move.
  24862. @see getPitchWheelValue, pitchWheel
  24863. */
  24864. bool isPitchWheel() const throw();
  24865. /** Returns the pitch wheel position from a pitch-wheel move message.
  24866. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  24867. If called for messages which aren't pitch wheel events, the number returned will be
  24868. nonsense.
  24869. @see isPitchWheel
  24870. */
  24871. int getPitchWheelValue() const throw();
  24872. /** Creates a pitch-wheel move message.
  24873. @param channel the midi channel, in the range 1 to 16
  24874. @param position the wheel position, in the range 0 to 16383
  24875. @see isPitchWheel
  24876. */
  24877. static const MidiMessage pitchWheel (int channel, int position) throw();
  24878. /** Returns true if the message is an aftertouch event.
  24879. For aftertouch events, use the getNoteNumber() method to find out the key
  24880. that it applies to, and getAftertouchValue() to find out the amount. Use
  24881. getChannel() to find out the channel.
  24882. @see getAftertouchValue, getNoteNumber
  24883. */
  24884. bool isAftertouch() const throw();
  24885. /** Returns the amount of aftertouch from an aftertouch messages.
  24886. The value returned is in the range 0 to 127, and will be nonsense for messages
  24887. other than aftertouch messages.
  24888. @see isAftertouch
  24889. */
  24890. int getAfterTouchValue() const throw();
  24891. /** Creates an aftertouch message.
  24892. @param channel the midi channel, in the range 1 to 16
  24893. @param noteNumber the key number, 0 to 127
  24894. @param aftertouchAmount the amount of aftertouch, 0 to 127
  24895. @see isAftertouch
  24896. */
  24897. static const MidiMessage aftertouchChange (int channel,
  24898. int noteNumber,
  24899. int aftertouchAmount) throw();
  24900. /** Returns true if the message is a channel-pressure change event.
  24901. This is like aftertouch, but common to the whole channel rather than a specific
  24902. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  24903. to find out the channel.
  24904. @see channelPressureChange
  24905. */
  24906. bool isChannelPressure() const throw();
  24907. /** Returns the pressure from a channel pressure change message.
  24908. @returns the pressure, in the range 0 to 127
  24909. @see isChannelPressure, channelPressureChange
  24910. */
  24911. int getChannelPressureValue() const throw();
  24912. /** Creates a channel-pressure change event.
  24913. @param channel the midi channel: 1 to 16
  24914. @param pressure the pressure, 0 to 127
  24915. @see isChannelPressure
  24916. */
  24917. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  24918. /** Returns true if this is a midi controller message.
  24919. @see getControllerNumber, getControllerValue, controllerEvent
  24920. */
  24921. bool isController() const throw();
  24922. /** Returns the controller number of a controller message.
  24923. The name of the controller can be looked up using the getControllerName() method.
  24924. Note that the value returned is invalid for messages that aren't controller changes.
  24925. @see isController, getControllerName, getControllerValue
  24926. */
  24927. int getControllerNumber() const throw();
  24928. /** Returns the controller value from a controller message.
  24929. A value 0 to 127 is returned to indicate the new controller position.
  24930. Note that the value returned is invalid for messages that aren't controller changes.
  24931. @see isController, getControllerNumber
  24932. */
  24933. int getControllerValue() const throw();
  24934. /** Creates a controller message.
  24935. @param channel the midi channel, in the range 1 to 16
  24936. @param controllerType the type of controller
  24937. @param value the controller value
  24938. @see isController
  24939. */
  24940. static const MidiMessage controllerEvent (int channel,
  24941. int controllerType,
  24942. int value) throw();
  24943. /** Checks whether this message is an all-notes-off message.
  24944. @see allNotesOff
  24945. */
  24946. bool isAllNotesOff() const throw();
  24947. /** Checks whether this message is an all-sound-off message.
  24948. @see allSoundOff
  24949. */
  24950. bool isAllSoundOff() const throw();
  24951. /** Creates an all-notes-off message.
  24952. @param channel the midi channel, in the range 1 to 16
  24953. @see isAllNotesOff
  24954. */
  24955. static const MidiMessage allNotesOff (int channel) throw();
  24956. /** Creates an all-sound-off message.
  24957. @param channel the midi channel, in the range 1 to 16
  24958. @see isAllSoundOff
  24959. */
  24960. static const MidiMessage allSoundOff (int channel) throw();
  24961. /** Creates an all-controllers-off message.
  24962. @param channel the midi channel, in the range 1 to 16
  24963. */
  24964. static const MidiMessage allControllersOff (int channel) throw();
  24965. /** Returns true if this event is a meta-event.
  24966. Meta-events are things like tempo changes, track names, etc.
  24967. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24968. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24969. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24970. */
  24971. bool isMetaEvent() const throw();
  24972. /** Returns a meta-event's type number.
  24973. If the message isn't a meta-event, this will return -1.
  24974. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24975. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24976. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24977. */
  24978. int getMetaEventType() const throw();
  24979. /** Returns a pointer to the data in a meta-event.
  24980. @see isMetaEvent, getMetaEventLength
  24981. */
  24982. const uint8* getMetaEventData() const throw();
  24983. /** Returns the length of the data for a meta-event.
  24984. @see isMetaEvent, getMetaEventData
  24985. */
  24986. int getMetaEventLength() const throw();
  24987. /** Returns true if this is a 'track' meta-event. */
  24988. bool isTrackMetaEvent() const throw();
  24989. /** Returns true if this is an 'end-of-track' meta-event. */
  24990. bool isEndOfTrackMetaEvent() const throw();
  24991. /** Creates an end-of-track meta-event.
  24992. @see isEndOfTrackMetaEvent
  24993. */
  24994. static const MidiMessage endOfTrack() throw();
  24995. /** Returns true if this is an 'track name' meta-event.
  24996. You can use the getTextFromTextMetaEvent() method to get the track's name.
  24997. */
  24998. bool isTrackNameEvent() const throw();
  24999. /** Returns true if this is a 'text' meta-event.
  25000. @see getTextFromTextMetaEvent
  25001. */
  25002. bool isTextMetaEvent() const throw();
  25003. /** Returns the text from a text meta-event.
  25004. @see isTextMetaEvent
  25005. */
  25006. const String getTextFromTextMetaEvent() const;
  25007. /** Returns true if this is a 'tempo' meta-event.
  25008. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  25009. */
  25010. bool isTempoMetaEvent() const throw();
  25011. /** Returns the tick length from a tempo meta-event.
  25012. @param timeFormat the 16-bit time format value from the midi file's header.
  25013. @returns the tick length (in seconds).
  25014. @see isTempoMetaEvent
  25015. */
  25016. double getTempoMetaEventTickLength (short timeFormat) const throw();
  25017. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  25018. @see isTempoMetaEvent, getTempoMetaEventTickLength
  25019. */
  25020. double getTempoSecondsPerQuarterNote() const throw();
  25021. /** Creates a tempo meta-event.
  25022. @see isTempoMetaEvent
  25023. */
  25024. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  25025. /** Returns true if this is a 'time-signature' meta-event.
  25026. @see getTimeSignatureInfo
  25027. */
  25028. bool isTimeSignatureMetaEvent() const throw();
  25029. /** Returns the time-signature values from a time-signature meta-event.
  25030. @see isTimeSignatureMetaEvent
  25031. */
  25032. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  25033. /** Creates a time-signature meta-event.
  25034. @see isTimeSignatureMetaEvent
  25035. */
  25036. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  25037. /** Returns true if this is a 'key-signature' meta-event.
  25038. @see getKeySignatureNumberOfSharpsOrFlats
  25039. */
  25040. bool isKeySignatureMetaEvent() const throw();
  25041. /** Returns the key from a key-signature meta-event.
  25042. @see isKeySignatureMetaEvent
  25043. */
  25044. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  25045. /** Returns true if this is a 'channel' meta-event.
  25046. A channel meta-event specifies the midi channel that should be used
  25047. for subsequent meta-events.
  25048. @see getMidiChannelMetaEventChannel
  25049. */
  25050. bool isMidiChannelMetaEvent() const throw();
  25051. /** Returns the channel number from a channel meta-event.
  25052. @returns the channel, in the range 1 to 16.
  25053. @see isMidiChannelMetaEvent
  25054. */
  25055. int getMidiChannelMetaEventChannel() const throw();
  25056. /** Creates a midi channel meta-event.
  25057. @param channel the midi channel, in the range 1 to 16
  25058. @see isMidiChannelMetaEvent
  25059. */
  25060. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  25061. /** Returns true if this is an active-sense message. */
  25062. bool isActiveSense() const throw();
  25063. /** Returns true if this is a midi start event.
  25064. @see midiStart
  25065. */
  25066. bool isMidiStart() const throw();
  25067. /** Creates a midi start event. */
  25068. static const MidiMessage midiStart() throw();
  25069. /** Returns true if this is a midi continue event.
  25070. @see midiContinue
  25071. */
  25072. bool isMidiContinue() const throw();
  25073. /** Creates a midi continue event. */
  25074. static const MidiMessage midiContinue() throw();
  25075. /** Returns true if this is a midi stop event.
  25076. @see midiStop
  25077. */
  25078. bool isMidiStop() const throw();
  25079. /** Creates a midi stop event. */
  25080. static const MidiMessage midiStop() throw();
  25081. /** Returns true if this is a midi clock event.
  25082. @see midiClock, songPositionPointer
  25083. */
  25084. bool isMidiClock() const throw();
  25085. /** Creates a midi clock event. */
  25086. static const MidiMessage midiClock() throw();
  25087. /** Returns true if this is a song-position-pointer message.
  25088. @see getSongPositionPointerMidiBeat, songPositionPointer
  25089. */
  25090. bool isSongPositionPointer() const throw();
  25091. /** Returns the midi beat-number of a song-position-pointer message.
  25092. @see isSongPositionPointer, songPositionPointer
  25093. */
  25094. int getSongPositionPointerMidiBeat() const throw();
  25095. /** Creates a song-position-pointer message.
  25096. The position is a number of midi beats from the start of the song, where 1 midi
  25097. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  25098. are 4 midi beats in a quarter-note.
  25099. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  25100. */
  25101. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  25102. /** Returns true if this is a quarter-frame midi timecode message.
  25103. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  25104. */
  25105. bool isQuarterFrame() const throw();
  25106. /** Returns the sequence number of a quarter-frame midi timecode message.
  25107. This will be a value between 0 and 7.
  25108. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  25109. */
  25110. int getQuarterFrameSequenceNumber() const throw();
  25111. /** Returns the value from a quarter-frame message.
  25112. This will be the lower nybble of the message's data-byte, a value
  25113. between 0 and 15
  25114. */
  25115. int getQuarterFrameValue() const throw();
  25116. /** Creates a quarter-frame MTC message.
  25117. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  25118. @param value a value 0 to 15 for the lower nybble of the message's data byte
  25119. */
  25120. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  25121. /** SMPTE timecode types.
  25122. Used by the getFullFrameParameters() and fullFrame() methods.
  25123. */
  25124. enum SmpteTimecodeType
  25125. {
  25126. fps24 = 0,
  25127. fps25 = 1,
  25128. fps30drop = 2,
  25129. fps30 = 3
  25130. };
  25131. /** Returns true if this is a full-frame midi timecode message.
  25132. */
  25133. bool isFullFrame() const throw();
  25134. /** Extracts the timecode information from a full-frame midi timecode message.
  25135. You should only call this on messages where you've used isFullFrame() to
  25136. check that they're the right kind.
  25137. */
  25138. void getFullFrameParameters (int& hours,
  25139. int& minutes,
  25140. int& seconds,
  25141. int& frames,
  25142. SmpteTimecodeType& timecodeType) const throw();
  25143. /** Creates a full-frame MTC message.
  25144. */
  25145. static const MidiMessage fullFrame (int hours,
  25146. int minutes,
  25147. int seconds,
  25148. int frames,
  25149. SmpteTimecodeType timecodeType);
  25150. /** Types of MMC command.
  25151. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  25152. */
  25153. enum MidiMachineControlCommand
  25154. {
  25155. mmc_stop = 1,
  25156. mmc_play = 2,
  25157. mmc_deferredplay = 3,
  25158. mmc_fastforward = 4,
  25159. mmc_rewind = 5,
  25160. mmc_recordStart = 6,
  25161. mmc_recordStop = 7,
  25162. mmc_pause = 9
  25163. };
  25164. /** Checks whether this is an MMC message.
  25165. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  25166. */
  25167. bool isMidiMachineControlMessage() const throw();
  25168. /** For an MMC message, this returns its type.
  25169. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  25170. calling this method.
  25171. */
  25172. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  25173. /** Creates an MMC message.
  25174. */
  25175. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  25176. /** Checks whether this is an MMC "goto" message.
  25177. If it is, the parameters passed-in are set to the time that the message contains.
  25178. @see midiMachineControlGoto
  25179. */
  25180. bool isMidiMachineControlGoto (int& hours,
  25181. int& minutes,
  25182. int& seconds,
  25183. int& frames) const throw();
  25184. /** Creates an MMC "goto" message.
  25185. This messages tells the device to go to a specific frame.
  25186. @see isMidiMachineControlGoto
  25187. */
  25188. static const MidiMessage midiMachineControlGoto (int hours,
  25189. int minutes,
  25190. int seconds,
  25191. int frames);
  25192. /** Creates a master-volume change message.
  25193. @param volume the volume, 0 to 1.0
  25194. */
  25195. static const MidiMessage masterVolume (float volume);
  25196. /** Creates a system-exclusive message.
  25197. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  25198. */
  25199. static const MidiMessage createSysExMessage (const uint8* sysexData,
  25200. int dataSize);
  25201. /** Reads a midi variable-length integer.
  25202. @param data the data to read the number from
  25203. @param numBytesUsed on return, this will be set to the number of bytes that were read
  25204. */
  25205. static int readVariableLengthVal (const uint8* data,
  25206. int& numBytesUsed) throw();
  25207. /** Based on the first byte of a short midi message, this uses a lookup table
  25208. to return the message length (either 1, 2, or 3 bytes).
  25209. The value passed in must be 0x80 or higher.
  25210. */
  25211. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  25212. /** Returns the name of a midi note number.
  25213. E.g "C", "D#", etc.
  25214. @param noteNumber the midi note number, 0 to 127
  25215. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  25216. they'll be flattened, e.g. "Db"
  25217. @param includeOctaveNumber if true, the octave number will be appended to the string,
  25218. e.g. "C#4"
  25219. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  25220. number that will be used for middle C's octave
  25221. @see getMidiNoteInHertz
  25222. */
  25223. static const String getMidiNoteName (int noteNumber,
  25224. bool useSharps,
  25225. bool includeOctaveNumber,
  25226. int octaveNumForMiddleC) throw();
  25227. /** Returns the frequency of a midi note number.
  25228. @see getMidiNoteName
  25229. */
  25230. static const double getMidiNoteInHertz (int noteNumber) throw();
  25231. /** Returns the standard name of a GM instrument.
  25232. @param midiInstrumentNumber the program number 0 to 127
  25233. @see getProgramChangeNumber
  25234. */
  25235. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  25236. /** Returns the name of a bank of GM instruments.
  25237. @param midiBankNumber the bank, 0 to 15
  25238. */
  25239. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  25240. /** Returns the standard name of a channel 10 percussion sound.
  25241. @param midiNoteNumber the key number, 35 to 81
  25242. */
  25243. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  25244. /** Returns the name of a controller type number.
  25245. @see getControllerNumber
  25246. */
  25247. static const String getControllerName (int controllerNumber) throw();
  25248. juce_UseDebuggingNewOperator
  25249. private:
  25250. double timeStamp;
  25251. uint8* data;
  25252. int size;
  25253. union
  25254. {
  25255. uint8 asBytes[4];
  25256. uint32 asInt32;
  25257. } preallocatedData;
  25258. };
  25259. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  25260. /*** End of inlined file: juce_MidiMessage.h ***/
  25261. class MidiInput;
  25262. /**
  25263. Receives midi messages from a midi input device.
  25264. This class is overridden to handle incoming midi messages. See the MidiInput
  25265. class for more details.
  25266. @see MidiInput
  25267. */
  25268. class JUCE_API MidiInputCallback
  25269. {
  25270. public:
  25271. /** Destructor. */
  25272. virtual ~MidiInputCallback() {}
  25273. /** Receives an incoming message.
  25274. A MidiInput object will call this method when a midi event arrives. It'll be
  25275. called on a high-priority system thread, so avoid doing anything time-consuming
  25276. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  25277. for queueing incoming messages for use later.
  25278. @param source the MidiInput object that generated the message
  25279. @param message the incoming message. The message's timestamp is set to a value
  25280. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  25281. time when the message arrived.
  25282. */
  25283. virtual void handleIncomingMidiMessage (MidiInput* source,
  25284. const MidiMessage& message) = 0;
  25285. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  25286. If a long sysex message is broken up into multiple packets, this callback is made
  25287. for each packet that arrives until the message is finished, at which point
  25288. the normal handleIncomingMidiMessage() callback will be made with the entire
  25289. message.
  25290. The message passed in will contain the start of a sysex, but won't be finished
  25291. with the terminating 0xf7 byte.
  25292. */
  25293. virtual void handlePartialSysexMessage (MidiInput* source,
  25294. const uint8* messageData,
  25295. const int numBytesSoFar,
  25296. const double timestamp)
  25297. {
  25298. // (this bit is just to avoid compiler warnings about unused variables)
  25299. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  25300. }
  25301. };
  25302. /**
  25303. Represents a midi input device.
  25304. To create one of these, use the static getDevices() method to find out what inputs are
  25305. available, and then use the openDevice() method to try to open one.
  25306. @see MidiOutput
  25307. */
  25308. class JUCE_API MidiInput
  25309. {
  25310. public:
  25311. /** Returns a list of the available midi input devices.
  25312. You can open one of the devices by passing its index into the
  25313. openDevice() method.
  25314. @see getDefaultDeviceIndex, openDevice
  25315. */
  25316. static const StringArray getDevices();
  25317. /** Returns the index of the default midi input device to use.
  25318. This refers to the index in the list returned by getDevices().
  25319. */
  25320. static int getDefaultDeviceIndex();
  25321. /** Tries to open one of the midi input devices.
  25322. This will return a MidiInput object if it manages to open it. You can then
  25323. call start() and stop() on this device, and delete it when no longer needed.
  25324. If the device can't be opened, this will return a null pointer.
  25325. @param deviceIndex the index of a device from the list returned by getDevices()
  25326. @param callback the object that will receive the midi messages from this device.
  25327. @see MidiInputCallback, getDevices
  25328. */
  25329. static MidiInput* openDevice (int deviceIndex,
  25330. MidiInputCallback* callback);
  25331. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25332. /** This will try to create a new midi input device (Not available on Windows).
  25333. This will attempt to create a new midi input device with the specified name,
  25334. for other apps to connect to.
  25335. Returns 0 if a device can't be created.
  25336. @param deviceName the name to use for the new device
  25337. @param callback the object that will receive the midi messages from this device.
  25338. */
  25339. static MidiInput* createNewDevice (const String& deviceName,
  25340. MidiInputCallback* callback);
  25341. #endif
  25342. /** Destructor. */
  25343. virtual ~MidiInput();
  25344. /** Returns the name of this device.
  25345. */
  25346. virtual const String getName() const throw() { return name; }
  25347. /** Allows you to set a custom name for the device, in case you don't like the name
  25348. it was given when created.
  25349. */
  25350. virtual void setName (const String& newName) throw() { name = newName; }
  25351. /** Starts the device running.
  25352. After calling this, the device will start sending midi messages to the
  25353. MidiInputCallback object that was specified when the openDevice() method
  25354. was called.
  25355. @see stop
  25356. */
  25357. virtual void start();
  25358. /** Stops the device running.
  25359. @see start
  25360. */
  25361. virtual void stop();
  25362. juce_UseDebuggingNewOperator
  25363. protected:
  25364. String name;
  25365. void* internal;
  25366. explicit MidiInput (const String& name);
  25367. private:
  25368. MidiInput (const MidiInput&);
  25369. MidiInput& operator= (const MidiInput&);
  25370. };
  25371. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  25372. /*** End of inlined file: juce_MidiInput.h ***/
  25373. /*** Start of inlined file: juce_MidiOutput.h ***/
  25374. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25375. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  25376. /*** Start of inlined file: juce_MidiBuffer.h ***/
  25377. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  25378. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  25379. /**
  25380. Holds a sequence of time-stamped midi events.
  25381. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  25382. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  25383. @see MidiMessage
  25384. */
  25385. class JUCE_API MidiBuffer
  25386. {
  25387. public:
  25388. /** Creates an empty MidiBuffer. */
  25389. MidiBuffer() throw();
  25390. /** Creates a MidiBuffer containing a single midi message. */
  25391. explicit MidiBuffer (const MidiMessage& message) throw();
  25392. /** Creates a copy of another MidiBuffer. */
  25393. MidiBuffer (const MidiBuffer& other) throw();
  25394. /** Makes a copy of another MidiBuffer. */
  25395. MidiBuffer& operator= (const MidiBuffer& other) throw();
  25396. /** Destructor */
  25397. ~MidiBuffer() throw();
  25398. /** Removes all events from the buffer. */
  25399. void clear() throw();
  25400. /** Removes all events between two times from the buffer.
  25401. All events for which (start <= event position < start + numSamples) will
  25402. be removed.
  25403. */
  25404. void clear (const int start,
  25405. const int numSamples) throw();
  25406. /** Returns true if the buffer is empty.
  25407. To actually retrieve the events, use a MidiBuffer::Iterator object
  25408. */
  25409. bool isEmpty() const throw();
  25410. /** Counts the number of events in the buffer.
  25411. This is actually quite a slow operation, as it has to iterate through all
  25412. the events, so you might prefer to call isEmpty() if that's all you need
  25413. to know.
  25414. */
  25415. int getNumEvents() const throw();
  25416. /** Adds an event to the buffer.
  25417. The sample number will be used to determine the position of the event in
  25418. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  25419. ignored.
  25420. If an event is added whose sample position is the same as one or more events
  25421. already in the buffer, the new event will be placed after the existing ones.
  25422. To retrieve events, use a MidiBuffer::Iterator object
  25423. */
  25424. void addEvent (const MidiMessage& midiMessage,
  25425. const int sampleNumber) throw();
  25426. /** Adds an event to the buffer from raw midi data.
  25427. The sample number will be used to determine the position of the event in
  25428. the buffer, which is always kept sorted.
  25429. If an event is added whose sample position is the same as one or more events
  25430. already in the buffer, the new event will be placed after the existing ones.
  25431. The event data will be inspected to calculate the number of bytes in length that
  25432. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  25433. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  25434. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  25435. add an event at all.
  25436. To retrieve events, use a MidiBuffer::Iterator object
  25437. */
  25438. void addEvent (const uint8* const rawMidiData,
  25439. const int maxBytesOfMidiData,
  25440. const int sampleNumber) throw();
  25441. /** Adds some events from another buffer to this one.
  25442. @param otherBuffer the buffer containing the events you want to add
  25443. @param startSample the lowest sample number in the source buffer for which
  25444. events should be added. Any source events whose timestamp is
  25445. less than this will be ignored
  25446. @param numSamples the valid range of samples from the source buffer for which
  25447. events should be added - i.e. events in the source buffer whose
  25448. timestamp is greater than or equal to (startSample + numSamples)
  25449. will be ignored. If this value is less than 0, all events after
  25450. startSample will be taken.
  25451. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  25452. that are added to this buffer
  25453. */
  25454. void addEvents (const MidiBuffer& otherBuffer,
  25455. const int startSample,
  25456. const int numSamples,
  25457. const int sampleDeltaToAdd) throw();
  25458. /** Returns the sample number of the first event in the buffer.
  25459. If the buffer's empty, this will just return 0.
  25460. */
  25461. int getFirstEventTime() const throw();
  25462. /** Returns the sample number of the last event in the buffer.
  25463. If the buffer's empty, this will just return 0.
  25464. */
  25465. int getLastEventTime() const throw();
  25466. /** Exchanges the contents of this buffer with another one.
  25467. This is a quick operation, because no memory allocating or copying is done, it
  25468. just swaps the internal state of the two buffers.
  25469. */
  25470. void swapWith (MidiBuffer& other);
  25471. /** Preallocates some memory for the buffer to use.
  25472. This helps to avoid needing to reallocate space when the buffer has messages
  25473. added to it.
  25474. */
  25475. void ensureSize (size_t minimumNumBytes);
  25476. /**
  25477. Used to iterate through the events in a MidiBuffer.
  25478. Note that altering the buffer while an iterator is using it isn't a
  25479. safe operation.
  25480. @see MidiBuffer
  25481. */
  25482. class Iterator
  25483. {
  25484. public:
  25485. /** Creates an Iterator for this MidiBuffer. */
  25486. Iterator (const MidiBuffer& buffer) throw();
  25487. /** Destructor. */
  25488. ~Iterator() throw();
  25489. /** Repositions the iterator so that the next event retrieved will be the first
  25490. one whose sample position is at greater than or equal to the given position.
  25491. */
  25492. void setNextSamplePosition (const int samplePosition) throw();
  25493. /** Retrieves a copy of the next event from the buffer.
  25494. @param result on return, this will be the message (the MidiMessage's timestamp
  25495. is not set)
  25496. @param samplePosition on return, this will be the position of the event
  25497. @returns true if an event was found, or false if the iterator has reached
  25498. the end of the buffer
  25499. */
  25500. bool getNextEvent (MidiMessage& result,
  25501. int& samplePosition) throw();
  25502. /** Retrieves the next event from the buffer.
  25503. @param midiData on return, this pointer will be set to a block of data containing
  25504. the midi message. Note that to make it fast, this is a pointer
  25505. directly into the MidiBuffer's internal data, so is only valid
  25506. temporarily until the MidiBuffer is altered.
  25507. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  25508. midi message
  25509. @param samplePosition on return, this will be the position of the event
  25510. @returns true if an event was found, or false if the iterator has reached
  25511. the end of the buffer
  25512. */
  25513. bool getNextEvent (const uint8* &midiData,
  25514. int& numBytesOfMidiData,
  25515. int& samplePosition) throw();
  25516. juce_UseDebuggingNewOperator
  25517. private:
  25518. const MidiBuffer& buffer;
  25519. const uint8* data;
  25520. Iterator (const Iterator&);
  25521. Iterator& operator= (const Iterator&);
  25522. };
  25523. juce_UseDebuggingNewOperator
  25524. private:
  25525. friend class MidiBuffer::Iterator;
  25526. MemoryBlock data;
  25527. int bytesUsed;
  25528. uint8* getData() const throw();
  25529. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  25530. static int getEventTime (const void* d) throw();
  25531. static uint16 getEventDataSize (const void* d) throw();
  25532. static uint16 getEventTotalSize (const void* d) throw();
  25533. };
  25534. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  25535. /*** End of inlined file: juce_MidiBuffer.h ***/
  25536. /**
  25537. Represents a midi output device.
  25538. To create one of these, use the static getDevices() method to find out what
  25539. outputs are available, then use the openDevice() method to try to open one.
  25540. @see MidiInput
  25541. */
  25542. class JUCE_API MidiOutput : private Thread
  25543. {
  25544. public:
  25545. /** Returns a list of the available midi output devices.
  25546. You can open one of the devices by passing its index into the
  25547. openDevice() method.
  25548. @see getDefaultDeviceIndex, openDevice
  25549. */
  25550. static const StringArray getDevices();
  25551. /** Returns the index of the default midi output device to use.
  25552. This refers to the index in the list returned by getDevices().
  25553. */
  25554. static int getDefaultDeviceIndex();
  25555. /** Tries to open one of the midi output devices.
  25556. This will return a MidiOutput object if it manages to open it. You can then
  25557. send messages to this device, and delete it when no longer needed.
  25558. If the device can't be opened, this will return a null pointer.
  25559. @param deviceIndex the index of a device from the list returned by getDevices()
  25560. @see getDevices
  25561. */
  25562. static MidiOutput* openDevice (int deviceIndex);
  25563. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25564. /** This will try to create a new midi output device (Not available on Windows).
  25565. This will attempt to create a new midi output device that other apps can connect
  25566. to and use as their midi input.
  25567. Returns 0 if a device can't be created.
  25568. @param deviceName the name to use for the new device
  25569. */
  25570. static MidiOutput* createNewDevice (const String& deviceName);
  25571. #endif
  25572. /** Destructor. */
  25573. virtual ~MidiOutput();
  25574. /** Makes this device output a midi message.
  25575. @see MidiMessage
  25576. */
  25577. virtual void sendMessageNow (const MidiMessage& message);
  25578. /** Sends a midi reset to the device. */
  25579. virtual void reset();
  25580. /** Returns the current volume setting for this device. */
  25581. virtual bool getVolume (float& leftVol,
  25582. float& rightVol);
  25583. /** Changes the overall volume for this device. */
  25584. virtual void setVolume (float leftVol,
  25585. float rightVol);
  25586. /** This lets you supply a block of messages that will be sent out at some point
  25587. in the future.
  25588. The MidiOutput class has an internal thread that can send out timestamped
  25589. messages - this appends a set of messages to its internal buffer, ready for
  25590. sending.
  25591. This will only work if you've already started the thread with startBackgroundThread().
  25592. A time is supplied, at which the block of messages should be sent. This time uses
  25593. the same time base as Time::getMillisecondCounter(), and must be in the future.
  25594. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  25595. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  25596. samplesPerSecondForBuffer value is needed to convert this sample position to a
  25597. real time.
  25598. */
  25599. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  25600. double millisecondCounterToStartAt,
  25601. double samplesPerSecondForBuffer);
  25602. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  25603. */
  25604. virtual void clearAllPendingMessages();
  25605. /** Starts up a background thread so that the device can send blocks of data.
  25606. Call this to get the device ready, before using sendBlockOfMessages().
  25607. */
  25608. virtual void startBackgroundThread();
  25609. /** Stops the background thread, and clears any pending midi events.
  25610. @see startBackgroundThread
  25611. */
  25612. virtual void stopBackgroundThread();
  25613. juce_UseDebuggingNewOperator
  25614. protected:
  25615. void* internal;
  25616. struct PendingMessage
  25617. {
  25618. PendingMessage (const uint8* data, int len, double sampleNumber);
  25619. MidiMessage message;
  25620. PendingMessage* next;
  25621. juce_UseDebuggingNewOperator
  25622. };
  25623. CriticalSection lock;
  25624. PendingMessage* firstMessage;
  25625. MidiOutput();
  25626. void run();
  25627. private:
  25628. MidiOutput (const MidiOutput&);
  25629. MidiOutput& operator= (const MidiOutput&);
  25630. };
  25631. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  25632. /*** End of inlined file: juce_MidiOutput.h ***/
  25633. /*** Start of inlined file: juce_ComboBox.h ***/
  25634. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  25635. #define __JUCE_COMBOBOX_JUCEHEADER__
  25636. /*** Start of inlined file: juce_Label.h ***/
  25637. #ifndef __JUCE_LABEL_JUCEHEADER__
  25638. #define __JUCE_LABEL_JUCEHEADER__
  25639. /*** Start of inlined file: juce_TextEditor.h ***/
  25640. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  25641. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  25642. /*** Start of inlined file: juce_Viewport.h ***/
  25643. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  25644. #define __JUCE_VIEWPORT_JUCEHEADER__
  25645. /*** Start of inlined file: juce_ScrollBar.h ***/
  25646. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  25647. #define __JUCE_SCROLLBAR_JUCEHEADER__
  25648. /*** Start of inlined file: juce_Button.h ***/
  25649. #ifndef __JUCE_BUTTON_JUCEHEADER__
  25650. #define __JUCE_BUTTON_JUCEHEADER__
  25651. /*** Start of inlined file: juce_TooltipWindow.h ***/
  25652. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25653. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25654. /*** Start of inlined file: juce_TooltipClient.h ***/
  25655. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25656. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25657. /**
  25658. Components that want to use pop-up tooltips should implement this interface.
  25659. A TooltipWindow will wait for the mouse to hover over a component that
  25660. implements the TooltipClient interface, and when it finds one, it will display
  25661. the tooltip returned by its getTooltip() method.
  25662. @see TooltipWindow, SettableTooltipClient
  25663. */
  25664. class JUCE_API TooltipClient
  25665. {
  25666. public:
  25667. /** Destructor. */
  25668. virtual ~TooltipClient() {}
  25669. /** Returns the string that this object wants to show as its tooltip. */
  25670. virtual const String getTooltip() = 0;
  25671. };
  25672. /**
  25673. An implementation of TooltipClient that stores the tooltip string and a method
  25674. for changing it.
  25675. This makes it easy to add a tooltip to a custom component, by simply adding this
  25676. as a base class and calling setTooltip().
  25677. Many of the Juce widgets already use this as a base class to implement their
  25678. tooltips.
  25679. @see TooltipClient, TooltipWindow
  25680. */
  25681. class JUCE_API SettableTooltipClient : public TooltipClient
  25682. {
  25683. public:
  25684. /** Destructor. */
  25685. virtual ~SettableTooltipClient() {}
  25686. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  25687. virtual const String getTooltip() { return tooltipString; }
  25688. juce_UseDebuggingNewOperator
  25689. protected:
  25690. String tooltipString;
  25691. };
  25692. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25693. /*** End of inlined file: juce_TooltipClient.h ***/
  25694. /**
  25695. A window that displays a pop-up tooltip when the mouse hovers over another component.
  25696. To enable tooltips in your app, just create a single instance of a TooltipWindow
  25697. object.
  25698. The TooltipWindow object will then stay invisible, waiting until the mouse
  25699. hovers for the specified length of time - it will then see if it's currently
  25700. over a component which implements the TooltipClient interface, and if so,
  25701. it will make itself visible to show the tooltip in the appropriate place.
  25702. @see TooltipClient, SettableTooltipClient
  25703. */
  25704. class JUCE_API TooltipWindow : public Component,
  25705. private Timer
  25706. {
  25707. public:
  25708. /** Creates a tooltip window.
  25709. Make sure your app only creates one instance of this class, otherwise you'll
  25710. get multiple overlaid tooltips appearing. The window will initially be invisible
  25711. and will make itself visible when it needs to display a tip.
  25712. To change the style of tooltips, see the LookAndFeel class for its tooltip
  25713. methods.
  25714. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  25715. otherwise the tooltip will be added to the given parent
  25716. component.
  25717. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  25718. before a tooltip will be shown
  25719. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  25720. */
  25721. explicit TooltipWindow (Component* parentComponent = 0,
  25722. int millisecondsBeforeTipAppears = 700);
  25723. /** Destructor. */
  25724. ~TooltipWindow();
  25725. /** Changes the time before the tip appears.
  25726. This lets you change the value that was set in the constructor.
  25727. */
  25728. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  25729. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  25730. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25731. methods.
  25732. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25733. */
  25734. enum ColourIds
  25735. {
  25736. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  25737. textColourId = 0x1001c00, /**< The colour to use for the text. */
  25738. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  25739. };
  25740. juce_UseDebuggingNewOperator
  25741. private:
  25742. int millisecondsBeforeTipAppears;
  25743. Point<int> lastMousePos;
  25744. int mouseClicks;
  25745. unsigned int lastCompChangeTime, lastHideTime;
  25746. Component* lastComponentUnderMouse;
  25747. bool changedCompsSinceShown;
  25748. String tipShowing, lastTipUnderMouse;
  25749. void paint (Graphics& g);
  25750. void mouseEnter (const MouseEvent& e);
  25751. void timerCallback();
  25752. static const String getTipFor (Component* c);
  25753. void showFor (const String& tip);
  25754. void hide();
  25755. TooltipWindow (const TooltipWindow&);
  25756. TooltipWindow& operator= (const TooltipWindow&);
  25757. };
  25758. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25759. /*** End of inlined file: juce_TooltipWindow.h ***/
  25760. /**
  25761. A base class for buttons.
  25762. This contains all the logic for button behaviours such as enabling/disabling,
  25763. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  25764. and radio groups, etc.
  25765. @see TextButton, DrawableButton, ToggleButton
  25766. */
  25767. class JUCE_API Button : public Component,
  25768. public SettableTooltipClient,
  25769. public ApplicationCommandManagerListener,
  25770. public Value::Listener,
  25771. private KeyListener
  25772. {
  25773. protected:
  25774. /** Creates a button.
  25775. @param buttonName the text to put in the button (the component's name is also
  25776. initially set to this string, but these can be changed later
  25777. using the setName() and setButtonText() methods)
  25778. */
  25779. explicit Button (const String& buttonName);
  25780. public:
  25781. /** Destructor. */
  25782. virtual ~Button();
  25783. /** Changes the button's text.
  25784. @see getButtonText
  25785. */
  25786. void setButtonText (const String& newText);
  25787. /** Returns the text displayed in the button.
  25788. @see setButtonText
  25789. */
  25790. const String getButtonText() const { return text; }
  25791. /** Returns true if the button is currently being held down by the mouse.
  25792. @see isOver
  25793. */
  25794. bool isDown() const throw();
  25795. /** Returns true if the mouse is currently over the button.
  25796. This will be also be true if the mouse is being held down.
  25797. @see isDown
  25798. */
  25799. bool isOver() const throw();
  25800. /** A button has an on/off state associated with it, and this changes that.
  25801. By default buttons are 'off' and for simple buttons that you click to perform
  25802. an action you won't change this. Toggle buttons, however will want to
  25803. change their state when turned on or off.
  25804. @param shouldBeOn whether to set the button's toggle state to be on or
  25805. off. If it's a member of a button group, this will
  25806. always try to turn it on, and to turn off any other
  25807. buttons in the group
  25808. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  25809. the button will be repainted but no notification will
  25810. be sent
  25811. @see getToggleState, setRadioGroupId
  25812. */
  25813. void setToggleState (bool shouldBeOn,
  25814. bool sendChangeNotification);
  25815. /** Returns true if the button in 'on'.
  25816. By default buttons are 'off' and for simple buttons that you click to perform
  25817. an action you won't change this. Toggle buttons, however will want to
  25818. change their state when turned on or off.
  25819. @see setToggleState
  25820. */
  25821. bool getToggleState() const throw() { return isOn.getValue(); }
  25822. /** Returns the Value object that represents the botton's toggle state.
  25823. You can use this Value object to connect the button's state to external values or setters,
  25824. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  25825. your own Value object.
  25826. @see getToggleState, Value
  25827. */
  25828. Value& getToggleStateValue() { return isOn; }
  25829. /** This tells the button to automatically flip the toggle state when
  25830. the button is clicked.
  25831. If set to true, then before the clicked() callback occurs, the toggle-state
  25832. of the button is flipped.
  25833. */
  25834. void setClickingTogglesState (bool shouldToggle) throw();
  25835. /** Returns true if this button is set to be an automatic toggle-button.
  25836. This returns the last value that was passed to setClickingTogglesState().
  25837. */
  25838. bool getClickingTogglesState() const throw();
  25839. /** Enables the button to act as a member of a mutually-exclusive group
  25840. of 'radio buttons'.
  25841. If the group ID is set to a non-zero number, then this button will
  25842. act as part of a group of buttons with the same ID, only one of
  25843. which can be 'on' at the same time. Note that when it's part of
  25844. a group, clicking a toggle-button that's 'on' won't turn it off.
  25845. To find other buttons with the same ID, this button will search through
  25846. its sibling components for ToggleButtons, so all the buttons for a
  25847. particular group must be placed inside the same parent component.
  25848. Set the group ID back to zero if you want it to act as a normal toggle
  25849. button again.
  25850. @see getRadioGroupId
  25851. */
  25852. void setRadioGroupId (int newGroupId);
  25853. /** Returns the ID of the group to which this button belongs.
  25854. (See setRadioGroupId() for an explanation of this).
  25855. */
  25856. int getRadioGroupId() const throw() { return radioGroupId; }
  25857. /**
  25858. Used to receive callbacks when a button is clicked.
  25859. @see Button::addButtonListener, Button::removeButtonListener
  25860. */
  25861. class JUCE_API Listener
  25862. {
  25863. public:
  25864. /** Destructor. */
  25865. virtual ~Listener() {}
  25866. /** Called when the button is clicked. */
  25867. virtual void buttonClicked (Button* button) = 0;
  25868. /** Called when the button's state changes. */
  25869. virtual void buttonStateChanged (Button*) {}
  25870. };
  25871. /** Registers a listener to receive events when this button's state changes.
  25872. If the listener is already registered, this will not register it again.
  25873. @see removeButtonListener
  25874. */
  25875. void addButtonListener (Listener* newListener);
  25876. /** Removes a previously-registered button listener
  25877. @see addButtonListener
  25878. */
  25879. void removeButtonListener (Listener* listener);
  25880. /** Causes the button to act as if it's been clicked.
  25881. This will asynchronously make the button draw itself going down and up, and
  25882. will then call back the clicked() method as if mouse was clicked on it.
  25883. @see clicked
  25884. */
  25885. virtual void triggerClick();
  25886. /** Sets a command ID for this button to automatically invoke when it's clicked.
  25887. When the button is pressed, it will use the given manager to trigger the
  25888. command ID.
  25889. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  25890. before this button is. To disable the command triggering, call this method and
  25891. pass 0 for the parameters.
  25892. If generateTooltip is true, then the button's tooltip will be automatically
  25893. generated based on the name of this command and its current shortcut key.
  25894. @see addShortcut, getCommandID
  25895. */
  25896. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  25897. int commandID,
  25898. bool generateTooltip);
  25899. /** Returns the command ID that was set by setCommandToTrigger().
  25900. */
  25901. int getCommandID() const throw() { return commandID; }
  25902. /** Assigns a shortcut key to trigger the button.
  25903. The button registers itself with its top-level parent component for keypresses.
  25904. Note that a different way of linking buttons to keypresses is by using the
  25905. setCommandToTrigger() method to invoke a command.
  25906. @see clearShortcuts
  25907. */
  25908. void addShortcut (const KeyPress& key);
  25909. /** Removes all key shortcuts that had been set for this button.
  25910. @see addShortcut
  25911. */
  25912. void clearShortcuts();
  25913. /** Returns true if the given keypress is a shortcut for this button.
  25914. @see addShortcut
  25915. */
  25916. bool isRegisteredForShortcut (const KeyPress& key) const;
  25917. /** Sets an auto-repeat speed for the button when it is held down.
  25918. (Auto-repeat is disabled by default).
  25919. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  25920. triggering the next click. If this is zero, auto-repeat
  25921. is disabled
  25922. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  25923. triggered
  25924. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  25925. get faster, the longer the button is held down, up to the
  25926. minimum interval specified here
  25927. */
  25928. void setRepeatSpeed (int initialDelayInMillisecs,
  25929. int repeatDelayInMillisecs,
  25930. int minimumDelayInMillisecs = -1) throw();
  25931. /** Sets whether the button click should happen when the mouse is pressed or released.
  25932. By default the button is only considered to have been clicked when the mouse is
  25933. released, but setting this to true will make it call the clicked() method as soon
  25934. as the button is pressed.
  25935. This is useful if the button is being used to show a pop-up menu, as it allows
  25936. the click to be used as a drag onto the menu.
  25937. */
  25938. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  25939. /** Returns the number of milliseconds since the last time the button
  25940. went into the 'down' state.
  25941. */
  25942. uint32 getMillisecondsSinceButtonDown() const throw();
  25943. /** (overridden from Component to do special stuff). */
  25944. void setVisible (bool shouldBeVisible);
  25945. /** Sets the tooltip for this button.
  25946. @see TooltipClient, TooltipWindow
  25947. */
  25948. void setTooltip (const String& newTooltip);
  25949. // (implementation of the TooltipClient method)
  25950. const String getTooltip();
  25951. /** A combination of these flags are used by setConnectedEdges().
  25952. */
  25953. enum ConnectedEdgeFlags
  25954. {
  25955. ConnectedOnLeft = 1,
  25956. ConnectedOnRight = 2,
  25957. ConnectedOnTop = 4,
  25958. ConnectedOnBottom = 8
  25959. };
  25960. /** Hints about which edges of the button might be connected to adjoining buttons.
  25961. The value passed in is a bitwise combination of any of the values in the
  25962. ConnectedEdgeFlags enum.
  25963. E.g. if you are placing two buttons adjacent to each other, you could use this to
  25964. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  25965. without rounded corners on the edges that connect. It's only a hint, so the
  25966. LookAndFeel can choose to ignore it if it's not relevent for this type of
  25967. button.
  25968. */
  25969. void setConnectedEdges (int connectedEdgeFlags);
  25970. /** Returns the set of flags passed into setConnectedEdges(). */
  25971. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  25972. /** Indicates whether the button adjoins another one on its left edge.
  25973. @see setConnectedEdges
  25974. */
  25975. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  25976. /** Indicates whether the button adjoins another one on its right edge.
  25977. @see setConnectedEdges
  25978. */
  25979. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  25980. /** Indicates whether the button adjoins another one on its top edge.
  25981. @see setConnectedEdges
  25982. */
  25983. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  25984. /** Indicates whether the button adjoins another one on its bottom edge.
  25985. @see setConnectedEdges
  25986. */
  25987. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  25988. /** Used by setState(). */
  25989. enum ButtonState
  25990. {
  25991. buttonNormal,
  25992. buttonOver,
  25993. buttonDown
  25994. };
  25995. /** Can be used to force the button into a particular state.
  25996. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  25997. from happening.
  25998. The state that you set here will only last until it is automatically changed when the mouse
  25999. enters or exits the button, or the mouse-button is pressed or released.
  26000. */
  26001. void setState (const ButtonState newState);
  26002. juce_UseDebuggingNewOperator
  26003. protected:
  26004. /** This method is called when the button has been clicked.
  26005. Subclasses can override this to perform whatever they actions they need
  26006. to do.
  26007. Alternatively, a ButtonListener can be added to the button, and these listeners
  26008. will be called when the click occurs.
  26009. @see triggerClick
  26010. */
  26011. virtual void clicked();
  26012. /** This method is called when the button has been clicked.
  26013. By default it just calls clicked(), but you might want to override it to handle
  26014. things like clicking when a modifier key is pressed, etc.
  26015. @see ModifierKeys
  26016. */
  26017. virtual void clicked (const ModifierKeys& modifiers);
  26018. /** Subclasses should override this to actually paint the button's contents.
  26019. It's better to use this than the paint method, because it gives you information
  26020. about the over/down state of the button.
  26021. @param g the graphics context to use
  26022. @param isMouseOverButton true if the button is either in the 'over' or
  26023. 'down' state
  26024. @param isButtonDown true if the button should be drawn in the 'down' position
  26025. */
  26026. virtual void paintButton (Graphics& g,
  26027. bool isMouseOverButton,
  26028. bool isButtonDown) = 0;
  26029. /** Called when the button's up/down/over state changes.
  26030. Subclasses can override this if they need to do something special when the button
  26031. goes up or down.
  26032. @see isDown, isOver
  26033. */
  26034. virtual void buttonStateChanged();
  26035. /** @internal */
  26036. virtual void internalClickCallback (const ModifierKeys& modifiers);
  26037. /** @internal */
  26038. void handleCommandMessage (int commandId);
  26039. /** @internal */
  26040. void mouseEnter (const MouseEvent& e);
  26041. /** @internal */
  26042. void mouseExit (const MouseEvent& e);
  26043. /** @internal */
  26044. void mouseDown (const MouseEvent& e);
  26045. /** @internal */
  26046. void mouseDrag (const MouseEvent& e);
  26047. /** @internal */
  26048. void mouseUp (const MouseEvent& e);
  26049. /** @internal */
  26050. bool keyPressed (const KeyPress& key);
  26051. /** @internal */
  26052. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  26053. /** @internal */
  26054. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  26055. /** @internal */
  26056. void paint (Graphics& g);
  26057. /** @internal */
  26058. void parentHierarchyChanged();
  26059. /** @internal */
  26060. void focusGained (FocusChangeType cause);
  26061. /** @internal */
  26062. void focusLost (FocusChangeType cause);
  26063. /** @internal */
  26064. void enablementChanged();
  26065. /** @internal */
  26066. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  26067. /** @internal */
  26068. void applicationCommandListChanged();
  26069. /** @internal */
  26070. void valueChanged (Value& value);
  26071. private:
  26072. Array <KeyPress> shortcuts;
  26073. Component::SafePointer<Component> keySource;
  26074. String text;
  26075. ListenerList <Listener> buttonListeners;
  26076. class RepeatTimer;
  26077. friend class RepeatTimer;
  26078. friend class ScopedPointer <RepeatTimer>;
  26079. ScopedPointer <RepeatTimer> repeatTimer;
  26080. uint32 buttonPressTime, lastTimeCallbackTime;
  26081. ApplicationCommandManager* commandManagerToUse;
  26082. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  26083. int radioGroupId, commandID, connectedEdgeFlags;
  26084. ButtonState buttonState;
  26085. Value isOn;
  26086. bool lastToggleState : 1;
  26087. bool clickTogglesState : 1;
  26088. bool needsToRelease : 1;
  26089. bool needsRepainting : 1;
  26090. bool isKeyDown : 1;
  26091. bool triggerOnMouseDown : 1;
  26092. bool generateTooltip : 1;
  26093. void repeatTimerCallback();
  26094. RepeatTimer& getRepeatTimer();
  26095. ButtonState updateState (const MouseEvent* const e);
  26096. bool isShortcutPressed() const;
  26097. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  26098. void flashButtonState();
  26099. void sendClickMessage (const ModifierKeys& modifiers);
  26100. void sendStateMessage();
  26101. Button (const Button&);
  26102. Button& operator= (const Button&);
  26103. };
  26104. /** This typedef is just for compatibility with old code - newer code should use Button::Listener instead. */
  26105. typedef Button::Listener ButtonListener;
  26106. #endif // __JUCE_BUTTON_JUCEHEADER__
  26107. /*** End of inlined file: juce_Button.h ***/
  26108. /**
  26109. A scrollbar component.
  26110. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  26111. sets the range of values it can represent. Then you can use setCurrentRange() to
  26112. change the position and size of the scrollbar's 'thumb'.
  26113. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  26114. the user moves it, and you can use the getCurrentRangeStart() to find out where
  26115. they moved it to.
  26116. The scrollbar will adjust its own visibility according to whether its thumb size
  26117. allows it to actually be scrolled.
  26118. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  26119. instead of handling a scrollbar directly.
  26120. @see ScrollBar::Listener
  26121. */
  26122. class JUCE_API ScrollBar : public Component,
  26123. public AsyncUpdater,
  26124. private Timer
  26125. {
  26126. public:
  26127. /** Creates a Scrollbar.
  26128. @param isVertical whether it should be a vertical or horizontal bar
  26129. @param buttonsAreVisible whether to show the up/down or left/right buttons
  26130. */
  26131. ScrollBar (bool isVertical,
  26132. bool buttonsAreVisible = true);
  26133. /** Destructor. */
  26134. ~ScrollBar();
  26135. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  26136. bool isVertical() const throw() { return vertical; }
  26137. /** Changes the scrollbar's direction.
  26138. You'll also need to resize the bar appropriately - this just changes its internal
  26139. layout.
  26140. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  26141. */
  26142. void setOrientation (bool shouldBeVertical);
  26143. /** Shows or hides the scrollbar's buttons. */
  26144. void setButtonVisibility (bool buttonsAreVisible);
  26145. /** Tells the scrollbar whether to make itself invisible when not needed.
  26146. The default behaviour is for a scrollbar to become invisible when the thumb
  26147. fills the whole of its range (i.e. when it can't be moved). Setting this
  26148. value to false forces the bar to always be visible.
  26149. @see autoHides()
  26150. */
  26151. void setAutoHide (bool shouldHideWhenFullRange);
  26152. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  26153. as its maximum range.
  26154. @see setAutoHide
  26155. */
  26156. bool autoHides() const throw();
  26157. /** Sets the minimum and maximum values that the bar will move between.
  26158. The bar's thumb will always be constrained so that the entire thumb lies
  26159. within this range.
  26160. @see setCurrentRange
  26161. */
  26162. void setRangeLimits (const Range<double>& newRangeLimit);
  26163. /** Sets the minimum and maximum values that the bar will move between.
  26164. The bar's thumb will always be constrained so that the entire thumb lies
  26165. within this range.
  26166. @see setCurrentRange
  26167. */
  26168. void setRangeLimits (double minimum, double maximum);
  26169. /** Returns the current limits on the thumb position.
  26170. @see setRangeLimits
  26171. */
  26172. const Range<double> getRangeLimit() const throw() { return totalRange; }
  26173. /** Returns the lower value that the thumb can be set to.
  26174. This is the value set by setRangeLimits().
  26175. */
  26176. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  26177. /** Returns the upper value that the thumb can be set to.
  26178. This is the value set by setRangeLimits().
  26179. */
  26180. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  26181. /** Changes the position of the scrollbar's 'thumb'.
  26182. If this method call actually changes the scrollbar's position, it will trigger an
  26183. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  26184. are registered.
  26185. @see getCurrentRange. setCurrentRangeStart
  26186. */
  26187. void setCurrentRange (const Range<double>& newRange);
  26188. /** Changes the position of the scrollbar's 'thumb'.
  26189. This sets both the position and size of the thumb - to just set the position without
  26190. changing the size, you can use setCurrentRangeStart().
  26191. If this method call actually changes the scrollbar's position, it will trigger an
  26192. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  26193. are registered.
  26194. @param newStart the top (or left) of the thumb, in the range
  26195. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  26196. value is beyond these limits, it will be clipped.
  26197. @param newSize the size of the thumb, such that
  26198. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  26199. size is beyond these limits, it will be clipped.
  26200. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  26201. */
  26202. void setCurrentRange (double newStart, double newSize);
  26203. /** Moves the bar's thumb position.
  26204. This will move the thumb position without changing the thumb size. Note
  26205. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  26206. If this method call actually changes the scrollbar's position, it will trigger an
  26207. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  26208. are registered.
  26209. @see setCurrentRange
  26210. */
  26211. void setCurrentRangeStart (double newStart);
  26212. /** Returns the current thumb range.
  26213. @see getCurrentRange, setCurrentRange
  26214. */
  26215. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  26216. /** Returns the position of the top of the thumb.
  26217. @see getCurrentRange, setCurrentRangeStart
  26218. */
  26219. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  26220. /** Returns the current size of the thumb.
  26221. @see getCurrentRange, setCurrentRange
  26222. */
  26223. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  26224. /** Sets the amount by which the up and down buttons will move the bar.
  26225. The value here is in terms of the total range, and is added or subtracted
  26226. from the thumb position when the user clicks an up/down (or left/right) button.
  26227. */
  26228. void setSingleStepSize (double newSingleStepSize);
  26229. /** Moves the scrollbar by a number of single-steps.
  26230. This will move the bar by a multiple of its single-step interval (as
  26231. specified using the setSingleStepSize() method).
  26232. A positive value here will move the bar down or to the right, a negative
  26233. value moves it up or to the left.
  26234. */
  26235. void moveScrollbarInSteps (int howManySteps);
  26236. /** Moves the scroll bar up or down in pages.
  26237. This will move the bar by a multiple of its current thumb size, effectively
  26238. doing a page-up or down.
  26239. A positive value here will move the bar down or to the right, a negative
  26240. value moves it up or to the left.
  26241. */
  26242. void moveScrollbarInPages (int howManyPages);
  26243. /** Scrolls to the top (or left).
  26244. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  26245. */
  26246. void scrollToTop();
  26247. /** Scrolls to the bottom (or right).
  26248. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  26249. */
  26250. void scrollToBottom();
  26251. /** Changes the delay before the up and down buttons autorepeat when they are held
  26252. down.
  26253. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  26254. @see Button::setRepeatSpeed
  26255. */
  26256. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  26257. int repeatDelayInMillisecs,
  26258. int minimumDelayInMillisecs = -1);
  26259. /** A set of colour IDs to use to change the colour of various aspects of the component.
  26260. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26261. methods.
  26262. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26263. */
  26264. enum ColourIds
  26265. {
  26266. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  26267. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  26268. 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. */
  26269. };
  26270. /**
  26271. A class for receiving events from a ScrollBar.
  26272. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  26273. method, and it will be called when the bar's position changes.
  26274. @see ScrollBar::addListener, ScrollBar::removeListener
  26275. */
  26276. class JUCE_API Listener
  26277. {
  26278. public:
  26279. /** Destructor. */
  26280. virtual ~Listener() {}
  26281. /** Called when a ScrollBar is moved.
  26282. @param scrollBarThatHasMoved the bar that has moved
  26283. @param newRangeStart the new range start of this bar
  26284. */
  26285. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  26286. double newRangeStart) = 0;
  26287. };
  26288. /** Registers a listener that will be called when the scrollbar is moved. */
  26289. void addListener (Listener* listener);
  26290. /** Deregisters a previously-registered listener. */
  26291. void removeListener (Listener* listener);
  26292. /** @internal */
  26293. bool keyPressed (const KeyPress& key);
  26294. /** @internal */
  26295. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26296. /** @internal */
  26297. void lookAndFeelChanged();
  26298. /** @internal */
  26299. void handleAsyncUpdate();
  26300. /** @internal */
  26301. void mouseDown (const MouseEvent& e);
  26302. /** @internal */
  26303. void mouseDrag (const MouseEvent& e);
  26304. /** @internal */
  26305. void mouseUp (const MouseEvent& e);
  26306. /** @internal */
  26307. void paint (Graphics& g);
  26308. /** @internal */
  26309. void resized();
  26310. juce_UseDebuggingNewOperator
  26311. private:
  26312. Range <double> totalRange, visibleRange;
  26313. double singleStepSize, dragStartRange;
  26314. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  26315. int dragStartMousePos, lastMousePos;
  26316. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  26317. bool vertical, isDraggingThumb, autohides;
  26318. class ScrollbarButton;
  26319. friend class ScopedPointer<ScrollbarButton>;
  26320. ScopedPointer<ScrollbarButton> upButton, downButton;
  26321. ListenerList <Listener> listeners;
  26322. void updateThumbPosition();
  26323. void timerCallback();
  26324. ScrollBar (const ScrollBar&);
  26325. ScrollBar& operator= (const ScrollBar&);
  26326. };
  26327. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  26328. typedef ScrollBar::Listener ScrollBarListener;
  26329. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  26330. /*** End of inlined file: juce_ScrollBar.h ***/
  26331. /**
  26332. A Viewport is used to contain a larger child component, and allows the child
  26333. to be automatically scrolled around.
  26334. To use a Viewport, just create one and set the component that goes inside it
  26335. using the setViewedComponent() method. When the child component changes size,
  26336. the Viewport will adjust its scrollbars accordingly.
  26337. A subclass of the viewport can be created which will receive calls to its
  26338. visibleAreaChanged() method when the subcomponent changes position or size.
  26339. */
  26340. class JUCE_API Viewport : public Component,
  26341. private ComponentListener,
  26342. private ScrollBar::Listener
  26343. {
  26344. public:
  26345. /** Creates a Viewport.
  26346. The viewport is initially empty - use the setViewedComponent() method to
  26347. add a child component for it to manage.
  26348. */
  26349. explicit Viewport (const String& componentName = String::empty);
  26350. /** Destructor. */
  26351. ~Viewport();
  26352. /** Sets the component that this viewport will contain and scroll around.
  26353. This will add the given component to this Viewport and position it at
  26354. (0, 0).
  26355. (Don't add or remove any child components directly using the normal
  26356. Component::addChildComponent() methods).
  26357. @param newViewedComponent the component to add to this viewport (this pointer
  26358. may be null). The component passed in will be deleted
  26359. by the Viewport when it's no longer needed
  26360. @see getViewedComponent
  26361. */
  26362. void setViewedComponent (Component* newViewedComponent);
  26363. /** Returns the component that's currently being used inside the Viewport.
  26364. @see setViewedComponent
  26365. */
  26366. Component* getViewedComponent() const throw() { return contentComp; }
  26367. /** Changes the position of the viewed component.
  26368. The inner component will be moved so that the pixel at the top left of
  26369. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  26370. within the inner component.
  26371. This will update the scrollbars and might cause a call to visibleAreaChanged().
  26372. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  26373. */
  26374. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  26375. /** Changes the position of the viewed component.
  26376. The inner component will be moved so that the pixel at the top left of
  26377. the viewport will be the pixel at the specified coordinates within the
  26378. inner component.
  26379. This will update the scrollbars and might cause a call to visibleAreaChanged().
  26380. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  26381. */
  26382. void setViewPosition (const Point<int>& newPosition);
  26383. /** Changes the view position as a proportion of the distance it can move.
  26384. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  26385. visible area in the top-left, and (1, 1) would put it as far down and
  26386. to the right as it's possible to go whilst keeping the child component
  26387. on-screen.
  26388. */
  26389. void setViewPositionProportionately (double proportionX, double proportionY);
  26390. /** If the specified position is at the edges of the viewport, this method scrolls
  26391. the viewport to bring that position nearer to the centre.
  26392. Call this if you're dragging an object inside a viewport and want to make it scroll
  26393. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  26394. useful when auto-scrolling.
  26395. @param mouseX the x position, relative to the Viewport's top-left
  26396. @param mouseY the y position, relative to the Viewport's top-left
  26397. @param distanceFromEdge specifies how close to an edge the position needs to be
  26398. before the viewport should scroll in that direction
  26399. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  26400. to scroll by.
  26401. @returns true if the viewport was scrolled
  26402. */
  26403. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  26404. /** Returns the position within the child component of the top-left of its visible area.
  26405. */
  26406. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  26407. /** Returns the position within the child component of the top-left of its visible area.
  26408. @see getViewWidth, setViewPosition
  26409. */
  26410. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  26411. /** Returns the position within the child component of the top-left of its visible area.
  26412. @see getViewHeight, setViewPosition
  26413. */
  26414. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  26415. /** Returns the width of the visible area of the child component.
  26416. This may be less than the width of this Viewport if there's a vertical scrollbar
  26417. or if the child component is itself smaller.
  26418. */
  26419. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  26420. /** Returns the height of the visible area of the child component.
  26421. This may be less than the height of this Viewport if there's a horizontal scrollbar
  26422. or if the child component is itself smaller.
  26423. */
  26424. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  26425. /** Returns the width available within this component for the contents.
  26426. This will be the width of the viewport component minus the width of a
  26427. vertical scrollbar (if visible).
  26428. */
  26429. int getMaximumVisibleWidth() const;
  26430. /** Returns the height available within this component for the contents.
  26431. This will be the height of the viewport component minus the space taken up
  26432. by a horizontal scrollbar (if visible).
  26433. */
  26434. int getMaximumVisibleHeight() const;
  26435. /** Callback method that is called when the visible area changes.
  26436. This will be called when the visible area is moved either be scrolling or
  26437. by calls to setViewPosition(), etc.
  26438. */
  26439. virtual void visibleAreaChanged (int visibleX, int visibleY,
  26440. int visibleW, int visibleH);
  26441. /** Turns scrollbars on or off.
  26442. If set to false, the scrollbars won't ever appear. When true (the default)
  26443. they will appear only when needed.
  26444. */
  26445. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  26446. bool showHorizontalScrollbarIfNeeded);
  26447. /** True if the vertical scrollbar is enabled.
  26448. @see setScrollBarsShown
  26449. */
  26450. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  26451. /** True if the horizontal scrollbar is enabled.
  26452. @see setScrollBarsShown
  26453. */
  26454. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  26455. /** Changes the width of the scrollbars.
  26456. If this isn't specified, the default width from the LookAndFeel class will be used.
  26457. @see LookAndFeel::getDefaultScrollbarWidth
  26458. */
  26459. void setScrollBarThickness (int thickness);
  26460. /** Returns the thickness of the scrollbars.
  26461. @see setScrollBarThickness
  26462. */
  26463. int getScrollBarThickness() const;
  26464. /** Changes the distance that a single-step click on a scrollbar button
  26465. will move the viewport.
  26466. */
  26467. void setSingleStepSizes (int stepX, int stepY);
  26468. /** Shows or hides the buttons on any scrollbars that are used.
  26469. @see ScrollBar::setButtonVisibility
  26470. */
  26471. void setScrollBarButtonVisibility (bool buttonsVisible);
  26472. /** Returns a pointer to the scrollbar component being used.
  26473. Handy if you need to customise the bar somehow.
  26474. */
  26475. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  26476. /** Returns a pointer to the scrollbar component being used.
  26477. Handy if you need to customise the bar somehow.
  26478. */
  26479. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  26480. juce_UseDebuggingNewOperator
  26481. /** @internal */
  26482. void resized();
  26483. /** @internal */
  26484. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  26485. /** @internal */
  26486. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26487. /** @internal */
  26488. bool keyPressed (const KeyPress& key);
  26489. /** @internal */
  26490. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26491. /** @internal */
  26492. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26493. private:
  26494. Component::SafePointer<Component> contentComp;
  26495. Rectangle<int> lastVisibleArea;
  26496. int scrollBarThickness;
  26497. int singleStepX, singleStepY;
  26498. bool showHScrollbar, showVScrollbar;
  26499. Component contentHolder;
  26500. ScrollBar verticalScrollBar;
  26501. ScrollBar horizontalScrollBar;
  26502. void updateVisibleArea();
  26503. Viewport (const Viewport&);
  26504. Viewport& operator= (const Viewport&);
  26505. };
  26506. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  26507. /*** End of inlined file: juce_Viewport.h ***/
  26508. /*** Start of inlined file: juce_PopupMenu.h ***/
  26509. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  26510. #define __JUCE_POPUPMENU_JUCEHEADER__
  26511. class PopupMenuCustomComponent;
  26512. /** Creates and displays a popup-menu.
  26513. To show a popup-menu, you create one of these, add some items to it, then
  26514. call its show() method, which returns the id of the item the user selects.
  26515. E.g. @code
  26516. void MyWidget::mouseDown (const MouseEvent& e)
  26517. {
  26518. PopupMenu m;
  26519. m.addItem (1, "item 1");
  26520. m.addItem (2, "item 2");
  26521. const int result = m.show();
  26522. if (result == 0)
  26523. {
  26524. // user dismissed the menu without picking anything
  26525. }
  26526. else if (result == 1)
  26527. {
  26528. // user picked item 1
  26529. }
  26530. else if (result == 2)
  26531. {
  26532. // user picked item 2
  26533. }
  26534. }
  26535. @endcode
  26536. Submenus are easy too: @code
  26537. void MyWidget::mouseDown (const MouseEvent& e)
  26538. {
  26539. PopupMenu subMenu;
  26540. subMenu.addItem (1, "item 1");
  26541. subMenu.addItem (2, "item 2");
  26542. PopupMenu mainMenu;
  26543. mainMenu.addItem (3, "item 3");
  26544. mainMenu.addSubMenu ("other choices", subMenu);
  26545. const int result = m.show();
  26546. ...etc
  26547. }
  26548. @endcode
  26549. */
  26550. class JUCE_API PopupMenu
  26551. {
  26552. public:
  26553. /** Creates an empty popup menu. */
  26554. PopupMenu();
  26555. /** Creates a copy of another menu. */
  26556. PopupMenu (const PopupMenu& other);
  26557. /** Destructor. */
  26558. ~PopupMenu();
  26559. /** Copies this menu from another one. */
  26560. PopupMenu& operator= (const PopupMenu& other);
  26561. /** Resets the menu, removing all its items. */
  26562. void clear();
  26563. /** Appends a new text item for this menu to show.
  26564. @param itemResultId the number that will be returned from the show() method
  26565. if the user picks this item. The value should never be
  26566. zero, because that's used to indicate that the user didn't
  26567. select anything.
  26568. @param itemText the text to show.
  26569. @param isActive if false, the item will be shown 'greyed-out' and can't be
  26570. picked
  26571. @param isTicked if true, the item will be shown with a tick next to it
  26572. @param iconToUse if this is non-zero, it should be an image that will be
  26573. displayed to the left of the item. This method will take its
  26574. own copy of the image passed-in, so there's no need to keep
  26575. it hanging around.
  26576. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  26577. */
  26578. void addItem (int itemResultId,
  26579. const String& itemText,
  26580. bool isActive = true,
  26581. bool isTicked = false,
  26582. const Image& iconToUse = Image::null);
  26583. /** Adds an item that represents one of the commands in a command manager object.
  26584. @param commandManager the manager to use to trigger the command and get information
  26585. about it
  26586. @param commandID the ID of the command
  26587. @param displayName if this is non-empty, then this string will be used instead of
  26588. the command's registered name
  26589. */
  26590. void addCommandItem (ApplicationCommandManager* commandManager,
  26591. int commandID,
  26592. const String& displayName = String::empty);
  26593. /** Appends a text item with a special colour.
  26594. This is the same as addItem(), but specifies a colour to use for the
  26595. text, which will override the default colours that are used by the
  26596. current look-and-feel. See addItem() for a description of the parameters.
  26597. */
  26598. void addColouredItem (int itemResultId,
  26599. const String& itemText,
  26600. const Colour& itemTextColour,
  26601. bool isActive = true,
  26602. bool isTicked = false,
  26603. const Image& iconToUse = Image::null);
  26604. /** Appends a custom menu item.
  26605. This will add a user-defined component to use as a menu item. The component
  26606. passed in will be deleted by this menu when it's no longer needed.
  26607. @see PopupMenuCustomComponent
  26608. */
  26609. void addCustomItem (int itemResultId, PopupMenuCustomComponent* customComponent);
  26610. /** Appends a custom menu item that can't be used to trigger a result.
  26611. This will add a user-defined component to use as a menu item. Unlike the
  26612. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  26613. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  26614. delete the component when it's finished, so it's the caller's responsibility
  26615. to manage the component that is passed-in.
  26616. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  26617. detection of a mouse-click on your component, and use that to trigger the
  26618. menu ID specified in itemResultId. If this is false, the menu item can't
  26619. be triggered, so itemResultId is not used.
  26620. @see PopupMenuCustomComponent
  26621. */
  26622. void addCustomItem (int itemResultId,
  26623. Component* customComponent,
  26624. int idealWidth, int idealHeight,
  26625. bool triggerMenuItemAutomaticallyWhenClicked);
  26626. /** Appends a sub-menu.
  26627. If the menu that's passed in is empty, it will appear as an inactive item.
  26628. */
  26629. void addSubMenu (const String& subMenuName,
  26630. const PopupMenu& subMenu,
  26631. bool isActive = true,
  26632. const Image& iconToUse = Image::null,
  26633. bool isTicked = false);
  26634. /** Appends a separator to the menu, to help break it up into sections.
  26635. The menu class is smart enough not to display separators at the top or bottom
  26636. of the menu, and it will replace mutliple adjacent separators with a single
  26637. one, so your code can be quite free and easy about adding these, and it'll
  26638. always look ok.
  26639. */
  26640. void addSeparator();
  26641. /** Adds a non-clickable text item to the menu.
  26642. This is a bold-font items which can be used as a header to separate the items
  26643. into named groups.
  26644. */
  26645. void addSectionHeader (const String& title);
  26646. /** Returns the number of items that the menu currently contains.
  26647. (This doesn't count separators).
  26648. */
  26649. int getNumItems() const throw();
  26650. /** Returns true if the menu contains a command item that triggers the given command. */
  26651. bool containsCommandItem (int commandID) const;
  26652. /** Returns true if the menu contains any items that can be used. */
  26653. bool containsAnyActiveItems() const throw();
  26654. /** Displays the menu and waits for the user to pick something.
  26655. This will display the menu modally, and return the ID of the item that the
  26656. user picks. If they click somewhere off the menu to get rid of it without
  26657. choosing anything, this will return 0.
  26658. The current location of the mouse will be used as the position to show the
  26659. menu - to explicitly set the menu's position, use showAt() instead. Depending
  26660. on where this point is on the screen, the menu will appear above, below or
  26661. to the side of the point.
  26662. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  26663. then when the menu first appears, it will make sure
  26664. that this item is visible. So if the menu has too many
  26665. items to fit on the screen, it will be scrolled to a
  26666. position where this item is visible.
  26667. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  26668. than this if some items are too long to fit.
  26669. @param maximumNumColumns if there are too many items to fit on-screen in a single
  26670. vertical column, the menu may be laid out as a series of
  26671. columns - this is the maximum number allowed. To use the
  26672. default value for this (probably about 7), you can pass
  26673. in zero.
  26674. @param standardItemHeight if this is non-zero, it will be used as the standard
  26675. height for menu items (apart from custom items)
  26676. @param callback if this is non-zero, the menu will be launched asynchronously,
  26677. returning immediately, and the callback will receive a
  26678. call when the menu is either dismissed or has an item
  26679. selected. This object will be owned and deleted by the
  26680. system, so make sure that it works safely and that any
  26681. pointers that it uses are safely within scope.
  26682. @see showAt
  26683. */
  26684. int show (int itemIdThatMustBeVisible = 0,
  26685. int minimumWidth = 0,
  26686. int maximumNumColumns = 0,
  26687. int standardItemHeight = 0,
  26688. ModalComponentManager::Callback* callback = 0);
  26689. /** Displays the menu at a specific location.
  26690. This is the same as show(), but uses a specific location (in global screen
  26691. co-ordinates) rather than the current mouse position.
  26692. Note that the co-ordinates don't specify the top-left of the menu - they
  26693. indicate a point of interest, and the menu will position itself nearby to
  26694. this point, trying to keep it fully on-screen.
  26695. @see show()
  26696. */
  26697. int showAt (int screenX,
  26698. int screenY,
  26699. int itemIdThatMustBeVisible = 0,
  26700. int minimumWidth = 0,
  26701. int maximumNumColumns = 0,
  26702. int standardItemHeight = 0,
  26703. ModalComponentManager::Callback* callback = 0);
  26704. /** Displays the menu as if it's attached to a component such as a button.
  26705. This is similar to showAt(), but will position it next to the given component, e.g.
  26706. so that the menu's edge is aligned with that of the component. This is intended for
  26707. things like buttons that trigger a pop-up menu.
  26708. */
  26709. int showAt (Component* componentToAttachTo,
  26710. int itemIdThatMustBeVisible = 0,
  26711. int minimumWidth = 0,
  26712. int maximumNumColumns = 0,
  26713. int standardItemHeight = 0,
  26714. ModalComponentManager::Callback* callback = 0);
  26715. /** Closes any menus that are currently open.
  26716. This might be useful if you have a situation where your window is being closed
  26717. by some means other than a user action, and you'd like to make sure that menus
  26718. aren't left hanging around.
  26719. */
  26720. static void JUCE_CALLTYPE dismissAllActiveMenus();
  26721. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  26722. This can be called before show() if you need a customised menu. Be careful
  26723. not to delete the LookAndFeel object before the menu has been deleted.
  26724. */
  26725. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  26726. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  26727. These constants can be used either via the LookAndFeel::setColour()
  26728. method for the look and feel that is set for this menu with setLookAndFeel()
  26729. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  26730. */
  26731. enum ColourIds
  26732. {
  26733. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  26734. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  26735. colour is specified when the item is added). */
  26736. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  26737. addSectionHeader() method). */
  26738. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  26739. highlighted menu item. */
  26740. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  26741. highlighted item. */
  26742. };
  26743. /**
  26744. Allows you to iterate through the items in a pop-up menu, and examine
  26745. their properties.
  26746. To use this, just create one and repeatedly call its next() method. When this
  26747. returns true, all the member variables of the iterator are filled-out with
  26748. information describing the menu item. When it returns false, the end of the
  26749. list has been reached.
  26750. */
  26751. class JUCE_API MenuItemIterator
  26752. {
  26753. public:
  26754. /** Creates an iterator that will scan through the items in the specified
  26755. menu.
  26756. Be careful not to add any items to a menu while it is being iterated,
  26757. or things could get out of step.
  26758. */
  26759. MenuItemIterator (const PopupMenu& menu);
  26760. /** Destructor. */
  26761. ~MenuItemIterator();
  26762. /** Returns true if there is another item, and sets up all this object's
  26763. member variables to reflect that item's properties.
  26764. */
  26765. bool next();
  26766. String itemName;
  26767. const PopupMenu* subMenu;
  26768. int itemId;
  26769. bool isSeparator;
  26770. bool isTicked;
  26771. bool isEnabled;
  26772. bool isCustomComponent;
  26773. bool isSectionHeader;
  26774. const Colour* customColour;
  26775. Image customImage;
  26776. ApplicationCommandManager* commandManager;
  26777. juce_UseDebuggingNewOperator
  26778. private:
  26779. const PopupMenu& menu;
  26780. int index;
  26781. MenuItemIterator (const MenuItemIterator&);
  26782. MenuItemIterator& operator= (const MenuItemIterator&);
  26783. };
  26784. juce_UseDebuggingNewOperator
  26785. private:
  26786. class Item;
  26787. class ItemComponent;
  26788. class Window;
  26789. friend class MenuItemIterator;
  26790. friend class ItemComponent;
  26791. friend class Window;
  26792. friend class PopupMenuCustomComponent;
  26793. friend class MenuBarComponent;
  26794. friend class OwnedArray <Item>;
  26795. friend class ScopedPointer <Window>;
  26796. OwnedArray <Item> items;
  26797. LookAndFeel* lookAndFeel;
  26798. bool separatorPending;
  26799. void addSeparatorIfPending();
  26800. int showMenu (const Rectangle<int>& target,
  26801. int itemIdThatMustBeVisible,
  26802. int minimumWidth,
  26803. int maximumNumColumns,
  26804. int standardItemHeight,
  26805. bool alignToRectangle,
  26806. Component* componentAttachedTo,
  26807. ModalComponentManager::Callback* callback);
  26808. };
  26809. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  26810. /*** End of inlined file: juce_PopupMenu.h ***/
  26811. /*** Start of inlined file: juce_TextInputTarget.h ***/
  26812. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26813. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26814. /** An abstract base class that is implemented by components that wish to be used
  26815. as text editors.
  26816. This class allows different types of text editor component to provide a uniform
  26817. interface, which can be used by things like OS-specific input methods, on-screen
  26818. keyboards, etc.
  26819. */
  26820. class JUCE_API TextInputTarget
  26821. {
  26822. public:
  26823. /** */
  26824. TextInputTarget() {}
  26825. /** Destructor. */
  26826. virtual ~TextInputTarget() {}
  26827. /** Returns true if this input target is currently accepting input.
  26828. For example, a text editor might return false if it's in read-only mode.
  26829. */
  26830. virtual bool isTextInputActive() const = 0;
  26831. /** Returns the extents of the selected text region, or an empty range if
  26832. nothing is selected,
  26833. */
  26834. virtual const Range<int> getHighlightedRegion() const = 0;
  26835. /** Sets the currently-selected text region.
  26836. */
  26837. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  26838. /** Returns a specified sub-section of the text.
  26839. */
  26840. virtual const String getTextInRange (const Range<int>& range) const = 0;
  26841. /** Inserts some text, overwriting the selected text region, if there is one. */
  26842. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  26843. };
  26844. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26845. /*** End of inlined file: juce_TextInputTarget.h ***/
  26846. /**
  26847. A component containing text that can be edited.
  26848. A TextEditor can either be in single- or multi-line mode, and supports mixed
  26849. fonts and colours.
  26850. @see TextEditor::Listener, Label
  26851. */
  26852. class JUCE_API TextEditor : public Component,
  26853. public TextInputTarget,
  26854. public SettableTooltipClient
  26855. {
  26856. public:
  26857. /** Creates a new, empty text editor.
  26858. @param componentName the name to pass to the component for it to use as its name
  26859. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26860. for all characters that are drawn on screen - e.g. to create
  26861. a password-style textbox containing circular blobs instead of text,
  26862. you could set this value to 0x25cf, which is the unicode character
  26863. for a black splodge (not all fonts include this, though), or 0x2022,
  26864. which is a bullet (probably the best choice for linux).
  26865. */
  26866. explicit TextEditor (const String& componentName = String::empty,
  26867. juce_wchar passwordCharacter = 0);
  26868. /** Destructor. */
  26869. virtual ~TextEditor();
  26870. /** Puts the editor into either multi- or single-line mode.
  26871. By default, the editor will be in single-line mode, so use this if you need a multi-line
  26872. editor.
  26873. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  26874. on if you want a multi-line editor with line-breaks.
  26875. @see isMultiLine, setReturnKeyStartsNewLine
  26876. */
  26877. void setMultiLine (bool shouldBeMultiLine,
  26878. bool shouldWordWrap = true);
  26879. /** Returns true if the editor is in multi-line mode.
  26880. */
  26881. bool isMultiLine() const;
  26882. /** Changes the behaviour of the return key.
  26883. If set to true, the return key will insert a new-line into the text; if false
  26884. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  26885. method. By default this is set to false, and when true it will only insert
  26886. new-lines when in multi-line mode (see setMultiLine()).
  26887. */
  26888. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  26889. /** Returns the value set by setReturnKeyStartsNewLine().
  26890. See setReturnKeyStartsNewLine() for more info.
  26891. */
  26892. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  26893. /** Indicates whether the tab key should be accepted and used to input a tab character,
  26894. or whether it gets ignored.
  26895. By default the tab key is ignored, so that it can be used to switch keyboard focus
  26896. between components.
  26897. */
  26898. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  26899. /** Returns true if the tab key is being used for input.
  26900. @see setTabKeyUsedAsCharacter
  26901. */
  26902. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  26903. /** Changes the editor to read-only mode.
  26904. By default, the text editor is not read-only. If you're making it read-only, you
  26905. might also want to call setCaretVisible (false) to get rid of the caret.
  26906. The text can still be highlighted and copied when in read-only mode.
  26907. @see isReadOnly, setCaretVisible
  26908. */
  26909. void setReadOnly (bool shouldBeReadOnly);
  26910. /** Returns true if the editor is in read-only mode.
  26911. */
  26912. bool isReadOnly() const;
  26913. /** Makes the caret visible or invisible.
  26914. By default the caret is visible.
  26915. @see setCaretColour, setCaretPosition
  26916. */
  26917. void setCaretVisible (bool shouldBeVisible);
  26918. /** Returns true if the caret is enabled.
  26919. @see setCaretVisible
  26920. */
  26921. bool isCaretVisible() const { return caretVisible; }
  26922. /** Enables/disables a vertical scrollbar.
  26923. (This only applies when in multi-line mode). When the text gets too long to fit
  26924. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  26925. this is enabled, the scrollbar will be hidden unless it's needed.
  26926. By default the scrollbar is enabled.
  26927. */
  26928. void setScrollbarsShown (bool shouldBeEnabled);
  26929. /** Returns true if scrollbars are enabled.
  26930. @see setScrollbarsShown
  26931. */
  26932. bool areScrollbarsShown() const { return scrollbarVisible; }
  26933. /** Changes the password character used to disguise the text.
  26934. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26935. for all characters that are drawn on screen - e.g. to create
  26936. a password-style textbox containing circular blobs instead of text,
  26937. you could set this value to 0x25cf, which is the unicode character
  26938. for a black splodge (not all fonts include this, though), or 0x2022,
  26939. which is a bullet (probably the best choice for linux).
  26940. */
  26941. void setPasswordCharacter (juce_wchar passwordCharacter);
  26942. /** Returns the current password character.
  26943. @see setPasswordCharacter
  26944. */
  26945. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  26946. /** Allows a right-click menu to appear for the editor.
  26947. (This defaults to being enabled).
  26948. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  26949. of options such as cut/copy/paste, undo/redo, etc.
  26950. */
  26951. void setPopupMenuEnabled (bool menuEnabled);
  26952. /** Returns true if the right-click menu is enabled.
  26953. @see setPopupMenuEnabled
  26954. */
  26955. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  26956. /** Returns true if a popup-menu is currently being displayed.
  26957. */
  26958. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  26959. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  26960. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26961. methods.
  26962. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26963. */
  26964. enum ColourIds
  26965. {
  26966. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  26967. transparent if necessary. */
  26968. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  26969. that because the editor can contain multiple colours, calling this
  26970. method won't change the colour of existing text - to do that, call
  26971. applyFontToAllText() after calling this method.*/
  26972. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  26973. the text - this can be transparent if you don't want to show any
  26974. highlighting.*/
  26975. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  26976. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  26977. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  26978. the edge of the component. */
  26979. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  26980. the edge of the component when it has focus. */
  26981. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  26982. around the edge of the editor. */
  26983. };
  26984. /** Sets the font to use for newly added text.
  26985. This will change the font that will be used next time any text is added or entered
  26986. into the editor. It won't change the font of any existing text - to do that, use
  26987. applyFontToAllText() instead.
  26988. @see applyFontToAllText
  26989. */
  26990. void setFont (const Font& newFont);
  26991. /** Applies a font to all the text in the editor.
  26992. This will also set the current font to use for any new text that's added.
  26993. @see setFont
  26994. */
  26995. void applyFontToAllText (const Font& newFont);
  26996. /** Returns the font that's currently being used for new text.
  26997. @see setFont
  26998. */
  26999. const Font getFont() const;
  27000. /** If set to true, focusing on the editor will highlight all its text.
  27001. (Set to false by default).
  27002. This is useful for boxes where you expect the user to re-enter all the
  27003. text when they focus on the component, rather than editing what's already there.
  27004. */
  27005. void setSelectAllWhenFocused (bool b);
  27006. /** Sets limits on the characters that can be entered.
  27007. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  27008. limit is set
  27009. @param allowedCharacters if this is non-empty, then only characters that occur in
  27010. this string are allowed to be entered into the editor.
  27011. */
  27012. void setInputRestrictions (int maxTextLength,
  27013. const String& allowedCharacters = String::empty);
  27014. /** When the text editor is empty, it can be set to display a message.
  27015. This is handy for things like telling the user what to type in the box - the
  27016. string is only displayed, it's not taken to actually be the contents of
  27017. the editor.
  27018. */
  27019. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  27020. /** Changes the size of the scrollbars that are used.
  27021. Handy if you need smaller scrollbars for a small text box.
  27022. */
  27023. void setScrollBarThickness (int newThicknessPixels);
  27024. /** Shows or hides the buttons on any scrollbars that are used.
  27025. @see ScrollBar::setButtonVisibility
  27026. */
  27027. void setScrollBarButtonVisibility (bool buttonsVisible);
  27028. /**
  27029. Receives callbacks from a TextEditor component when it changes.
  27030. @see TextEditor::addListener
  27031. */
  27032. class JUCE_API Listener
  27033. {
  27034. public:
  27035. /** Destructor. */
  27036. virtual ~Listener() {}
  27037. /** Called when the user changes the text in some way. */
  27038. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  27039. /** Called when the user presses the return key. */
  27040. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  27041. /** Called when the user presses the escape key. */
  27042. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  27043. /** Called when the text editor loses focus. */
  27044. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  27045. };
  27046. /** Registers a listener to be told when things happen to the text.
  27047. @see removeListener
  27048. */
  27049. void addListener (Listener* newListener);
  27050. /** Deregisters a listener.
  27051. @see addListener
  27052. */
  27053. void removeListener (Listener* listenerToRemove);
  27054. /** Returns the entire contents of the editor. */
  27055. const String getText() const;
  27056. /** Returns a section of the contents of the editor. */
  27057. const String getTextInRange (const Range<int>& textRange) const;
  27058. /** Returns true if there are no characters in the editor.
  27059. This is more efficient than calling getText().isEmpty().
  27060. */
  27061. bool isEmpty() const;
  27062. /** Sets the entire content of the editor.
  27063. This will clear the editor and insert the given text (using the current text colour
  27064. and font). You can set the current text colour using
  27065. @code setColour (TextEditor::textColourId, ...);
  27066. @endcode
  27067. @param newText the text to add
  27068. @param sendTextChangeMessage if true, this will cause a change message to
  27069. be sent to all the listeners.
  27070. @see insertText
  27071. */
  27072. void setText (const String& newText,
  27073. bool sendTextChangeMessage = true);
  27074. /** Returns a Value object that can be used to get or set the text.
  27075. Bear in mind that this operate quite slowly if your text box contains large
  27076. amounts of text, as it needs to dynamically build the string that's involved. It's
  27077. best used for small text boxes.
  27078. */
  27079. Value& getTextValue();
  27080. /** Inserts some text at the current cursor position.
  27081. If a section of the text is highlighted, it will be replaced by
  27082. this string, otherwise it will be inserted.
  27083. To delete a section of text, you can use setHighlightedRegion() to
  27084. highlight it, and call insertTextAtCursor (String::empty).
  27085. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  27086. */
  27087. void insertTextAtCaret (const String& textToInsert);
  27088. /** Deletes all the text from the editor. */
  27089. void clear();
  27090. /** Deletes the currently selected region, and puts it on the clipboard.
  27091. @see copy, paste, SystemClipboard
  27092. */
  27093. void cut();
  27094. /** Copies any currently selected region to the clipboard.
  27095. @see cut, paste, SystemClipboard
  27096. */
  27097. void copy();
  27098. /** Pastes the contents of the clipboard into the editor at the cursor position.
  27099. @see cut, copy, SystemClipboard
  27100. */
  27101. void paste();
  27102. /** Moves the caret to be in front of a given character.
  27103. @see getCaretPosition
  27104. */
  27105. void setCaretPosition (int newIndex);
  27106. /** Returns the current index of the caret.
  27107. @see setCaretPosition
  27108. */
  27109. int getCaretPosition() const;
  27110. /** Attempts to scroll the text editor so that the caret ends up at
  27111. a specified position.
  27112. This won't affect the caret's position within the text, it tries to scroll
  27113. the entire editor vertically and horizontally so that the caret is sitting
  27114. at the given position (relative to the top-left of this component).
  27115. Depending on the amount of text available, it might not be possible to
  27116. scroll far enough for the caret to reach this exact position, but it
  27117. will go as far as it can in that direction.
  27118. */
  27119. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  27120. /** Get the graphical position of the caret.
  27121. The rectangle returned is relative to the component's top-left corner.
  27122. @see scrollEditorToPositionCaret
  27123. */
  27124. const Rectangle<int> getCaretRectangle();
  27125. /** Selects a section of the text. */
  27126. void setHighlightedRegion (const Range<int>& newSelection);
  27127. /** Returns the range of characters that are selected.
  27128. If nothing is selected, this will return an empty range.
  27129. @see setHighlightedRegion
  27130. */
  27131. const Range<int> getHighlightedRegion() const { return selection; }
  27132. /** Returns the section of text that is currently selected. */
  27133. const String getHighlightedText() const;
  27134. /** Finds the index of the character at a given position.
  27135. The co-ordinates are relative to the component's top-left.
  27136. */
  27137. int getTextIndexAt (int x, int y);
  27138. /** Counts the number of characters in the text.
  27139. This is quicker than getting the text as a string if you just need to know
  27140. the length.
  27141. */
  27142. int getTotalNumChars() const;
  27143. /** Returns the total width of the text, as it is currently laid-out.
  27144. This may be larger than the size of the TextEditor, and can change when
  27145. the TextEditor is resized or the text changes.
  27146. */
  27147. int getTextWidth() const;
  27148. /** Returns the maximum height of the text, as it is currently laid-out.
  27149. This may be larger than the size of the TextEditor, and can change when
  27150. the TextEditor is resized or the text changes.
  27151. */
  27152. int getTextHeight() const;
  27153. /** Changes the size of the gap at the top and left-edge of the editor.
  27154. By default there's a gap of 4 pixels.
  27155. */
  27156. void setIndents (int newLeftIndent, int newTopIndent);
  27157. /** Changes the size of border left around the edge of the component.
  27158. @see getBorder
  27159. */
  27160. void setBorder (const BorderSize& border);
  27161. /** Returns the size of border around the edge of the component.
  27162. @see setBorder
  27163. */
  27164. const BorderSize getBorder() const;
  27165. /** Used to disable the auto-scrolling which keeps the cursor visible.
  27166. If true (the default), the editor will scroll when the cursor moves offscreen. If
  27167. set to false, it won't.
  27168. */
  27169. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  27170. /** @internal */
  27171. void paint (Graphics& g);
  27172. /** @internal */
  27173. void paintOverChildren (Graphics& g);
  27174. /** @internal */
  27175. void mouseDown (const MouseEvent& e);
  27176. /** @internal */
  27177. void mouseUp (const MouseEvent& e);
  27178. /** @internal */
  27179. void mouseDrag (const MouseEvent& e);
  27180. /** @internal */
  27181. void mouseDoubleClick (const MouseEvent& e);
  27182. /** @internal */
  27183. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27184. /** @internal */
  27185. bool keyPressed (const KeyPress& key);
  27186. /** @internal */
  27187. bool keyStateChanged (bool isKeyDown);
  27188. /** @internal */
  27189. void focusGained (FocusChangeType cause);
  27190. /** @internal */
  27191. void focusLost (FocusChangeType cause);
  27192. /** @internal */
  27193. void resized();
  27194. /** @internal */
  27195. void enablementChanged();
  27196. /** @internal */
  27197. void colourChanged();
  27198. /** @internal */
  27199. bool isTextInputActive() const;
  27200. /** This adds the items to the popup menu.
  27201. By default it adds the cut/copy/paste items, but you can override this if
  27202. you need to replace these with your own items.
  27203. If you want to add your own items to the existing ones, you can override this,
  27204. call the base class's addPopupMenuItems() method, then append your own items.
  27205. When the menu has been shown, performPopupMenuAction() will be called to
  27206. perform the item that the user has chosen.
  27207. The default menu items will be added using item IDs in the range
  27208. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  27209. menu IDs.
  27210. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  27211. a pointer to the info about it, or may be null if the menu is being triggered
  27212. by some other means.
  27213. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  27214. */
  27215. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  27216. const MouseEvent* mouseClickEvent);
  27217. /** This is called to perform one of the items that was shown on the popup menu.
  27218. If you've overridden addPopupMenuItems(), you should also override this
  27219. to perform the actions that you've added.
  27220. If you've overridden addPopupMenuItems() but have still left the default items
  27221. on the menu, remember to call the superclass's performPopupMenuAction()
  27222. so that it can perform the default actions if that's what the user clicked on.
  27223. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  27224. */
  27225. virtual void performPopupMenuAction (int menuItemID);
  27226. juce_UseDebuggingNewOperator
  27227. protected:
  27228. /** Scrolls the minimum distance needed to get the caret into view. */
  27229. void scrollToMakeSureCursorIsVisible();
  27230. /** @internal */
  27231. void moveCaret (int newCaretPos);
  27232. /** @internal */
  27233. void moveCursorTo (int newPosition, bool isSelecting);
  27234. /** Used internally to dispatch a text-change message. */
  27235. void textChanged();
  27236. /** Begins a new transaction in the UndoManager.
  27237. */
  27238. void newTransaction();
  27239. /** Used internally to trigger an undo or redo. */
  27240. void doUndoRedo (bool isRedo);
  27241. /** Can be overridden to intercept return key presses directly */
  27242. virtual void returnPressed();
  27243. /** Can be overridden to intercept escape key presses directly */
  27244. virtual void escapePressed();
  27245. /** @internal */
  27246. void handleCommandMessage (int commandId);
  27247. private:
  27248. class Iterator;
  27249. class UniformTextSection;
  27250. class TextHolderComponent;
  27251. class InsertAction;
  27252. class RemoveAction;
  27253. friend class InsertAction;
  27254. friend class RemoveAction;
  27255. ScopedPointer <Viewport> viewport;
  27256. TextHolderComponent* textHolder;
  27257. BorderSize borderSize;
  27258. bool readOnly : 1;
  27259. bool multiline : 1;
  27260. bool wordWrap : 1;
  27261. bool returnKeyStartsNewLine : 1;
  27262. bool caretVisible : 1;
  27263. bool popupMenuEnabled : 1;
  27264. bool selectAllTextWhenFocused : 1;
  27265. bool scrollbarVisible : 1;
  27266. bool wasFocused : 1;
  27267. bool caretFlashState : 1;
  27268. bool keepCursorOnScreen : 1;
  27269. bool tabKeyUsed : 1;
  27270. bool menuActive : 1;
  27271. bool valueTextNeedsUpdating : 1;
  27272. UndoManager undoManager;
  27273. float cursorX, cursorY, cursorHeight;
  27274. int maxTextLength;
  27275. Range<int> selection;
  27276. int leftIndent, topIndent;
  27277. unsigned int lastTransactionTime;
  27278. Font currentFont;
  27279. mutable int totalNumChars;
  27280. int caretPosition;
  27281. Array <UniformTextSection*> sections;
  27282. String textToShowWhenEmpty;
  27283. Colour colourForTextWhenEmpty;
  27284. juce_wchar passwordCharacter;
  27285. Value textValue;
  27286. enum
  27287. {
  27288. notDragging,
  27289. draggingSelectionStart,
  27290. draggingSelectionEnd
  27291. } dragType;
  27292. String allowedCharacters;
  27293. ListenerList <Listener> listeners;
  27294. void coalesceSimilarSections();
  27295. void splitSection (int sectionIndex, int charToSplitAt);
  27296. void clearInternal (UndoManager* um);
  27297. void insert (const String& text, int insertIndex, const Font& font,
  27298. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  27299. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  27300. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  27301. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  27302. void updateCaretPosition();
  27303. void textWasChangedByValue();
  27304. int indexAtPosition (float x, float y);
  27305. int findWordBreakAfter (int position) const;
  27306. int findWordBreakBefore (int position) const;
  27307. friend class TextHolderComponent;
  27308. friend class TextEditorViewport;
  27309. void drawContent (Graphics& g);
  27310. void updateTextHolderSize();
  27311. float getWordWrapWidth() const;
  27312. void timerCallbackInt();
  27313. void repaintCaret();
  27314. void repaintText (const Range<int>& range);
  27315. UndoManager* getUndoManager() throw();
  27316. TextEditor (const TextEditor&);
  27317. TextEditor& operator= (const TextEditor&);
  27318. };
  27319. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  27320. typedef TextEditor::Listener TextEditorListener;
  27321. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  27322. /*** End of inlined file: juce_TextEditor.h ***/
  27323. /**
  27324. A component that displays a text string, and can optionally become a text
  27325. editor when clicked.
  27326. */
  27327. class JUCE_API Label : public Component,
  27328. public SettableTooltipClient,
  27329. protected TextEditor::Listener,
  27330. private ComponentListener,
  27331. private Value::Listener
  27332. {
  27333. public:
  27334. /** Creates a Label.
  27335. @param componentName the name to give the component
  27336. @param labelText the text to show in the label
  27337. */
  27338. Label (const String& componentName = String::empty,
  27339. const String& labelText = String::empty);
  27340. /** Destructor. */
  27341. ~Label();
  27342. /** Changes the label text.
  27343. If broadcastChangeMessage is true and the new text is different to the current
  27344. text, then the class will broadcast a change message to any Label::Listener objects
  27345. that are registered.
  27346. */
  27347. void setText (const String& newText, bool broadcastChangeMessage);
  27348. /** Returns the label's current text.
  27349. @param returnActiveEditorContents if this is true and the label is currently
  27350. being edited, then this method will return the
  27351. text as it's being shown in the editor. If false,
  27352. then the value returned here won't be updated until
  27353. the user has finished typing and pressed the return
  27354. key.
  27355. */
  27356. const String getText (bool returnActiveEditorContents = false) const throw();
  27357. /** Returns the text content as a Value object.
  27358. You can call Value::referTo() on this object to make the label read and control
  27359. a Value object that you supply.
  27360. */
  27361. Value& getTextValue() { return textValue; }
  27362. /** Changes the font to use to draw the text.
  27363. @see getFont
  27364. */
  27365. void setFont (const Font& newFont) throw();
  27366. /** Returns the font currently being used.
  27367. @see setFont
  27368. */
  27369. const Font& getFont() const throw();
  27370. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27371. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27372. methods.
  27373. Note that you can also use the constants from TextEditor::ColourIds to change the
  27374. colour of the text editor that is opened when a label is editable.
  27375. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27376. */
  27377. enum ColourIds
  27378. {
  27379. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  27380. textColourId = 0x1000281, /**< The colour for the text. */
  27381. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  27382. Leave this transparent to not have an outline. */
  27383. };
  27384. /** Sets the style of justification to be used for positioning the text.
  27385. (The default is Justification::centredLeft)
  27386. */
  27387. void setJustificationType (const Justification& justification) throw();
  27388. /** Returns the type of justification, as set in setJustificationType(). */
  27389. const Justification getJustificationType() const throw() { return justification; }
  27390. /** Changes the gap that is left between the edge of the component and the text.
  27391. By default there's a small gap left at the sides of the component to allow for
  27392. the drawing of the border, but you can change this if necessary.
  27393. */
  27394. void setBorderSize (int horizontalBorder, int verticalBorder);
  27395. /** Returns the size of the horizontal gap being left around the text.
  27396. */
  27397. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  27398. /** Returns the size of the vertical gap being left around the text.
  27399. */
  27400. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  27401. /** Makes this label "stick to" another component.
  27402. This will cause the label to follow another component around, staying
  27403. either to its left or above it.
  27404. @param owner the component to follow
  27405. @param onLeft if true, the label will stay on the left of its component; if
  27406. false, it will stay above it.
  27407. */
  27408. void attachToComponent (Component* owner, bool onLeft);
  27409. /** If this label has been attached to another component using attachToComponent, this
  27410. returns the other component.
  27411. Returns 0 if the label is not attached.
  27412. */
  27413. Component* getAttachedComponent() const;
  27414. /** If the label is attached to the left of another component, this returns true.
  27415. Returns false if the label is above the other component. This is only relevent if
  27416. attachToComponent() has been called.
  27417. */
  27418. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  27419. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  27420. using ellipsis.
  27421. @see Graphics::drawFittedText
  27422. */
  27423. void setMinimumHorizontalScale (float newScale);
  27424. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  27425. /**
  27426. A class for receiving events from a Label.
  27427. You can register a Label::Listener with a Label using the Label::addListener()
  27428. method, and it will be called when the text of the label changes, either because
  27429. of a call to Label::setText() or by the user editing the text (if the label is
  27430. editable).
  27431. @see Label::addListener, Label::removeListener
  27432. */
  27433. class JUCE_API Listener
  27434. {
  27435. public:
  27436. /** Destructor. */
  27437. virtual ~Listener() {}
  27438. /** Called when a Label's text has changed.
  27439. */
  27440. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  27441. };
  27442. /** Registers a listener that will be called when the label's text changes. */
  27443. void addListener (Listener* listener) throw();
  27444. /** Deregisters a previously-registered listener. */
  27445. void removeListener (Listener* listener) throw();
  27446. /** Makes the label turn into a TextEditor when clicked.
  27447. By default this is turned off.
  27448. If turned on, then single- or double-clicking will turn the label into
  27449. an editor. If the user then changes the text, then the ChangeBroadcaster
  27450. base class will be used to send change messages to any listeners that
  27451. have registered.
  27452. If the user changes the text, the textWasEdited() method will be called
  27453. afterwards, and subclasses can override this if they need to do anything
  27454. special.
  27455. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  27456. @param editOnDoubleClick if true, a double-click is needed to start editing
  27457. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  27458. edited will discard any changes; if false, then this will
  27459. commit the changes.
  27460. @see showEditor, setEditorColours, TextEditor
  27461. */
  27462. void setEditable (bool editOnSingleClick,
  27463. bool editOnDoubleClick = false,
  27464. bool lossOfFocusDiscardsChanges = false) throw();
  27465. /** Returns true if this option was set using setEditable(). */
  27466. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  27467. /** Returns true if this option was set using setEditable(). */
  27468. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  27469. /** Returns true if this option has been set in a call to setEditable(). */
  27470. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  27471. /** Returns true if the user can edit this label's text. */
  27472. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  27473. /** Makes the editor appear as if the label had been clicked by the user.
  27474. @see textWasEdited, setEditable
  27475. */
  27476. void showEditor();
  27477. /** Hides the editor if it was being shown.
  27478. @param discardCurrentEditorContents if true, the label's text will be
  27479. reset to whatever it was before the editor
  27480. was shown; if false, the current contents of the
  27481. editor will be used to set the label's text
  27482. before it is hidden.
  27483. */
  27484. void hideEditor (bool discardCurrentEditorContents);
  27485. /** Returns true if the editor is currently focused and active. */
  27486. bool isBeingEdited() const throw();
  27487. juce_UseDebuggingNewOperator
  27488. protected:
  27489. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  27490. Subclasses can override this if they need to customise this component in some way.
  27491. */
  27492. virtual TextEditor* createEditorComponent();
  27493. /** Called after the user changes the text. */
  27494. virtual void textWasEdited();
  27495. /** Called when the text has been altered. */
  27496. virtual void textWasChanged();
  27497. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  27498. virtual void editorShown (TextEditor* editorComponent);
  27499. /** Called when the text editor is going to be deleted, after editing has finished. */
  27500. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  27501. /** @internal */
  27502. void paint (Graphics& g);
  27503. /** @internal */
  27504. void resized();
  27505. /** @internal */
  27506. void mouseUp (const MouseEvent& e);
  27507. /** @internal */
  27508. void mouseDoubleClick (const MouseEvent& e);
  27509. /** @internal */
  27510. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  27511. /** @internal */
  27512. void componentParentHierarchyChanged (Component& component);
  27513. /** @internal */
  27514. void componentVisibilityChanged (Component& component);
  27515. /** @internal */
  27516. void inputAttemptWhenModal();
  27517. /** @internal */
  27518. void focusGained (FocusChangeType);
  27519. /** @internal */
  27520. void enablementChanged();
  27521. /** @internal */
  27522. KeyboardFocusTraverser* createFocusTraverser();
  27523. /** @internal */
  27524. void textEditorTextChanged (TextEditor& editor);
  27525. /** @internal */
  27526. void textEditorReturnKeyPressed (TextEditor& editor);
  27527. /** @internal */
  27528. void textEditorEscapeKeyPressed (TextEditor& editor);
  27529. /** @internal */
  27530. void textEditorFocusLost (TextEditor& editor);
  27531. /** @internal */
  27532. void colourChanged();
  27533. /** @internal */
  27534. void valueChanged (Value&);
  27535. private:
  27536. Value textValue;
  27537. String lastTextValue;
  27538. Font font;
  27539. Justification justification;
  27540. ScopedPointer <TextEditor> editor;
  27541. ListenerList <Listener> listeners;
  27542. Component::SafePointer<Component> ownerComponent;
  27543. int horizontalBorderSize, verticalBorderSize;
  27544. float minimumHorizontalScale;
  27545. bool editSingleClick : 1;
  27546. bool editDoubleClick : 1;
  27547. bool lossOfFocusDiscardsChanges : 1;
  27548. bool leftOfOwnerComp : 1;
  27549. bool updateFromTextEditorContents();
  27550. void callChangeListeners();
  27551. Label (const Label&);
  27552. Label& operator= (const Label&);
  27553. };
  27554. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  27555. typedef Label::Listener LabelListener;
  27556. #endif // __JUCE_LABEL_JUCEHEADER__
  27557. /*** End of inlined file: juce_Label.h ***/
  27558. /**
  27559. A component that lets the user choose from a drop-down list of choices.
  27560. The combo-box has a list of text strings, each with an associated id number,
  27561. that will be shown in the drop-down list when the user clicks on the component.
  27562. The currently selected choice is displayed in the combo-box, and this can
  27563. either be read-only text, or editable.
  27564. To find out when the user selects a different item or edits the text, you
  27565. can register a ComboBox::Listener to receive callbacks.
  27566. @see ComboBox::Listener
  27567. */
  27568. class JUCE_API ComboBox : public Component,
  27569. public SettableTooltipClient,
  27570. private AsyncUpdater,
  27571. private Label::Listener,
  27572. private Value::Listener
  27573. {
  27574. public:
  27575. /** Creates a combo-box.
  27576. On construction, the text field will be empty, so you should call the
  27577. setSelectedId() or setText() method to choose the initial value before
  27578. displaying it.
  27579. @param componentName the name to set for the component (see Component::setName())
  27580. */
  27581. explicit ComboBox (const String& componentName = String::empty);
  27582. /** Destructor. */
  27583. ~ComboBox();
  27584. /** Sets whether the test in the combo-box is editable.
  27585. The default state for a new ComboBox is non-editable, and can only be changed
  27586. by choosing from the drop-down list.
  27587. */
  27588. void setEditableText (bool isEditable);
  27589. /** Returns true if the text is directly editable.
  27590. @see setEditableText
  27591. */
  27592. bool isTextEditable() const throw();
  27593. /** Sets the style of justification to be used for positioning the text.
  27594. The default is Justification::centredLeft. The text is displayed using a
  27595. Label component inside the ComboBox.
  27596. */
  27597. void setJustificationType (const Justification& justification) throw();
  27598. /** Returns the current justification for the text box.
  27599. @see setJustificationType
  27600. */
  27601. const Justification getJustificationType() const throw();
  27602. /** Adds an item to be shown in the drop-down list.
  27603. @param newItemText the text of the item to show in the list
  27604. @param newItemId an associated ID number that can be set or retrieved - see
  27605. getSelectedId() and setSelectedId()
  27606. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  27607. */
  27608. void addItem (const String& newItemText,
  27609. int newItemId) throw();
  27610. /** Adds a separator line to the drop-down list.
  27611. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  27612. */
  27613. void addSeparator() throw();
  27614. /** Adds a heading to the drop-down list, so that you can group the items into
  27615. different sections.
  27616. The headings are indented slightly differently to set them apart from the
  27617. items on the list, and obviously can't be selected. You might want to add
  27618. separators between your sections too.
  27619. @see addItem, addSeparator
  27620. */
  27621. void addSectionHeading (const String& headingName) throw();
  27622. /** This allows items in the drop-down list to be selectively disabled.
  27623. When you add an item, it's enabled by default, but you can call this
  27624. method to change its status.
  27625. If you disable an item which is already selected, this won't change the
  27626. current selection - it just stops the user choosing that item from the list.
  27627. */
  27628. void setItemEnabled (int itemId,
  27629. bool shouldBeEnabled) throw();
  27630. /** Changes the text for an existing item.
  27631. */
  27632. void changeItemText (int itemId,
  27633. const String& newText) throw();
  27634. /** Removes all the items from the drop-down list.
  27635. If this call causes the content to be cleared, then a change-message
  27636. will be broadcast unless dontSendChangeMessage is true.
  27637. @see addItem, removeItem, getNumItems
  27638. */
  27639. void clear (bool dontSendChangeMessage = false);
  27640. /** Returns the number of items that have been added to the list.
  27641. Note that this doesn't include headers or separators.
  27642. */
  27643. int getNumItems() const throw();
  27644. /** Returns the text for one of the items in the list.
  27645. Note that this doesn't include headers or separators.
  27646. @param index the item's index from 0 to (getNumItems() - 1)
  27647. */
  27648. const String getItemText (int index) const throw();
  27649. /** Returns the ID for one of the items in the list.
  27650. Note that this doesn't include headers or separators.
  27651. @param index the item's index from 0 to (getNumItems() - 1)
  27652. */
  27653. int getItemId (int index) const throw();
  27654. /** Returns the index in the list of a particular item ID.
  27655. If no such ID is found, this will return -1.
  27656. */
  27657. int indexOfItemId (int itemId) const throw();
  27658. /** Returns the ID of the item that's currently shown in the box.
  27659. If no item is selected, or if the text is editable and the user
  27660. has entered something which isn't one of the items in the list, then
  27661. this will return 0.
  27662. @see setSelectedId, getSelectedItemIndex, getText
  27663. */
  27664. int getSelectedId() const throw();
  27665. /** Returns a Value object that can be used to get or set the selected item's ID.
  27666. You can call Value::referTo() on this object to make the combo box control
  27667. another Value object.
  27668. */
  27669. Value& getSelectedIdAsValue() throw() { return currentId; }
  27670. /** Sets one of the items to be the current selection.
  27671. This will set the ComboBox's text to that of the item that matches
  27672. this ID.
  27673. @param newItemId the new item to select
  27674. @param dontSendChangeMessage if set to true, this method won't trigger a
  27675. change notification
  27676. @see getSelectedId, setSelectedItemIndex, setText
  27677. */
  27678. void setSelectedId (int newItemId,
  27679. bool dontSendChangeMessage = false) throw();
  27680. /** Returns the index of the item that's currently shown in the box.
  27681. If no item is selected, or if the text is editable and the user
  27682. has entered something which isn't one of the items in the list, then
  27683. this will return -1.
  27684. @see setSelectedItemIndex, getSelectedId, getText
  27685. */
  27686. int getSelectedItemIndex() const throw();
  27687. /** Sets one of the items to be the current selection.
  27688. This will set the ComboBox's text to that of the item at the given
  27689. index in the list.
  27690. @param newItemIndex the new item to select
  27691. @param dontSendChangeMessage if set to true, this method won't trigger a
  27692. change notification
  27693. @see getSelectedItemIndex, setSelectedId, setText
  27694. */
  27695. void setSelectedItemIndex (int newItemIndex,
  27696. bool dontSendChangeMessage = false) throw();
  27697. /** Returns the text that is currently shown in the combo-box's text field.
  27698. If the ComboBox has editable text, then this text may have been edited
  27699. by the user; otherwise it will be one of the items from the list, or
  27700. possibly an empty string if nothing was selected.
  27701. @see setText, getSelectedId, getSelectedItemIndex
  27702. */
  27703. const String getText() const throw();
  27704. /** Sets the contents of the combo-box's text field.
  27705. The text passed-in will be set as the current text regardless of whether
  27706. it is one of the items in the list. If the current text isn't one of the
  27707. items, then getSelectedId() will return -1, otherwise it wil return
  27708. the approriate ID.
  27709. @param newText the text to select
  27710. @param dontSendChangeMessage if set to true, this method won't trigger a
  27711. change notification
  27712. @see getText
  27713. */
  27714. void setText (const String& newText,
  27715. bool dontSendChangeMessage = false) throw();
  27716. /** Programmatically opens the text editor to allow the user to edit the current item.
  27717. This is the same effect as when the box is clicked-on.
  27718. @see Label::showEditor();
  27719. */
  27720. void showEditor();
  27721. /** Pops up the combo box's list. */
  27722. void showPopup();
  27723. /**
  27724. A class for receiving events from a ComboBox.
  27725. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  27726. method, and it will be called when the selected item in the box changes.
  27727. @see ComboBox::addListener, ComboBox::removeListener
  27728. */
  27729. class JUCE_API Listener
  27730. {
  27731. public:
  27732. /** Destructor. */
  27733. virtual ~Listener() {}
  27734. /** Called when a ComboBox has its selected item changed. */
  27735. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  27736. };
  27737. /** Registers a listener that will be called when the box's content changes. */
  27738. void addListener (Listener* listener) throw();
  27739. /** Deregisters a previously-registered listener. */
  27740. void removeListener (Listener* listener) throw();
  27741. /** Sets a message to display when there is no item currently selected.
  27742. @see getTextWhenNothingSelected
  27743. */
  27744. void setTextWhenNothingSelected (const String& newMessage) throw();
  27745. /** Returns the text that is shown when no item is selected.
  27746. @see setTextWhenNothingSelected
  27747. */
  27748. const String getTextWhenNothingSelected() const throw();
  27749. /** Sets the message to show when there are no items in the list, and the user clicks
  27750. on the drop-down box.
  27751. By default it just says "no choices", but this lets you change it to something more
  27752. meaningful.
  27753. */
  27754. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  27755. /** Returns the text shown when no items have been added to the list.
  27756. @see setTextWhenNoChoicesAvailable
  27757. */
  27758. const String getTextWhenNoChoicesAvailable() const throw();
  27759. /** Gives the ComboBox a tooltip. */
  27760. void setTooltip (const String& newTooltip);
  27761. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  27762. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27763. methods.
  27764. To change the colours of the menu that pops up
  27765. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27766. */
  27767. enum ColourIds
  27768. {
  27769. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  27770. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  27771. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  27772. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  27773. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  27774. };
  27775. /** @internal */
  27776. void labelTextChanged (Label*);
  27777. /** @internal */
  27778. void enablementChanged();
  27779. /** @internal */
  27780. void colourChanged();
  27781. /** @internal */
  27782. void focusGained (Component::FocusChangeType cause);
  27783. /** @internal */
  27784. void focusLost (Component::FocusChangeType cause);
  27785. /** @internal */
  27786. void handleAsyncUpdate();
  27787. /** @internal */
  27788. const String getTooltip() { return label->getTooltip(); }
  27789. /** @internal */
  27790. void mouseDown (const MouseEvent&);
  27791. /** @internal */
  27792. void mouseDrag (const MouseEvent&);
  27793. /** @internal */
  27794. void mouseUp (const MouseEvent&);
  27795. /** @internal */
  27796. void lookAndFeelChanged();
  27797. /** @internal */
  27798. void paint (Graphics&);
  27799. /** @internal */
  27800. void resized();
  27801. /** @internal */
  27802. bool keyStateChanged (bool isKeyDown);
  27803. /** @internal */
  27804. bool keyPressed (const KeyPress&);
  27805. /** @internal */
  27806. void valueChanged (Value&);
  27807. juce_UseDebuggingNewOperator
  27808. private:
  27809. struct ItemInfo
  27810. {
  27811. String name;
  27812. int itemId;
  27813. bool isEnabled : 1, isHeading : 1;
  27814. bool isSeparator() const throw();
  27815. bool isRealItem() const throw();
  27816. };
  27817. class Callback;
  27818. friend class Callback;
  27819. OwnedArray <ItemInfo> items;
  27820. Value currentId;
  27821. int lastCurrentId;
  27822. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  27823. ListenerList <Listener> listeners;
  27824. ScopedPointer<Label> label;
  27825. String textWhenNothingSelected, noChoicesMessage;
  27826. ItemInfo* getItemForId (int itemId) const throw();
  27827. ItemInfo* getItemForIndex (int index) const throw();
  27828. ComboBox (const ComboBox&);
  27829. ComboBox& operator= (const ComboBox&);
  27830. };
  27831. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  27832. typedef ComboBox::Listener ComboBoxListener;
  27833. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  27834. /*** End of inlined file: juce_ComboBox.h ***/
  27835. /**
  27836. Manages the state of some audio and midi i/o devices.
  27837. This class keeps tracks of a currently-selected audio device, through
  27838. with which it continuously streams data from an audio callback, as well as
  27839. one or more midi inputs.
  27840. The idea is that your application will create one global instance of this object,
  27841. and let it take care of creating and deleting specific types of audio devices
  27842. internally. So when the device is changed, your callbacks will just keep running
  27843. without having to worry about this.
  27844. The manager can save and reload all of its device settings as XML, which
  27845. makes it very easy for you to save and reload the audio setup of your
  27846. application.
  27847. And to make it easy to let the user change its settings, there's a component
  27848. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  27849. device selection/sample-rate/latency controls.
  27850. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  27851. call addAudioCallback() to register your audio callback with it, and use that to process
  27852. your audio data.
  27853. The manager also acts as a handy hub for incoming midi messages, allowing a
  27854. listener to register for messages from either a specific midi device, or from whatever
  27855. the current default midi input device is. The listener then doesn't have to worry about
  27856. re-registering with different midi devices if they are changed or deleted.
  27857. And yet another neat trick is that amount of CPU time being used is measured and
  27858. available with the getCpuUsage() method.
  27859. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  27860. listeners whenever one of its settings is changed.
  27861. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  27862. */
  27863. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  27864. {
  27865. public:
  27866. /** Creates a default AudioDeviceManager.
  27867. Initially no audio device will be selected. You should call the initialise() method
  27868. and register an audio callback with setAudioCallback() before it'll be able to
  27869. actually make any noise.
  27870. */
  27871. AudioDeviceManager();
  27872. /** Destructor. */
  27873. ~AudioDeviceManager();
  27874. /**
  27875. This structure holds a set of properties describing the current audio setup.
  27876. An AudioDeviceManager uses this class to save/load its current settings, and to
  27877. specify your preferred options when opening a device.
  27878. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  27879. */
  27880. struct JUCE_API AudioDeviceSetup
  27881. {
  27882. /** Creates an AudioDeviceSetup object.
  27883. The default constructor sets all the member variables to indicate default values.
  27884. You can then fill-in any values you want to before passing the object to
  27885. AudioDeviceManager::initialise().
  27886. */
  27887. AudioDeviceSetup();
  27888. bool operator== (const AudioDeviceSetup& other) const;
  27889. /** The name of the audio device used for output.
  27890. The name has to be one of the ones listed by the AudioDeviceManager's currently
  27891. selected device type.
  27892. This may be the same as the input device.
  27893. An empty string indicates the default device.
  27894. */
  27895. String outputDeviceName;
  27896. /** The name of the audio device used for input.
  27897. This may be the same as the output device.
  27898. An empty string indicates the default device.
  27899. */
  27900. String inputDeviceName;
  27901. /** The current sample rate.
  27902. This rate is used for both the input and output devices.
  27903. A value of 0 indicates the default rate.
  27904. */
  27905. double sampleRate;
  27906. /** The buffer size, in samples.
  27907. This buffer size is used for both the input and output devices.
  27908. A value of 0 indicates the default buffer size.
  27909. */
  27910. int bufferSize;
  27911. /** The set of active input channels.
  27912. The bits that are set in this array indicate the channels of the
  27913. input device that are active.
  27914. If useDefaultInputChannels is true, this value is ignored.
  27915. */
  27916. BigInteger inputChannels;
  27917. /** If this is true, it indicates that the inputChannels array
  27918. should be ignored, and instead, the device's default channels
  27919. should be used.
  27920. */
  27921. bool useDefaultInputChannels;
  27922. /** The set of active output channels.
  27923. The bits that are set in this array indicate the channels of the
  27924. input device that are active.
  27925. If useDefaultOutputChannels is true, this value is ignored.
  27926. */
  27927. BigInteger outputChannels;
  27928. /** If this is true, it indicates that the outputChannels array
  27929. should be ignored, and instead, the device's default channels
  27930. should be used.
  27931. */
  27932. bool useDefaultOutputChannels;
  27933. };
  27934. /** Opens a set of audio devices ready for use.
  27935. This will attempt to open either a default audio device, or one that was
  27936. previously saved as XML.
  27937. @param numInputChannelsNeeded a minimum number of input channels needed
  27938. by your app.
  27939. @param numOutputChannelsNeeded a minimum number of output channels to open
  27940. @param savedState either a previously-saved state that was produced
  27941. by createStateXml(), or 0 if you want the manager
  27942. to choose the best device to open.
  27943. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  27944. fails to open, then a default device will be used
  27945. instead. If false, then on failure, no device is
  27946. opened.
  27947. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  27948. name, then that will be used as the default device
  27949. (assuming that there wasn't one specified in the XML).
  27950. The string can actually be a simple wildcard, containing "*"
  27951. and "?" characters
  27952. @param preferredSetupOptions if this is non-null, the structure will be used as the
  27953. set of preferred settings when opening the device. If you
  27954. use this parameter, the preferredDefaultDeviceName
  27955. field will be ignored
  27956. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27957. */
  27958. const String initialise (int numInputChannelsNeeded,
  27959. int numOutputChannelsNeeded,
  27960. const XmlElement* savedState,
  27961. bool selectDefaultDeviceOnFailure,
  27962. const String& preferredDefaultDeviceName = String::empty,
  27963. const AudioDeviceSetup* preferredSetupOptions = 0);
  27964. /** Returns some XML representing the current state of the manager.
  27965. This stores the current device, its samplerate, block size, etc, and
  27966. can be restored later with initialise().
  27967. */
  27968. XmlElement* createStateXml() const;
  27969. /** Returns the current device properties that are in use.
  27970. @see setAudioDeviceSetup
  27971. */
  27972. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  27973. /** Changes the current device or its settings.
  27974. If you want to change a device property, like the current sample rate or
  27975. block size, you can call getAudioDeviceSetup() to retrieve the current
  27976. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  27977. and pass it back into this method to apply the new settings.
  27978. @param newSetup the settings that you'd like to use
  27979. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  27980. settings will be taken as having been explicitly chosen by the
  27981. user, and the next time createStateXml() is called, these settings
  27982. will be returned. If it's false, then the device is treated as a
  27983. temporary or default device, and a call to createStateXml() will
  27984. return either the last settings that were made with treatAsChosenDevice
  27985. as true, or the last XML settings that were passed into initialise().
  27986. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27987. @see getAudioDeviceSetup
  27988. */
  27989. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  27990. bool treatAsChosenDevice);
  27991. /** Returns the currently-active audio device. */
  27992. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  27993. /** Returns the type of audio device currently in use.
  27994. @see setCurrentAudioDeviceType
  27995. */
  27996. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  27997. /** Returns the currently active audio device type object.
  27998. Don't keep a copy of this pointer - it's owned by the device manager and could
  27999. change at any time.
  28000. */
  28001. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  28002. /** Changes the class of audio device being used.
  28003. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  28004. this because there's only one type: CoreAudio.
  28005. For a list of types, see getAvailableDeviceTypes().
  28006. */
  28007. void setCurrentAudioDeviceType (const String& type,
  28008. bool treatAsChosenDevice);
  28009. /** Closes the currently-open device.
  28010. You can call restartLastAudioDevice() later to reopen it in the same state
  28011. that it was just in.
  28012. */
  28013. void closeAudioDevice();
  28014. /** Tries to reload the last audio device that was running.
  28015. Note that this only reloads the last device that was running before
  28016. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  28017. and can only be called after a device has been opened with SetAudioDevice().
  28018. If a device is already open, this call will do nothing.
  28019. */
  28020. void restartLastAudioDevice();
  28021. /** Registers an audio callback to be used.
  28022. The manager will redirect callbacks from whatever audio device is currently
  28023. in use to all registered callback objects. If more than one callback is
  28024. active, they will all be given the same input data, and their outputs will
  28025. be summed.
  28026. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  28027. object before returning.
  28028. To remove a callback, use removeAudioCallback().
  28029. */
  28030. void addAudioCallback (AudioIODeviceCallback* newCallback);
  28031. /** Deregisters a previously added callback.
  28032. If necessary, this method will invoke audioDeviceStopped() on the callback
  28033. object before returning.
  28034. @see addAudioCallback
  28035. */
  28036. void removeAudioCallback (AudioIODeviceCallback* callback);
  28037. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  28038. Returns a value between 0 and 1.0
  28039. */
  28040. double getCpuUsage() const;
  28041. /** Enables or disables a midi input device.
  28042. The list of devices can be obtained with the MidiInput::getDevices() method.
  28043. Any incoming messages from enabled input devices will be forwarded on to all the
  28044. listeners that have been registered with the addMidiInputCallback() method. They
  28045. can either register for messages from a particular device, or from just the
  28046. "default" midi input.
  28047. Routing the midi input via an AudioDeviceManager means that when a listener
  28048. registers for the default midi input, this default device can be changed by the
  28049. manager without the listeners having to know about it or re-register.
  28050. It also means that a listener can stay registered for a midi input that is disabled
  28051. or not present, so that when the input is re-enabled, the listener will start
  28052. receiving messages again.
  28053. @see addMidiInputCallback, isMidiInputEnabled
  28054. */
  28055. void setMidiInputEnabled (const String& midiInputDeviceName,
  28056. bool enabled);
  28057. /** Returns true if a given midi input device is being used.
  28058. @see setMidiInputEnabled
  28059. */
  28060. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  28061. /** Registers a listener for callbacks when midi events arrive from a midi input.
  28062. The device name can be empty to indicate that it wants events from whatever the
  28063. current "default" device is. Or it can be the name of one of the midi input devices
  28064. (see MidiInput::getDevices() for the names).
  28065. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  28066. events forwarded on to listeners.
  28067. */
  28068. void addMidiInputCallback (const String& midiInputDeviceName,
  28069. MidiInputCallback* callback);
  28070. /** Removes a listener that was previously registered with addMidiInputCallback().
  28071. */
  28072. void removeMidiInputCallback (const String& midiInputDeviceName,
  28073. MidiInputCallback* callback);
  28074. /** Sets a midi output device to use as the default.
  28075. The list of devices can be obtained with the MidiOutput::getDevices() method.
  28076. The specified device will be opened automatically and can be retrieved with the
  28077. getDefaultMidiOutput() method.
  28078. Pass in an empty string to deselect all devices. For the default device, you
  28079. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  28080. @see getDefaultMidiOutput, getDefaultMidiOutputName
  28081. */
  28082. void setDefaultMidiOutput (const String& deviceName);
  28083. /** Returns the name of the default midi output.
  28084. @see setDefaultMidiOutput, getDefaultMidiOutput
  28085. */
  28086. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  28087. /** Returns the current default midi output device.
  28088. If no device has been selected, or the device can't be opened, this will
  28089. return 0.
  28090. @see getDefaultMidiOutputName
  28091. */
  28092. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  28093. /** Returns a list of the types of device supported.
  28094. */
  28095. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  28096. /** Creates a list of available types.
  28097. This will add a set of new AudioIODeviceType objects to the specified list, to
  28098. represent each available types of device.
  28099. You can override this if your app needs to do something specific, like avoid
  28100. using DirectSound devices, etc.
  28101. */
  28102. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  28103. /** Plays a beep through the current audio device.
  28104. This is here to allow the audio setup UI panels to easily include a "test"
  28105. button so that the user can check where the audio is coming from.
  28106. */
  28107. void playTestSound();
  28108. /** Turns on level-measuring.
  28109. When enabled, the device manager will measure the peak input level
  28110. across all channels, and you can get this level by calling getCurrentInputLevel().
  28111. This is mainly intended for audio setup UI panels to use to create a mic
  28112. level display, so that the user can check that they've selected the right
  28113. device.
  28114. A simple filter is used to make the level decay smoothly, but this is
  28115. only intended for giving rough feedback, and not for any kind of accurate
  28116. measurement.
  28117. */
  28118. void enableInputLevelMeasurement (bool enableMeasurement);
  28119. /** Returns the current input level.
  28120. To use this, you must first enable it by calling enableInputLevelMeasurement().
  28121. See enableInputLevelMeasurement() for more info.
  28122. */
  28123. double getCurrentInputLevel() const;
  28124. juce_UseDebuggingNewOperator
  28125. private:
  28126. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  28127. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  28128. AudioDeviceSetup currentSetup;
  28129. ScopedPointer <AudioIODevice> currentAudioDevice;
  28130. SortedSet <AudioIODeviceCallback*> callbacks;
  28131. int numInputChansNeeded, numOutputChansNeeded;
  28132. String currentDeviceType;
  28133. BigInteger inputChannels, outputChannels;
  28134. ScopedPointer <XmlElement> lastExplicitSettings;
  28135. mutable bool listNeedsScanning;
  28136. bool useInputNames;
  28137. int inputLevelMeasurementEnabledCount;
  28138. double inputLevel;
  28139. ScopedPointer <AudioSampleBuffer> testSound;
  28140. int testSoundPosition;
  28141. AudioSampleBuffer tempBuffer;
  28142. StringArray midiInsFromXml;
  28143. OwnedArray <MidiInput> enabledMidiInputs;
  28144. Array <MidiInputCallback*> midiCallbacks;
  28145. Array <MidiInput*> midiCallbackDevices;
  28146. String defaultMidiOutputName;
  28147. ScopedPointer <MidiOutput> defaultMidiOutput;
  28148. CriticalSection audioCallbackLock, midiCallbackLock;
  28149. double cpuUsageMs, timeToCpuScale;
  28150. class CallbackHandler : public AudioIODeviceCallback,
  28151. public MidiInputCallback
  28152. {
  28153. public:
  28154. AudioDeviceManager* owner;
  28155. void audioDeviceIOCallback (const float** inputChannelData,
  28156. int totalNumInputChannels,
  28157. float** outputChannelData,
  28158. int totalNumOutputChannels,
  28159. int numSamples);
  28160. void audioDeviceAboutToStart (AudioIODevice*);
  28161. void audioDeviceStopped();
  28162. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28163. };
  28164. CallbackHandler callbackHandler;
  28165. friend class CallbackHandler;
  28166. void audioDeviceIOCallbackInt (const float** inputChannelData,
  28167. int totalNumInputChannels,
  28168. float** outputChannelData,
  28169. int totalNumOutputChannels,
  28170. int numSamples);
  28171. void audioDeviceAboutToStartInt (AudioIODevice* device);
  28172. void audioDeviceStoppedInt();
  28173. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  28174. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  28175. const BigInteger& ins, const BigInteger& outs);
  28176. void stopDevice();
  28177. void updateXml();
  28178. void createDeviceTypesIfNeeded();
  28179. void scanDevicesIfNeeded();
  28180. void deleteCurrentDevice();
  28181. double chooseBestSampleRate (double preferred) const;
  28182. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  28183. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  28184. AudioDeviceManager (const AudioDeviceManager&);
  28185. AudioDeviceManager& operator= (const AudioDeviceManager&);
  28186. };
  28187. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  28188. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  28189. #endif
  28190. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28191. #endif
  28192. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  28193. #endif
  28194. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  28195. #endif
  28196. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  28197. #endif
  28198. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28199. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  28200. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28201. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28202. /**
  28203. A set of routines to convert buffers of 32-bit floating point data to and from
  28204. various integer formats.
  28205. */
  28206. class JUCE_API AudioDataConverters
  28207. {
  28208. public:
  28209. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  28210. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  28211. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  28212. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  28213. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28214. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28215. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28216. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28217. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  28218. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  28219. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  28220. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  28221. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28222. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28223. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28224. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28225. enum DataFormat
  28226. {
  28227. int16LE,
  28228. int16BE,
  28229. int24LE,
  28230. int24BE,
  28231. int32LE,
  28232. int32BE,
  28233. float32LE,
  28234. float32BE,
  28235. };
  28236. static void convertFloatToFormat (DataFormat destFormat,
  28237. const float* source, void* dest, int numSamples);
  28238. static void convertFormatToFloat (DataFormat sourceFormat,
  28239. const void* source, float* dest, int numSamples);
  28240. static void interleaveSamples (const float** source, float* dest,
  28241. int numSamples, int numChannels);
  28242. static void deinterleaveSamples (const float* source, float** dest,
  28243. int numSamples, int numChannels);
  28244. private:
  28245. AudioDataConverters();
  28246. AudioDataConverters (const AudioDataConverters&);
  28247. AudioDataConverters& operator= (const AudioDataConverters&);
  28248. };
  28249. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28250. /*** End of inlined file: juce_AudioDataConverters.h ***/
  28251. #endif
  28252. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  28253. #endif
  28254. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  28255. #endif
  28256. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  28257. #endif
  28258. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  28259. /*** Start of inlined file: juce_MidiFile.h ***/
  28260. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  28261. #define __JUCE_MIDIFILE_JUCEHEADER__
  28262. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  28263. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28264. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28265. /**
  28266. A sequence of timestamped midi messages.
  28267. This allows the sequence to be manipulated, and also to be read from and
  28268. written to a standard midi file.
  28269. @see MidiMessage, MidiFile
  28270. */
  28271. class JUCE_API MidiMessageSequence
  28272. {
  28273. public:
  28274. /** Creates an empty midi sequence object. */
  28275. MidiMessageSequence();
  28276. /** Creates a copy of another sequence. */
  28277. MidiMessageSequence (const MidiMessageSequence& other);
  28278. /** Replaces this sequence with another one. */
  28279. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  28280. /** Destructor. */
  28281. ~MidiMessageSequence();
  28282. /** Structure used to hold midi events in the sequence.
  28283. These structures act as 'handles' on the events as they are moved about in
  28284. the list, and make it quick to find the matching note-offs for note-on events.
  28285. @see MidiMessageSequence::getEventPointer
  28286. */
  28287. class MidiEventHolder
  28288. {
  28289. public:
  28290. /** Destructor. */
  28291. ~MidiEventHolder();
  28292. /** The message itself, whose timestamp is used to specify the event's time.
  28293. */
  28294. MidiMessage message;
  28295. /** The matching note-off event (if this is a note-on event).
  28296. If this isn't a note-on, this pointer will be null.
  28297. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  28298. note-offs up-to-date after events have been moved around in the sequence
  28299. or deleted.
  28300. */
  28301. MidiEventHolder* noteOffObject;
  28302. juce_UseDebuggingNewOperator
  28303. private:
  28304. friend class MidiMessageSequence;
  28305. MidiEventHolder (const MidiMessage& message);
  28306. };
  28307. /** Clears the sequence. */
  28308. void clear();
  28309. /** Returns the number of events in the sequence. */
  28310. int getNumEvents() const;
  28311. /** Returns a pointer to one of the events. */
  28312. MidiEventHolder* getEventPointer (int index) const;
  28313. /** Returns the time of the note-up that matches the note-on at this index.
  28314. If the event at this index isn't a note-on, it'll just return 0.
  28315. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  28316. */
  28317. double getTimeOfMatchingKeyUp (int index) const;
  28318. /** Returns the index of the note-up that matches the note-on at this index.
  28319. If the event at this index isn't a note-on, it'll just return -1.
  28320. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  28321. */
  28322. int getIndexOfMatchingKeyUp (int index) const;
  28323. /** Returns the index of an event. */
  28324. int getIndexOf (MidiEventHolder* event) const;
  28325. /** Returns the index of the first event on or after the given timestamp.
  28326. If the time is beyond the end of the sequence, this will return the
  28327. number of events.
  28328. */
  28329. int getNextIndexAtTime (double timeStamp) const;
  28330. /** Returns the timestamp of the first event in the sequence.
  28331. @see getEndTime
  28332. */
  28333. double getStartTime() const;
  28334. /** Returns the timestamp of the last event in the sequence.
  28335. @see getStartTime
  28336. */
  28337. double getEndTime() const;
  28338. /** Returns the timestamp of the event at a given index.
  28339. If the index is out-of-range, this will return 0.0
  28340. */
  28341. double getEventTime (int index) const;
  28342. /** Inserts a midi message into the sequence.
  28343. The index at which the new message gets inserted will depend on its timestamp,
  28344. because the sequence is kept sorted.
  28345. Remember to call updateMatchedPairs() after adding note-on events.
  28346. @param newMessage the new message to add (an internal copy will be made)
  28347. @param timeAdjustment an optional value to add to the timestamp of the message
  28348. that will be inserted
  28349. @see updateMatchedPairs
  28350. */
  28351. void addEvent (const MidiMessage& newMessage,
  28352. double timeAdjustment = 0);
  28353. /** Deletes one of the events in the sequence.
  28354. Remember to call updateMatchedPairs() after removing events.
  28355. @param index the index of the event to delete
  28356. @param deleteMatchingNoteUp whether to also remove the matching note-off
  28357. if the event you're removing is a note-on
  28358. */
  28359. void deleteEvent (int index, bool deleteMatchingNoteUp);
  28360. /** Merges another sequence into this one.
  28361. Remember to call updateMatchedPairs() after using this method.
  28362. @param other the sequence to add from
  28363. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  28364. as they are read from the other sequence
  28365. @param firstAllowableDestTime events will not be added if their time is earlier
  28366. than this time. (This is after their time has been adjusted
  28367. by the timeAdjustmentDelta)
  28368. @param endOfAllowableDestTimes events will not be added if their time is equal to
  28369. or greater than this time. (This is after their time has
  28370. been adjusted by the timeAdjustmentDelta)
  28371. */
  28372. void addSequence (const MidiMessageSequence& other,
  28373. double timeAdjustmentDelta,
  28374. double firstAllowableDestTime,
  28375. double endOfAllowableDestTimes);
  28376. /** Makes sure all the note-on and note-off pairs are up-to-date.
  28377. Call this after moving messages about or deleting/adding messages, and it
  28378. will scan the list and make sure all the note-offs in the MidiEventHolder
  28379. structures are pointing at the correct ones.
  28380. */
  28381. void updateMatchedPairs();
  28382. /** Copies all the messages for a particular midi channel to another sequence.
  28383. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  28384. @param destSequence the sequence that the chosen events should be copied to
  28385. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  28386. channel) will also be copied across.
  28387. @see extractSysExMessages
  28388. */
  28389. void extractMidiChannelMessages (int channelNumberToExtract,
  28390. MidiMessageSequence& destSequence,
  28391. bool alsoIncludeMetaEvents) const;
  28392. /** Copies all midi sys-ex messages to another sequence.
  28393. @param destSequence this is the sequence to which any sys-exes in this sequence
  28394. will be added
  28395. @see extractMidiChannelMessages
  28396. */
  28397. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  28398. /** Removes any messages in this sequence that have a specific midi channel.
  28399. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  28400. */
  28401. void deleteMidiChannelMessages (int channelNumberToRemove);
  28402. /** Removes any sys-ex messages from this sequence.
  28403. */
  28404. void deleteSysExMessages();
  28405. /** Adds an offset to the timestamps of all events in the sequence.
  28406. @param deltaTime the amount to add to each timestamp.
  28407. */
  28408. void addTimeToMessages (double deltaTime);
  28409. /** Scans through the sequence to determine the state of any midi controllers at
  28410. a given time.
  28411. This will create a sequence of midi controller changes that can be
  28412. used to set all midi controllers to the state they would be in at the
  28413. specified time within this sequence.
  28414. As well as controllers, it will also recreate the midi program number
  28415. and pitch bend position.
  28416. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  28417. for other channels will be ignored.
  28418. @param time the time at which you want to find out the state - there are
  28419. no explicit units for this time measurement, it's the same units
  28420. as used for the timestamps of the messages
  28421. @param resultMessages an array to which midi controller-change messages will be added. This
  28422. will be the minimum number of controller changes to recreate the
  28423. state at the required time.
  28424. */
  28425. void createControllerUpdatesForTime (int channelNumber, double time,
  28426. OwnedArray<MidiMessage>& resultMessages);
  28427. /** Swaps this sequence with another one. */
  28428. void swapWith (MidiMessageSequence& other) throw();
  28429. juce_UseDebuggingNewOperator
  28430. /** @internal */
  28431. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  28432. const MidiMessageSequence::MidiEventHolder* second) throw();
  28433. private:
  28434. friend class MidiFile;
  28435. OwnedArray <MidiEventHolder> list;
  28436. void sort();
  28437. };
  28438. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28439. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  28440. /**
  28441. Reads/writes standard midi format files.
  28442. To read a midi file, create a MidiFile object and call its readFrom() method. You
  28443. can then get the individual midi tracks from it using the getTrack() method.
  28444. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  28445. to it using the addTrack() method, and then call its writeTo() method to stream
  28446. it out.
  28447. @see MidiMessageSequence
  28448. */
  28449. class JUCE_API MidiFile
  28450. {
  28451. public:
  28452. /** Creates an empty MidiFile object.
  28453. */
  28454. MidiFile();
  28455. /** Destructor. */
  28456. ~MidiFile();
  28457. /** Returns the number of tracks in the file.
  28458. @see getTrack, addTrack
  28459. */
  28460. int getNumTracks() const throw();
  28461. /** Returns a pointer to one of the tracks in the file.
  28462. @returns a pointer to the track, or 0 if the index is out-of-range
  28463. @see getNumTracks, addTrack
  28464. */
  28465. const MidiMessageSequence* getTrack (const int index) const throw();
  28466. /** Adds a midi track to the file.
  28467. This will make its own internal copy of the sequence that is passed-in.
  28468. @see getNumTracks, getTrack
  28469. */
  28470. void addTrack (const MidiMessageSequence& trackSequence);
  28471. /** Removes all midi tracks from the file.
  28472. @see getNumTracks
  28473. */
  28474. void clear();
  28475. /** Returns the raw time format code that will be written to a stream.
  28476. After reading a midi file, this method will return the time-format that
  28477. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  28478. or setSmpteTimeFormat() methods.
  28479. If the value returned is positive, it indicates the number of midi ticks
  28480. per quarter-note - see setTicksPerQuarterNote().
  28481. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  28482. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  28483. */
  28484. short getTimeFormat() const throw();
  28485. /** Sets the time format to use when this file is written to a stream.
  28486. If this is called, the file will be written as bars/beats using the
  28487. specified resolution, rather than SMPTE absolute times, as would be
  28488. used if setSmpteTimeFormat() had been called instead.
  28489. @param ticksPerQuarterNote e.g. 96, 960
  28490. @see setSmpteTimeFormat
  28491. */
  28492. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  28493. /** Sets the time format to use when this file is written to a stream.
  28494. If this is called, the file will be written using absolute times, rather
  28495. than bars/beats as would be the case if setTicksPerBeat() had been called
  28496. instead.
  28497. @param framesPerSecond must be 24, 25, 29 or 30
  28498. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  28499. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  28500. timing, setSmpteTimeFormat (25, 40)
  28501. @see setTicksPerBeat
  28502. */
  28503. void setSmpteTimeFormat (const int framesPerSecond,
  28504. const int subframeResolution) throw();
  28505. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  28506. Useful for finding the positions of all the tempo changes in a file.
  28507. @param tempoChangeEvents a list to which all the events will be added
  28508. */
  28509. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  28510. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  28511. Useful for finding the positions of all the tempo changes in a file.
  28512. @param timeSigEvents a list to which all the events will be added
  28513. */
  28514. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  28515. /** Returns the latest timestamp in any of the tracks.
  28516. (Useful for finding the length of the file).
  28517. */
  28518. double getLastTimestamp() const;
  28519. /** Reads a midi file format stream.
  28520. After calling this, you can get the tracks that were read from the file by using the
  28521. getNumTracks() and getTrack() methods.
  28522. The timestamps of the midi events in the tracks will represent their positions in
  28523. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  28524. method.
  28525. @returns true if the stream was read successfully
  28526. */
  28527. bool readFrom (InputStream& sourceStream);
  28528. /** Writes the midi tracks as a standard midi file.
  28529. @returns true if the operation succeeded.
  28530. */
  28531. bool writeTo (OutputStream& destStream);
  28532. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  28533. This will use the midi time format and tempo/time signature info in the
  28534. tracks to convert all the timestamps to absolute values in seconds.
  28535. */
  28536. void convertTimestampTicksToSeconds();
  28537. juce_UseDebuggingNewOperator
  28538. /** @internal */
  28539. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  28540. const MidiMessageSequence::MidiEventHolder* const second);
  28541. private:
  28542. OwnedArray <MidiMessageSequence> tracks;
  28543. short timeFormat;
  28544. MidiFile (const MidiFile&);
  28545. MidiFile& operator= (const MidiFile&);
  28546. void readNextTrack (const uint8* data, int size);
  28547. void writeTrack (OutputStream& mainOut, const int trackNum);
  28548. };
  28549. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  28550. /*** End of inlined file: juce_MidiFile.h ***/
  28551. #endif
  28552. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28553. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  28554. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28555. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28556. class MidiKeyboardState;
  28557. /**
  28558. Receives events from a MidiKeyboardState object.
  28559. @see MidiKeyboardState
  28560. */
  28561. class JUCE_API MidiKeyboardStateListener
  28562. {
  28563. public:
  28564. MidiKeyboardStateListener() throw() {}
  28565. virtual ~MidiKeyboardStateListener() {}
  28566. /** Called when one of the MidiKeyboardState's keys is pressed.
  28567. This will be called synchronously when the state is either processing a
  28568. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28569. when a note is being played with its MidiKeyboardState::noteOn() method.
  28570. Note that this callback could happen from an audio callback thread, so be
  28571. careful not to block, and avoid any UI activity in the callback.
  28572. */
  28573. virtual void handleNoteOn (MidiKeyboardState* source,
  28574. int midiChannel, int midiNoteNumber, float velocity) = 0;
  28575. /** Called when one of the MidiKeyboardState's keys is released.
  28576. This will be called synchronously when the state is either processing a
  28577. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28578. when a note is being played with its MidiKeyboardState::noteOff() method.
  28579. Note that this callback could happen from an audio callback thread, so be
  28580. careful not to block, and avoid any UI activity in the callback.
  28581. */
  28582. virtual void handleNoteOff (MidiKeyboardState* source,
  28583. int midiChannel, int midiNoteNumber) = 0;
  28584. };
  28585. /**
  28586. Represents a piano keyboard, keeping track of which keys are currently pressed.
  28587. This object can parse a stream of midi events, using them to update its idea
  28588. of which keys are pressed for each individiual midi channel.
  28589. When keys go up or down, it can broadcast these events to listener objects.
  28590. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  28591. methods, and midi messages for these events will be merged into the
  28592. midi stream that gets processed by processNextMidiBuffer().
  28593. */
  28594. class JUCE_API MidiKeyboardState
  28595. {
  28596. public:
  28597. MidiKeyboardState();
  28598. ~MidiKeyboardState();
  28599. /** Resets the state of the object.
  28600. All internal data for all the channels is reset, but no events are sent as a
  28601. result.
  28602. If you want to release any keys that are currently down, and to send out note-up
  28603. midi messages for this, use the allNotesOff() method instead.
  28604. */
  28605. void reset();
  28606. /** Returns true if the given midi key is currently held down for the given midi channel.
  28607. The channel number must be between 1 and 16. If you want to see if any notes are
  28608. on for a range of channels, use the isNoteOnForChannels() method.
  28609. */
  28610. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  28611. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  28612. The channel mask has a bit set for each midi channel you want to test for - bit
  28613. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  28614. If a note is on for at least one of the specified channels, this returns true.
  28615. */
  28616. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  28617. /** Turns a specified note on.
  28618. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  28619. next call to processNextMidiBuffer().
  28620. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28621. gone down.
  28622. */
  28623. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  28624. /** Turns a specified note off.
  28625. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  28626. next call to processNextMidiBuffer().
  28627. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28628. gone up.
  28629. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  28630. */
  28631. void noteOff (const int midiChannel, const int midiNoteNumber);
  28632. /** This will turn off any currently-down notes for the given midi channel.
  28633. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  28634. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  28635. and events being added to the midi stream.
  28636. */
  28637. void allNotesOff (const int midiChannel);
  28638. /** Looks at a key-up/down event and uses it to update the state of this object.
  28639. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  28640. instead.
  28641. */
  28642. void processNextMidiEvent (const MidiMessage& message);
  28643. /** Scans a midi stream for up/down events and adds its own events to it.
  28644. This will look for any up/down events and use them to update the internal state,
  28645. synchronously making suitable callbacks to the listeners.
  28646. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  28647. and noteOff() calls will be added into the buffer.
  28648. Only the section of the buffer whose timestamps are between startSample and
  28649. (startSample + numSamples) will be affected, and any events added will be placed
  28650. between these times.
  28651. If you're going to use this method, you'll need to keep calling it regularly for
  28652. it to work satisfactorily.
  28653. To process a single midi event at a time, use the processNextMidiEvent() method
  28654. instead.
  28655. */
  28656. void processNextMidiBuffer (MidiBuffer& buffer,
  28657. const int startSample,
  28658. const int numSamples,
  28659. const bool injectIndirectEvents);
  28660. /** Registers a listener for callbacks when keys go up or down.
  28661. @see removeListener
  28662. */
  28663. void addListener (MidiKeyboardStateListener* const listener) throw();
  28664. /** Deregisters a listener.
  28665. @see addListener
  28666. */
  28667. void removeListener (MidiKeyboardStateListener* const listener) throw();
  28668. juce_UseDebuggingNewOperator
  28669. private:
  28670. CriticalSection lock;
  28671. uint16 noteStates [128];
  28672. MidiBuffer eventsToAdd;
  28673. Array <MidiKeyboardStateListener*> listeners;
  28674. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  28675. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  28676. MidiKeyboardState (const MidiKeyboardState&);
  28677. MidiKeyboardState& operator= (const MidiKeyboardState&);
  28678. };
  28679. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28680. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  28681. #endif
  28682. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  28683. #endif
  28684. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28685. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  28686. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28687. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28688. /**
  28689. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  28690. processing by a block-based audio callback.
  28691. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  28692. so it can easily use a midi input or keyboard component as its source.
  28693. @see MidiMessage, MidiInput
  28694. */
  28695. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  28696. public MidiInputCallback
  28697. {
  28698. public:
  28699. /** Creates a MidiMessageCollector. */
  28700. MidiMessageCollector();
  28701. /** Destructor. */
  28702. ~MidiMessageCollector();
  28703. /** Clears any messages from the queue.
  28704. You need to call this method before starting to use the collector, so that
  28705. it knows the correct sample rate to use.
  28706. */
  28707. void reset (double sampleRate);
  28708. /** Takes an incoming real-time message and adds it to the queue.
  28709. The message's timestamp is taken, and it will be ready for retrieval as part
  28710. of the block returned by the next call to removeNextBlockOfMessages().
  28711. This method is fully thread-safe when overlapping calls are made with
  28712. removeNextBlockOfMessages().
  28713. */
  28714. void addMessageToQueue (const MidiMessage& message);
  28715. /** Removes all the pending messages from the queue as a buffer.
  28716. This will also correct the messages' timestamps to make sure they're in
  28717. the range 0 to numSamples - 1.
  28718. This call should be made regularly by something like an audio processing
  28719. callback, because the time that it happens is used in calculating the
  28720. midi event positions.
  28721. This method is fully thread-safe when overlapping calls are made with
  28722. addMessageToQueue().
  28723. */
  28724. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  28725. /** @internal */
  28726. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  28727. /** @internal */
  28728. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  28729. /** @internal */
  28730. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28731. juce_UseDebuggingNewOperator
  28732. private:
  28733. double lastCallbackTime;
  28734. CriticalSection midiCallbackLock;
  28735. MidiBuffer incomingMessages;
  28736. double sampleRate;
  28737. MidiMessageCollector (const MidiMessageCollector&);
  28738. MidiMessageCollector& operator= (const MidiMessageCollector&);
  28739. };
  28740. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28741. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  28742. #endif
  28743. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28744. #endif
  28745. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28746. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  28747. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28748. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28749. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  28750. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28751. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28752. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  28753. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28754. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28755. /*** Start of inlined file: juce_AudioProcessor.h ***/
  28756. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28757. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28758. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  28759. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28760. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28761. class AudioProcessor;
  28762. /**
  28763. Base class for the component that acts as the GUI for an AudioProcessor.
  28764. Derive your editor component from this class, and create an instance of it
  28765. by overriding the AudioProcessor::createEditor() method.
  28766. @see AudioProcessor, GenericAudioProcessorEditor
  28767. */
  28768. class JUCE_API AudioProcessorEditor : public Component
  28769. {
  28770. protected:
  28771. /** Creates an editor for the specified processor.
  28772. */
  28773. AudioProcessorEditor (AudioProcessor* const owner);
  28774. public:
  28775. /** Destructor. */
  28776. ~AudioProcessorEditor();
  28777. /** Returns a pointer to the processor that this editor represents. */
  28778. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  28779. private:
  28780. AudioProcessor* const owner;
  28781. AudioProcessorEditor (const AudioProcessorEditor&);
  28782. AudioProcessorEditor& operator= (const AudioProcessorEditor&);
  28783. };
  28784. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28785. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  28786. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  28787. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28788. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28789. class AudioProcessor;
  28790. /**
  28791. Base class for listeners that want to know about changes to an AudioProcessor.
  28792. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  28793. @see AudioProcessor
  28794. */
  28795. class JUCE_API AudioProcessorListener
  28796. {
  28797. public:
  28798. /** Destructor. */
  28799. virtual ~AudioProcessorListener() {}
  28800. /** Receives a callback when a parameter is changed.
  28801. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  28802. many audio processors will change their parameter during their audio callback.
  28803. This means that not only has your handler code got to be completely thread-safe,
  28804. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  28805. this event on your message thread, use this callback to trigger an AsyncUpdater
  28806. or ChangeBroadcaster which you can respond to on the message thread.
  28807. */
  28808. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  28809. int parameterIndex,
  28810. float newValue) = 0;
  28811. /** Called to indicate that something else in the plugin has changed, like its
  28812. program, number of parameters, etc.
  28813. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28814. call it during their audio callback. This means that not only has your handler code
  28815. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28816. blocking. If you need to handle this event on your message thread, use this callback
  28817. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28818. message thread.
  28819. */
  28820. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  28821. /** Indicates that a parameter change gesture has started.
  28822. E.g. if the user is dragging a slider, this would be called when they first
  28823. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  28824. called when they release it.
  28825. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28826. call it during their audio callback. This means that not only has your handler code
  28827. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28828. blocking. If you need to handle this event on your message thread, use this callback
  28829. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28830. message thread.
  28831. @see audioProcessorParameterChangeGestureEnd
  28832. */
  28833. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  28834. int parameterIndex);
  28835. /** Indicates that a parameter change gesture has finished.
  28836. E.g. if the user is dragging a slider, this would be called when they release
  28837. the mouse button.
  28838. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28839. call it during their audio callback. This means that not only has your handler code
  28840. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28841. blocking. If you need to handle this event on your message thread, use this callback
  28842. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28843. message thread.
  28844. @see audioPluginParameterChangeGestureStart
  28845. */
  28846. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  28847. int parameterIndex);
  28848. };
  28849. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28850. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  28851. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  28852. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28853. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28854. /**
  28855. A subclass of AudioPlayHead can supply information about the position and
  28856. status of a moving play head during audio playback.
  28857. One of these can be supplied to an AudioProcessor object so that it can find
  28858. out about the position of the audio that it is rendering.
  28859. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  28860. */
  28861. class JUCE_API AudioPlayHead
  28862. {
  28863. protected:
  28864. AudioPlayHead() {}
  28865. public:
  28866. virtual ~AudioPlayHead() {}
  28867. /** Frame rate types. */
  28868. enum FrameRateType
  28869. {
  28870. fps24 = 0,
  28871. fps25 = 1,
  28872. fps2997 = 2,
  28873. fps30 = 3,
  28874. fps2997drop = 4,
  28875. fps30drop = 5,
  28876. fpsUnknown = 99
  28877. };
  28878. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  28879. */
  28880. struct CurrentPositionInfo
  28881. {
  28882. /** The tempo in BPM */
  28883. double bpm;
  28884. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  28885. int timeSigNumerator;
  28886. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  28887. int timeSigDenominator;
  28888. /** The current play position, in seconds from the start of the edit. */
  28889. double timeInSeconds;
  28890. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  28891. double editOriginTime;
  28892. /** The current play position in pulses-per-quarter-note.
  28893. This is the number of quarter notes since the edit start.
  28894. */
  28895. double ppqPosition;
  28896. /** The position of the start of the last bar, in pulses-per-quarter-note.
  28897. This is the number of quarter notes from the start of the edit to the
  28898. start of the current bar.
  28899. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  28900. it's not available, the value will be 0.
  28901. */
  28902. double ppqPositionOfLastBarStart;
  28903. /** The video frame rate, if applicable. */
  28904. FrameRateType frameRate;
  28905. /** True if the transport is currently playing. */
  28906. bool isPlaying;
  28907. /** True if the transport is currently recording.
  28908. (When isRecording is true, then isPlaying will also be true).
  28909. */
  28910. bool isRecording;
  28911. bool operator== (const CurrentPositionInfo& other) const throw();
  28912. bool operator!= (const CurrentPositionInfo& other) const throw();
  28913. void resetToDefault();
  28914. };
  28915. /** Fills-in the given structure with details about the transport's
  28916. position at the start of the current processing block.
  28917. */
  28918. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  28919. };
  28920. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28921. /*** End of inlined file: juce_AudioPlayHead.h ***/
  28922. /**
  28923. Base class for audio processing filters or plugins.
  28924. This is intended to act as a base class of audio filter that is general enough to
  28925. be wrapped as a VST, AU, RTAS, etc, or used internally.
  28926. It is also used by the plugin hosting code as the wrapper around an instance
  28927. of a loaded plugin.
  28928. Derive your filter class from this base class, and if you're building a plugin,
  28929. you should implement a global function called createPluginFilter() which creates
  28930. and returns a new instance of your subclass.
  28931. */
  28932. class JUCE_API AudioProcessor
  28933. {
  28934. protected:
  28935. /** Constructor.
  28936. You can also do your initialisation tasks in the initialiseFilterInfo()
  28937. call, which will be made after this object has been created.
  28938. */
  28939. AudioProcessor();
  28940. public:
  28941. /** Destructor. */
  28942. virtual ~AudioProcessor();
  28943. /** Returns the name of this processor.
  28944. */
  28945. virtual const String getName() const = 0;
  28946. /** Called before playback starts, to let the filter prepare itself.
  28947. The sample rate is the target sample rate, and will remain constant until
  28948. playback stops.
  28949. The estimatedSamplesPerBlock value is a HINT about the typical number of
  28950. samples that will be processed for each callback, but isn't any kind
  28951. of guarantee. The actual block sizes that the host uses may be different
  28952. each time the callback happens, and may be more or less than this value.
  28953. */
  28954. virtual void prepareToPlay (double sampleRate,
  28955. int estimatedSamplesPerBlock) = 0;
  28956. /** Called after playback has stopped, to let the filter free up any resources it
  28957. no longer needs.
  28958. */
  28959. virtual void releaseResources() = 0;
  28960. /** Renders the next block.
  28961. When this method is called, the buffer contains a number of channels which is
  28962. at least as great as the maximum number of input and output channels that
  28963. this filter is using. It will be filled with the filter's input data and
  28964. should be replaced with the filter's output.
  28965. So for example if your filter has 2 input channels and 4 output channels, then
  28966. the buffer will contain 4 channels, the first two being filled with the
  28967. input data. Your filter should read these, do its processing, and replace
  28968. the contents of all 4 channels with its output.
  28969. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  28970. all filled with data, and your filter should overwrite the first 2 of these
  28971. with its output. But be VERY careful not to write anything to the last 3
  28972. channels, as these might be mapped to memory that the host assumes is read-only!
  28973. Note that if you have more outputs than inputs, then only those channels that
  28974. correspond to an input channel are guaranteed to contain sensible data - e.g.
  28975. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  28976. but the last two channels may contain garbage, so you should be careful not to
  28977. let this pass through without being overwritten or cleared.
  28978. Also note that the buffer may have more channels than are strictly necessary,
  28979. but your should only read/write from the ones that your filter is supposed to
  28980. be using.
  28981. The number of samples in these buffers is NOT guaranteed to be the same for every
  28982. callback, and may be more or less than the estimated value given to prepareToPlay().
  28983. Your code must be able to cope with variable-sized blocks, or you're going to get
  28984. clicks and crashes!
  28985. If the filter is receiving a midi input, then the midiMessages array will be filled
  28986. with the midi messages for this block. Each message's timestamp will indicate the
  28987. message's time, as a number of samples from the start of the block.
  28988. Any messages left in the midi buffer when this method has finished are assumed to
  28989. be the filter's midi output. This means that your filter should be careful to
  28990. clear any incoming messages from the array if it doesn't want them to be passed-on.
  28991. Be very careful about what you do in this callback - it's going to be called by
  28992. the audio thread, so any kind of interaction with the UI is absolutely
  28993. out of the question. If you change a parameter in here and need to tell your UI to
  28994. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  28995. the UI components register as listeners, and then call sendChangeMessage() inside the
  28996. processBlock() method to send out an asynchronous message. You could also use
  28997. the AsyncUpdater class in a similar way.
  28998. */
  28999. virtual void processBlock (AudioSampleBuffer& buffer,
  29000. MidiBuffer& midiMessages) = 0;
  29001. /** Returns the current AudioPlayHead object that should be used to find
  29002. out the state and position of the playhead.
  29003. You can call this from your processBlock() method, and use the AudioPlayHead
  29004. object to get the details about the time of the start of the block currently
  29005. being processed.
  29006. If the host hasn't supplied a playhead object, this will return 0.
  29007. */
  29008. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  29009. /** Returns the current sample rate.
  29010. This can be called from your processBlock() method - it's not guaranteed
  29011. to be valid at any other time, and may return 0 if it's unknown.
  29012. */
  29013. double getSampleRate() const throw() { return sampleRate; }
  29014. /** Returns the current typical block size that is being used.
  29015. This can be called from your processBlock() method - it's not guaranteed
  29016. to be valid at any other time.
  29017. Remember it's not the ONLY block size that may be used when calling
  29018. processBlock, it's just the normal one. The actual block sizes used may be
  29019. larger or smaller than this, and will vary between successive calls.
  29020. */
  29021. int getBlockSize() const throw() { return blockSize; }
  29022. /** Returns the number of input channels that the host will be sending the filter.
  29023. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  29024. number of channels that your filter would prefer to have, and this method lets
  29025. you know how many the host is actually using.
  29026. Note that this method is only valid during or after the prepareToPlay()
  29027. method call. Until that point, the number of channels will be unknown.
  29028. */
  29029. int getNumInputChannels() const throw() { return numInputChannels; }
  29030. /** Returns the number of output channels that the host will be sending the filter.
  29031. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  29032. number of channels that your filter would prefer to have, and this method lets
  29033. you know how many the host is actually using.
  29034. Note that this method is only valid during or after the prepareToPlay()
  29035. method call. Until that point, the number of channels will be unknown.
  29036. */
  29037. int getNumOutputChannels() const throw() { return numOutputChannels; }
  29038. /** Returns the name of one of the input channels, as returned by the host.
  29039. The host might not supply very useful names for channels, and this might be
  29040. something like "1", "2", "left", "right", etc.
  29041. */
  29042. virtual const String getInputChannelName (const int channelIndex) const = 0;
  29043. /** Returns the name of one of the output channels, as returned by the host.
  29044. The host might not supply very useful names for channels, and this might be
  29045. something like "1", "2", "left", "right", etc.
  29046. */
  29047. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  29048. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  29049. virtual bool isInputChannelStereoPair (int index) const = 0;
  29050. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  29051. virtual bool isOutputChannelStereoPair (int index) const = 0;
  29052. /** This returns the number of samples delay that the filter imposes on the audio
  29053. passing through it.
  29054. The host will call this to find the latency - the filter itself should set this value
  29055. by calling setLatencySamples() as soon as it can during its initialisation.
  29056. */
  29057. int getLatencySamples() const throw() { return latencySamples; }
  29058. /** The filter should call this to set the number of samples delay that it introduces.
  29059. The filter should call this as soon as it can during initialisation, and can call it
  29060. later if the value changes.
  29061. */
  29062. void setLatencySamples (const int newLatency);
  29063. /** Returns true if the processor wants midi messages. */
  29064. virtual bool acceptsMidi() const = 0;
  29065. /** Returns true if the processor produces midi messages. */
  29066. virtual bool producesMidi() const = 0;
  29067. /** This returns a critical section that will automatically be locked while the host
  29068. is calling the processBlock() method.
  29069. Use it from your UI or other threads to lock access to variables that are used
  29070. by the process callback, but obviously be careful not to keep it locked for
  29071. too long, because that could cause stuttering playback. If you need to do something
  29072. that'll take a long time and need the processing to stop while it happens, use the
  29073. suspendProcessing() method instead.
  29074. @see suspendProcessing
  29075. */
  29076. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  29077. /** Enables and disables the processing callback.
  29078. If you need to do something time-consuming on a thread and would like to make sure
  29079. the audio processing callback doesn't happen until you've finished, use this
  29080. to disable the callback and re-enable it again afterwards.
  29081. E.g.
  29082. @code
  29083. void loadNewPatch()
  29084. {
  29085. suspendProcessing (true);
  29086. ..do something that takes ages..
  29087. suspendProcessing (false);
  29088. }
  29089. @endcode
  29090. If the host tries to make an audio callback while processing is suspended, the
  29091. filter will return an empty buffer, but won't block the audio thread like it would
  29092. do if you use the getCallbackLock() critical section to synchronise access.
  29093. If you're going to use this, your processBlock() method must call isSuspended() and
  29094. check whether it's suspended or not. If it is, then it should skip doing any real
  29095. processing, either emitting silence or passing the input through unchanged.
  29096. @see getCallbackLock
  29097. */
  29098. void suspendProcessing (const bool shouldBeSuspended);
  29099. /** Returns true if processing is currently suspended.
  29100. @see suspendProcessing
  29101. */
  29102. bool isSuspended() const throw() { return suspended; }
  29103. /** A plugin can override this to be told when it should reset any playing voices.
  29104. The default implementation does nothing, but a host may call this to tell the
  29105. plugin that it should stop any tails or sounds that have been left running.
  29106. */
  29107. virtual void reset();
  29108. /** Returns true if the processor is being run in an offline mode for rendering.
  29109. If the processor is being run live on realtime signals, this returns false.
  29110. If the mode is unknown, this will assume it's realtime and return false.
  29111. This value may be unreliable until the prepareToPlay() method has been called,
  29112. and could change each time prepareToPlay() is called.
  29113. @see setNonRealtime()
  29114. */
  29115. bool isNonRealtime() const throw() { return nonRealtime; }
  29116. /** Called by the host to tell this processor whether it's being used in a non-realime
  29117. capacity for offline rendering or bouncing.
  29118. Whatever value is passed-in will be
  29119. */
  29120. void setNonRealtime (const bool isNonRealtime) throw();
  29121. /** Creates the filter's UI.
  29122. This can return 0 if you want a UI-less filter, in which case the host may create
  29123. a generic UI that lets the user twiddle the parameters directly.
  29124. If you do want to pass back a component, the component should be created and set to
  29125. the correct size before returning it.
  29126. Remember not to do anything silly like allowing your filter to keep a pointer to
  29127. the component that gets created - it could be deleted later without any warning, which
  29128. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  29129. The correct way to handle the connection between an editor component and its
  29130. filter is to use something like a ChangeBroadcaster so that the editor can
  29131. register itself as a listener, and be told when a change occurs. This lets them
  29132. safely unregister themselves when they are deleted.
  29133. Here are a few things to bear in mind when writing an editor:
  29134. - Initially there won't be an editor, until the user opens one, or they might
  29135. not open one at all. Your filter mustn't rely on it being there.
  29136. - An editor object may be deleted and a replacement one created again at any time.
  29137. - It's safe to assume that an editor will be deleted before its filter.
  29138. */
  29139. virtual AudioProcessorEditor* createEditor() = 0;
  29140. /** Returns the active editor, if there is one.
  29141. Bear in mind this can return 0, even if an editor has previously been
  29142. opened.
  29143. */
  29144. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  29145. /** Returns the active editor, or if there isn't one, it will create one.
  29146. This may call createEditor() internally to create the component.
  29147. */
  29148. AudioProcessorEditor* createEditorIfNeeded();
  29149. /** This must return the correct value immediately after the object has been
  29150. created, and mustn't change the number of parameters later.
  29151. */
  29152. virtual int getNumParameters() = 0;
  29153. /** Returns the name of a particular parameter. */
  29154. virtual const String getParameterName (int parameterIndex) = 0;
  29155. /** Called by the host to find out the value of one of the filter's parameters.
  29156. The host will expect the value returned to be between 0 and 1.0.
  29157. This could be called quite frequently, so try to make your code efficient.
  29158. It's also likely to be called by non-UI threads, so the code in here should
  29159. be thread-aware.
  29160. */
  29161. virtual float getParameter (int parameterIndex) = 0;
  29162. /** Returns the value of a parameter as a text string. */
  29163. virtual const String getParameterText (int parameterIndex) = 0;
  29164. /** The host will call this method to change the value of one of the filter's parameters.
  29165. The host may call this at any time, including during the audio processing
  29166. callback, so the filter has to process this very fast and avoid blocking.
  29167. If you want to set the value of a parameter internally, e.g. from your
  29168. editor component, then don't call this directly - instead, use the
  29169. setParameterNotifyingHost() method, which will also send a message to
  29170. the host telling it about the change. If the message isn't sent, the host
  29171. won't be able to automate your parameters properly.
  29172. The value passed will be between 0 and 1.0.
  29173. */
  29174. virtual void setParameter (int parameterIndex,
  29175. float newValue) = 0;
  29176. /** Your filter can call this when it needs to change one of its parameters.
  29177. This could happen when the editor or some other internal operation changes
  29178. a parameter. This method will call the setParameter() method to change the
  29179. value, and will then send a message to the host telling it about the change.
  29180. Note that to make sure the host correctly handles automation, you should call
  29181. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  29182. tell the host when the user has started and stopped changing the parameter.
  29183. */
  29184. void setParameterNotifyingHost (int parameterIndex,
  29185. float newValue);
  29186. /** Returns true if the host can automate this parameter.
  29187. By default, this returns true for all parameters.
  29188. */
  29189. virtual bool isParameterAutomatable (int parameterIndex) const;
  29190. /** Should return true if this parameter is a "meta" parameter.
  29191. A meta-parameter is a parameter that changes other params. It is used
  29192. by some hosts (e.g. AudioUnit hosts).
  29193. By default this returns false.
  29194. */
  29195. virtual bool isMetaParameter (int parameterIndex) const;
  29196. /** Sends a signal to the host to tell it that the user is about to start changing this
  29197. parameter.
  29198. This allows the host to know when a parameter is actively being held by the user, and
  29199. it may use this information to help it record automation.
  29200. If you call this, it must be matched by a later call to endParameterChangeGesture().
  29201. */
  29202. void beginParameterChangeGesture (int parameterIndex);
  29203. /** Tells the host that the user has finished changing this parameter.
  29204. This allows the host to know when a parameter is actively being held by the user, and
  29205. it may use this information to help it record automation.
  29206. A call to this method must follow a call to beginParameterChangeGesture().
  29207. */
  29208. void endParameterChangeGesture (int parameterIndex);
  29209. /** The filter can call this when something (apart from a parameter value) has changed.
  29210. It sends a hint to the host that something like the program, number of parameters,
  29211. etc, has changed, and that it should update itself.
  29212. */
  29213. void updateHostDisplay();
  29214. /** Returns the number of preset programs the filter supports.
  29215. The value returned must be valid as soon as this object is created, and
  29216. must not change over its lifetime.
  29217. This value shouldn't be less than 1.
  29218. */
  29219. virtual int getNumPrograms() = 0;
  29220. /** Returns the number of the currently active program.
  29221. */
  29222. virtual int getCurrentProgram() = 0;
  29223. /** Called by the host to change the current program.
  29224. */
  29225. virtual void setCurrentProgram (int index) = 0;
  29226. /** Must return the name of a given program. */
  29227. virtual const String getProgramName (int index) = 0;
  29228. /** Called by the host to rename a program.
  29229. */
  29230. virtual void changeProgramName (int index, const String& newName) = 0;
  29231. /** The host will call this method when it wants to save the filter's internal state.
  29232. This must copy any info about the filter's state into the block of memory provided,
  29233. so that the host can store this and later restore it using setStateInformation().
  29234. Note that there's also a getCurrentProgramStateInformation() method, which only
  29235. stores the current program, not the state of the entire filter.
  29236. See also the helper function copyXmlToBinary() for storing settings as XML.
  29237. @see getCurrentProgramStateInformation
  29238. */
  29239. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  29240. /** The host will call this method if it wants to save the state of just the filter's
  29241. current program.
  29242. Unlike getStateInformation, this should only return the current program's state.
  29243. Not all hosts support this, and if you don't implement it, the base class
  29244. method just calls getStateInformation() instead. If you do implement it, be
  29245. sure to also implement getCurrentProgramStateInformation.
  29246. @see getStateInformation, setCurrentProgramStateInformation
  29247. */
  29248. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  29249. /** This must restore the filter's state from a block of data previously created
  29250. using getStateInformation().
  29251. Note that there's also a setCurrentProgramStateInformation() method, which tries
  29252. to restore just the current program, not the state of the entire filter.
  29253. See also the helper function getXmlFromBinary() for loading settings as XML.
  29254. @see setCurrentProgramStateInformation
  29255. */
  29256. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  29257. /** The host will call this method if it wants to restore the state of just the filter's
  29258. current program.
  29259. Not all hosts support this, and if you don't implement it, the base class
  29260. method just calls setStateInformation() instead. If you do implement it, be
  29261. sure to also implement getCurrentProgramStateInformation.
  29262. @see setStateInformation, getCurrentProgramStateInformation
  29263. */
  29264. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  29265. /** Adds a listener that will be called when an aspect of this processor changes. */
  29266. void addListener (AudioProcessorListener* const newListener) throw();
  29267. /** Removes a previously added listener. */
  29268. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  29269. /** Not for public use - this is called before deleting an editor component. */
  29270. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  29271. /** Not for public use - this is called to initialise the processor. */
  29272. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  29273. /** Not for public use - this is called to initialise the processor before playing. */
  29274. void setPlayConfigDetails (const int numIns, const int numOuts,
  29275. const double sampleRate,
  29276. const int blockSize) throw();
  29277. juce_UseDebuggingNewOperator
  29278. protected:
  29279. /** Helper function that just converts an xml element into a binary blob.
  29280. Use this in your filter's getStateInformation() method if you want to
  29281. store its state as xml.
  29282. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  29283. from a binary blob.
  29284. */
  29285. static void copyXmlToBinary (const XmlElement& xml,
  29286. JUCE_NAMESPACE::MemoryBlock& destData);
  29287. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  29288. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  29289. an XmlElement object that the caller must delete when no longer needed.
  29290. */
  29291. static XmlElement* getXmlFromBinary (const void* data,
  29292. const int sizeInBytes);
  29293. /** @internal */
  29294. AudioPlayHead* playHead;
  29295. /** @internal */
  29296. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  29297. private:
  29298. Array <AudioProcessorListener*> listeners;
  29299. AudioProcessorEditor* activeEditor;
  29300. double sampleRate;
  29301. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  29302. bool suspended, nonRealtime;
  29303. CriticalSection callbackLock, listenerLock;
  29304. #if JUCE_DEBUG
  29305. BigInteger changingParams;
  29306. #endif
  29307. AudioProcessor (const AudioProcessor&);
  29308. AudioProcessor& operator= (const AudioProcessor&);
  29309. };
  29310. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  29311. /*** End of inlined file: juce_AudioProcessor.h ***/
  29312. /*** Start of inlined file: juce_PluginDescription.h ***/
  29313. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29314. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29315. /**
  29316. A small class to represent some facts about a particular type of plugin.
  29317. This class is for storing and managing the details about a plugin without
  29318. actually having to load an instance of it.
  29319. A KnownPluginList contains a list of PluginDescription objects.
  29320. @see KnownPluginList
  29321. */
  29322. class JUCE_API PluginDescription
  29323. {
  29324. public:
  29325. PluginDescription() throw();
  29326. PluginDescription (const PluginDescription& other) throw();
  29327. PluginDescription& operator= (const PluginDescription& other) throw();
  29328. ~PluginDescription() throw();
  29329. /** The name of the plugin. */
  29330. String name;
  29331. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  29332. */
  29333. String pluginFormatName;
  29334. /** A category, such as "Dynamics", "Reverbs", etc.
  29335. */
  29336. String category;
  29337. /** The manufacturer. */
  29338. String manufacturerName;
  29339. /** The version. This string doesn't have any particular format. */
  29340. String version;
  29341. /** Either the file containing the plugin module, or some other unique way
  29342. of identifying it.
  29343. E.g. for an AU, this would be an ID string that the component manager
  29344. could use to retrieve the plugin. For a VST, it's the file path.
  29345. */
  29346. String fileOrIdentifier;
  29347. /** The last time the plugin file was changed.
  29348. This is handy when scanning for new or changed plugins.
  29349. */
  29350. Time lastFileModTime;
  29351. /** A unique ID for the plugin.
  29352. Note that this might not be unique between formats, e.g. a VST and some
  29353. other format might actually have the same id.
  29354. @see createIdentifierString
  29355. */
  29356. int uid;
  29357. /** True if the plugin identifies itself as a synthesiser. */
  29358. bool isInstrument;
  29359. /** The number of inputs. */
  29360. int numInputChannels;
  29361. /** The number of outputs. */
  29362. int numOutputChannels;
  29363. /** Returns true if the two descriptions refer the the same plugin.
  29364. This isn't quite as simple as them just having the same file (because of
  29365. shell plugins).
  29366. */
  29367. bool isDuplicateOf (const PluginDescription& other) const;
  29368. /** Returns a string that can be saved and used to uniquely identify the
  29369. plugin again.
  29370. This contains less info than the XML encoding, and is independent of the
  29371. plugin's file location, so can be used to store a plugin ID for use
  29372. across different machines.
  29373. */
  29374. const String createIdentifierString() const throw();
  29375. /** Creates an XML object containing these details.
  29376. @see loadFromXml
  29377. */
  29378. XmlElement* createXml() const;
  29379. /** Reloads the info in this structure from an XML record that was previously
  29380. saved with createXML().
  29381. Returns true if the XML was a valid plugin description.
  29382. */
  29383. bool loadFromXml (const XmlElement& xml);
  29384. juce_UseDebuggingNewOperator
  29385. };
  29386. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29387. /*** End of inlined file: juce_PluginDescription.h ***/
  29388. /**
  29389. Base class for an active instance of a plugin.
  29390. This derives from the AudioProcessor class, and adds some extra functionality
  29391. that helps when wrapping dynamically loaded plugins.
  29392. @see AudioProcessor, AudioPluginFormat
  29393. */
  29394. class JUCE_API AudioPluginInstance : public AudioProcessor
  29395. {
  29396. public:
  29397. /** Destructor.
  29398. Make sure that you delete any UI components that belong to this plugin before
  29399. deleting the plugin.
  29400. */
  29401. virtual ~AudioPluginInstance();
  29402. /** Fills-in the appropriate parts of this plugin description object.
  29403. */
  29404. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  29405. juce_UseDebuggingNewOperator
  29406. protected:
  29407. AudioPluginInstance();
  29408. AudioPluginInstance (const AudioPluginInstance&);
  29409. AudioPluginInstance& operator= (const AudioPluginInstance&);
  29410. };
  29411. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29412. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  29413. class PluginDescription;
  29414. /**
  29415. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  29416. Use the static getNumFormats() and getFormat() calls to find the types
  29417. of format that are available.
  29418. */
  29419. class JUCE_API AudioPluginFormat
  29420. {
  29421. public:
  29422. /** Destructor. */
  29423. virtual ~AudioPluginFormat();
  29424. /** Returns the format name.
  29425. E.g. "VST", "AudioUnit", etc.
  29426. */
  29427. virtual const String getName() const = 0;
  29428. /** This tries to create descriptions for all the plugin types available in
  29429. a binary module file.
  29430. The file will be some kind of DLL or bundle.
  29431. Normally there will only be one type returned, but some plugins
  29432. (e.g. VST shells) can use a single DLL to create a set of different plugin
  29433. subtypes, so in that case, each subtype is returned as a separate object.
  29434. */
  29435. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  29436. const String& fileOrIdentifier) = 0;
  29437. /** Tries to recreate a type from a previously generated PluginDescription.
  29438. @see PluginDescription::createInstance
  29439. */
  29440. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  29441. /** Should do a quick check to see if this file or directory might be a plugin of
  29442. this format.
  29443. This is for searching for potential files, so it shouldn't actually try to
  29444. load the plugin or do anything time-consuming.
  29445. */
  29446. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  29447. /** Returns a readable version of the name of the plugin that this identifier refers to.
  29448. */
  29449. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  29450. /** Checks whether this plugin could possibly be loaded.
  29451. It doesn't actually need to load it, just to check whether the file or component
  29452. still exists.
  29453. */
  29454. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  29455. /** Searches a suggested set of directories for any plugins in this format.
  29456. The path might be ignored, e.g. by AUs, which are found by the OS rather
  29457. than manually.
  29458. */
  29459. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  29460. bool recursive) = 0;
  29461. /** Returns the typical places to look for this kind of plugin.
  29462. Note that if this returns no paths, it means that the format can't be scanned-for
  29463. (i.e. it's an internal format that doesn't live in files)
  29464. */
  29465. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  29466. juce_UseDebuggingNewOperator
  29467. protected:
  29468. AudioPluginFormat() throw();
  29469. AudioPluginFormat (const AudioPluginFormat&);
  29470. AudioPluginFormat& operator= (const AudioPluginFormat&);
  29471. };
  29472. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29473. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  29474. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  29475. /**
  29476. Implements a plugin format manager for AudioUnits.
  29477. */
  29478. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  29479. {
  29480. public:
  29481. AudioUnitPluginFormat();
  29482. ~AudioUnitPluginFormat();
  29483. const String getName() const { return "AudioUnit"; }
  29484. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29485. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29486. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29487. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29488. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29489. bool doesPluginStillExist (const PluginDescription& desc);
  29490. const FileSearchPath getDefaultLocationsToSearch();
  29491. juce_UseDebuggingNewOperator
  29492. private:
  29493. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  29494. AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  29495. };
  29496. #endif
  29497. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  29498. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  29499. #endif
  29500. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29501. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  29502. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29503. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29504. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  29505. // Sorry, this file is just a placeholder at the moment!...
  29506. /**
  29507. Implements a plugin format manager for DirectX plugins.
  29508. */
  29509. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  29510. {
  29511. public:
  29512. DirectXPluginFormat();
  29513. ~DirectXPluginFormat();
  29514. const String getName() const { return "DirectX"; }
  29515. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29516. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29517. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29518. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29519. const FileSearchPath getDefaultLocationsToSearch();
  29520. juce_UseDebuggingNewOperator
  29521. private:
  29522. DirectXPluginFormat (const DirectXPluginFormat&);
  29523. DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  29524. };
  29525. #endif
  29526. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29527. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  29528. #endif
  29529. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29530. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  29531. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29532. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29533. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  29534. // Sorry, this file is just a placeholder at the moment!...
  29535. /**
  29536. Implements a plugin format manager for DirectX plugins.
  29537. */
  29538. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  29539. {
  29540. public:
  29541. LADSPAPluginFormat();
  29542. ~LADSPAPluginFormat();
  29543. const String getName() const { return "LADSPA"; }
  29544. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29545. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29546. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29547. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29548. const FileSearchPath getDefaultLocationsToSearch();
  29549. juce_UseDebuggingNewOperator
  29550. private:
  29551. LADSPAPluginFormat (const LADSPAPluginFormat&);
  29552. LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  29553. };
  29554. #endif
  29555. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29556. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  29557. #endif
  29558. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29559. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  29560. #ifdef __aeffect__
  29561. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29562. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29563. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  29564. events to the list.
  29565. This is used by both the VST hosting code and the plugin wrapper.
  29566. */
  29567. class VSTMidiEventList
  29568. {
  29569. public:
  29570. VSTMidiEventList()
  29571. : numEventsUsed (0), numEventsAllocated (0)
  29572. {
  29573. }
  29574. ~VSTMidiEventList()
  29575. {
  29576. freeEvents();
  29577. }
  29578. void clear()
  29579. {
  29580. numEventsUsed = 0;
  29581. if (events != 0)
  29582. events->numEvents = 0;
  29583. }
  29584. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  29585. {
  29586. ensureSize (numEventsUsed + 1);
  29587. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  29588. events->numEvents = ++numEventsUsed;
  29589. if (numBytes <= 4)
  29590. {
  29591. if (e->type == kVstSysExType)
  29592. {
  29593. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29594. e->type = kVstMidiType;
  29595. e->byteSize = sizeof (VstMidiEvent);
  29596. e->noteLength = 0;
  29597. e->noteOffset = 0;
  29598. e->detune = 0;
  29599. e->noteOffVelocity = 0;
  29600. }
  29601. e->deltaFrames = frameOffset;
  29602. memcpy (e->midiData, midiData, numBytes);
  29603. }
  29604. else
  29605. {
  29606. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  29607. if (se->type == kVstSysExType)
  29608. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  29609. else
  29610. se->sysexDump = (char*) juce_malloc (numBytes);
  29611. memcpy (se->sysexDump, midiData, numBytes);
  29612. se->type = kVstSysExType;
  29613. se->byteSize = sizeof (VstMidiSysexEvent);
  29614. se->deltaFrames = frameOffset;
  29615. se->flags = 0;
  29616. se->dumpBytes = numBytes;
  29617. se->resvd1 = 0;
  29618. se->resvd2 = 0;
  29619. }
  29620. }
  29621. // Handy method to pull the events out of an event buffer supplied by the host
  29622. // or plugin.
  29623. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  29624. {
  29625. for (int i = 0; i < events->numEvents; ++i)
  29626. {
  29627. const VstEvent* const e = events->events[i];
  29628. if (e != 0)
  29629. {
  29630. if (e->type == kVstMidiType)
  29631. {
  29632. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  29633. 4, e->deltaFrames);
  29634. }
  29635. else if (e->type == kVstSysExType)
  29636. {
  29637. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  29638. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  29639. e->deltaFrames);
  29640. }
  29641. }
  29642. }
  29643. }
  29644. void ensureSize (int numEventsNeeded)
  29645. {
  29646. if (numEventsNeeded > numEventsAllocated)
  29647. {
  29648. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  29649. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  29650. if (events == 0)
  29651. events.calloc (size, 1);
  29652. else
  29653. events.realloc (size, 1);
  29654. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  29655. {
  29656. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  29657. (int) sizeof (VstMidiSysexEvent)));
  29658. e->type = kVstMidiType;
  29659. e->byteSize = sizeof (VstMidiEvent);
  29660. events->events[i] = (VstEvent*) e;
  29661. }
  29662. numEventsAllocated = numEventsNeeded;
  29663. }
  29664. }
  29665. void freeEvents()
  29666. {
  29667. if (events != 0)
  29668. {
  29669. for (int i = numEventsAllocated; --i >= 0;)
  29670. {
  29671. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  29672. if (e->type == kVstSysExType)
  29673. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29674. juce_free (e);
  29675. }
  29676. events.free();
  29677. numEventsUsed = 0;
  29678. numEventsAllocated = 0;
  29679. }
  29680. }
  29681. HeapBlock <VstEvents> events;
  29682. private:
  29683. int numEventsUsed, numEventsAllocated;
  29684. };
  29685. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29686. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29687. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  29688. #endif
  29689. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29690. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  29691. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29692. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29693. #if JUCE_PLUGINHOST_VST
  29694. /**
  29695. Implements a plugin format manager for VSTs.
  29696. */
  29697. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  29698. {
  29699. public:
  29700. VSTPluginFormat();
  29701. ~VSTPluginFormat();
  29702. const String getName() const { return "VST"; }
  29703. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29704. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29705. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29706. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29707. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29708. bool doesPluginStillExist (const PluginDescription& desc);
  29709. const FileSearchPath getDefaultLocationsToSearch();
  29710. juce_UseDebuggingNewOperator
  29711. private:
  29712. VSTPluginFormat (const VSTPluginFormat&);
  29713. VSTPluginFormat& operator= (const VSTPluginFormat&);
  29714. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  29715. };
  29716. #endif
  29717. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29718. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  29719. #endif
  29720. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29721. #endif
  29722. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29723. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  29724. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29725. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29726. /**
  29727. This maintains a list of known AudioPluginFormats.
  29728. @see AudioPluginFormat
  29729. */
  29730. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  29731. {
  29732. public:
  29733. AudioPluginFormatManager() throw();
  29734. /** Destructor. */
  29735. ~AudioPluginFormatManager() throw();
  29736. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  29737. /** Adds any formats that it knows about, e.g. VST.
  29738. */
  29739. void addDefaultFormats();
  29740. /** Returns the number of types of format that are available.
  29741. Use getFormat() to get one of them.
  29742. */
  29743. int getNumFormats() throw();
  29744. /** Returns one of the available formats.
  29745. @see getNumFormats
  29746. */
  29747. AudioPluginFormat* getFormat (const int index) throw();
  29748. /** Adds a format to the list.
  29749. The object passed in will be owned and deleted by the manager.
  29750. */
  29751. void addFormat (AudioPluginFormat* const format) throw();
  29752. /** Tries to load the type for this description, by trying all the formats
  29753. that this manager knows about.
  29754. The caller is responsible for deleting the object that is returned.
  29755. If it can't load the plugin, it returns 0 and leaves a message in the
  29756. errorMessage string.
  29757. */
  29758. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  29759. String& errorMessage) const;
  29760. /** Checks that the file or component for this plugin actually still exists.
  29761. (This won't try to load the plugin)
  29762. */
  29763. bool doesPluginStillExist (const PluginDescription& description) const;
  29764. juce_UseDebuggingNewOperator
  29765. private:
  29766. OwnedArray <AudioPluginFormat> formats;
  29767. AudioPluginFormatManager (const AudioPluginFormatManager&);
  29768. AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  29769. };
  29770. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29771. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  29772. #endif
  29773. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29774. #endif
  29775. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29776. /*** Start of inlined file: juce_KnownPluginList.h ***/
  29777. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29778. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29779. /**
  29780. Manages a list of plugin types.
  29781. This can be easily edited, saved and loaded, and used to create instances of
  29782. the plugin types in it.
  29783. @see PluginListComponent
  29784. */
  29785. class JUCE_API KnownPluginList : public ChangeBroadcaster
  29786. {
  29787. public:
  29788. /** Creates an empty list.
  29789. */
  29790. KnownPluginList();
  29791. /** Destructor. */
  29792. ~KnownPluginList();
  29793. /** Clears the list. */
  29794. void clear();
  29795. /** Returns the number of types currently in the list.
  29796. @see getType
  29797. */
  29798. int getNumTypes() const throw() { return types.size(); }
  29799. /** Returns one of the types.
  29800. @see getNumTypes
  29801. */
  29802. PluginDescription* getType (int index) const throw() { return types [index]; }
  29803. /** Looks for a type in the list which comes from this file.
  29804. */
  29805. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  29806. /** Looks for a type in the list which matches a plugin type ID.
  29807. The identifierString parameter must have been created by
  29808. PluginDescription::createIdentifierString().
  29809. */
  29810. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  29811. /** Adds a type manually from its description. */
  29812. bool addType (const PluginDescription& type);
  29813. /** Removes a type. */
  29814. void removeType (int index) throw();
  29815. /** Looks for all types that can be loaded from a given file, and adds them
  29816. to the list.
  29817. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29818. re-tested if it's not already in the list, or if the file's modification
  29819. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29820. false, the file will always be reloaded and tested.
  29821. Returns true if any new types were added, and all the types found in this
  29822. file (even if it was already known and hasn't been re-scanned) get returned
  29823. in the array.
  29824. */
  29825. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  29826. bool dontRescanIfAlreadyInList,
  29827. OwnedArray <PluginDescription>& typesFound,
  29828. AudioPluginFormat& formatToUse);
  29829. /** Returns true if the specified file is already known about and if it
  29830. hasn't been modified since our entry was created.
  29831. */
  29832. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  29833. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  29834. If any types are found in the files, their descriptions are returned in the array.
  29835. */
  29836. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  29837. OwnedArray <PluginDescription>& typesFound);
  29838. /** Sort methods used to change the order of the plugins in the list.
  29839. */
  29840. enum SortMethod
  29841. {
  29842. defaultOrder = 0,
  29843. sortAlphabetically,
  29844. sortByCategory,
  29845. sortByManufacturer,
  29846. sortByFileSystemLocation
  29847. };
  29848. /** Adds all the plugin types to a popup menu so that the user can select one.
  29849. Depending on the sort method, it may add sub-menus for categories,
  29850. manufacturers, etc.
  29851. Use getIndexChosenByMenu() to find out the type that was chosen.
  29852. */
  29853. void addToMenu (PopupMenu& menu,
  29854. const SortMethod sortMethod) const;
  29855. /** Converts a menu item index that has been chosen into its index in this list.
  29856. Returns -1 if it's not an ID that was used.
  29857. @see addToMenu
  29858. */
  29859. int getIndexChosenByMenu (int menuResultCode) const;
  29860. /** Sorts the list. */
  29861. void sort (const SortMethod method);
  29862. /** Creates some XML that can be used to store the state of this list.
  29863. */
  29864. XmlElement* createXml() const;
  29865. /** Recreates the state of this list from its stored XML format.
  29866. */
  29867. void recreateFromXml (const XmlElement& xml);
  29868. juce_UseDebuggingNewOperator
  29869. private:
  29870. OwnedArray <PluginDescription> types;
  29871. KnownPluginList (const KnownPluginList&);
  29872. KnownPluginList& operator= (const KnownPluginList&);
  29873. };
  29874. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29875. /*** End of inlined file: juce_KnownPluginList.h ***/
  29876. #endif
  29877. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29878. #endif
  29879. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29880. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  29881. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29882. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29883. /**
  29884. Scans a directory for plugins, and adds them to a KnownPluginList.
  29885. To use one of these, create it and call scanNextFile() repeatedly, until
  29886. it returns false.
  29887. */
  29888. class JUCE_API PluginDirectoryScanner
  29889. {
  29890. public:
  29891. /**
  29892. Creates a scanner.
  29893. @param listToAddResultsTo this will get the new types added to it.
  29894. @param formatToLookFor this is the type of format that you want to look for
  29895. @param directoriesToSearch the path to search
  29896. @param searchRecursively true to search recursively
  29897. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  29898. be used as a file to store the names of any plugins
  29899. that crash during initialisation. If there are
  29900. any plugins listed in it, then these will always
  29901. be scanned after all other possible files have
  29902. been tried - in this way, even if there's a few
  29903. dodgy plugins in your path, then a couple of rescans
  29904. will still manage to find all the proper plugins.
  29905. It's probably best to choose a file in the user's
  29906. application data directory (alongside your app's
  29907. settings file) for this. The file format it uses
  29908. is just a list of filenames of the modules that
  29909. failed.
  29910. */
  29911. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  29912. AudioPluginFormat& formatToLookFor,
  29913. FileSearchPath directoriesToSearch,
  29914. bool searchRecursively,
  29915. const File& deadMansPedalFile);
  29916. /** Destructor. */
  29917. ~PluginDirectoryScanner();
  29918. /** Tries the next likely-looking file.
  29919. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29920. re-tested if it's not already in the list, or if the file's modification
  29921. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29922. false, the file will always be reloaded and tested.
  29923. Returns false when there are no more files to try.
  29924. */
  29925. bool scanNextFile (bool dontRescanIfAlreadyInList);
  29926. /** Returns the description of the plugin that will be scanned during the next
  29927. call to scanNextFile().
  29928. This is handy if you want to show the user which file is currently getting
  29929. scanned.
  29930. */
  29931. const String getNextPluginFileThatWillBeScanned() const throw();
  29932. /** Returns the estimated progress, between 0 and 1.
  29933. */
  29934. float getProgress() const { return progress; }
  29935. /** This returns a list of all the filenames of things that looked like being
  29936. a plugin file, but which failed to open for some reason.
  29937. */
  29938. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  29939. juce_UseDebuggingNewOperator
  29940. private:
  29941. KnownPluginList& list;
  29942. AudioPluginFormat& format;
  29943. StringArray filesOrIdentifiersToScan;
  29944. File deadMansPedalFile;
  29945. StringArray failedFiles;
  29946. int nextIndex;
  29947. float progress;
  29948. const StringArray getDeadMansPedalFile() throw();
  29949. void setDeadMansPedalFile (const StringArray& newContents) throw();
  29950. PluginDirectoryScanner (const PluginDirectoryScanner&);
  29951. PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  29952. };
  29953. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29954. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  29955. #endif
  29956. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29957. /*** Start of inlined file: juce_PluginListComponent.h ***/
  29958. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29959. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29960. /*** Start of inlined file: juce_ListBox.h ***/
  29961. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  29962. #define __JUCE_LISTBOX_JUCEHEADER__
  29963. class ListViewport;
  29964. /**
  29965. A subclass of this is used to drive a ListBox.
  29966. @see ListBox
  29967. */
  29968. class JUCE_API ListBoxModel
  29969. {
  29970. public:
  29971. /** Destructor. */
  29972. virtual ~ListBoxModel() {}
  29973. /** This has to return the number of items in the list.
  29974. @see ListBox::getNumRows()
  29975. */
  29976. virtual int getNumRows() = 0;
  29977. /** This method must be implemented to draw a row of the list.
  29978. */
  29979. virtual void paintListBoxItem (int rowNumber,
  29980. Graphics& g,
  29981. int width, int height,
  29982. bool rowIsSelected) = 0;
  29983. /** This is used to create or update a custom component to go in a row of the list.
  29984. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  29985. and handle mouse clicks with listBoxItemClicked().
  29986. This method will be called whenever a custom component might need to be updated - e.g.
  29987. when the table is changed, or TableListBox::updateContent() is called.
  29988. If you don't need a custom component for the specified row, then return 0.
  29989. If you do want a custom component, and the existingComponentToUpdate is null, then
  29990. this method must create a suitable new component and return it.
  29991. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  29992. by this method. In this case, the method must either update it to make sure it's correctly representing
  29993. the given row (which may be different from the one that the component was created for), or it can
  29994. delete this component and return a new one.
  29995. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  29996. */
  29997. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  29998. Component* existingComponentToUpdate);
  29999. /** This can be overridden to react to the user clicking on a row.
  30000. @see listBoxItemDoubleClicked
  30001. */
  30002. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  30003. /** This can be overridden to react to the user double-clicking on a row.
  30004. @see listBoxItemClicked
  30005. */
  30006. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  30007. /** This can be overridden to react to the user double-clicking on a part of the list where
  30008. there are no rows.
  30009. @see listBoxItemClicked
  30010. */
  30011. virtual void backgroundClicked();
  30012. /** Override this to be informed when rows are selected or deselected.
  30013. This will be called whenever a row is selected or deselected. If a range of
  30014. rows is selected all at once, this will just be called once for that event.
  30015. @param lastRowSelected the last row that the user selected. If no
  30016. rows are currently selected, this may be -1.
  30017. */
  30018. virtual void selectedRowsChanged (int lastRowSelected);
  30019. /** Override this to be informed when the delete key is pressed.
  30020. If no rows are selected when they press the key, this won't be called.
  30021. @param lastRowSelected the last row that had been selected when they pressed the
  30022. key - if there are multiple selections, this might not be
  30023. very useful
  30024. */
  30025. virtual void deleteKeyPressed (int lastRowSelected);
  30026. /** Override this to be informed when the return key is pressed.
  30027. If no rows are selected when they press the key, this won't be called.
  30028. @param lastRowSelected the last row that had been selected when they pressed the
  30029. key - if there are multiple selections, this might not be
  30030. very useful
  30031. */
  30032. virtual void returnKeyPressed (int lastRowSelected);
  30033. /** Override this to be informed when the list is scrolled.
  30034. This might be caused by the user moving the scrollbar, or by programmatic changes
  30035. to the list position.
  30036. */
  30037. virtual void listWasScrolled();
  30038. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  30039. If this returns a non-empty name then when the user drags a row, the listbox will
  30040. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  30041. a drag-and-drop operation, using this string as the source description, with the listbox
  30042. itself as the source component.
  30043. @see DragAndDropContainer::startDragging
  30044. */
  30045. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  30046. /** You can override this to provide tool tips for specific rows.
  30047. @see TooltipClient
  30048. */
  30049. virtual const String getTooltipForRow (int row);
  30050. };
  30051. /**
  30052. A list of items that can be scrolled vertically.
  30053. To create a list, you'll need to create a subclass of ListBoxModel. This can
  30054. either paint each row of the list and respond to events via callbacks, or for
  30055. more specialised tasks, it can supply a custom component to fill each row.
  30056. @see ComboBox, TableListBox
  30057. */
  30058. class JUCE_API ListBox : public Component,
  30059. public SettableTooltipClient
  30060. {
  30061. public:
  30062. /** Creates a ListBox.
  30063. The model pointer passed-in can be null, in which case you can set it later
  30064. with setModel().
  30065. */
  30066. ListBox (const String& componentName,
  30067. ListBoxModel* model);
  30068. /** Destructor. */
  30069. ~ListBox();
  30070. /** Changes the current data model to display. */
  30071. void setModel (ListBoxModel* newModel);
  30072. /** Returns the current list model. */
  30073. ListBoxModel* getModel() const throw() { return model; }
  30074. /** Causes the list to refresh its content.
  30075. Call this when the number of rows in the list changes, or if you want it
  30076. to call refreshComponentForRow() on all the row components.
  30077. Be careful not to call it from a different thread, though, as it's not
  30078. thread-safe.
  30079. */
  30080. void updateContent();
  30081. /** Turns on multiple-selection of rows.
  30082. By default this is disabled.
  30083. When your row component gets clicked you'll need to call the
  30084. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  30085. clicked and to get it to do the appropriate selection based on whether
  30086. the ctrl/shift keys are held down.
  30087. */
  30088. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  30089. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  30090. This function is here primarily for the ComboBox class to use, but might be
  30091. useful for some other purpose too.
  30092. */
  30093. void setMouseMoveSelectsRows (bool shouldSelect);
  30094. /** Selects a row.
  30095. If the row is already selected, this won't do anything.
  30096. @param rowNumber the row to select
  30097. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  30098. the selected row is off-screen, it'll scroll to make
  30099. sure that row is on-screen
  30100. @param deselectOthersFirst if true and there are multiple selections, these will
  30101. first be deselected before this item is selected
  30102. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  30103. deselectAllRows, selectRangeOfRows
  30104. */
  30105. void selectRow (int rowNumber,
  30106. bool dontScrollToShowThisRow = false,
  30107. bool deselectOthersFirst = true);
  30108. /** Selects a set of rows.
  30109. This will add these rows to the current selection, so you might need to
  30110. clear the current selection first with deselectAllRows()
  30111. @param firstRow the first row to select (inclusive)
  30112. @param lastRow the last row to select (inclusive)
  30113. */
  30114. void selectRangeOfRows (int firstRow,
  30115. int lastRow);
  30116. /** Deselects a row.
  30117. If it's not currently selected, this will do nothing.
  30118. @see selectRow, deselectAllRows
  30119. */
  30120. void deselectRow (int rowNumber);
  30121. /** Deselects any currently selected rows.
  30122. @see deselectRow
  30123. */
  30124. void deselectAllRows();
  30125. /** Selects or deselects a row.
  30126. If the row's currently selected, this deselects it, and vice-versa.
  30127. */
  30128. void flipRowSelection (int rowNumber);
  30129. /** Returns a sparse set indicating the rows that are currently selected.
  30130. @see setSelectedRows
  30131. */
  30132. const SparseSet<int> getSelectedRows() const;
  30133. /** Sets the rows that should be selected, based on an explicit set of ranges.
  30134. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  30135. method will be called. If it's false, no notification will be sent to the model.
  30136. @see getSelectedRows
  30137. */
  30138. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  30139. bool sendNotificationEventToModel = true);
  30140. /** Checks whether a row is selected.
  30141. */
  30142. bool isRowSelected (int rowNumber) const;
  30143. /** Returns the number of rows that are currently selected.
  30144. @see getSelectedRow, isRowSelected, getLastRowSelected
  30145. */
  30146. int getNumSelectedRows() const;
  30147. /** Returns the row number of a selected row.
  30148. This will return the row number of the Nth selected row. The row numbers returned will
  30149. be sorted in order from low to high.
  30150. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  30151. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  30152. selected
  30153. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  30154. */
  30155. int getSelectedRow (int index = 0) const;
  30156. /** Returns the last row that the user selected.
  30157. This isn't the same as the highest row number that is currently selected - if the user
  30158. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  30159. If nothing is selected, it will return -1.
  30160. */
  30161. int getLastRowSelected() const;
  30162. /** Multiply-selects rows based on the modifier keys.
  30163. If no modifier keys are down, this will select the given row and
  30164. deselect any others.
  30165. If the ctrl (or command on the Mac) key is down, it'll flip the
  30166. state of the selected row.
  30167. If the shift key is down, it'll select up to the given row from the
  30168. last row selected.
  30169. @see selectRow
  30170. */
  30171. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  30172. const ModifierKeys& modifiers);
  30173. /** Scrolls the list to a particular position.
  30174. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  30175. 1.0 scrolls to the bottom.
  30176. If the total number of rows all fit onto the screen at once, then this
  30177. method won't do anything.
  30178. @see getVerticalPosition
  30179. */
  30180. void setVerticalPosition (double newProportion);
  30181. /** Returns the current vertical position as a proportion of the total.
  30182. This can be used in conjunction with setVerticalPosition() to save and restore
  30183. the list's position. It returns a value in the range 0 to 1.
  30184. @see setVerticalPosition
  30185. */
  30186. double getVerticalPosition() const;
  30187. /** Scrolls if necessary to make sure that a particular row is visible.
  30188. */
  30189. void scrollToEnsureRowIsOnscreen (int row);
  30190. /** Returns a pointer to the scrollbar.
  30191. (Unlikely to be useful for most people).
  30192. */
  30193. ScrollBar* getVerticalScrollBar() const throw();
  30194. /** Returns a pointer to the scrollbar.
  30195. (Unlikely to be useful for most people).
  30196. */
  30197. ScrollBar* getHorizontalScrollBar() const throw();
  30198. /** Finds the row index that contains a given x,y position.
  30199. The position is relative to the ListBox's top-left.
  30200. If no row exists at this position, the method will return -1.
  30201. @see getComponentForRowNumber
  30202. */
  30203. int getRowContainingPosition (int x, int y) const throw();
  30204. /** Finds a row index that would be the most suitable place to insert a new
  30205. item for a given position.
  30206. This is useful when the user is e.g. dragging and dropping onto the listbox,
  30207. because it lets you easily choose the best position to insert the item that
  30208. they drop, based on where they drop it.
  30209. If the position is out of range, this will return -1. If the position is
  30210. beyond the end of the list, it will return getNumRows() to indicate the end
  30211. of the list.
  30212. @see getComponentForRowNumber
  30213. */
  30214. int getInsertionIndexForPosition (int x, int y) const throw();
  30215. /** Returns the position of one of the rows, relative to the top-left of
  30216. the listbox.
  30217. This may be off-screen, and the range of the row number that is passed-in is
  30218. not checked to see if it's a valid row.
  30219. */
  30220. const Rectangle<int> getRowPosition (int rowNumber,
  30221. bool relativeToComponentTopLeft) const throw();
  30222. /** Finds the row component for a given row in the list.
  30223. The component returned will have been created using createRowComponent().
  30224. If the component for this row is off-screen or if the row is out-of-range,
  30225. this will return 0.
  30226. @see getRowContainingPosition
  30227. */
  30228. Component* getComponentForRowNumber (int rowNumber) const throw();
  30229. /** Returns the row number that the given component represents.
  30230. If the component isn't one of the list's rows, this will return -1.
  30231. */
  30232. int getRowNumberOfComponent (Component* rowComponent) const throw();
  30233. /** Returns the width of a row (which may be less than the width of this component
  30234. if there's a scrollbar).
  30235. */
  30236. int getVisibleRowWidth() const throw();
  30237. /** Sets the height of each row in the list.
  30238. The default height is 22 pixels.
  30239. @see getRowHeight
  30240. */
  30241. void setRowHeight (int newHeight);
  30242. /** Returns the height of a row in the list.
  30243. @see setRowHeight
  30244. */
  30245. int getRowHeight() const throw() { return rowHeight; }
  30246. /** Returns the number of rows actually visible.
  30247. This is the number of whole rows which will fit on-screen, so the value might
  30248. be more than the actual number of rows in the list.
  30249. */
  30250. int getNumRowsOnScreen() const throw();
  30251. /** A set of colour IDs to use to change the colour of various aspects of the label.
  30252. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30253. methods.
  30254. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30255. */
  30256. enum ColourIds
  30257. {
  30258. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  30259. Make this transparent if you don't want the background to be filled. */
  30260. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  30261. Make this transparent to not have an outline. */
  30262. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  30263. };
  30264. /** Sets the thickness of a border that will be drawn around the box.
  30265. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  30266. @see outlineColourId
  30267. */
  30268. void setOutlineThickness (int outlineThickness);
  30269. /** Returns the thickness of outline that will be drawn around the listbox.
  30270. @see setOutlineColour
  30271. */
  30272. int getOutlineThickness() const throw() { return outlineThickness; }
  30273. /** Sets a component that the list should use as a header.
  30274. This will position the given component at the top of the list, maintaining the
  30275. height of the component passed-in, but rescaling it horizontally to match the
  30276. width of the items in the listbox.
  30277. The component will be deleted when setHeaderComponent() is called with a
  30278. different component, or when the listbox is deleted.
  30279. */
  30280. void setHeaderComponent (Component* newHeaderComponent);
  30281. /** Changes the width of the rows in the list.
  30282. This can be used to make the list's row components wider than the list itself - the
  30283. width of the rows will be either the width of the list or this value, whichever is
  30284. greater, and if the rows become wider than the list, a horizontal scrollbar will
  30285. appear.
  30286. The default value for this is 0, which means that the rows will always
  30287. be the same width as the list.
  30288. */
  30289. void setMinimumContentWidth (int newMinimumWidth);
  30290. /** Returns the space currently available for the row items, taking into account
  30291. borders, scrollbars, etc.
  30292. */
  30293. int getVisibleContentWidth() const throw();
  30294. /** Repaints one of the rows.
  30295. This is a lightweight alternative to calling updateContent, and just causes a
  30296. repaint of the row's area.
  30297. */
  30298. void repaintRow (int rowNumber) throw();
  30299. /** This fairly obscure method creates an image that just shows the currently
  30300. selected row components.
  30301. It's a handy method for doing drag-and-drop, as it can be passed to the
  30302. DragAndDropContainer for use as the drag image.
  30303. Note that it will make the row components temporarily invisible, so if you're
  30304. using custom components this could affect them if they're sensitive to that
  30305. sort of thing.
  30306. @see Component::createComponentSnapshot
  30307. */
  30308. const Image createSnapshotOfSelectedRows (int& x, int& y);
  30309. /** Returns the viewport that this ListBox uses.
  30310. You may need to use this to change parameters such as whether scrollbars
  30311. are shown, etc.
  30312. */
  30313. Viewport* getViewport() const throw();
  30314. /** @internal */
  30315. bool keyPressed (const KeyPress& key);
  30316. /** @internal */
  30317. bool keyStateChanged (bool isKeyDown);
  30318. /** @internal */
  30319. void paint (Graphics& g);
  30320. /** @internal */
  30321. void paintOverChildren (Graphics& g);
  30322. /** @internal */
  30323. void resized();
  30324. /** @internal */
  30325. void visibilityChanged();
  30326. /** @internal */
  30327. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30328. /** @internal */
  30329. void mouseMove (const MouseEvent&);
  30330. /** @internal */
  30331. void mouseExit (const MouseEvent&);
  30332. /** @internal */
  30333. void mouseUp (const MouseEvent&);
  30334. /** @internal */
  30335. void colourChanged();
  30336. /** @internal */
  30337. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  30338. juce_UseDebuggingNewOperator
  30339. private:
  30340. friend class ListViewport;
  30341. friend class TableListBox;
  30342. ListBoxModel* model;
  30343. ScopedPointer<ListViewport> viewport;
  30344. ScopedPointer<Component> headerComponent;
  30345. int totalItems, rowHeight, minimumRowWidth;
  30346. int outlineThickness;
  30347. int lastRowSelected;
  30348. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  30349. SparseSet <int> selected;
  30350. void selectRowInternal (int rowNumber,
  30351. bool dontScrollToShowThisRow,
  30352. bool deselectOthersFirst,
  30353. bool isMouseClick);
  30354. ListBox (const ListBox&);
  30355. ListBox& operator= (const ListBox&);
  30356. };
  30357. #endif // __JUCE_LISTBOX_JUCEHEADER__
  30358. /*** End of inlined file: juce_ListBox.h ***/
  30359. /*** Start of inlined file: juce_TextButton.h ***/
  30360. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30361. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  30362. /**
  30363. A button that uses the standard lozenge-shaped background with a line of
  30364. text on it.
  30365. @see Button, DrawableButton
  30366. */
  30367. class JUCE_API TextButton : public Button
  30368. {
  30369. public:
  30370. /** Creates a TextButton.
  30371. @param buttonName the text to put in the button (the component's name is also
  30372. initially set to this string, but these can be changed later
  30373. using the setName() and setButtonText() methods)
  30374. @param toolTip an optional string to use as a toolip
  30375. @see Button
  30376. */
  30377. TextButton (const String& buttonName = String::empty,
  30378. const String& toolTip = String::empty);
  30379. /** Destructor. */
  30380. ~TextButton();
  30381. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30382. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30383. methods.
  30384. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30385. */
  30386. enum ColourIds
  30387. {
  30388. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  30389. 'off'). The look-and-feel class might re-interpret this to add
  30390. effects, etc. */
  30391. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  30392. 'on'). The look-and-feel class might re-interpret this to add
  30393. effects, etc. */
  30394. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  30395. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  30396. };
  30397. /** Resizes the button to fit neatly around its current text.
  30398. If newHeight is >= 0, the button's height will be changed to this
  30399. value. If it's less than zero, its height will be unaffected.
  30400. */
  30401. void changeWidthToFitText (int newHeight = -1);
  30402. /** This can be overridden to use different fonts than the default one.
  30403. Note that you'll need to set the font's size appropriately, too.
  30404. */
  30405. virtual const Font getFont();
  30406. juce_UseDebuggingNewOperator
  30407. protected:
  30408. /** @internal */
  30409. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  30410. /** @internal */
  30411. void colourChanged();
  30412. private:
  30413. TextButton (const TextButton&);
  30414. TextButton& operator= (const TextButton&);
  30415. };
  30416. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  30417. /*** End of inlined file: juce_TextButton.h ***/
  30418. /**
  30419. A component displaying a list of plugins, with options to scan for them,
  30420. add, remove and sort them.
  30421. */
  30422. class JUCE_API PluginListComponent : public Component,
  30423. public ListBoxModel,
  30424. public ChangeListener,
  30425. public Button::Listener,
  30426. public Timer
  30427. {
  30428. public:
  30429. /**
  30430. Creates the list component.
  30431. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  30432. The properties file, if supplied, is used to store the user's last search paths.
  30433. */
  30434. PluginListComponent (KnownPluginList& listToRepresent,
  30435. const File& deadMansPedalFile,
  30436. PropertiesFile* propertiesToUse);
  30437. /** Destructor. */
  30438. ~PluginListComponent();
  30439. /** @internal */
  30440. void resized();
  30441. /** @internal */
  30442. bool isInterestedInFileDrag (const StringArray& files);
  30443. /** @internal */
  30444. void filesDropped (const StringArray& files, int, int);
  30445. /** @internal */
  30446. int getNumRows();
  30447. /** @internal */
  30448. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  30449. /** @internal */
  30450. void deleteKeyPressed (int lastRowSelected);
  30451. /** @internal */
  30452. void buttonClicked (Button* b);
  30453. /** @internal */
  30454. void changeListenerCallback (void*);
  30455. /** @internal */
  30456. void timerCallback();
  30457. juce_UseDebuggingNewOperator
  30458. private:
  30459. KnownPluginList& list;
  30460. File deadMansPedalFile;
  30461. ListBox* listBox;
  30462. TextButton* optionsButton;
  30463. PropertiesFile* propertiesToUse;
  30464. int typeToScan;
  30465. void scanFor (AudioPluginFormat* format);
  30466. PluginListComponent (const PluginListComponent&);
  30467. PluginListComponent& operator= (const PluginListComponent&);
  30468. };
  30469. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  30470. /*** End of inlined file: juce_PluginListComponent.h ***/
  30471. #endif
  30472. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  30473. #endif
  30474. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  30475. #endif
  30476. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  30477. #endif
  30478. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30479. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  30480. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30481. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30482. /**
  30483. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  30484. Use one of these objects if you want to wire-up a set of AudioProcessors
  30485. and play back the result.
  30486. Processors can be added to the graph as "nodes" using addNode(), and once
  30487. added, you can connect any of their input or output channels to other
  30488. nodes using addConnection().
  30489. To play back a graph through an audio device, you might want to use an
  30490. AudioProcessorPlayer object.
  30491. */
  30492. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  30493. public AsyncUpdater
  30494. {
  30495. public:
  30496. /** Creates an empty graph.
  30497. */
  30498. AudioProcessorGraph();
  30499. /** Destructor.
  30500. Any processor objects that have been added to the graph will also be deleted.
  30501. */
  30502. ~AudioProcessorGraph();
  30503. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  30504. To create a node, call AudioProcessorGraph::addNode().
  30505. */
  30506. class JUCE_API Node : public ReferenceCountedObject
  30507. {
  30508. public:
  30509. /** Destructor.
  30510. */
  30511. ~Node();
  30512. /** The ID number assigned to this node.
  30513. This is assigned by the graph that owns it, and can't be changed.
  30514. */
  30515. const uint32 id;
  30516. /** The actual processor object that this node represents.
  30517. */
  30518. AudioProcessor* const processor;
  30519. /** A set of user-definable properties that are associated with this node.
  30520. This can be used to attach values to the node for whatever purpose seems
  30521. useful. For example, you might store an x and y position if your application
  30522. is displaying the nodes on-screen.
  30523. */
  30524. NamedValueSet properties;
  30525. /** A convenient typedef for referring to a pointer to a node object.
  30526. */
  30527. typedef ReferenceCountedObjectPtr <Node> Ptr;
  30528. juce_UseDebuggingNewOperator
  30529. private:
  30530. friend class AudioProcessorGraph;
  30531. bool isPrepared;
  30532. Node (uint32 id, AudioProcessor* processor);
  30533. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  30534. void unprepare();
  30535. Node (const Node&);
  30536. Node& operator= (const Node&);
  30537. };
  30538. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  30539. To create a connection, use AudioProcessorGraph::addConnection().
  30540. */
  30541. struct JUCE_API Connection
  30542. {
  30543. public:
  30544. /** The ID number of the node which is the input source for this connection.
  30545. @see AudioProcessorGraph::getNodeForId
  30546. */
  30547. uint32 sourceNodeId;
  30548. /** The index of the output channel of the source node from which this
  30549. connection takes its data.
  30550. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30551. it is referring to the source node's midi output. Otherwise, it is the zero-based
  30552. index of an audio output channel in the source node.
  30553. */
  30554. int sourceChannelIndex;
  30555. /** The ID number of the node which is the destination for this connection.
  30556. @see AudioProcessorGraph::getNodeForId
  30557. */
  30558. uint32 destNodeId;
  30559. /** The index of the input channel of the destination node to which this
  30560. connection delivers its data.
  30561. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30562. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  30563. index of an audio input channel in the destination node.
  30564. */
  30565. int destChannelIndex;
  30566. juce_UseDebuggingNewOperator
  30567. private:
  30568. };
  30569. /** Deletes all nodes and connections from this graph.
  30570. Any processor objects in the graph will be deleted.
  30571. */
  30572. void clear();
  30573. /** Returns the number of nodes in the graph. */
  30574. int getNumNodes() const { return nodes.size(); }
  30575. /** Returns a pointer to one of the nodes in the graph.
  30576. This will return 0 if the index is out of range.
  30577. @see getNodeForId
  30578. */
  30579. Node* getNode (const int index) const { return nodes [index]; }
  30580. /** Searches the graph for a node with the given ID number and returns it.
  30581. If no such node was found, this returns 0.
  30582. @see getNode
  30583. */
  30584. Node* getNodeForId (const uint32 nodeId) const;
  30585. /** Adds a node to the graph.
  30586. This creates a new node in the graph, for the specified processor. Once you have
  30587. added a processor to the graph, the graph owns it and will delete it later when
  30588. it is no longer needed.
  30589. The optional nodeId parameter lets you specify an ID to use for the node, but
  30590. if the value is already in use, this new node will overwrite the old one.
  30591. If this succeeds, it returns a pointer to the newly-created node.
  30592. */
  30593. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  30594. /** Deletes a node within the graph which has the specified ID.
  30595. This will also delete any connections that are attached to this node.
  30596. */
  30597. bool removeNode (uint32 nodeId);
  30598. /** Returns the number of connections in the graph. */
  30599. int getNumConnections() const { return connections.size(); }
  30600. /** Returns a pointer to one of the connections in the graph. */
  30601. const Connection* getConnection (int index) const { return connections [index]; }
  30602. /** Searches for a connection between some specified channels.
  30603. If no such connection is found, this returns 0.
  30604. */
  30605. const Connection* getConnectionBetween (uint32 sourceNodeId,
  30606. int sourceChannelIndex,
  30607. uint32 destNodeId,
  30608. int destChannelIndex) const;
  30609. /** Returns true if there is a connection between any of the channels of
  30610. two specified nodes.
  30611. */
  30612. bool isConnected (uint32 possibleSourceNodeId,
  30613. uint32 possibleDestNodeId) const;
  30614. /** Returns true if it would be legal to connect the specified points.
  30615. */
  30616. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  30617. uint32 destNodeId, int destChannelIndex) const;
  30618. /** Attempts to connect two specified channels of two nodes.
  30619. If this isn't allowed (e.g. because you're trying to connect a midi channel
  30620. to an audio one or other such nonsense), then it'll return false.
  30621. */
  30622. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30623. uint32 destNodeId, int destChannelIndex);
  30624. /** Deletes the connection with the specified index.
  30625. Returns true if a connection was actually deleted.
  30626. */
  30627. void removeConnection (int index);
  30628. /** Deletes any connection between two specified points.
  30629. Returns true if a connection was actually deleted.
  30630. */
  30631. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30632. uint32 destNodeId, int destChannelIndex);
  30633. /** Removes all connections from the specified node.
  30634. */
  30635. bool disconnectNode (uint32 nodeId);
  30636. /** Performs a sanity checks of all the connections.
  30637. This might be useful if some of the processors are doing things like changing
  30638. their channel counts, which could render some connections obsolete.
  30639. */
  30640. bool removeIllegalConnections();
  30641. /** A special number that represents the midi channel of a node.
  30642. This is used as a channel index value if you want to refer to the midi input
  30643. or output instead of an audio channel.
  30644. */
  30645. static const int midiChannelIndex;
  30646. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  30647. in order to use the audio that comes into and out of the graph itself.
  30648. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  30649. node in the graph which delivers the audio that is coming into the parent
  30650. graph. This allows you to stream the data to other nodes and process the
  30651. incoming audio.
  30652. Likewise, one of these in "output" mode can be sent data which it will add to
  30653. the sum of data being sent to the graph's output.
  30654. @see AudioProcessorGraph
  30655. */
  30656. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  30657. {
  30658. public:
  30659. /** Specifies the mode in which this processor will operate.
  30660. */
  30661. enum IODeviceType
  30662. {
  30663. audioInputNode, /**< In this mode, the processor has output channels
  30664. representing all the audio input channels that are
  30665. coming into its parent audio graph. */
  30666. audioOutputNode, /**< In this mode, the processor has input channels
  30667. representing all the audio output channels that are
  30668. going out of its parent audio graph. */
  30669. midiInputNode, /**< In this mode, the processor has a midi output which
  30670. delivers the same midi data that is arriving at its
  30671. parent graph. */
  30672. midiOutputNode /**< In this mode, the processor has a midi input and
  30673. any data sent to it will be passed out of the parent
  30674. graph. */
  30675. };
  30676. /** Returns the mode of this processor. */
  30677. IODeviceType getType() const { return type; }
  30678. /** Returns the parent graph to which this processor belongs, or 0 if it
  30679. hasn't yet been added to one. */
  30680. AudioProcessorGraph* getParentGraph() const { return graph; }
  30681. /** True if this is an audio or midi input. */
  30682. bool isInput() const;
  30683. /** True if this is an audio or midi output. */
  30684. bool isOutput() const;
  30685. AudioGraphIOProcessor (const IODeviceType type);
  30686. ~AudioGraphIOProcessor();
  30687. const String getName() const;
  30688. void fillInPluginDescription (PluginDescription& d) const;
  30689. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30690. void releaseResources();
  30691. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30692. const String getInputChannelName (const int channelIndex) const;
  30693. const String getOutputChannelName (const int channelIndex) const;
  30694. bool isInputChannelStereoPair (int index) const;
  30695. bool isOutputChannelStereoPair (int index) const;
  30696. bool acceptsMidi() const;
  30697. bool producesMidi() const;
  30698. AudioProcessorEditor* createEditor();
  30699. int getNumParameters();
  30700. const String getParameterName (int);
  30701. float getParameter (int);
  30702. const String getParameterText (int);
  30703. void setParameter (int, float);
  30704. int getNumPrograms();
  30705. int getCurrentProgram();
  30706. void setCurrentProgram (int);
  30707. const String getProgramName (int);
  30708. void changeProgramName (int, const String&);
  30709. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30710. void setStateInformation (const void* data, int sizeInBytes);
  30711. /** @internal */
  30712. void setParentGraph (AudioProcessorGraph* graph);
  30713. juce_UseDebuggingNewOperator
  30714. private:
  30715. const IODeviceType type;
  30716. AudioProcessorGraph* graph;
  30717. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  30718. AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  30719. };
  30720. // AudioProcessor methods:
  30721. const String getName() const;
  30722. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30723. void releaseResources();
  30724. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30725. const String getInputChannelName (const int channelIndex) const;
  30726. const String getOutputChannelName (const int channelIndex) const;
  30727. bool isInputChannelStereoPair (int index) const;
  30728. bool isOutputChannelStereoPair (int index) const;
  30729. bool acceptsMidi() const;
  30730. bool producesMidi() const;
  30731. AudioProcessorEditor* createEditor() { return 0; }
  30732. int getNumParameters() { return 0; }
  30733. const String getParameterName (int) { return String::empty; }
  30734. float getParameter (int) { return 0; }
  30735. const String getParameterText (int) { return String::empty; }
  30736. void setParameter (int, float) { }
  30737. int getNumPrograms() { return 0; }
  30738. int getCurrentProgram() { return 0; }
  30739. void setCurrentProgram (int) { }
  30740. const String getProgramName (int) { return String::empty; }
  30741. void changeProgramName (int, const String&) { }
  30742. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30743. void setStateInformation (const void* data, int sizeInBytes);
  30744. /** @internal */
  30745. void handleAsyncUpdate();
  30746. juce_UseDebuggingNewOperator
  30747. private:
  30748. ReferenceCountedArray <Node> nodes;
  30749. OwnedArray <Connection> connections;
  30750. int lastNodeId;
  30751. AudioSampleBuffer renderingBuffers;
  30752. OwnedArray <MidiBuffer> midiBuffers;
  30753. CriticalSection renderLock;
  30754. Array<void*> renderingOps;
  30755. friend class AudioGraphIOProcessor;
  30756. AudioSampleBuffer* currentAudioInputBuffer;
  30757. AudioSampleBuffer currentAudioOutputBuffer;
  30758. MidiBuffer* currentMidiInputBuffer;
  30759. MidiBuffer currentMidiOutputBuffer;
  30760. void clearRenderingSequence();
  30761. void buildRenderingSequence();
  30762. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  30763. AudioProcessorGraph (const AudioProcessorGraph&);
  30764. AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  30765. };
  30766. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30767. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  30768. #endif
  30769. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  30770. #endif
  30771. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30772. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  30773. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30774. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30775. /**
  30776. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  30777. To use one of these, just make it the callback used by your AudioIODevice, and
  30778. give it a processor to use by calling setProcessor().
  30779. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  30780. input to send both streams through the processor.
  30781. @see AudioProcessor, AudioProcessorGraph
  30782. */
  30783. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  30784. public MidiInputCallback
  30785. {
  30786. public:
  30787. /**
  30788. */
  30789. AudioProcessorPlayer();
  30790. /** Destructor. */
  30791. virtual ~AudioProcessorPlayer();
  30792. /** Sets the processor that should be played.
  30793. The processor that is passed in will not be deleted or owned by this object.
  30794. To stop anything playing, pass in 0 to this method.
  30795. */
  30796. void setProcessor (AudioProcessor* const processorToPlay);
  30797. /** Returns the current audio processor that is being played.
  30798. */
  30799. AudioProcessor* getCurrentProcessor() const { return processor; }
  30800. /** Returns a midi message collector that you can pass midi messages to if you
  30801. want them to be injected into the midi stream that is being sent to the
  30802. processor.
  30803. */
  30804. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  30805. /** @internal */
  30806. void audioDeviceIOCallback (const float** inputChannelData,
  30807. int totalNumInputChannels,
  30808. float** outputChannelData,
  30809. int totalNumOutputChannels,
  30810. int numSamples);
  30811. /** @internal */
  30812. void audioDeviceAboutToStart (AudioIODevice* device);
  30813. /** @internal */
  30814. void audioDeviceStopped();
  30815. /** @internal */
  30816. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30817. juce_UseDebuggingNewOperator
  30818. private:
  30819. AudioProcessor* processor;
  30820. CriticalSection lock;
  30821. double sampleRate;
  30822. int blockSize;
  30823. bool isPrepared;
  30824. int numInputChans, numOutputChans;
  30825. float* channels [128];
  30826. AudioSampleBuffer tempBuffer;
  30827. MidiBuffer incomingMidi;
  30828. MidiMessageCollector messageCollector;
  30829. AudioProcessorPlayer (const AudioProcessorPlayer&);
  30830. AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  30831. };
  30832. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30833. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  30834. #endif
  30835. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30836. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30837. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30838. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30839. /*** Start of inlined file: juce_PropertyPanel.h ***/
  30840. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  30841. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  30842. /*** Start of inlined file: juce_PropertyComponent.h ***/
  30843. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30844. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30845. class EditableProperty;
  30846. /**
  30847. A base class for a component that goes in a PropertyPanel and displays one of
  30848. an item's properties.
  30849. Subclasses of this are used to display a property in various forms, e.g. a
  30850. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  30851. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  30852. A subclass must implement the refresh() method which will be called to tell the
  30853. component to update itself, and is also responsible for calling this it when the
  30854. item that it refers to is changed.
  30855. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  30856. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  30857. */
  30858. class JUCE_API PropertyComponent : public Component,
  30859. public SettableTooltipClient
  30860. {
  30861. public:
  30862. /** Creates a PropertyComponent.
  30863. @param propertyName the name is stored as this component's name, and is
  30864. used as the name displayed next to this component in
  30865. a property panel
  30866. @param preferredHeight the height that the component should be given - some
  30867. items may need to be larger than a normal row height.
  30868. This value can also be set if a subclass changes the
  30869. preferredHeight member variable.
  30870. */
  30871. PropertyComponent (const String& propertyName,
  30872. int preferredHeight = 25);
  30873. /** Destructor. */
  30874. ~PropertyComponent();
  30875. /** Returns this item's preferred height.
  30876. This value is specified either in the constructor or by a subclass changing the
  30877. preferredHeight member variable.
  30878. */
  30879. int getPreferredHeight() const throw() { return preferredHeight; }
  30880. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  30881. /** Updates the property component if the item it refers to has changed.
  30882. A subclass must implement this method, and other objects may call it to
  30883. force it to refresh itself.
  30884. The subclass should be economical in the amount of work is done, so for
  30885. example it should check whether it really needs to do a repaint rather than
  30886. just doing one every time this method is called, as it may be called when
  30887. the value being displayed hasn't actually changed.
  30888. */
  30889. virtual void refresh() = 0;
  30890. /** The default paint method fills the background and draws a label for the
  30891. item's name.
  30892. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  30893. */
  30894. void paint (Graphics& g);
  30895. /** The default resize method positions any child component to the right of this
  30896. one, based on the look and feel's default label size.
  30897. */
  30898. void resized();
  30899. /** By default, this just repaints the component. */
  30900. void enablementChanged();
  30901. juce_UseDebuggingNewOperator
  30902. protected:
  30903. /** Used by the PropertyPanel to determine how high this component needs to be.
  30904. A subclass can update this value in its constructor but shouldn't alter it later
  30905. as changes won't necessarily be picked up.
  30906. */
  30907. int preferredHeight;
  30908. };
  30909. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30910. /*** End of inlined file: juce_PropertyComponent.h ***/
  30911. /**
  30912. A panel that holds a list of PropertyComponent objects.
  30913. This panel displays a list of PropertyComponents, and allows them to be organised
  30914. into collapsible sections.
  30915. To use, simply create one of these and add your properties to it with addProperties()
  30916. or addSection().
  30917. @see PropertyComponent
  30918. */
  30919. class JUCE_API PropertyPanel : public Component
  30920. {
  30921. public:
  30922. /** Creates an empty property panel. */
  30923. PropertyPanel();
  30924. /** Destructor. */
  30925. ~PropertyPanel();
  30926. /** Deletes all property components from the panel.
  30927. */
  30928. void clear();
  30929. /** Adds a set of properties to the panel.
  30930. The components in the list will be owned by this object and will be automatically
  30931. deleted later on when no longer needed.
  30932. These properties are added without them being inside a named section. If you
  30933. want them to be kept together in a collapsible section, use addSection() instead.
  30934. */
  30935. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  30936. /** Adds a set of properties to the panel.
  30937. These properties are added at the bottom of the list, under a section heading with
  30938. a plus/minus button that allows it to be opened and closed.
  30939. The components in the list will be owned by this object and will be automatically
  30940. deleted later on when no longer needed.
  30941. To add properies without them being in a section, use addProperties().
  30942. */
  30943. void addSection (const String& sectionTitle,
  30944. const Array <PropertyComponent*>& newPropertyComponents,
  30945. bool shouldSectionInitiallyBeOpen = true);
  30946. /** Calls the refresh() method of all PropertyComponents in the panel */
  30947. void refreshAll() const;
  30948. /** Returns a list of all the names of sections in the panel.
  30949. These are the sections that have been added with addSection().
  30950. */
  30951. const StringArray getSectionNames() const;
  30952. /** Returns true if the section at this index is currently open.
  30953. The index is from 0 up to the number of items returned by getSectionNames().
  30954. */
  30955. bool isSectionOpen (int sectionIndex) const;
  30956. /** Opens or closes one of the sections.
  30957. The index is from 0 up to the number of items returned by getSectionNames().
  30958. */
  30959. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  30960. /** Enables or disables one of the sections.
  30961. The index is from 0 up to the number of items returned by getSectionNames().
  30962. */
  30963. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  30964. /** Saves the current state of open/closed sections so it can be restored later.
  30965. The caller is responsible for deleting the object that is returned.
  30966. To restore this state, use restoreOpennessState().
  30967. @see restoreOpennessState
  30968. */
  30969. XmlElement* getOpennessState() const;
  30970. /** Restores a previously saved arrangement of open/closed sections.
  30971. This will try to restore a snapshot of the panel's state that was created by
  30972. the getOpennessState() method. If any of the sections named in the original
  30973. XML aren't present, they will be ignored.
  30974. @see getOpennessState
  30975. */
  30976. void restoreOpennessState (const XmlElement& newState);
  30977. /** Sets a message to be displayed when there are no properties in the panel.
  30978. The default message is "nothing selected".
  30979. */
  30980. void setMessageWhenEmpty (const String& newMessage);
  30981. /** Returns the message that is displayed when there are no properties.
  30982. @see setMessageWhenEmpty
  30983. */
  30984. const String& getMessageWhenEmpty() const;
  30985. /** @internal */
  30986. void paint (Graphics& g);
  30987. /** @internal */
  30988. void resized();
  30989. juce_UseDebuggingNewOperator
  30990. private:
  30991. Viewport viewport;
  30992. class PropertyHolderComponent;
  30993. PropertyHolderComponent* propertyHolderComponent;
  30994. String messageWhenEmpty;
  30995. void updatePropHolderLayout() const;
  30996. void updatePropHolderLayout (int width) const;
  30997. };
  30998. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  30999. /*** End of inlined file: juce_PropertyPanel.h ***/
  31000. /**
  31001. A type of UI component that displays the parameters of an AudioProcessor as
  31002. a simple list of sliders.
  31003. This can be used for showing an editor for a processor that doesn't supply
  31004. its own custom editor.
  31005. @see AudioProcessor
  31006. */
  31007. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  31008. {
  31009. public:
  31010. GenericAudioProcessorEditor (AudioProcessor* const owner);
  31011. ~GenericAudioProcessorEditor();
  31012. void paint (Graphics& g);
  31013. void resized();
  31014. juce_UseDebuggingNewOperator
  31015. private:
  31016. PropertyPanel* panel;
  31017. GenericAudioProcessorEditor (const GenericAudioProcessorEditor&);
  31018. GenericAudioProcessorEditor& operator= (const GenericAudioProcessorEditor&);
  31019. };
  31020. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  31021. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  31022. #endif
  31023. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  31024. /*** Start of inlined file: juce_Sampler.h ***/
  31025. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  31026. #define __JUCE_SAMPLER_JUCEHEADER__
  31027. /*** Start of inlined file: juce_Synthesiser.h ***/
  31028. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  31029. #define __JUCE_SYNTHESISER_JUCEHEADER__
  31030. /**
  31031. Describes one of the sounds that a Synthesiser can play.
  31032. A synthesiser can contain one or more sounds, and a sound can choose which
  31033. midi notes and channels can trigger it.
  31034. The SynthesiserSound is a passive class that just describes what the sound is -
  31035. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  31036. more than one SynthesiserVoice to play the same sound at the same time.
  31037. @see Synthesiser, SynthesiserVoice
  31038. */
  31039. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  31040. {
  31041. protected:
  31042. SynthesiserSound();
  31043. public:
  31044. /** Destructor. */
  31045. virtual ~SynthesiserSound();
  31046. /** Returns true if this sound should be played when a given midi note is pressed.
  31047. The Synthesiser will use this information when deciding which sounds to trigger
  31048. for a given note.
  31049. */
  31050. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  31051. /** Returns true if the sound should be triggered by midi events on a given channel.
  31052. The Synthesiser will use this information when deciding which sounds to trigger
  31053. for a given note.
  31054. */
  31055. virtual bool appliesToChannel (const int midiChannel) = 0;
  31056. /**
  31057. */
  31058. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  31059. juce_UseDebuggingNewOperator
  31060. };
  31061. /**
  31062. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  31063. A voice plays a single sound at a time, and a synthesiser holds an array of
  31064. voices so that it can play polyphonically.
  31065. @see Synthesiser, SynthesiserSound
  31066. */
  31067. class JUCE_API SynthesiserVoice
  31068. {
  31069. public:
  31070. /** Creates a voice. */
  31071. SynthesiserVoice();
  31072. /** Destructor. */
  31073. virtual ~SynthesiserVoice();
  31074. /** Returns the midi note that this voice is currently playing.
  31075. Returns a value less than 0 if no note is playing.
  31076. */
  31077. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  31078. /** Returns the sound that this voice is currently playing.
  31079. Returns 0 if it's not playing.
  31080. */
  31081. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  31082. /** Must return true if this voice object is capable of playing the given sound.
  31083. If there are different classes of sound, and different classes of voice, a voice can
  31084. choose which ones it wants to take on.
  31085. A typical implementation of this method may just return true if there's only one type
  31086. of voice and sound, or it might check the type of the sound object passed-in and
  31087. see if it's one that it understands.
  31088. */
  31089. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  31090. /** Called to start a new note.
  31091. This will be called during the rendering callback, so must be fast and thread-safe.
  31092. */
  31093. virtual void startNote (const int midiNoteNumber,
  31094. const float velocity,
  31095. SynthesiserSound* sound,
  31096. const int currentPitchWheelPosition) = 0;
  31097. /** Called to stop a note.
  31098. This will be called during the rendering callback, so must be fast and thread-safe.
  31099. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  31100. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  31101. and allow the synth to reassign it another sound.
  31102. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  31103. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  31104. finishes playing (during the rendering callback), it must make sure that it calls
  31105. clearCurrentNote().
  31106. */
  31107. virtual void stopNote (const bool allowTailOff) = 0;
  31108. /** Called to let the voice know that the pitch wheel has been moved.
  31109. This will be called during the rendering callback, so must be fast and thread-safe.
  31110. */
  31111. virtual void pitchWheelMoved (const int newValue) = 0;
  31112. /** Called to let the voice know that a midi controller has been moved.
  31113. This will be called during the rendering callback, so must be fast and thread-safe.
  31114. */
  31115. virtual void controllerMoved (const int controllerNumber,
  31116. const int newValue) = 0;
  31117. /** Renders the next block of data for this voice.
  31118. The output audio data must be added to the current contents of the buffer provided.
  31119. Only the region of the buffer between startSample and (startSample + numSamples)
  31120. should be altered by this method.
  31121. If the voice is currently silent, it should just return without doing anything.
  31122. If the sound that the voice is playing finishes during the course of this rendered
  31123. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  31124. The size of the blocks that are rendered can change each time it is called, and may
  31125. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  31126. the voice's methods will be called to tell it about note and controller events.
  31127. */
  31128. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  31129. int startSample,
  31130. int numSamples) = 0;
  31131. /** Returns true if the voice is currently playing a sound which is mapped to the given
  31132. midi channel.
  31133. If it's not currently playing, this will return false.
  31134. */
  31135. bool isPlayingChannel (int midiChannel) const;
  31136. /** Changes the voice's reference sample rate.
  31137. The rate is set so that subclasses know the output rate and can set their pitch
  31138. accordingly.
  31139. This method is called by the synth, and subclasses can access the current rate with
  31140. the currentSampleRate member.
  31141. */
  31142. void setCurrentPlaybackSampleRate (double newRate);
  31143. juce_UseDebuggingNewOperator
  31144. protected:
  31145. /** Returns the current target sample rate at which rendering is being done.
  31146. This is available for subclasses so they can pitch things correctly.
  31147. */
  31148. double getSampleRate() const { return currentSampleRate; }
  31149. /** Resets the state of this voice after a sound has finished playing.
  31150. The subclass must call this when it finishes playing a note and becomes available
  31151. to play new ones.
  31152. It must either call it in the stopNote() method, or if the voice is tailing off,
  31153. then it should call it later during the renderNextBlock method, as soon as it
  31154. finishes its tail-off.
  31155. It can also be called at any time during the render callback if the sound happens
  31156. to have finished, e.g. if it's playing a sample and the sample finishes.
  31157. */
  31158. void clearCurrentNote();
  31159. private:
  31160. friend class Synthesiser;
  31161. double currentSampleRate;
  31162. int currentlyPlayingNote;
  31163. uint32 noteOnTime;
  31164. SynthesiserSound::Ptr currentlyPlayingSound;
  31165. };
  31166. /**
  31167. Base class for a musical device that can play sounds.
  31168. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  31169. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  31170. which can play back one of these sounds.
  31171. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  31172. set of sounds, and a set of voices it can use to play them. If you only give it
  31173. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  31174. have available.
  31175. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  31176. events that go in will be scanned for note on/off messages, and these are used to
  31177. start and stop the voices playing the appropriate sounds.
  31178. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  31179. noteOff() and other controller methods.
  31180. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  31181. what the target playback rate is. This value is passed on to the voices so that
  31182. they can pitch their output correctly.
  31183. */
  31184. class JUCE_API Synthesiser
  31185. {
  31186. public:
  31187. /** Creates a new synthesiser.
  31188. You'll need to add some sounds and voices before it'll make any sound..
  31189. */
  31190. Synthesiser();
  31191. /** Destructor. */
  31192. virtual ~Synthesiser();
  31193. /** Deletes all voices. */
  31194. void clearVoices();
  31195. /** Returns the number of voices that have been added. */
  31196. int getNumVoices() const { return voices.size(); }
  31197. /** Returns one of the voices that have been added. */
  31198. SynthesiserVoice* getVoice (int index) const;
  31199. /** Adds a new voice to the synth.
  31200. All the voices should be the same class of object and are treated equally.
  31201. The object passed in will be managed by the synthesiser, which will delete
  31202. it later on when no longer needed. The caller should not retain a pointer to the
  31203. voice.
  31204. */
  31205. void addVoice (SynthesiserVoice* newVoice);
  31206. /** Deletes one of the voices. */
  31207. void removeVoice (int index);
  31208. /** Deletes all sounds. */
  31209. void clearSounds();
  31210. /** Returns the number of sounds that have been added to the synth. */
  31211. int getNumSounds() const { return sounds.size(); }
  31212. /** Returns one of the sounds. */
  31213. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  31214. /** Adds a new sound to the synthesiser.
  31215. The object passed in is reference counted, so will be deleted when it is removed
  31216. from the synthesiser, and when no voices are still using it.
  31217. */
  31218. void addSound (const SynthesiserSound::Ptr& newSound);
  31219. /** Removes and deletes one of the sounds. */
  31220. void removeSound (int index);
  31221. /** If set to true, then the synth will try to take over an existing voice if
  31222. it runs out and needs to play another note.
  31223. The value of this boolean is passed into findFreeVoice(), so the result will
  31224. depend on the implementation of this method.
  31225. */
  31226. void setNoteStealingEnabled (bool shouldStealNotes);
  31227. /** Returns true if note-stealing is enabled.
  31228. @see setNoteStealingEnabled
  31229. */
  31230. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  31231. /** Triggers a note-on event.
  31232. The default method here will find all the sounds that want to be triggered by
  31233. this note/channel. For each sound, it'll try to find a free voice, and use the
  31234. voice to start playing the sound.
  31235. Subclasses might want to override this if they need a more complex algorithm.
  31236. This method will be called automatically according to the midi data passed into
  31237. renderNextBlock(), but may be called explicitly too.
  31238. */
  31239. virtual void noteOn (const int midiChannel,
  31240. const int midiNoteNumber,
  31241. const float velocity);
  31242. /** Triggers a note-off event.
  31243. This will turn off any voices that are playing a sound for the given note/channel.
  31244. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  31245. (if they can do). If this is false, the notes will all be cut off immediately.
  31246. This method will be called automatically according to the midi data passed into
  31247. renderNextBlock(), but may be called explicitly too.
  31248. */
  31249. virtual void noteOff (const int midiChannel,
  31250. const int midiNoteNumber,
  31251. const bool allowTailOff);
  31252. /** Turns off all notes.
  31253. This will turn off any voices that are playing a sound on the given midi channel.
  31254. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  31255. which channel they're playing.
  31256. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  31257. (if they can do). If this is false, the notes will all be cut off immediately.
  31258. This method will be called automatically according to the midi data passed into
  31259. renderNextBlock(), but may be called explicitly too.
  31260. */
  31261. virtual void allNotesOff (const int midiChannel,
  31262. const bool allowTailOff);
  31263. /** Sends a pitch-wheel message.
  31264. This will send a pitch-wheel message to any voices that are playing sounds on
  31265. the given midi channel.
  31266. This method will be called automatically according to the midi data passed into
  31267. renderNextBlock(), but may be called explicitly too.
  31268. @param midiChannel the midi channel for the event
  31269. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  31270. */
  31271. virtual void handlePitchWheel (const int midiChannel,
  31272. const int wheelValue);
  31273. /** Sends a midi controller message.
  31274. This will send a midi controller message to any voices that are playing sounds on
  31275. the given midi channel.
  31276. This method will be called automatically according to the midi data passed into
  31277. renderNextBlock(), but may be called explicitly too.
  31278. @param midiChannel the midi channel for the event
  31279. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  31280. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  31281. */
  31282. virtual void handleController (const int midiChannel,
  31283. const int controllerNumber,
  31284. const int controllerValue);
  31285. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  31286. render.
  31287. This value is propagated to the voices so that they can use it to render the correct
  31288. pitches.
  31289. */
  31290. void setCurrentPlaybackSampleRate (const double sampleRate);
  31291. /** Creates the next block of audio output.
  31292. This will process the next numSamples of data from all the voices, and add that output
  31293. to the audio block supplied, starting from the offset specified. Note that the
  31294. data will be added to the current contents of the buffer, so you should clear it
  31295. before calling this method if necessary.
  31296. The midi events in the inputMidi buffer are parsed for note and controller events,
  31297. and these are used to trigger the voices. Note that the startSample offset applies
  31298. both to the audio output buffer and the midi input buffer, so any midi events
  31299. with timestamps outside the specified region will be ignored.
  31300. */
  31301. void renderNextBlock (AudioSampleBuffer& outputAudio,
  31302. const MidiBuffer& inputMidi,
  31303. int startSample,
  31304. int numSamples);
  31305. juce_UseDebuggingNewOperator
  31306. protected:
  31307. /** This is used to control access to the rendering callback and the note trigger methods. */
  31308. CriticalSection lock;
  31309. OwnedArray <SynthesiserVoice> voices;
  31310. ReferenceCountedArray <SynthesiserSound> sounds;
  31311. /** The last pitch-wheel values for each midi channel. */
  31312. int lastPitchWheelValues [16];
  31313. /** Searches through the voices to find one that's not currently playing, and which
  31314. can play the given sound.
  31315. Returns 0 if all voices are busy and stealing isn't enabled.
  31316. This can be overridden to implement custom voice-stealing algorithms.
  31317. */
  31318. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  31319. const bool stealIfNoneAvailable) const;
  31320. /** Starts a specified voice playing a particular sound.
  31321. You'll probably never need to call this, it's used internally by noteOn(), but
  31322. may be needed by subclasses for custom behaviours.
  31323. */
  31324. void startVoice (SynthesiserVoice* voice,
  31325. SynthesiserSound* sound,
  31326. int midiChannel,
  31327. int midiNoteNumber,
  31328. float velocity);
  31329. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  31330. int findFreeVoice (const bool) const { return 0; }
  31331. private:
  31332. double sampleRate;
  31333. uint32 lastNoteOnCounter;
  31334. bool shouldStealNotes;
  31335. Synthesiser (const Synthesiser&);
  31336. Synthesiser& operator= (const Synthesiser&);
  31337. };
  31338. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  31339. /*** End of inlined file: juce_Synthesiser.h ***/
  31340. /**
  31341. A subclass of SynthesiserSound that represents a sampled audio clip.
  31342. This is a pretty basic sampler, and just attempts to load the whole audio stream
  31343. into memory.
  31344. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  31345. give it some SampledSound objects to play.
  31346. @see SamplerVoice, Synthesiser, SynthesiserSound
  31347. */
  31348. class JUCE_API SamplerSound : public SynthesiserSound
  31349. {
  31350. public:
  31351. /** Creates a sampled sound from an audio reader.
  31352. This will attempt to load the audio from the source into memory and store
  31353. it in this object.
  31354. @param name a name for the sample
  31355. @param source the audio to load. This object can be safely deleted by the
  31356. caller after this constructor returns
  31357. @param midiNotes the set of midi keys that this sound should be played on. This
  31358. is used by the SynthesiserSound::appliesToNote() method
  31359. @param midiNoteForNormalPitch the midi note at which the sample should be played
  31360. with its natural rate. All other notes will be pitched
  31361. up or down relative to this one
  31362. @param attackTimeSecs the attack (fade-in) time, in seconds
  31363. @param releaseTimeSecs the decay (fade-out) time, in seconds
  31364. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  31365. source, in seconds
  31366. */
  31367. SamplerSound (const String& name,
  31368. AudioFormatReader& source,
  31369. const BigInteger& midiNotes,
  31370. int midiNoteForNormalPitch,
  31371. double attackTimeSecs,
  31372. double releaseTimeSecs,
  31373. double maxSampleLengthSeconds);
  31374. /** Destructor. */
  31375. ~SamplerSound();
  31376. /** Returns the sample's name */
  31377. const String& getName() const { return name; }
  31378. /** Returns the audio sample data.
  31379. This could be 0 if there was a problem loading it.
  31380. */
  31381. AudioSampleBuffer* getAudioData() const { return data; }
  31382. bool appliesToNote (const int midiNoteNumber);
  31383. bool appliesToChannel (const int midiChannel);
  31384. juce_UseDebuggingNewOperator
  31385. private:
  31386. friend class SamplerVoice;
  31387. String name;
  31388. ScopedPointer <AudioSampleBuffer> data;
  31389. double sourceSampleRate;
  31390. BigInteger midiNotes;
  31391. int length, attackSamples, releaseSamples;
  31392. int midiRootNote;
  31393. };
  31394. /**
  31395. A subclass of SynthesiserVoice that can play a SamplerSound.
  31396. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  31397. give it some SampledSound objects to play.
  31398. @see SamplerSound, Synthesiser, SynthesiserVoice
  31399. */
  31400. class JUCE_API SamplerVoice : public SynthesiserVoice
  31401. {
  31402. public:
  31403. /** Creates a SamplerVoice.
  31404. */
  31405. SamplerVoice();
  31406. /** Destructor. */
  31407. ~SamplerVoice();
  31408. bool canPlaySound (SynthesiserSound* sound);
  31409. void startNote (const int midiNoteNumber,
  31410. const float velocity,
  31411. SynthesiserSound* sound,
  31412. const int currentPitchWheelPosition);
  31413. void stopNote (const bool allowTailOff);
  31414. void pitchWheelMoved (const int newValue);
  31415. void controllerMoved (const int controllerNumber,
  31416. const int newValue);
  31417. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  31418. juce_UseDebuggingNewOperator
  31419. private:
  31420. double pitchRatio;
  31421. double sourceSamplePosition;
  31422. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  31423. bool isInAttack, isInRelease;
  31424. };
  31425. #endif // __JUCE_SAMPLER_JUCEHEADER__
  31426. /*** End of inlined file: juce_Sampler.h ***/
  31427. #endif
  31428. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  31429. #endif
  31430. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31431. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  31432. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31433. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31434. /*** Start of inlined file: juce_ActionListenerList.h ***/
  31435. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31436. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31437. /**
  31438. A set of ActionListeners.
  31439. Listeners can be added and removed from the list, and messages can be
  31440. broadcast to all the listeners.
  31441. @see ActionListener, ActionBroadcaster
  31442. */
  31443. class JUCE_API ActionListenerList : public MessageListener
  31444. {
  31445. public:
  31446. /** Creates an empty list. */
  31447. ActionListenerList() throw();
  31448. /** Destructor. */
  31449. ~ActionListenerList() throw();
  31450. /** Adds a listener to the list.
  31451. (Trying to add a listener that's already on the list will have no effect).
  31452. */
  31453. void addActionListener (ActionListener* listener) throw();
  31454. /** Removes a listener from the list.
  31455. If the listener isn't on the list, this won't have any effect.
  31456. */
  31457. void removeActionListener (ActionListener* listener) throw();
  31458. /** Removes all listeners from the list. */
  31459. void removeAllActionListeners() throw();
  31460. /** Broadcasts a message to all the registered listeners.
  31461. This sends the message asynchronously.
  31462. If a listener is on the list when this method is called but is removed from
  31463. the list before the message arrives, it won't receive the message. Similarly
  31464. listeners that are added to the list after the message is sent but before it
  31465. arrives won't get the message either.
  31466. */
  31467. void sendActionMessage (const String& message) const;
  31468. /** @internal */
  31469. void handleMessage (const Message&);
  31470. juce_UseDebuggingNewOperator
  31471. private:
  31472. SortedSet <void*> actionListeners_;
  31473. CriticalSection actionListenerLock_;
  31474. ActionListenerList (const ActionListenerList&);
  31475. ActionListenerList& operator= (const ActionListenerList&);
  31476. };
  31477. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31478. /*** End of inlined file: juce_ActionListenerList.h ***/
  31479. /** Manages a list of ActionListeners, and can send them messages.
  31480. To quickly add methods to your class that can add/remove action
  31481. listeners and broadcast to them, you can derive from this.
  31482. @see ActionListenerList, ActionListener
  31483. */
  31484. class JUCE_API ActionBroadcaster
  31485. {
  31486. public:
  31487. /** Creates an ActionBroadcaster. */
  31488. ActionBroadcaster() throw();
  31489. /** Destructor. */
  31490. virtual ~ActionBroadcaster();
  31491. /** Adds a listener to the list.
  31492. (Trying to add a listener that's already on the list will have no effect).
  31493. */
  31494. void addActionListener (ActionListener* listener);
  31495. /** Removes a listener from the list.
  31496. If the listener isn't on the list, this won't have any effect.
  31497. */
  31498. void removeActionListener (ActionListener* listener);
  31499. /** Removes all listeners from the list. */
  31500. void removeAllActionListeners();
  31501. /** Broadcasts a message to all the registered listeners.
  31502. @see ActionListenerList::sendActionMessage
  31503. */
  31504. void sendActionMessage (const String& message) const;
  31505. private:
  31506. ActionListenerList actionListenerList;
  31507. ActionBroadcaster (const ActionBroadcaster&);
  31508. ActionBroadcaster& operator= (const ActionBroadcaster&);
  31509. };
  31510. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31511. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  31512. #endif
  31513. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  31514. #endif
  31515. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31516. #endif
  31517. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  31518. #endif
  31519. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31520. /*** Start of inlined file: juce_CallbackMessage.h ***/
  31521. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31522. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31523. /**
  31524. A message that calls a custom function when it gets delivered.
  31525. You can use this class to fire off actions that you want to be performed later
  31526. on the message thread.
  31527. Unlike other Message objects, these don't get sent to a MessageListener, you
  31528. just call the post() method to send them, and when they arrive, your
  31529. messageCallback() method will automatically be invoked.
  31530. @see MessageListener, MessageManager, ActionListener, ChangeListener
  31531. */
  31532. class JUCE_API CallbackMessage : public Message
  31533. {
  31534. public:
  31535. CallbackMessage() throw();
  31536. /** Destructor. */
  31537. ~CallbackMessage() throw();
  31538. /** Called when the message is delivered.
  31539. You should implement this method and make it do whatever action you want
  31540. to perform.
  31541. Note that like all other messages, this object will be deleted immediately
  31542. after this method has been invoked.
  31543. */
  31544. virtual void messageCallback() = 0;
  31545. /** Instead of sending this message to a MessageListener, just call this method
  31546. to post it to the event queue.
  31547. After you've called this, this object will belong to the MessageManager,
  31548. which will delete it later. So make sure you don't delete the object yourself,
  31549. call post() more than once, or call post() on a stack-based obect!
  31550. */
  31551. void post();
  31552. juce_UseDebuggingNewOperator
  31553. private:
  31554. CallbackMessage (const CallbackMessage&);
  31555. CallbackMessage& operator= (const CallbackMessage&);
  31556. };
  31557. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31558. /*** End of inlined file: juce_CallbackMessage.h ***/
  31559. #endif
  31560. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  31561. #endif
  31562. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  31563. #endif
  31564. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  31565. #endif
  31566. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31567. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  31568. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31569. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31570. class InterprocessConnectionServer;
  31571. /**
  31572. Manages a simple two-way messaging connection to another process, using either
  31573. a socket or a named pipe as the transport medium.
  31574. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  31575. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  31576. and incoming messages will result in a callback via the messageReceived()
  31577. method.
  31578. To open a pipe and wait for another client to connect to it, use the createPipe()
  31579. method.
  31580. To act as a socket server and create connections for one or more client, see the
  31581. InterprocessConnectionServer class.
  31582. @see InterprocessConnectionServer, Socket, NamedPipe
  31583. */
  31584. class JUCE_API InterprocessConnection : public Thread,
  31585. private MessageListener
  31586. {
  31587. public:
  31588. /** Creates a connection.
  31589. Connections are created manually, connecting them with the connectToSocket()
  31590. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  31591. when a client wants to connect.
  31592. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  31593. connectionLost() and messageReceived() methods will
  31594. always be made using the message thread; if false,
  31595. these will be called immediately on the connection's
  31596. own thread.
  31597. @param magicMessageHeaderNumber a magic number to use in the header to check the
  31598. validity of the data blocks being sent and received. This
  31599. can be any number, but the sender and receiver must obviously
  31600. use matching values or they won't recognise each other.
  31601. */
  31602. InterprocessConnection (bool callbacksOnMessageThread = true,
  31603. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  31604. /** Destructor. */
  31605. ~InterprocessConnection();
  31606. /** Tries to connect this object to a socket.
  31607. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  31608. object waiting to receive client connections on this port number.
  31609. @param hostName the host computer, either a network address or name
  31610. @param portNumber the socket port number to try to connect to
  31611. @param timeOutMillisecs how long to keep trying before giving up
  31612. @returns true if the connection is established successfully
  31613. @see Socket
  31614. */
  31615. bool connectToSocket (const String& hostName,
  31616. int portNumber,
  31617. int timeOutMillisecs);
  31618. /** Tries to connect the object to an existing named pipe.
  31619. For this to work, another process on the same computer must already have opened
  31620. an InterprocessConnection object and used createPipe() to create a pipe for this
  31621. to connect to.
  31622. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31623. @returns true if it connects successfully.
  31624. @see createPipe, NamedPipe
  31625. */
  31626. bool connectToPipe (const String& pipeName,
  31627. int pipeReceiveMessageTimeoutMs = -1);
  31628. /** Tries to create a new pipe for other processes to connect to.
  31629. This creates a pipe with the given name, so that other processes can use
  31630. connectToPipe() to connect to the other end.
  31631. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31632. If another process is already using this pipe, this will fail and return false.
  31633. */
  31634. bool createPipe (const String& pipeName,
  31635. int pipeReceiveMessageTimeoutMs = -1);
  31636. /** Disconnects and closes any currently-open sockets or pipes. */
  31637. void disconnect();
  31638. /** True if a socket or pipe is currently active. */
  31639. bool isConnected() const;
  31640. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  31641. StreamingSocket* getSocket() const throw() { return socket; }
  31642. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  31643. NamedPipe* getPipe() const throw() { return pipe; }
  31644. /** Returns the name of the machine at the other end of this connection.
  31645. This will return an empty string if the other machine isn't known for
  31646. some reason.
  31647. */
  31648. const String getConnectedHostName() const;
  31649. /** Tries to send a message to the other end of this connection.
  31650. This will fail if it's not connected, or if there's some kind of write error. If
  31651. it succeeds, the connection object at the other end will receive the message by
  31652. a callback to its messageReceived() method.
  31653. @see messageReceived
  31654. */
  31655. bool sendMessage (const MemoryBlock& message);
  31656. /** Called when the connection is first connected.
  31657. If the connection was created with the callbacksOnMessageThread flag set, then
  31658. this will be called on the message thread; otherwise it will be called on a server
  31659. thread.
  31660. */
  31661. virtual void connectionMade() = 0;
  31662. /** Called when the connection is broken.
  31663. If the connection was created with the callbacksOnMessageThread flag set, then
  31664. this will be called on the message thread; otherwise it will be called on a server
  31665. thread.
  31666. */
  31667. virtual void connectionLost() = 0;
  31668. /** Called when a message arrives.
  31669. When the object at the other end of this connection sends us a message with sendMessage(),
  31670. this callback is used to deliver it to us.
  31671. If the connection was created with the callbacksOnMessageThread flag set, then
  31672. this will be called on the message thread; otherwise it will be called on a server
  31673. thread.
  31674. @see sendMessage
  31675. */
  31676. virtual void messageReceived (const MemoryBlock& message) = 0;
  31677. juce_UseDebuggingNewOperator
  31678. private:
  31679. CriticalSection pipeAndSocketLock;
  31680. ScopedPointer <StreamingSocket> socket;
  31681. ScopedPointer <NamedPipe> pipe;
  31682. bool callbackConnectionState;
  31683. const bool useMessageThread;
  31684. const uint32 magicMessageHeader;
  31685. int pipeReceiveMessageTimeout;
  31686. friend class InterprocessConnectionServer;
  31687. void initialiseWithSocket (StreamingSocket* socket_);
  31688. void initialiseWithPipe (NamedPipe* pipe_);
  31689. void handleMessage (const Message& message);
  31690. void connectionMadeInt();
  31691. void connectionLostInt();
  31692. void deliverDataInt (const MemoryBlock& data);
  31693. bool readNextMessageInt();
  31694. void run();
  31695. InterprocessConnection (const InterprocessConnection&);
  31696. InterprocessConnection& operator= (const InterprocessConnection&);
  31697. };
  31698. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31699. /*** End of inlined file: juce_InterprocessConnection.h ***/
  31700. #endif
  31701. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31702. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  31703. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31704. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31705. /**
  31706. An object that waits for client sockets to connect to a port on this host, and
  31707. creates InterprocessConnection objects for each one.
  31708. To use this, create a class derived from it which implements the createConnectionObject()
  31709. method, so that it creates suitable connection objects for each client that tries
  31710. to connect.
  31711. @see InterprocessConnection
  31712. */
  31713. class JUCE_API InterprocessConnectionServer : private Thread
  31714. {
  31715. public:
  31716. /** Creates an uninitialised server object.
  31717. */
  31718. InterprocessConnectionServer();
  31719. /** Destructor. */
  31720. ~InterprocessConnectionServer();
  31721. /** Starts an internal thread which listens on the given port number.
  31722. While this is running, in another process tries to connect with the
  31723. InterprocessConnection::connectToSocket() method, this object will call
  31724. createConnectionObject() to create a connection to that client.
  31725. Use stop() to stop the thread running.
  31726. @see createConnectionObject, stop
  31727. */
  31728. bool beginWaitingForSocket (int portNumber);
  31729. /** Terminates the listener thread, if it's active.
  31730. @see beginWaitingForSocket
  31731. */
  31732. void stop();
  31733. protected:
  31734. /** Creates a suitable connection object for a client process that wants to
  31735. connect to this one.
  31736. This will be called by the listener thread when a client process tries
  31737. to connect, and must return a new InterprocessConnection object that will
  31738. then run as this end of the connection.
  31739. @see InterprocessConnection
  31740. */
  31741. virtual InterprocessConnection* createConnectionObject() = 0;
  31742. public:
  31743. juce_UseDebuggingNewOperator
  31744. private:
  31745. ScopedPointer <StreamingSocket> socket;
  31746. void run();
  31747. InterprocessConnectionServer (const InterprocessConnectionServer&);
  31748. InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  31749. };
  31750. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31751. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  31752. #endif
  31753. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  31754. #endif
  31755. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  31756. #endif
  31757. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  31758. #endif
  31759. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31760. /*** Start of inlined file: juce_MessageManager.h ***/
  31761. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31762. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31763. class Component;
  31764. class MessageManagerLock;
  31765. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  31766. */
  31767. typedef void* (MessageCallbackFunction) (void* userData);
  31768. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  31769. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  31770. */
  31771. class JUCE_API MessageManager
  31772. {
  31773. public:
  31774. /** Returns the global instance of the MessageManager. */
  31775. static MessageManager* getInstance() throw();
  31776. /** Runs the event dispatch loop until a stop message is posted.
  31777. This method is only intended to be run by the application's startup routine,
  31778. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  31779. @see stopDispatchLoop
  31780. */
  31781. void runDispatchLoop();
  31782. /** Sends a signal that the dispatch loop should terminate.
  31783. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  31784. will be interrupted and will return.
  31785. @see runDispatchLoop
  31786. */
  31787. void stopDispatchLoop();
  31788. /** Returns true if the stopDispatchLoop() method has been called.
  31789. */
  31790. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  31791. /** Synchronously dispatches messages until a given time has elapsed.
  31792. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  31793. otherwise returns true.
  31794. */
  31795. bool runDispatchLoopUntil (int millisecondsToRunFor);
  31796. /** Calls a function using the message-thread.
  31797. This can be used by any thread to cause this function to be called-back
  31798. by the message thread. If it's the message-thread that's calling this method,
  31799. then the function will just be called; if another thread is calling, a message
  31800. will be posted to the queue, and this method will block until that message
  31801. is delivered, the function is called, and the result is returned.
  31802. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  31803. thread has a critical section locked, which an unrelated message callback then tries to lock
  31804. before the message thread gets round to processing this callback.
  31805. @param callback the function to call - its signature must be @code
  31806. void* myCallbackFunction (void*) @endcode
  31807. @param userData a user-defined pointer that will be passed to the function that gets called
  31808. @returns the value that the callback function returns.
  31809. @see MessageManagerLock
  31810. */
  31811. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  31812. void* userData);
  31813. /** Returns true if the caller-thread is the message thread. */
  31814. bool isThisTheMessageThread() const throw();
  31815. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  31816. (Best to ignore this method unless you really know what you're doing..)
  31817. @see getCurrentMessageThread
  31818. */
  31819. void setCurrentThreadAsMessageThread();
  31820. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  31821. (Best to ignore this method unless you really know what you're doing..)
  31822. @see setCurrentMessageThread
  31823. */
  31824. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  31825. /** Returns true if the caller thread has currenltly got the message manager locked.
  31826. see the MessageManagerLock class for more info about this.
  31827. This will be true if the caller is the message thread, because that automatically
  31828. gains a lock while a message is being dispatched.
  31829. */
  31830. bool currentThreadHasLockedMessageManager() const throw();
  31831. /** Sends a message to all other JUCE applications that are running.
  31832. @param messageText the string that will be passed to the actionListenerCallback()
  31833. method of the broadcast listeners in the other app.
  31834. @see registerBroadcastListener, ActionListener
  31835. */
  31836. static void broadcastMessage (const String& messageText) throw();
  31837. /** Registers a listener to get told about broadcast messages.
  31838. The actionListenerCallback() callback's string parameter
  31839. is the message passed into broadcastMessage().
  31840. @see broadcastMessage
  31841. */
  31842. void registerBroadcastListener (ActionListener* listener) throw();
  31843. /** Deregisters a broadcast listener. */
  31844. void deregisterBroadcastListener (ActionListener* listener) throw();
  31845. /** @internal */
  31846. void deliverMessage (Message*);
  31847. /** @internal */
  31848. void deliverBroadcastMessage (const String&);
  31849. /** @internal */
  31850. ~MessageManager() throw();
  31851. juce_UseDebuggingNewOperator
  31852. private:
  31853. MessageManager() throw();
  31854. friend class MessageListener;
  31855. friend class ChangeBroadcaster;
  31856. friend class ActionBroadcaster;
  31857. friend class CallbackMessage;
  31858. static MessageManager* instance;
  31859. SortedSet <const MessageListener*> messageListeners;
  31860. ScopedPointer <ActionListenerList> broadcastListeners;
  31861. friend class JUCEApplication;
  31862. bool quitMessagePosted, quitMessageReceived;
  31863. Thread::ThreadID messageThreadId;
  31864. static void* exitModalLoopCallback (void*);
  31865. void postMessageToQueue (Message* message);
  31866. void postCallbackMessage (Message* message);
  31867. static void doPlatformSpecificInitialisation();
  31868. static void doPlatformSpecificShutdown();
  31869. friend class MessageManagerLock;
  31870. Thread::ThreadID volatile threadWithLock;
  31871. CriticalSection lockingLock;
  31872. MessageManager (const MessageManager&);
  31873. MessageManager& operator= (const MessageManager&);
  31874. };
  31875. /** Used to make sure that the calling thread has exclusive access to the message loop.
  31876. Because it's not thread-safe to call any of the Component or other UI classes
  31877. from threads other than the message thread, one of these objects can be used to
  31878. lock the message loop and allow this to be done. The message thread will be
  31879. suspended for the lifetime of the MessageManagerLock object, so create one on
  31880. the stack like this: @code
  31881. void MyThread::run()
  31882. {
  31883. someData = 1234;
  31884. const MessageManagerLock mmLock;
  31885. // the event loop will now be locked so it's safe to make a few calls..
  31886. myComponent->setBounds (newBounds);
  31887. myComponent->repaint();
  31888. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  31889. }
  31890. @endcode
  31891. Obviously be careful not to create one of these and leave it lying around, or
  31892. your app will grind to a halt!
  31893. Another caveat is that using this in conjunction with other CriticalSections
  31894. can create lots of interesting ways of producing a deadlock! In particular, if
  31895. your message thread calls stopThread() for a thread that uses these locks,
  31896. you'll get an (occasional) deadlock..
  31897. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  31898. */
  31899. class JUCE_API MessageManagerLock
  31900. {
  31901. public:
  31902. /** Tries to acquire a lock on the message manager.
  31903. The constructor attempts to gain a lock on the message loop, and the lock will be
  31904. kept for the lifetime of this object.
  31905. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  31906. this method will keep checking whether the thread has been given the
  31907. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  31908. without gaining the lock. If you pass a thread, you must check whether the lock was
  31909. successful by calling lockWasGained(). If this is false, your thread is being told to
  31910. die, so you should take evasive action.
  31911. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  31912. careful when doing this, because it's very easy to deadlock if your message thread
  31913. attempts to call stopThread() on a thread just as that thread attempts to get the
  31914. message lock.
  31915. If the calling thread already has the lock, nothing will be done, so it's safe and
  31916. quick to use these locks recursively.
  31917. E.g.
  31918. @code
  31919. void run()
  31920. {
  31921. ...
  31922. while (! threadShouldExit())
  31923. {
  31924. MessageManagerLock mml (Thread::getCurrentThread());
  31925. if (! mml.lockWasGained())
  31926. return; // another thread is trying to kill us!
  31927. ..do some locked stuff here..
  31928. }
  31929. ..and now the MM is now unlocked..
  31930. }
  31931. @endcode
  31932. */
  31933. MessageManagerLock (Thread* threadToCheckForExitSignal = 0) throw();
  31934. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  31935. instead of a thread.
  31936. See the MessageManagerLock (Thread*) constructor for details on how this works.
  31937. */
  31938. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal) throw();
  31939. /** Releases the current thread's lock on the message manager.
  31940. Make sure this object is created and deleted by the same thread,
  31941. otherwise there are no guarantees what will happen!
  31942. */
  31943. ~MessageManagerLock() throw();
  31944. /** Returns true if the lock was successfully acquired.
  31945. (See the constructor that takes a Thread for more info).
  31946. */
  31947. bool lockWasGained() const throw() { return locked; }
  31948. private:
  31949. class SharedEvents;
  31950. class BlockingMessage;
  31951. friend class SharedEvents;
  31952. friend class BlockingMessage;
  31953. SharedEvents* sharedEvents;
  31954. bool locked;
  31955. void init (Thread* thread, ThreadPoolJob* job) throw();
  31956. MessageManagerLock (const MessageManagerLock&);
  31957. MessageManagerLock& operator= (const MessageManagerLock&);
  31958. };
  31959. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31960. /*** End of inlined file: juce_MessageManager.h ***/
  31961. #endif
  31962. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31963. /*** Start of inlined file: juce_MultiTimer.h ***/
  31964. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31965. #define __JUCE_MULTITIMER_JUCEHEADER__
  31966. /**
  31967. A type of timer class that can run multiple timers with different frequencies,
  31968. all of which share a single callback.
  31969. This class is very similar to the Timer class, but allows you run multiple
  31970. separate timers, where each one has a unique ID number. The methods in this
  31971. class are exactly equivalent to those in Timer, but with the addition of
  31972. this ID number.
  31973. To use it, you need to create a subclass of MultiTimer, implementing the
  31974. timerCallback() method. Then you can start timers with startTimer(), and
  31975. each time the callback is triggered, it passes in the ID of the timer that
  31976. caused it.
  31977. @see Timer
  31978. */
  31979. class JUCE_API MultiTimer
  31980. {
  31981. protected:
  31982. /** Creates a MultiTimer.
  31983. When created, no timers are running, so use startTimer() to start things off.
  31984. */
  31985. MultiTimer() throw();
  31986. /** Creates a copy of another timer.
  31987. Note that this timer will not contain any running timers, even if the one you're
  31988. copying from was running.
  31989. */
  31990. MultiTimer (const MultiTimer& other) throw();
  31991. public:
  31992. /** Destructor. */
  31993. virtual ~MultiTimer();
  31994. /** The user-defined callback routine that actually gets called by each of the
  31995. timers that are running.
  31996. It's perfectly ok to call startTimer() or stopTimer() from within this
  31997. callback to change the subsequent intervals.
  31998. */
  31999. virtual void timerCallback (int timerId) = 0;
  32000. /** Starts a timer and sets the length of interval required.
  32001. If the timer is already started, this will reset it, so the
  32002. time between calling this method and the next timer callback
  32003. will not be less than the interval length passed in.
  32004. @param timerId a unique Id number that identifies the timer to
  32005. start. This is the id that will be passed back
  32006. to the timerCallback() method when this timer is
  32007. triggered
  32008. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  32009. rounded up to 1)
  32010. */
  32011. void startTimer (int timerId, int intervalInMilliseconds) throw();
  32012. /** Stops a timer.
  32013. If a timer has been started with the given ID number, it will be cancelled.
  32014. No more callbacks will be made for the specified timer after this method returns.
  32015. If this is called from a different thread, any callbacks that may
  32016. be currently executing may be allowed to finish before the method
  32017. returns.
  32018. */
  32019. void stopTimer (int timerId) throw();
  32020. /** Checks whether a timer has been started for a specified ID.
  32021. @returns true if a timer with the given ID is running.
  32022. */
  32023. bool isTimerRunning (int timerId) const throw();
  32024. /** Returns the interval for a specified timer ID.
  32025. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  32026. is running for the ID number specified.
  32027. */
  32028. int getTimerInterval (int timerId) const throw();
  32029. private:
  32030. class MultiTimerCallback;
  32031. CriticalSection timerListLock;
  32032. OwnedArray <MultiTimerCallback> timers;
  32033. MultiTimer& operator= (const MultiTimer&);
  32034. };
  32035. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  32036. /*** End of inlined file: juce_MultiTimer.h ***/
  32037. #endif
  32038. #ifndef __JUCE_TIMER_JUCEHEADER__
  32039. #endif
  32040. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  32041. /*** Start of inlined file: juce_ArrowButton.h ***/
  32042. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  32043. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  32044. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  32045. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32046. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32047. /**
  32048. An effect filter that adds a drop-shadow behind the image's content.
  32049. (This will only work on images/components that aren't opaque, of course).
  32050. When added to a component, this effect will draw a soft-edged
  32051. shadow based on what gets drawn inside it. The shadow will also
  32052. be applied to the component's children.
  32053. For speed, this doesn't use a proper gaussian blur, but cheats by
  32054. using a simple bilinear filter. If you need a really high-quality
  32055. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  32056. @see Component::setComponentEffect
  32057. */
  32058. class JUCE_API DropShadowEffect : public ImageEffectFilter
  32059. {
  32060. public:
  32061. /** Creates a default drop-shadow effect.
  32062. To customise the shadow's appearance, use the setShadowProperties()
  32063. method.
  32064. */
  32065. DropShadowEffect();
  32066. /** Destructor. */
  32067. ~DropShadowEffect();
  32068. /** Sets up parameters affecting the shadow's appearance.
  32069. @param newRadius the (approximate) radius of the blur used
  32070. @param newOpacity the opacity with which the shadow is rendered
  32071. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  32072. component's contents
  32073. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  32074. component's contents
  32075. */
  32076. void setShadowProperties (float newRadius,
  32077. float newOpacity,
  32078. int newShadowOffsetX,
  32079. int newShadowOffsetY);
  32080. /** @internal */
  32081. void applyEffect (Image& sourceImage, Graphics& destContext);
  32082. juce_UseDebuggingNewOperator
  32083. private:
  32084. int offsetX, offsetY;
  32085. float radius, opacity;
  32086. };
  32087. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32088. /*** End of inlined file: juce_DropShadowEffect.h ***/
  32089. /**
  32090. A button with an arrow in it.
  32091. @see Button
  32092. */
  32093. class JUCE_API ArrowButton : public Button
  32094. {
  32095. public:
  32096. /** Creates an ArrowButton.
  32097. @param buttonName the name to give the button
  32098. @param arrowDirection the direction the arrow should point in, where 0.0 is
  32099. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  32100. @param arrowColour the colour to use for the arrow
  32101. */
  32102. ArrowButton (const String& buttonName,
  32103. float arrowDirection,
  32104. const Colour& arrowColour);
  32105. /** Destructor. */
  32106. ~ArrowButton();
  32107. juce_UseDebuggingNewOperator
  32108. protected:
  32109. /** @internal */
  32110. void paintButton (Graphics& g,
  32111. bool isMouseOverButton,
  32112. bool isButtonDown);
  32113. /** @internal */
  32114. void buttonStateChanged();
  32115. private:
  32116. Colour colour;
  32117. DropShadowEffect shadow;
  32118. Path path;
  32119. int offset;
  32120. ArrowButton (const ArrowButton&);
  32121. ArrowButton& operator= (const ArrowButton&);
  32122. };
  32123. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  32124. /*** End of inlined file: juce_ArrowButton.h ***/
  32125. #endif
  32126. #ifndef __JUCE_BUTTON_JUCEHEADER__
  32127. #endif
  32128. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32129. /*** Start of inlined file: juce_DrawableButton.h ***/
  32130. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32131. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32132. /*** Start of inlined file: juce_Drawable.h ***/
  32133. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  32134. #define __JUCE_DRAWABLE_JUCEHEADER__
  32135. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  32136. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32137. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32138. /**
  32139. Expresses a coordinate as an absolute or proportional distance from other
  32140. named coordinates.
  32141. A RelativeCoordinate represents a position as either:
  32142. - an absolute distance from the origin
  32143. - an absolute distance from another named RelativeCoordinate
  32144. - a proportion of the distance between two other named RelativeCoordinates
  32145. Of course, the coordinates that this one is relative to may themselves be relative
  32146. to other coordinates, so complex arrangements can be built up (as long as you're careful
  32147. not to create recursive loops!)
  32148. Rather than keeping pointers to the coordinates that this one is dependent on, it
  32149. stores their names, and when resolving this coordinate to an absolute value, a
  32150. NamedCoordinateFinder class is required to retrieve these coordinates by name.
  32151. @see RelativePoint, RelativeRectangle
  32152. */
  32153. class JUCE_API RelativeCoordinate
  32154. {
  32155. public:
  32156. /** Creates a zero coordinate. */
  32157. RelativeCoordinate();
  32158. /** Creates an absolute position from the parent origin on either the X or Y axis.
  32159. @param absoluteDistanceFromOrigin the distance from the origin
  32160. */
  32161. RelativeCoordinate (double absoluteDistanceFromOrigin);
  32162. /** Creates an absolute position relative to a named coordinate.
  32163. @param absoluteDistanceFromAnchor the distance to add to the named anchor point
  32164. @param anchorPoint the name of the coordinate from which this one will be relative. See the constructor
  32165. notes for a description of the syntax for coordinate names.
  32166. */
  32167. RelativeCoordinate (double absoluteDistanceFromAnchor, const String& anchorPoint);
  32168. /** Creates a relative position between two named points.
  32169. @param relativeProportionBetweenAnchors a value between 0 and 1 indicating this coordinate's relative position
  32170. between anchorPoint1 and anchorPoint2.
  32171. @param anchorPoint1 the name of the first coordinate from which this one will be relative. See the constructor
  32172. notes for a description of the syntax for coordinate names.
  32173. @param anchorPoint2 the name of the first coordinate from which this one will be relative. See the constructor
  32174. notes for a description of the syntax for coordinate names.
  32175. */
  32176. RelativeCoordinate (double relativeProportionBetweenAnchors, const String& anchorPoint1, const String& anchorPoint2);
  32177. /** Recreates a coordinate from a string description.
  32178. The string can be in one of the following formats:
  32179. - "123" = 123 pixels from parent origin (this is equivalent to "parent.left + 123"
  32180. or "parent.top + 123", depending on which axis the coordinate is using)
  32181. - "anchor" = the same position as the coordinate named "anchor"
  32182. - "anchor + 123" = the coordinate named "anchor" + 123 pixels
  32183. - "anchor - 123" = the coordinate named "anchor" - 123 pixels
  32184. - "50%" = 50% of the distance between the coordinate space's top-left origin and its extent
  32185. (this is equivalent to "50% * parent.left -> parent.right" or "50% * parent.top -> parent.bottom")
  32186. - "50% * anchor" = 50% of the distance between the coordinate space's origin and the coordinate named "anchor"
  32187. (this is equivalent to "50% * parent.left -> anchor" or "50% * parent.top -> anchor")
  32188. - "50% * anchor1 -> anchor2" = 50% of the distance between the coordinate "anchor1" and the coordinate "anchor2"
  32189. An anchor name can either be just a single identifier (letters, digits and underscores only - no spaces),
  32190. e.g. "marker1", or it can be a two-part name in the form "objectName.edge". For example "parent.left" is
  32191. the origin, or "myComponent.top" is the top edge of a component called "myComponent". The exact names that
  32192. will be recognised are dependent on the NamedCoordinateFinder that you provide for looking them up, but
  32193. "parent.left" and "parent.top" are always available, meaning the origin. "parent.right" and "parent.bottom"
  32194. may also be available if the coordinate space has a fixed size.
  32195. @param stringVersion the string to parse
  32196. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  32197. @see toString
  32198. */
  32199. RelativeCoordinate (const String& stringVersion, bool isHorizontal);
  32200. /** Destructor. */
  32201. ~RelativeCoordinate();
  32202. bool operator== (const RelativeCoordinate& other) const throw();
  32203. bool operator!= (const RelativeCoordinate& other) const throw();
  32204. /**
  32205. Provides an interface for looking up the position of a named anchor when resolving a RelativeCoordinate.
  32206. When using RelativeCoordinates, to resolve their names you need to provide a subclass of this which
  32207. can retrieve a coordinate by name.
  32208. */
  32209. class JUCE_API NamedCoordinateFinder
  32210. {
  32211. public:
  32212. /** Destructor. */
  32213. virtual ~NamedCoordinateFinder() {}
  32214. /** Returns the coordinate for a given name.
  32215. The objectName parameter will be the first section of the name, and the edge the name of the second part.
  32216. E.g. for "parent.right", objectName would be "parent" and edge would be "right". If the name
  32217. has no dot, the edge parameter will be an empty string.
  32218. This method must be able to resolve "parent.left", "parent.top", "parent.right" and "parent.bottom", as
  32219. well as any other objects that your application uses.
  32220. */
  32221. virtual const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const = 0;
  32222. };
  32223. /** Calculates the absolute position of this coordinate.
  32224. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32225. be needed to calculate the result.
  32226. */
  32227. double resolve (const NamedCoordinateFinder* nameFinder) const;
  32228. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  32229. This will recursively check any coordinates upon which this one depends.
  32230. */
  32231. bool references (const String& coordName, const NamedCoordinateFinder* nameFinder) const;
  32232. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  32233. bool isRecursive (const NamedCoordinateFinder* nameFinder) const;
  32234. /** Returns true if this coordinate depends on any other coordinates for its position. */
  32235. bool isDynamic() const;
  32236. /** Changes the value of this coord to make it resolve to the specified position.
  32237. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  32238. or relative position to whatever value is necessary to make its resultant position
  32239. match the position that is provided.
  32240. */
  32241. void moveToAbsolute (double absoluteTargetPosition, const NamedCoordinateFinder* nameFinder);
  32242. /** Returns true if the coordinate is calculated as a proportion of the distance between two other points.
  32243. @see toggleProportionality
  32244. */
  32245. bool isProportional() const throw() { return anchor2.isNotEmpty(); }
  32246. /** Toggles the coordinate between using a proportional or absolute position.
  32247. Note that calling this will reset the names of any anchor points, and just make the
  32248. coordinate relative to the parent origin and parent size.
  32249. */
  32250. void toggleProportionality (const NamedCoordinateFinder* nameFinder,
  32251. const String& proportionalAnchor1, const String& proportionalAnchor2);
  32252. /** Returns a value that can be edited to set this coordinate's position.
  32253. The meaning of this number depends on the coordinate's mode. If the coordinate is
  32254. proportional, the number will be a percentage between 0 and 100. If the
  32255. coordinate is absolute, then it will be the number of pixels from its anchor point.
  32256. @see setEditableNumber
  32257. */
  32258. const double getEditableNumber() const;
  32259. /** Sets the value that controls this coordinate's position.
  32260. The meaning of this number depends on the coordinate's mode. If the coordinate is
  32261. proportional, the number must be a percentage between 0 and 100. If the
  32262. coordinate is absolute, then it indicates the number of pixels from its anchor point.
  32263. @see setEditableNumber
  32264. */
  32265. void setEditableNumber (const double newValue);
  32266. /** Returns the name of the first anchor point from which this coordinate is relative.
  32267. */
  32268. const String getAnchorName1 (const String& returnValueIfOrigin) const;
  32269. /** Returns the name of the second anchor point from which this coordinate is relative.
  32270. The second anchor is only valid if the coordinate is in proportional mode.
  32271. */
  32272. const String getAnchorName2 (const String& returnValueIfOrigin) const;
  32273. /** Returns the first anchor point as a coordinate. */
  32274. const RelativeCoordinate getAnchorCoordinate1() const;
  32275. /** Returns the first anchor point as a coordinate.
  32276. The second anchor is only valid if the coordinate is in proportional mode.
  32277. */
  32278. const RelativeCoordinate getAnchorCoordinate2() const;
  32279. /** Changes the first anchor point, keeping the resultant position of this coordinate in
  32280. the same place it was previously.
  32281. */
  32282. void changeAnchor1 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  32283. /** Changes the second anchor point, keeping the resultant position of this coordinate in
  32284. the same place it was previously.
  32285. */
  32286. void changeAnchor2 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  32287. /** Tells the coordinate that an object is changing its name or being deleted.
  32288. If either of this coordinates anchor points match this name, they will be replaced.
  32289. If the newName string is empty, it indicates that the object is being removed, so if
  32290. this coordinate was using it, the coordinate is changed to be relative to the origin
  32291. instead.
  32292. */
  32293. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32294. const NamedCoordinateFinder* nameFinder);
  32295. /** Returns a string which represents this coordinate.
  32296. For details of the string syntax, see the constructor notes.
  32297. */
  32298. const String toString() const;
  32299. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  32300. As well as avoiding using string literals in your code, using these preset values
  32301. has the advantage that all instances of the same string will share the same, reference-counted
  32302. String object, so if you have thousands of points which all refer to the same
  32303. anchor points, this can save a significant amount of memory allocation.
  32304. */
  32305. struct Strings
  32306. {
  32307. static const String parent; /**< "parent" */
  32308. static const String left; /**< "left" */
  32309. static const String right; /**< "right" */
  32310. static const String top; /**< "top" */
  32311. static const String bottom; /**< "bottom" */
  32312. static const String parentLeft; /**< "parent.left" */
  32313. static const String parentTop; /**< "parent.top" */
  32314. static const String parentRight; /**< "parent.right" */
  32315. static const String parentBottom; /**< "parent.bottom" */
  32316. };
  32317. private:
  32318. String anchor1, anchor2;
  32319. double value;
  32320. double resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const;
  32321. static double resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter);
  32322. };
  32323. /**
  32324. An X-Y position stored as a pair of RelativeCoordinate values.
  32325. @see RelativeCoordinate, RelativeRectangle
  32326. */
  32327. class JUCE_API RelativePoint
  32328. {
  32329. public:
  32330. /** Creates a point at the origin. */
  32331. RelativePoint();
  32332. /** Creates an absolute point, relative to the origin. */
  32333. RelativePoint (const Point<float>& absolutePoint);
  32334. /** Creates an absolute point, relative to the origin. */
  32335. RelativePoint (float absoluteX, float absoluteY);
  32336. /** Creates an absolute point from two coordinates. */
  32337. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  32338. /** Creates a point from a stringified representation.
  32339. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  32340. strings is explained in the RelativeCoordinate class.
  32341. @see toString
  32342. */
  32343. RelativePoint (const String& stringVersion);
  32344. bool operator== (const RelativePoint& other) const throw();
  32345. bool operator!= (const RelativePoint& other) const throw();
  32346. /** Calculates the absolute position of this point.
  32347. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32348. be needed to calculate the result.
  32349. */
  32350. const Point<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  32351. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  32352. Calling this will leave any anchor points unchanged, but will set any absolute
  32353. or relative positions to whatever values are necessary to make the resultant position
  32354. match the position that is provided.
  32355. */
  32356. void moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32357. /** Returns a string which represents this point.
  32358. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  32359. coordinates, see the RelativeCoordinate constructor notes.
  32360. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  32361. */
  32362. const String toString() const;
  32363. /** Tells the point that an object is changing its name or being deleted.
  32364. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  32365. */
  32366. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32367. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32368. /** Returns true if this point depends on any other coordinates for its position. */
  32369. bool isDynamic() const;
  32370. // The actual X and Y coords...
  32371. RelativeCoordinate x, y;
  32372. };
  32373. /**
  32374. An rectangle stored as a set of RelativeCoordinate values.
  32375. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  32376. @see RelativeCoordinate, RelativePoint
  32377. */
  32378. class JUCE_API RelativeRectangle
  32379. {
  32380. public:
  32381. /** Creates a zero-size rectangle at the origin. */
  32382. RelativeRectangle();
  32383. /** Creates an absolute rectangle, relative to the origin. */
  32384. explicit RelativeRectangle (const Rectangle<float>& rect, const String& componentName);
  32385. /** Creates a rectangle from four coordinates. */
  32386. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  32387. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  32388. /** Creates a rectangle from a stringified representation.
  32389. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  32390. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  32391. RelativeCoordinate class.
  32392. @see toString
  32393. */
  32394. explicit RelativeRectangle (const String& stringVersion);
  32395. bool operator== (const RelativeRectangle& other) const throw();
  32396. bool operator!= (const RelativeRectangle& other) const throw();
  32397. /** Calculates the absolute position of this rectangle.
  32398. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32399. be needed to calculate the result.
  32400. */
  32401. const Rectangle<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  32402. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  32403. Calling this will leave any anchor points unchanged, but will set any absolute
  32404. or relative positions to whatever values are necessary to make the resultant position
  32405. match the position that is provided.
  32406. */
  32407. void moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32408. /** Returns a string which represents this point.
  32409. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  32410. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  32411. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  32412. */
  32413. const String toString() const;
  32414. /** Tells the rectangle that an object is changing its name or being deleted.
  32415. This calls RelativeCoordinate::renameAnchorIfUsed() on the rectangle's coordinates.
  32416. */
  32417. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32418. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32419. // The actual rectangle coords...
  32420. RelativeCoordinate left, right, top, bottom;
  32421. };
  32422. /**
  32423. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  32424. One of these paths can be converted into a Path object for drawing and manipulation, but
  32425. unlike a Path, its points can be dynamic instead of just fixed.
  32426. @see RelativePoint, RelativeCoordinate
  32427. */
  32428. class JUCE_API RelativePointPath
  32429. {
  32430. public:
  32431. RelativePointPath();
  32432. RelativePointPath (const RelativePointPath& other);
  32433. RelativePointPath (const ValueTree& drawable);
  32434. RelativePointPath (const Path& path);
  32435. ~RelativePointPath();
  32436. /** Resolves this points in this path and adds them to a normal Path object. */
  32437. void createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32438. /** Returns true if the path contains any non-fixed points. */
  32439. bool containsAnyDynamicPoints() const;
  32440. /** Writes the path to this drawable encoding. */
  32441. void writeTo (ValueTree state, UndoManager* undoManager) const;
  32442. /** Quickly swaps the contents of this path with another. */
  32443. void swapWith (RelativePointPath& other) throw();
  32444. /** The types of element that may be contained in this path.
  32445. @see RelativePointPath::ElementBase
  32446. */
  32447. enum ElementType
  32448. {
  32449. nullElement,
  32450. startSubPathElement,
  32451. closeSubPathElement,
  32452. lineToElement,
  32453. quadraticToElement,
  32454. cubicToElement
  32455. };
  32456. /** Base class for the elements that make up a RelativePointPath.
  32457. */
  32458. class JUCE_API ElementBase
  32459. {
  32460. public:
  32461. ElementBase (ElementType type);
  32462. virtual ~ElementBase() {}
  32463. virtual const ValueTree createTree() const = 0;
  32464. virtual void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const = 0;
  32465. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  32466. const ElementType type;
  32467. private:
  32468. ElementBase (const ElementBase&);
  32469. ElementBase& operator= (const ElementBase&);
  32470. };
  32471. class JUCE_API StartSubPath : public ElementBase
  32472. {
  32473. public:
  32474. StartSubPath (const RelativePoint& pos);
  32475. ~StartSubPath() {}
  32476. const ValueTree createTree() const;
  32477. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32478. RelativePoint* getControlPoints (int& numPoints);
  32479. RelativePoint startPos;
  32480. private:
  32481. StartSubPath (const StartSubPath&);
  32482. StartSubPath& operator= (const StartSubPath&);
  32483. };
  32484. class JUCE_API CloseSubPath : public ElementBase
  32485. {
  32486. public:
  32487. CloseSubPath();
  32488. ~CloseSubPath() {}
  32489. const ValueTree createTree() const;
  32490. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32491. RelativePoint* getControlPoints (int& numPoints);
  32492. private:
  32493. CloseSubPath (const CloseSubPath&);
  32494. CloseSubPath& operator= (const CloseSubPath&);
  32495. };
  32496. class JUCE_API LineTo : public ElementBase
  32497. {
  32498. public:
  32499. LineTo (const RelativePoint& endPoint);
  32500. ~LineTo() {}
  32501. const ValueTree createTree() const;
  32502. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32503. RelativePoint* getControlPoints (int& numPoints);
  32504. RelativePoint endPoint;
  32505. private:
  32506. LineTo (const LineTo&);
  32507. LineTo& operator= (const LineTo&);
  32508. };
  32509. class JUCE_API QuadraticTo : public ElementBase
  32510. {
  32511. public:
  32512. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  32513. ~QuadraticTo() {}
  32514. const ValueTree createTree() const;
  32515. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32516. RelativePoint* getControlPoints (int& numPoints);
  32517. RelativePoint controlPoints[2];
  32518. private:
  32519. QuadraticTo (const QuadraticTo&);
  32520. QuadraticTo& operator= (const QuadraticTo&);
  32521. };
  32522. class JUCE_API CubicTo : public ElementBase
  32523. {
  32524. public:
  32525. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  32526. ~CubicTo() {}
  32527. const ValueTree createTree() const;
  32528. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32529. RelativePoint* getControlPoints (int& numPoints);
  32530. RelativePoint controlPoints[3];
  32531. private:
  32532. CubicTo (const CubicTo&);
  32533. CubicTo& operator= (const CubicTo&);
  32534. };
  32535. OwnedArray <ElementBase> elements;
  32536. bool usesNonZeroWinding;
  32537. private:
  32538. bool containsDynamicPoints;
  32539. void parse (const ValueTree& state);
  32540. RelativePointPath& operator= (const RelativePointPath&);
  32541. };
  32542. /**
  32543. A parallelogram defined by three RelativePoint positions.
  32544. @see RelativePoint, RelativeCoordinate
  32545. */
  32546. class JUCE_API RelativeParallelogram
  32547. {
  32548. public:
  32549. RelativeParallelogram();
  32550. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  32551. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  32552. ~RelativeParallelogram();
  32553. void resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32554. void resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32555. const Rectangle<float> getBounds (RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32556. void getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32557. const AffineTransform resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32558. bool operator== (const RelativeParallelogram& other) const throw();
  32559. bool operator!= (const RelativeParallelogram& other) const throw();
  32560. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  32561. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  32562. RelativePoint topLeft, topRight, bottomLeft;
  32563. };
  32564. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32565. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  32566. class DrawableComposite;
  32567. /**
  32568. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  32569. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32570. */
  32571. class JUCE_API Drawable
  32572. {
  32573. protected:
  32574. /** The base class can't be instantiated directly.
  32575. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32576. */
  32577. Drawable();
  32578. public:
  32579. /** Destructor. */
  32580. virtual ~Drawable();
  32581. /** Creates a deep copy of this Drawable object.
  32582. Use this to create a new copy of this and any sub-objects in the tree.
  32583. */
  32584. virtual Drawable* createCopy() const = 0;
  32585. /** Renders this Drawable object.
  32586. @see drawWithin
  32587. */
  32588. void draw (Graphics& g, float opacity,
  32589. const AffineTransform& transform = AffineTransform::identity) const;
  32590. /** Renders the Drawable at a given offset within the Graphics context.
  32591. The co-ordinates passed-in are used to translate the object relative to its own
  32592. origin before drawing it - this is basically a quick way of saying:
  32593. @code
  32594. draw (g, AffineTransform::translation (x, y)).
  32595. @endcode
  32596. */
  32597. void drawAt (Graphics& g,
  32598. float x, float y,
  32599. float opacity) const;
  32600. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  32601. changing its aspect-ratio.
  32602. The object can placed arbitrarily within the rectangle based on a Justification type,
  32603. and can either be made as big as possible, or just reduced to fit.
  32604. @param g the graphics context to render onto
  32605. @param destX top-left of the target rectangle to fit it into
  32606. @param destY top-left of the target rectangle to fit it into
  32607. @param destWidth size of the target rectangle to fit the image into
  32608. @param destHeight size of the target rectangle to fit the image into
  32609. @param placement defines the alignment and rescaling to use to fit
  32610. this object within the target rectangle.
  32611. @param opacity the opacity to use, in the range 0 to 1.0
  32612. */
  32613. void drawWithin (Graphics& g,
  32614. int destX,
  32615. int destY,
  32616. int destWidth,
  32617. int destHeight,
  32618. const RectanglePlacement& placement,
  32619. float opacity) const;
  32620. /** Holds the information needed when telling a drawable to render itself.
  32621. @see Drawable::draw
  32622. */
  32623. class RenderingContext
  32624. {
  32625. public:
  32626. RenderingContext (Graphics& g, const AffineTransform& transform, float opacity) throw();
  32627. Graphics& g;
  32628. AffineTransform transform;
  32629. float opacity;
  32630. private:
  32631. RenderingContext& operator= (const RenderingContext&);
  32632. };
  32633. /** Renders this Drawable object.
  32634. @see draw
  32635. */
  32636. virtual void render (const RenderingContext& context) const = 0;
  32637. /** Returns the smallest rectangle that can contain this Drawable object.
  32638. Co-ordinates are relative to the object's own origin.
  32639. */
  32640. virtual const Rectangle<float> getBounds() const = 0;
  32641. /** Returns true if the given point is somewhere inside this Drawable.
  32642. Co-ordinates are relative to the object's own origin.
  32643. */
  32644. virtual bool hitTest (float x, float y) const = 0;
  32645. /** Returns the name given to this drawable.
  32646. @see setName
  32647. */
  32648. const String& getName() const throw() { return name; }
  32649. /** Assigns a name to this drawable. */
  32650. void setName (const String& newName) throw() { name = newName; }
  32651. /** Returns the DrawableComposite that contains this object, if there is one. */
  32652. DrawableComposite* getParent() const throw() { return parent; }
  32653. /** Tries to turn some kind of image file into a drawable.
  32654. The data could be an image that the ImageFileFormat class understands, or it
  32655. could be SVG.
  32656. */
  32657. static Drawable* createFromImageData (const void* data, size_t numBytes);
  32658. /** Tries to turn a stream containing some kind of image data into a drawable.
  32659. The data could be an image that the ImageFileFormat class understands, or it
  32660. could be SVG.
  32661. */
  32662. static Drawable* createFromImageDataStream (InputStream& dataSource);
  32663. /** Tries to turn a file containing some kind of image data into a drawable.
  32664. The data could be an image that the ImageFileFormat class understands, or it
  32665. could be SVG.
  32666. */
  32667. static Drawable* createFromImageFile (const File& file);
  32668. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  32669. into a Drawable tree.
  32670. The object returned must be deleted by the caller. If something goes wrong
  32671. while parsing, it may return 0.
  32672. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  32673. implementation, but it can return the basic vector objects.
  32674. */
  32675. static Drawable* createFromSVG (const XmlElement& svgDocument);
  32676. /** This class is used when loading Drawables that contain images, and retrieves
  32677. the image for a stored identifier.
  32678. @see Drawable::createFromValueTree
  32679. */
  32680. class JUCE_API ImageProvider
  32681. {
  32682. public:
  32683. ImageProvider() {}
  32684. virtual ~ImageProvider() {}
  32685. /** Retrieves the image associated with this identifier, which could be any
  32686. kind of string, number, filename, etc.
  32687. The image that is returned will be owned by the caller, but it may come
  32688. from the ImageCache.
  32689. */
  32690. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  32691. /** Returns an identifier to be used to refer to a given image.
  32692. This is used when converting a drawable into a ValueTree, so if you're
  32693. only loading drawables, you can just return a var::null here.
  32694. */
  32695. virtual const var getIdentifierForImage (const Image& image) = 0;
  32696. };
  32697. /** Tries to create a Drawable from a previously-saved ValueTree.
  32698. The ValueTree must have been created by the createValueTree() method.
  32699. If there are any images used within the drawable, you'll need to provide a valid
  32700. ImageProvider object that can be used to retrieve these images from whatever type
  32701. of identifier is used to represent them.
  32702. */
  32703. static Drawable* createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  32704. /** Tries to refresh a Drawable from the same ValueTree that was used to create it.
  32705. @returns the damage rectangle that will need repainting due to any changes that were made.
  32706. */
  32707. virtual const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider) = 0;
  32708. /** Creates a ValueTree to represent this Drawable.
  32709. The VarTree that is returned can be turned back into a Drawable with
  32710. createFromValueTree().
  32711. If there are any images used in this drawable, you'll need to provide a valid
  32712. ImageProvider object that can be used to create storable representations of them.
  32713. */
  32714. virtual const ValueTree createValueTree (ImageProvider* imageProvider) const = 0;
  32715. /** Returns the tag ID that is used for a ValueTree that stores this type of drawable. */
  32716. virtual const Identifier getValueTreeType() const = 0;
  32717. /** Internal class used to manage ValueTrees that represent Drawables. */
  32718. class ValueTreeWrapperBase
  32719. {
  32720. public:
  32721. ValueTreeWrapperBase (const ValueTree& state);
  32722. ~ValueTreeWrapperBase();
  32723. ValueTree& getState() throw() { return state; }
  32724. const String getID() const;
  32725. void setID (const String& newID, UndoManager* undoManager);
  32726. static const Identifier idProperty;
  32727. static const FillType readFillType (const ValueTree& v, RelativePoint* gradientPoint1,
  32728. RelativePoint* gradientPoint2, RelativePoint* gradientPoint3,
  32729. RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  32730. ImageProvider* imageProvider);
  32731. static void writeFillType (ValueTree& v, const FillType& fillType,
  32732. const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  32733. const RelativePoint* gradientPoint3, ImageProvider* imageProvider,
  32734. UndoManager* undoManager);
  32735. ValueTree state;
  32736. static const Identifier type, gradientPoint1, gradientPoint2, gradientPoint3,
  32737. colour, radial, colours, imageId, imageOpacity;
  32738. };
  32739. juce_UseDebuggingNewOperator
  32740. protected:
  32741. friend class DrawableComposite;
  32742. DrawableComposite* parent;
  32743. virtual void invalidatePoints() = 0;
  32744. static Drawable* createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider);
  32745. private:
  32746. String name;
  32747. Drawable (const Drawable&);
  32748. Drawable& operator= (const Drawable&);
  32749. };
  32750. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  32751. /*** End of inlined file: juce_Drawable.h ***/
  32752. /**
  32753. A button that displays a Drawable.
  32754. Up to three Drawable objects can be given to this button, to represent the
  32755. 'normal', 'over' and 'down' states.
  32756. @see Button
  32757. */
  32758. class JUCE_API DrawableButton : public Button
  32759. {
  32760. public:
  32761. enum ButtonStyle
  32762. {
  32763. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  32764. ImageRaw, /**< The button will just display the images in their normal size and position.
  32765. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  32766. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  32767. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  32768. };
  32769. /** Creates a DrawableButton.
  32770. After creating one of these, use setImages() to specify the drawables to use.
  32771. @param buttonName the name to give the component
  32772. @param buttonStyle the layout to use
  32773. @see ButtonStyle, setButtonStyle, setImages
  32774. */
  32775. DrawableButton (const String& buttonName,
  32776. ButtonStyle buttonStyle);
  32777. /** Destructor. */
  32778. ~DrawableButton();
  32779. /** Sets up the images to draw for the various button states.
  32780. The button will keep its own internal copies of these drawables.
  32781. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  32782. will be made of the object passed-in if it is non-zero.
  32783. @param overImage the thing to draw for the button's 'over' state - if this is
  32784. zero, the button's normal image will be used when the mouse is
  32785. over it. An internal copy will be made of the object passed-in
  32786. if it is non-zero.
  32787. @param downImage the thing to draw for the button's 'down' state - if this is
  32788. zero, the 'over' image will be used instead (or the normal image
  32789. as a last resort). An internal copy will be made of the object
  32790. passed-in if it is non-zero.
  32791. @param disabledImage an image to draw when the button is disabled. If this is zero,
  32792. the normal image will be drawn with a reduced opacity instead.
  32793. An internal copy will be made of the object passed-in if it is
  32794. non-zero.
  32795. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  32796. state is 'on'. If this is 0, the normal image is used instead
  32797. @param overImageOn same as the overImage, but this is used when the button's toggle
  32798. state is 'on'. If this is 0, the normalImageOn is drawn instead
  32799. @param downImageOn same as the downImage, but this is used when the button's toggle
  32800. state is 'on'. If this is 0, the overImageOn is drawn instead
  32801. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  32802. state is 'on'. If this is 0, the normal image will be drawn instead
  32803. with a reduced opacity
  32804. */
  32805. void setImages (const Drawable* normalImage,
  32806. const Drawable* overImage = 0,
  32807. const Drawable* downImage = 0,
  32808. const Drawable* disabledImage = 0,
  32809. const Drawable* normalImageOn = 0,
  32810. const Drawable* overImageOn = 0,
  32811. const Drawable* downImageOn = 0,
  32812. const Drawable* disabledImageOn = 0);
  32813. /** Changes the button's style.
  32814. @see ButtonStyle
  32815. */
  32816. void setButtonStyle (ButtonStyle newStyle);
  32817. /** Changes the button's background colours.
  32818. The toggledOffColour is the colour to use when the button's toggle state
  32819. is off, and toggledOnColour when it's on.
  32820. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  32821. used to fill the background of the component.
  32822. For an ImageOnButtonBackground style, the colour is used to draw the
  32823. button's lozenge shape and exactly how the colour's used will depend
  32824. on the LookAndFeel.
  32825. */
  32826. void setBackgroundColours (const Colour& toggledOffColour,
  32827. const Colour& toggledOnColour);
  32828. /** Returns the current background colour being used.
  32829. @see setBackgroundColour
  32830. */
  32831. const Colour& getBackgroundColour() const throw();
  32832. /** Gives the button an optional amount of space around the edge of the drawable.
  32833. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  32834. ones on a button background. If the button is too small for the given gap, a
  32835. smaller gap will be used.
  32836. By default there's a gap of about 3 pixels.
  32837. */
  32838. void setEdgeIndent (int numPixelsIndent);
  32839. /** Returns the image that the button is currently displaying. */
  32840. const Drawable* getCurrentImage() const throw();
  32841. const Drawable* getNormalImage() const throw();
  32842. const Drawable* getOverImage() const throw();
  32843. const Drawable* getDownImage() const throw();
  32844. juce_UseDebuggingNewOperator
  32845. protected:
  32846. /** @internal */
  32847. void paintButton (Graphics& g,
  32848. bool isMouseOverButton,
  32849. bool isButtonDown);
  32850. private:
  32851. ButtonStyle style;
  32852. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  32853. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  32854. Colour backgroundOff, backgroundOn;
  32855. int edgeIndent;
  32856. void deleteImages();
  32857. DrawableButton (const DrawableButton&);
  32858. DrawableButton& operator= (const DrawableButton&);
  32859. };
  32860. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32861. /*** End of inlined file: juce_DrawableButton.h ***/
  32862. #endif
  32863. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32864. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  32865. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32866. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32867. /**
  32868. A button showing an underlined weblink, that will launch the link
  32869. when it's clicked.
  32870. @see Button
  32871. */
  32872. class JUCE_API HyperlinkButton : public Button
  32873. {
  32874. public:
  32875. /** Creates a HyperlinkButton.
  32876. @param linkText the text that will be displayed in the button - this is
  32877. also set as the Component's name, but the text can be
  32878. changed later with the Button::getButtonText() method
  32879. @param linkURL the URL to launch when the user clicks the button
  32880. */
  32881. HyperlinkButton (const String& linkText,
  32882. const URL& linkURL);
  32883. /** Destructor. */
  32884. ~HyperlinkButton();
  32885. /** Changes the font to use for the text.
  32886. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  32887. to match the size of the component.
  32888. */
  32889. void setFont (const Font& newFont,
  32890. bool resizeToMatchComponentHeight,
  32891. const Justification& justificationType = Justification::horizontallyCentred);
  32892. /** A set of colour IDs to use to change the colour of various aspects of the link.
  32893. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32894. methods.
  32895. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32896. */
  32897. enum ColourIds
  32898. {
  32899. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  32900. };
  32901. /** Changes the URL that the button will trigger. */
  32902. void setURL (const URL& newURL) throw();
  32903. /** Returns the URL that the button will trigger. */
  32904. const URL& getURL() const throw() { return url; }
  32905. /** Resizes the button horizontally to fit snugly around the text.
  32906. This won't affect the button's height.
  32907. */
  32908. void changeWidthToFitText();
  32909. juce_UseDebuggingNewOperator
  32910. protected:
  32911. /** @internal */
  32912. void clicked();
  32913. /** @internal */
  32914. void colourChanged();
  32915. /** @internal */
  32916. void paintButton (Graphics& g,
  32917. bool isMouseOverButton,
  32918. bool isButtonDown);
  32919. private:
  32920. URL url;
  32921. Font font;
  32922. bool resizeFont;
  32923. Justification justification;
  32924. const Font getFontToUse() const;
  32925. HyperlinkButton (const HyperlinkButton&);
  32926. HyperlinkButton& operator= (const HyperlinkButton&);
  32927. };
  32928. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32929. /*** End of inlined file: juce_HyperlinkButton.h ***/
  32930. #endif
  32931. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32932. /*** Start of inlined file: juce_ImageButton.h ***/
  32933. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32934. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  32935. /**
  32936. As the title suggests, this is a button containing an image.
  32937. The colour and transparency of the image can be set to vary when the
  32938. button state changes.
  32939. @see Button, ShapeButton, TextButton
  32940. */
  32941. class JUCE_API ImageButton : public Button
  32942. {
  32943. public:
  32944. /** Creates an ImageButton.
  32945. Use setImage() to specify the image to use. The colours and opacities that
  32946. are specified here can be changed later using setDrawingOptions().
  32947. @param name the name to give the component
  32948. */
  32949. explicit ImageButton (const String& name);
  32950. /** Destructor. */
  32951. ~ImageButton();
  32952. /** Sets up the images to draw in various states.
  32953. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  32954. resized to the same dimensions as the normal image
  32955. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  32956. button when the button's size changes
  32957. @param preserveImageProportions if true then any rescaling of the image to fit
  32958. the button will keep the image's x and y proportions
  32959. correct - i.e. it won't distort its shape, although
  32960. this might create gaps around the edges
  32961. @param normalImage the image to use when the button is in its normal state.
  32962. button no longer needs it.
  32963. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  32964. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  32965. normal image - if this colour is transparent, no overlay
  32966. will be drawn. The overlay will be drawn over the top of the
  32967. image, so you can basically add a solid or semi-transparent
  32968. colour to the image to brighten or darken it
  32969. @param overImage the image to use when the mouse is over the button. If
  32970. you want to use the same image as was set in the normalImage
  32971. parameter, this value can be a null image.
  32972. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  32973. is over the button
  32974. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  32975. image when the mouse is over - if this colour is transparent,
  32976. no overlay will be drawn
  32977. @param downImage an image to use when the button is pressed down. If set
  32978. to a null image, the 'over' image will be drawn instead (or the
  32979. normal image if there isn't an 'over' image either).
  32980. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  32981. is pressed
  32982. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  32983. image when the button is pressed down - if this colour is
  32984. transparent, no overlay will be drawn
  32985. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  32986. whenever it's inside the button's bounding rectangle. If
  32987. set to values higher than 0, the mouse will only be
  32988. considered to be over the image when the value of the
  32989. image's alpha channel at that position is greater than
  32990. this level.
  32991. */
  32992. void setImages (bool resizeButtonNowToFitThisImage,
  32993. bool rescaleImagesWhenButtonSizeChanges,
  32994. bool preserveImageProportions,
  32995. const Image& normalImage,
  32996. float imageOpacityWhenNormal,
  32997. const Colour& overlayColourWhenNormal,
  32998. const Image& overImage,
  32999. float imageOpacityWhenOver,
  33000. const Colour& overlayColourWhenOver,
  33001. const Image& downImage,
  33002. float imageOpacityWhenDown,
  33003. const Colour& overlayColourWhenDown,
  33004. float hitTestAlphaThreshold = 0.0f);
  33005. /** Returns the currently set 'normal' image. */
  33006. const Image getNormalImage() const;
  33007. /** Returns the image that's drawn when the mouse is over the button.
  33008. If a valid 'over' image has been set, this will return it; otherwise it'll
  33009. just return the normal image.
  33010. */
  33011. const Image getOverImage() const;
  33012. /** Returns the image that's drawn when the button is held down.
  33013. If a valid 'down' image has been set, this will return it; otherwise it'll
  33014. return the 'over' image or normal image, depending on what's available.
  33015. */
  33016. const Image getDownImage() const;
  33017. juce_UseDebuggingNewOperator
  33018. protected:
  33019. /** @internal */
  33020. bool hitTest (int x, int y);
  33021. /** @internal */
  33022. void paintButton (Graphics& g,
  33023. bool isMouseOverButton,
  33024. bool isButtonDown);
  33025. private:
  33026. bool scaleImageToFit, preserveProportions;
  33027. unsigned char alphaThreshold;
  33028. int imageX, imageY, imageW, imageH;
  33029. Image normalImage, overImage, downImage;
  33030. float normalOpacity, overOpacity, downOpacity;
  33031. Colour normalOverlay, overOverlay, downOverlay;
  33032. const Image getCurrentImage() const;
  33033. ImageButton (const ImageButton&);
  33034. ImageButton& operator= (const ImageButton&);
  33035. };
  33036. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  33037. /*** End of inlined file: juce_ImageButton.h ***/
  33038. #endif
  33039. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  33040. /*** Start of inlined file: juce_ShapeButton.h ***/
  33041. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  33042. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  33043. /**
  33044. A button that contains a filled shape.
  33045. @see Button, ImageButton, TextButton, ArrowButton
  33046. */
  33047. class JUCE_API ShapeButton : public Button
  33048. {
  33049. public:
  33050. /** Creates a ShapeButton.
  33051. @param name a name to give the component - see Component::setName()
  33052. @param normalColour the colour to fill the shape with when the mouse isn't over
  33053. @param overColour the colour to use when the mouse is over the shape
  33054. @param downColour the colour to use when the button is in the pressed-down state
  33055. */
  33056. ShapeButton (const String& name,
  33057. const Colour& normalColour,
  33058. const Colour& overColour,
  33059. const Colour& downColour);
  33060. /** Destructor. */
  33061. ~ShapeButton();
  33062. /** Sets the shape to use.
  33063. @param newShape the shape to use
  33064. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  33065. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  33066. the button is resized
  33067. @param hasDropShadow if true, the button will be given a drop-shadow effect
  33068. */
  33069. void setShape (const Path& newShape,
  33070. bool resizeNowToFitThisShape,
  33071. bool maintainShapeProportions,
  33072. bool hasDropShadow);
  33073. /** Set the colours to use for drawing the shape.
  33074. @param normalColour the colour to fill the shape with when the mouse isn't over
  33075. @param overColour the colour to use when the mouse is over the shape
  33076. @param downColour the colour to use when the button is in the pressed-down state
  33077. */
  33078. void setColours (const Colour& normalColour,
  33079. const Colour& overColour,
  33080. const Colour& downColour);
  33081. /** Sets up an outline to draw around the shape.
  33082. @param outlineColour the colour to use
  33083. @param outlineStrokeWidth the thickness of line to draw
  33084. */
  33085. void setOutline (const Colour& outlineColour,
  33086. float outlineStrokeWidth);
  33087. juce_UseDebuggingNewOperator
  33088. protected:
  33089. /** @internal */
  33090. void paintButton (Graphics& g,
  33091. bool isMouseOverButton,
  33092. bool isButtonDown);
  33093. private:
  33094. Colour normalColour, overColour, downColour, outlineColour;
  33095. DropShadowEffect shadow;
  33096. Path shape;
  33097. bool maintainShapeProportions;
  33098. float outlineWidth;
  33099. ShapeButton (const ShapeButton&);
  33100. ShapeButton& operator= (const ShapeButton&);
  33101. };
  33102. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  33103. /*** End of inlined file: juce_ShapeButton.h ***/
  33104. #endif
  33105. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  33106. #endif
  33107. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33108. /*** Start of inlined file: juce_ToggleButton.h ***/
  33109. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33110. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33111. /**
  33112. A button that can be toggled on/off.
  33113. All buttons can be toggle buttons, but this lets you create one of the
  33114. standard ones which has a tick-box and a text label next to it.
  33115. @see Button, DrawableButton, TextButton
  33116. */
  33117. class JUCE_API ToggleButton : public Button
  33118. {
  33119. public:
  33120. /** Creates a ToggleButton.
  33121. @param buttonText the text to put in the button (the component's name is also
  33122. initially set to this string, but these can be changed later
  33123. using the setName() and setButtonText() methods)
  33124. */
  33125. explicit ToggleButton (const String& buttonText = String::empty);
  33126. /** Destructor. */
  33127. ~ToggleButton();
  33128. /** Resizes the button to fit neatly around its current text.
  33129. The button's height won't be affected, only its width.
  33130. */
  33131. void changeWidthToFitText();
  33132. /** A set of colour IDs to use to change the colour of various aspects of the button.
  33133. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33134. methods.
  33135. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33136. */
  33137. enum ColourIds
  33138. {
  33139. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  33140. };
  33141. juce_UseDebuggingNewOperator
  33142. protected:
  33143. /** @internal */
  33144. void paintButton (Graphics& g,
  33145. bool isMouseOverButton,
  33146. bool isButtonDown);
  33147. /** @internal */
  33148. void colourChanged();
  33149. private:
  33150. ToggleButton (const ToggleButton&);
  33151. ToggleButton& operator= (const ToggleButton&);
  33152. };
  33153. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33154. /*** End of inlined file: juce_ToggleButton.h ***/
  33155. #endif
  33156. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33157. /*** Start of inlined file: juce_ToolbarButton.h ***/
  33158. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33159. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33160. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  33161. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33162. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33163. /*** Start of inlined file: juce_Toolbar.h ***/
  33164. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  33165. #define __JUCE_TOOLBAR_JUCEHEADER__
  33166. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  33167. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33168. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33169. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  33170. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33171. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33172. /**
  33173. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  33174. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  33175. derive your component from this class, and make sure that it is somewhere inside a
  33176. DragAndDropContainer component.
  33177. Note: If all that you need to do is to respond to files being drag-and-dropped from
  33178. the operating system onto your component, you don't need any of these classes: instead
  33179. see the FileDragAndDropTarget class.
  33180. @see DragAndDropContainer, FileDragAndDropTarget
  33181. */
  33182. class JUCE_API DragAndDropTarget
  33183. {
  33184. public:
  33185. /** Destructor. */
  33186. virtual ~DragAndDropTarget() {}
  33187. /** Callback to check whether this target is interested in the type of object being
  33188. dragged.
  33189. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33190. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33191. @returns true if this component wants to receive the other callbacks regarging this
  33192. type of object; if it returns false, no other callbacks will be made.
  33193. */
  33194. virtual bool isInterestedInDragSource (const String& sourceDescription,
  33195. Component* sourceComponent) = 0;
  33196. /** Callback to indicate that something is being dragged over this component.
  33197. This gets called when the user moves the mouse into this component while dragging
  33198. something.
  33199. Use this callback as a trigger to make your component repaint itself to give the
  33200. user feedback about whether the item can be dropped here or not.
  33201. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33202. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33203. @param x the mouse x position, relative to this component
  33204. @param y the mouse y position, relative to this component
  33205. @see itemDragExit
  33206. */
  33207. virtual void itemDragEnter (const String& sourceDescription,
  33208. Component* sourceComponent,
  33209. int x, int y);
  33210. /** Callback to indicate that the user is dragging something over this component.
  33211. This gets called when the user moves the mouse over this component while dragging
  33212. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33213. this lets you know what happens in-between.
  33214. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33215. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33216. @param x the mouse x position, relative to this component
  33217. @param y the mouse y position, relative to this component
  33218. */
  33219. virtual void itemDragMove (const String& sourceDescription,
  33220. Component* sourceComponent,
  33221. int x, int y);
  33222. /** Callback to indicate that something has been dragged off the edge of this component.
  33223. This gets called when the user moves the mouse out of this component while dragging
  33224. something.
  33225. If you've used itemDragEnter() to repaint your component and give feedback, use this
  33226. as a signal to repaint it in its normal state.
  33227. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33228. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33229. @see itemDragEnter
  33230. */
  33231. virtual void itemDragExit (const String& sourceDescription,
  33232. Component* sourceComponent);
  33233. /** Callback to indicate that the user has dropped something onto this component.
  33234. When the user drops an item this get called, and you can use the description to
  33235. work out whether your object wants to deal with it or not.
  33236. Note that after this is called, the itemDragExit method may not be called, so you should
  33237. clean up in here if there's anything you need to do when the drag finishes.
  33238. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33239. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33240. @param x the mouse x position, relative to this component
  33241. @param y the mouse y position, relative to this component
  33242. */
  33243. virtual void itemDropped (const String& sourceDescription,
  33244. Component* sourceComponent,
  33245. int x, int y) = 0;
  33246. /** Overriding this allows the target to tell the drag container whether to
  33247. draw the drag image while the cursor is over it.
  33248. By default it returns true, but if you return false, then the normal drag
  33249. image will not be shown when the cursor is over this target.
  33250. */
  33251. virtual bool shouldDrawDragImageWhenOver();
  33252. };
  33253. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33254. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  33255. /**
  33256. Enables drag-and-drop behaviour for a component and all its sub-components.
  33257. For a component to be able to make or receive drag-and-drop events, one of its parent
  33258. components must derive from this class. It's probably best for the top-level
  33259. component to implement it.
  33260. Then to start a drag operation, any sub-component can just call the startDragging()
  33261. method, and this object will take over, tracking the mouse and sending appropriate
  33262. callbacks to any child components derived from DragAndDropTarget which the mouse
  33263. moves over.
  33264. Note: If all that you need to do is to respond to files being drag-and-dropped from
  33265. the operating system onto your component, you don't need any of these classes: you can do this
  33266. simply by overriding Component::filesDropped().
  33267. @see DragAndDropTarget
  33268. */
  33269. class JUCE_API DragAndDropContainer
  33270. {
  33271. public:
  33272. /** Creates a DragAndDropContainer.
  33273. The object that derives from this class must also be a Component.
  33274. */
  33275. DragAndDropContainer();
  33276. /** Destructor. */
  33277. virtual ~DragAndDropContainer();
  33278. /** Begins a drag-and-drop operation.
  33279. This starts a drag-and-drop operation - call it when the user drags the
  33280. mouse in your drag-source component, and this object will track mouse
  33281. movements until the user lets go of the mouse button, and will send
  33282. appropriate messages to DragAndDropTarget objects that the mouse moves
  33283. over.
  33284. findParentDragContainerFor() is a handy method to call to find the
  33285. drag container to use for a component.
  33286. @param sourceDescription a string to use as the description of the thing being
  33287. dragged - this will be passed to the objects that might be
  33288. dropped-onto so they can decide if they want to handle it or
  33289. not
  33290. @param sourceComponent the component that is being dragged
  33291. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  33292. a snapshot of the sourceComponent will be used instead.
  33293. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  33294. window, and can be dragged to DragAndDropTargets that are the
  33295. children of components other than this one.
  33296. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  33297. at which the image should be drawn from the mouse. If it isn't
  33298. specified, then the image will be centred around the mouse. If
  33299. an image hasn't been passed-in, this will be ignored.
  33300. */
  33301. void startDragging (const String& sourceDescription,
  33302. Component* sourceComponent,
  33303. const Image& dragImage = Image::null,
  33304. bool allowDraggingToOtherJuceWindows = false,
  33305. const Point<int>* imageOffsetFromMouse = 0);
  33306. /** Returns true if something is currently being dragged. */
  33307. bool isDragAndDropActive() const;
  33308. /** Returns the description of the thing that's currently being dragged.
  33309. If nothing's being dragged, this will return an empty string, otherwise it's the
  33310. string that was passed into startDragging().
  33311. @see startDragging
  33312. */
  33313. const String getCurrentDragDescription() const;
  33314. /** Utility to find the DragAndDropContainer for a given Component.
  33315. This will search up this component's parent hierarchy looking for the first
  33316. parent component which is a DragAndDropContainer.
  33317. It's useful when a component wants to call startDragging but doesn't know
  33318. the DragAndDropContainer it should to use.
  33319. Obviously this may return 0 if it doesn't find a suitable component.
  33320. */
  33321. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  33322. /** This performs a synchronous drag-and-drop of a set of files to some external
  33323. application.
  33324. You can call this function in response to a mouseDrag callback, and it will
  33325. block, running its own internal message loop and tracking the mouse, while it
  33326. uses a native operating system drag-and-drop operation to move or copy some
  33327. files to another application.
  33328. @param files a list of filenames to drag
  33329. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  33330. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  33331. @returns true if the files were successfully dropped somewhere, or false if it
  33332. was interrupted
  33333. @see performExternalDragDropOfText
  33334. */
  33335. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  33336. /** This performs a synchronous drag-and-drop of a block of text to some external
  33337. application.
  33338. You can call this function in response to a mouseDrag callback, and it will
  33339. block, running its own internal message loop and tracking the mouse, while it
  33340. uses a native operating system drag-and-drop operation to move or copy some
  33341. text to another application.
  33342. @param text the text to copy
  33343. @returns true if the text was successfully dropped somewhere, or false if it
  33344. was interrupted
  33345. @see performExternalDragDropOfFiles
  33346. */
  33347. static bool performExternalDragDropOfText (const String& text);
  33348. juce_UseDebuggingNewOperator
  33349. protected:
  33350. /** Override this if you want to be able to perform an external drag a set of files
  33351. when the user drags outside of this container component.
  33352. This method will be called when a drag operation moves outside the Juce-based window,
  33353. and if you want it to then perform a file drag-and-drop, add the filenames you want
  33354. to the array passed in, and return true.
  33355. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  33356. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  33357. @param files on return, the filenames you want to drag
  33358. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  33359. it must make a copy of them (see the performExternalDragDropOfFiles()
  33360. method)
  33361. @see performExternalDragDropOfFiles
  33362. */
  33363. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  33364. Component* dragSourceComponent,
  33365. StringArray& files,
  33366. bool& canMoveFiles);
  33367. private:
  33368. friend class DragImageComponent;
  33369. ScopedPointer <Component> dragImageComponent;
  33370. String currentDragDesc;
  33371. };
  33372. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33373. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  33374. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  33375. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33376. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33377. /**
  33378. Animates a set of components, moving it to a new position.
  33379. To use this, create a ComponentAnimator, and use its animateComponent() method
  33380. to tell it to move components to destination positions. Any number of
  33381. components can be animated by one ComponentAnimator object (if you've got a
  33382. lot of components to move, it's much more efficient to share a single animator
  33383. than to have many animators running at once).
  33384. You'll need to make sure the animator object isn't deleted before it finishes
  33385. moving the components.
  33386. The class is a ChangeBroadcaster and sends a notification when any components
  33387. start or finish being animated.
  33388. */
  33389. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  33390. private Timer
  33391. {
  33392. public:
  33393. /** Creates a ComponentAnimator. */
  33394. ComponentAnimator();
  33395. /** Destructor. */
  33396. ~ComponentAnimator();
  33397. /** Starts a component moving from its current position to a specified position.
  33398. If the component is already in the middle of an animation, that will be abandoned,
  33399. and a new animation will begin, moving the component from its current location.
  33400. The start and end speed parameters let you apply some acceleration to the component's
  33401. movement.
  33402. @param component the component to move
  33403. @param finalPosition the destination position and size to move it to
  33404. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  33405. to arrive at its destination
  33406. @param startSpeed a value to indicate the relative start speed of the
  33407. animation. If this is 0, the component will start
  33408. by accelerating from rest; higher values mean that it
  33409. will have an initial speed greater than zero. If the
  33410. value if greater than 1, it will decelerate towards the
  33411. middle of its journey. To move the component at a constant
  33412. rate for its entire animation, set both the start and
  33413. end speeds to 1.0
  33414. @param endSpeed a relative speed at which the component should be moving
  33415. when the animation finishes. If this is 0, the component
  33416. will decelerate to a standstill at its final position; higher
  33417. values mean the component will still be moving when it stops.
  33418. To move the component at a constant rate for its entire
  33419. animation, set both the start and end speeds to 1.0
  33420. */
  33421. void animateComponent (Component* component,
  33422. const Rectangle<int>& finalPosition,
  33423. int millisecondsToSpendMoving,
  33424. double startSpeed = 1.0,
  33425. double endSpeed = 1.0);
  33426. /** Stops a component if it's currently being animated.
  33427. If moveComponentToItsFinalPosition is true, then the component will
  33428. be immediately moved to its destination position and size. If false, it will be
  33429. left in whatever location it currently occupies.
  33430. */
  33431. void cancelAnimation (Component* component,
  33432. bool moveComponentToItsFinalPosition);
  33433. /** Clears all of the active animations.
  33434. If moveComponentsToTheirFinalPositions is true, all the components will
  33435. be immediately set to their final positions. If false, they will be
  33436. left in whatever locations they currently occupy.
  33437. */
  33438. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  33439. /** Returns the destination position for a component.
  33440. If the component is being animated, this will return the target position that
  33441. was specified when animateComponent() was called.
  33442. If the specified component isn't currently being animated, this method will just
  33443. return its current position.
  33444. */
  33445. const Rectangle<int> getComponentDestination (Component* component);
  33446. /** Returns true if the specified component is currently being animated.
  33447. */
  33448. bool isAnimating (Component* component) const;
  33449. juce_UseDebuggingNewOperator
  33450. private:
  33451. class AnimationTask;
  33452. Array <AnimationTask*> tasks;
  33453. uint32 lastTime;
  33454. AnimationTask* findTaskFor (Component* component) const;
  33455. void timerCallback();
  33456. };
  33457. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33458. /*** End of inlined file: juce_ComponentAnimator.h ***/
  33459. class ToolbarItemComponent;
  33460. class ToolbarItemFactory;
  33461. /**
  33462. A toolbar component.
  33463. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  33464. and looks after their order and layout.
  33465. Items (icon buttons or other custom components) are added to a toolbar using a
  33466. ToolbarItemFactory - each type of item is given a unique ID number, and a
  33467. toolbar might contain more than one instance of a particular item type.
  33468. Toolbars can be interactively customised, allowing the user to drag the items
  33469. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  33470. component as a source of new items.
  33471. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  33472. */
  33473. class JUCE_API Toolbar : public Component,
  33474. public DragAndDropContainer,
  33475. public DragAndDropTarget,
  33476. private Button::Listener
  33477. {
  33478. public:
  33479. /** Creates an empty toolbar component.
  33480. To add some icons or other components to your toolbar, you'll need to
  33481. create a ToolbarItemFactory class that can create a suitable set of
  33482. ToolbarItemComponents.
  33483. @see ToolbarItemFactory, ToolbarItemComponents
  33484. */
  33485. Toolbar();
  33486. /** Destructor.
  33487. Any items on the bar will be deleted when the toolbar is deleted.
  33488. */
  33489. ~Toolbar();
  33490. /** Changes the bar's orientation.
  33491. @see isVertical
  33492. */
  33493. void setVertical (bool shouldBeVertical);
  33494. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  33495. You can change the bar's orientation with setVertical().
  33496. */
  33497. bool isVertical() const throw() { return vertical; }
  33498. /** Returns the depth of the bar.
  33499. If the bar is horizontal, this will return its height; if it's vertical, it
  33500. will return its width.
  33501. @see getLength
  33502. */
  33503. int getThickness() const throw();
  33504. /** Returns the length of the bar.
  33505. If the bar is horizontal, this will return its width; if it's vertical, it
  33506. will return its height.
  33507. @see getThickness
  33508. */
  33509. int getLength() const throw();
  33510. /** Deletes all items from the bar.
  33511. */
  33512. void clear();
  33513. /** Adds an item to the toolbar.
  33514. The factory's ToolbarItemFactory::createItem() will be called by this method
  33515. to create the component that will actually be added to the bar.
  33516. The new item will be inserted at the specified index (if the index is -1, it
  33517. will be added to the right-hand or bottom end of the bar).
  33518. Once added, the component will be automatically deleted by this object when it
  33519. is no longer needed.
  33520. @see ToolbarItemFactory
  33521. */
  33522. void addItem (ToolbarItemFactory& factory,
  33523. int itemId,
  33524. int insertIndex = -1);
  33525. /** Deletes one of the items from the bar.
  33526. */
  33527. void removeToolbarItem (int itemIndex);
  33528. /** Returns the number of items currently on the toolbar.
  33529. @see getItemId, getItemComponent
  33530. */
  33531. int getNumItems() const throw();
  33532. /** Returns the ID of the item with the given index.
  33533. If the index is less than zero or greater than the number of items,
  33534. this will return 0.
  33535. @see getNumItems
  33536. */
  33537. int getItemId (int itemIndex) const throw();
  33538. /** Returns the component being used for the item with the given index.
  33539. If the index is less than zero or greater than the number of items,
  33540. this will return 0.
  33541. @see getNumItems
  33542. */
  33543. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  33544. /** Clears this toolbar and adds to it the default set of items that the specified
  33545. factory creates.
  33546. @see ToolbarItemFactory::getDefaultItemSet
  33547. */
  33548. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  33549. /** Options for the way items should be displayed.
  33550. @see setStyle, getStyle
  33551. */
  33552. enum ToolbarItemStyle
  33553. {
  33554. iconsOnly, /**< Means that the toolbar should just contain icons. */
  33555. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  33556. textOnly /**< Means that the toolbar only display text labels for each item. */
  33557. };
  33558. /** Returns the toolbar's current style.
  33559. @see ToolbarItemStyle, setStyle
  33560. */
  33561. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33562. /** Changes the toolbar's current style.
  33563. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  33564. */
  33565. void setStyle (const ToolbarItemStyle& newStyle);
  33566. /** Flags used by the showCustomisationDialog() method. */
  33567. enum CustomisationFlags
  33568. {
  33569. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  33570. show the "icons only" option on its choice of toolbar styles. */
  33571. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  33572. show the "icons with text" option on its choice of toolbar styles. */
  33573. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  33574. show the "text only" option on its choice of toolbar styles. */
  33575. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  33576. show a button to reset the toolbar to its default set of items. */
  33577. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  33578. };
  33579. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  33580. The dialog contains a ToolbarItemPalette and various controls for editing other
  33581. aspects of the toolbar. This method will block and run the dialog box modally,
  33582. returning when the user closes it.
  33583. The factory is used to determine the set of items that will be shown on the
  33584. palette.
  33585. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  33586. enum.
  33587. @see ToolbarItemPalette
  33588. */
  33589. void showCustomisationDialog (ToolbarItemFactory& factory,
  33590. int optionFlags = allCustomisationOptionsEnabled);
  33591. /** Turns on or off the toolbar's editing mode, in which its items can be
  33592. rearranged by the user.
  33593. (In most cases it's easier just to use showCustomisationDialog() instead of
  33594. trying to enable editing directly).
  33595. @see ToolbarItemPalette
  33596. */
  33597. void setEditingActive (bool editingEnabled);
  33598. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  33599. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33600. methods.
  33601. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33602. */
  33603. enum ColourIds
  33604. {
  33605. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  33606. more control over this, override LookAndFeel::paintToolbarBackground(). */
  33607. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  33608. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  33609. over them. */
  33610. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  33611. held down on them. */
  33612. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  33613. when the style is set to iconsWithText or textOnly. */
  33614. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  33615. the customisation dialog is active and the mouse moves over them. */
  33616. };
  33617. /** Returns a string that represents the toolbar's current set of items.
  33618. This lets you later restore the same item layout using restoreFromString().
  33619. @see restoreFromString
  33620. */
  33621. const String toString() const;
  33622. /** Restores a set of items that was previously stored in a string by the toString()
  33623. method.
  33624. The factory object is used to create any item components that are needed.
  33625. @see toString
  33626. */
  33627. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  33628. const String& savedVersion);
  33629. /** @internal */
  33630. void paint (Graphics& g);
  33631. /** @internal */
  33632. void resized();
  33633. /** @internal */
  33634. void buttonClicked (Button*);
  33635. /** @internal */
  33636. void mouseDown (const MouseEvent&);
  33637. /** @internal */
  33638. bool isInterestedInDragSource (const String&, Component*);
  33639. /** @internal */
  33640. void itemDragMove (const String&, Component*, int, int);
  33641. /** @internal */
  33642. void itemDragExit (const String&, Component*);
  33643. /** @internal */
  33644. void itemDropped (const String&, Component*, int, int);
  33645. /** @internal */
  33646. void updateAllItemPositions (const bool animate);
  33647. /** @internal */
  33648. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  33649. juce_UseDebuggingNewOperator
  33650. private:
  33651. Button* missingItemsButton;
  33652. bool vertical, isEditingActive;
  33653. ToolbarItemStyle toolbarStyle;
  33654. ComponentAnimator animator;
  33655. class MissingItemsComponent;
  33656. friend class MissingItemsComponent;
  33657. Array <ToolbarItemComponent*> items;
  33658. friend class ItemDragAndDropOverlayComponent;
  33659. static const char* const toolbarDragDescriptor;
  33660. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  33661. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  33662. Toolbar (const Toolbar&);
  33663. Toolbar& operator= (const Toolbar&);
  33664. };
  33665. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  33666. /*** End of inlined file: juce_Toolbar.h ***/
  33667. class ItemDragAndDropOverlayComponent;
  33668. /**
  33669. A component that can be used as one of the items in a Toolbar.
  33670. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  33671. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  33672. class for further info about creating them.
  33673. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  33674. components too. To do this, set the value of isBeingUsedAsAButton to false when
  33675. calling the constructor, and override contentAreaChanged(), in which you can position
  33676. any sub-components you need to add.
  33677. To add basic buttons without writing a special subclass, have a look at the
  33678. ToolbarButton class.
  33679. @see ToolbarButton, Toolbar, ToolbarItemFactory
  33680. */
  33681. class JUCE_API ToolbarItemComponent : public Button
  33682. {
  33683. public:
  33684. /** Constructor.
  33685. @param itemId the ID of the type of toolbar item which this represents
  33686. @param labelText the text to display if the toolbar's style is set to
  33687. Toolbar::iconsWithText or Toolbar::textOnly
  33688. @param isBeingUsedAsAButton set this to false if you don't want the button
  33689. to draw itself with button over/down states when the mouse
  33690. moves over it or clicks
  33691. */
  33692. ToolbarItemComponent (int itemId,
  33693. const String& labelText,
  33694. bool isBeingUsedAsAButton);
  33695. /** Destructor. */
  33696. ~ToolbarItemComponent();
  33697. /** Returns the item type ID that this component represents.
  33698. This value is in the constructor.
  33699. */
  33700. int getItemId() const throw() { return itemId; }
  33701. /** Returns the toolbar that contains this component, or 0 if it's not currently
  33702. inside one.
  33703. */
  33704. Toolbar* getToolbar() const;
  33705. /** Returns true if this component is currently inside a toolbar which is vertical.
  33706. @see Toolbar::isVertical
  33707. */
  33708. bool isToolbarVertical() const;
  33709. /** Returns the current style setting of this item.
  33710. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  33711. @see setStyle, Toolbar::getStyle
  33712. */
  33713. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33714. /** Changes the current style setting of this item.
  33715. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  33716. by the toolbar that holds this item.
  33717. @see setStyle, Toolbar::setStyle
  33718. */
  33719. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  33720. /** Returns the area of the component that should be used to display the button image or
  33721. other contents of the item.
  33722. This content area may change when the item's style changes, and may leave a space around the
  33723. edge of the component where the text label can be shown.
  33724. @see contentAreaChanged
  33725. */
  33726. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  33727. /** This method must return the size criteria for this item, based on a given toolbar
  33728. size and orientation.
  33729. The preferredSize, minSize and maxSize values must all be set by your implementation
  33730. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  33731. toolbar, they refer to the item's height.
  33732. The preferredSize is the size that the component would like to be, and this must be
  33733. between the min and max sizes. For a fixed-size item, simply set all three variables to
  33734. the same value.
  33735. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  33736. Toolbar::getThickness().
  33737. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  33738. vertically.
  33739. */
  33740. virtual bool getToolbarItemSizes (int toolbarThickness,
  33741. bool isToolbarVertical,
  33742. int& preferredSize,
  33743. int& minSize,
  33744. int& maxSize) = 0;
  33745. /** Your subclass should use this method to draw its content area.
  33746. The graphics object that is passed-in will have been clipped and had its origin
  33747. moved to fit the content area as specified get getContentArea(). The width and height
  33748. parameters are the width and height of the content area.
  33749. If the component you're writing isn't a button, you can just do nothing in this method.
  33750. */
  33751. virtual void paintButtonArea (Graphics& g,
  33752. int width, int height,
  33753. bool isMouseOver, bool isMouseDown) = 0;
  33754. /** Callback to indicate that the content area of this item has changed.
  33755. This might be because the component was resized, or because the style changed and
  33756. the space needed for the text label is different.
  33757. See getContentArea() for a description of what the area is.
  33758. */
  33759. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  33760. /** Editing modes.
  33761. These are used by setEditingMode(), but will be rarely needed in user code.
  33762. */
  33763. enum ToolbarEditingMode
  33764. {
  33765. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  33766. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  33767. customisation mode, and the items can be dragged around. */
  33768. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  33769. dragged onto a toolbar to add it to that bar.*/
  33770. };
  33771. /** Changes the editing mode of this component.
  33772. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33773. and is unlikely to be of much use in end-user-code.
  33774. */
  33775. void setEditingMode (const ToolbarEditingMode newMode);
  33776. /** Returns the current editing mode of this component.
  33777. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33778. and is unlikely to be of much use in end-user-code.
  33779. */
  33780. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  33781. /** @internal */
  33782. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  33783. /** @internal */
  33784. void resized();
  33785. juce_UseDebuggingNewOperator
  33786. private:
  33787. friend class Toolbar;
  33788. friend class ItemDragAndDropOverlayComponent;
  33789. const int itemId;
  33790. ToolbarEditingMode mode;
  33791. Toolbar::ToolbarItemStyle toolbarStyle;
  33792. ScopedPointer <Component> overlayComp;
  33793. int dragOffsetX, dragOffsetY;
  33794. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  33795. Rectangle<int> contentArea;
  33796. ToolbarItemComponent (const ToolbarItemComponent&);
  33797. ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  33798. };
  33799. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33800. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  33801. /**
  33802. A type of button designed to go on a toolbar.
  33803. This simple button can have two Drawable objects specified - one for normal
  33804. use and another one (optionally) for the button's "on" state if it's a
  33805. toggle button.
  33806. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  33807. */
  33808. class JUCE_API ToolbarButton : public ToolbarItemComponent
  33809. {
  33810. public:
  33811. /** Creates a ToolbarButton.
  33812. @param itemId the ID for this toolbar item type. This is passed through to the
  33813. ToolbarItemComponent constructor
  33814. @param labelText the text to display on the button (if the toolbar is using a style
  33815. that shows text labels). This is passed through to the
  33816. ToolbarItemComponent constructor
  33817. @param normalImage a drawable object that the button should use as its icon. The object
  33818. that is passed-in here will be kept by this object and will be
  33819. deleted when no longer needed or when this button is deleted.
  33820. @param toggledOnImage a drawable object that the button can use as its icon if the button
  33821. is in a toggled-on state (see the Button::getToggleState() method). If
  33822. 0 is passed-in here, then the normal image will be used instead, regardless
  33823. of the toggle state. The object that is passed-in here will be kept by
  33824. this object and will be deleted when no longer needed or when this button
  33825. is deleted.
  33826. */
  33827. ToolbarButton (int itemId,
  33828. const String& labelText,
  33829. Drawable* normalImage,
  33830. Drawable* toggledOnImage);
  33831. /** Destructor. */
  33832. ~ToolbarButton();
  33833. /** @internal */
  33834. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  33835. int& minSize, int& maxSize);
  33836. /** @internal */
  33837. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  33838. /** @internal */
  33839. void contentAreaChanged (const Rectangle<int>& newBounds);
  33840. juce_UseDebuggingNewOperator
  33841. private:
  33842. ScopedPointer <Drawable> normalImage, toggledOnImage;
  33843. ToolbarButton (const ToolbarButton&);
  33844. ToolbarButton& operator= (const ToolbarButton&);
  33845. };
  33846. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33847. /*** End of inlined file: juce_ToolbarButton.h ***/
  33848. #endif
  33849. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33850. /*** Start of inlined file: juce_CodeDocument.h ***/
  33851. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33852. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33853. class CodeDocumentLine;
  33854. /**
  33855. A class for storing and manipulating a source code file.
  33856. When using a CodeEditorComponent, it takes one of these as its source object.
  33857. The CodeDocument stores its content as an array of lines, which makes it
  33858. quick to insert and delete.
  33859. @see CodeEditorComponent
  33860. */
  33861. class JUCE_API CodeDocument
  33862. {
  33863. public:
  33864. /** Creates a new, empty document.
  33865. */
  33866. CodeDocument();
  33867. /** Destructor. */
  33868. ~CodeDocument();
  33869. /** A position in a code document.
  33870. Using this class you can find a position in a code document and quickly get its
  33871. character position, line, and index. By calling setPositionMaintained (true), the
  33872. position is automatically updated when text is inserted or deleted in the document,
  33873. so that it maintains its original place in the text.
  33874. */
  33875. class JUCE_API Position
  33876. {
  33877. public:
  33878. /** Creates an uninitialised postion.
  33879. Don't attempt to call any methods on this until you've given it an owner document
  33880. to refer to!
  33881. */
  33882. Position() throw();
  33883. /** Creates a position based on a line and index in a document.
  33884. Note that this index is NOT the column number, it's the number of characters from the
  33885. start of the line. The "column" number isn't quite the same, because if the line
  33886. contains any tab characters, the relationship of the index to its visual column depends on
  33887. the number of spaces per tab being used!
  33888. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33889. they will be adjusted to keep them within its limits.
  33890. */
  33891. Position (const CodeDocument* ownerDocument,
  33892. int line, int indexInLine) throw();
  33893. /** Creates a position based on a character index in a document.
  33894. This position is placed at the specified number of characters from the start of the
  33895. document. The line and column are auto-calculated.
  33896. If the position is beyond the range of the document, it'll be adjusted to keep it
  33897. inside.
  33898. */
  33899. Position (const CodeDocument* ownerDocument,
  33900. int charactersFromStartOfDocument) throw();
  33901. /** Creates a copy of another position.
  33902. This will copy the position, but the new object will not be set to maintain its position,
  33903. even if the source object was set to do so.
  33904. */
  33905. Position (const Position& other) throw();
  33906. /** Destructor. */
  33907. ~Position() throw();
  33908. Position& operator= (const Position& other) throw();
  33909. bool operator== (const Position& other) const throw();
  33910. bool operator!= (const Position& other) const throw();
  33911. /** Points this object at a new position within the document.
  33912. If the position is beyond the range of the document, it'll be adjusted to keep it
  33913. inside.
  33914. @see getPosition, setLineAndIndex
  33915. */
  33916. void setPosition (int charactersFromStartOfDocument) throw();
  33917. /** Returns the position as the number of characters from the start of the document.
  33918. @see setPosition, getLineNumber, getIndexInLine
  33919. */
  33920. int getPosition() const throw() { return characterPos; }
  33921. /** Moves the position to a new line and index within the line.
  33922. Note that the index is NOT the column at which the position appears in an editor.
  33923. If the line contains any tab characters, the relationship of the index to its
  33924. visual position depends on the number of spaces per tab being used!
  33925. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33926. they will be adjusted to keep them within its limits.
  33927. */
  33928. void setLineAndIndex (int newLine, int newIndexInLine) throw();
  33929. /** Returns the line number of this position.
  33930. The first line in the document is numbered zero, not one!
  33931. */
  33932. int getLineNumber() const throw() { return line; }
  33933. /** Returns the number of characters from the start of the line.
  33934. Note that this value is NOT the column at which the position appears in an editor.
  33935. If the line contains any tab characters, the relationship of the index to its
  33936. visual position depends on the number of spaces per tab being used!
  33937. */
  33938. int getIndexInLine() const throw() { return indexInLine; }
  33939. /** Allows the position to be automatically updated when the document changes.
  33940. If this is set to true, the positon will register with its document so that
  33941. when the document has text inserted or deleted, this position will be automatically
  33942. moved to keep it at the same position in the text.
  33943. */
  33944. void setPositionMaintained (bool isMaintained) throw();
  33945. /** Moves the position forwards or backwards by the specified number of characters.
  33946. @see movedBy
  33947. */
  33948. void moveBy (int characterDelta) throw();
  33949. /** Returns a position which is the same as this one, moved by the specified number of
  33950. characters.
  33951. @see moveBy
  33952. */
  33953. const Position movedBy (int characterDelta) const throw();
  33954. /** Returns a position which is the same as this one, moved up or down by the specified
  33955. number of lines.
  33956. @see movedBy
  33957. */
  33958. const Position movedByLines (int deltaLines) const throw();
  33959. /** Returns the character in the document at this position.
  33960. @see getLineText
  33961. */
  33962. const juce_wchar getCharacter() const throw();
  33963. /** Returns the line from the document that this position is within.
  33964. @see getCharacter, getLineNumber
  33965. */
  33966. const String getLineText() const throw();
  33967. private:
  33968. CodeDocument* owner;
  33969. int characterPos, line, indexInLine;
  33970. bool positionMaintained;
  33971. };
  33972. /** Returns the full text of the document. */
  33973. const String getAllContent() const throw();
  33974. /** Returns a section of the document's text. */
  33975. const String getTextBetween (const Position& start, const Position& end) const throw();
  33976. /** Returns a line from the document. */
  33977. const String getLine (int lineIndex) const throw();
  33978. /** Returns the number of characters in the document. */
  33979. int getNumCharacters() const throw();
  33980. /** Returns the number of lines in the document. */
  33981. int getNumLines() const throw() { return lines.size(); }
  33982. /** Returns the number of characters in the longest line of the document. */
  33983. int getMaximumLineLength() throw();
  33984. /** Deletes a section of the text.
  33985. This operation is undoable.
  33986. */
  33987. void deleteSection (const Position& startPosition, const Position& endPosition);
  33988. /** Inserts some text into the document at a given position.
  33989. This operation is undoable.
  33990. */
  33991. void insertText (const Position& position, const String& text);
  33992. /** Clears the document and replaces it with some new text.
  33993. This operation is undoable - if you're trying to completely reset the document, you
  33994. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33995. */
  33996. void replaceAllContent (const String& newContent);
  33997. /** Replaces the editor's contents with the contents of a stream.
  33998. This will also reset the undo history and save point marker.
  33999. */
  34000. bool loadFromStream (InputStream& stream);
  34001. /** Writes the editor's current contents to a stream. */
  34002. bool writeToStream (OutputStream& stream);
  34003. /** Returns the preferred new-line characters for the document.
  34004. This will be either "\n", "\r\n", or (rarely) "\r".
  34005. @see setNewLineCharacters
  34006. */
  34007. const String getNewLineCharacters() const throw() { return newLineChars; }
  34008. /** Sets the new-line characters that the document should use.
  34009. The string must be either "\n", "\r\n", or (rarely) "\r".
  34010. @see getNewLineCharacters
  34011. */
  34012. void setNewLineCharacters (const String& newLine) throw();
  34013. /** Begins a new undo transaction.
  34014. The document itself will not call this internally, so relies on whatever is using the
  34015. document to periodically call this to break up the undo sequence into sensible chunks.
  34016. @see UndoManager::beginNewTransaction
  34017. */
  34018. void newTransaction();
  34019. /** Undo the last operation.
  34020. @see UndoManager::undo
  34021. */
  34022. void undo();
  34023. /** Redo the last operation.
  34024. @see UndoManager::redo
  34025. */
  34026. void redo();
  34027. /** Clears the undo history.
  34028. @see UndoManager::clearUndoHistory
  34029. */
  34030. void clearUndoHistory();
  34031. /** Returns the document's UndoManager */
  34032. UndoManager& getUndoManager() throw() { return undoManager; }
  34033. /** Makes a note that the document's current state matches the one that is saved.
  34034. After this has been called, hasChangedSinceSavePoint() will return false until
  34035. the document has been altered, and then it'll start returning true. If the document is
  34036. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  34037. will again return false.
  34038. @see hasChangedSinceSavePoint
  34039. */
  34040. void setSavePoint() throw();
  34041. /** Returns true if the state of the document differs from the state it was in when
  34042. setSavePoint() was last called.
  34043. @see setSavePoint
  34044. */
  34045. bool hasChangedSinceSavePoint() const throw();
  34046. /** Searches for a word-break. */
  34047. const Position findWordBreakAfter (const Position& position) const throw();
  34048. /** Searches for a word-break. */
  34049. const Position findWordBreakBefore (const Position& position) const throw();
  34050. /** An object that receives callbacks from the CodeDocument when its text changes.
  34051. @see CodeDocument::addListener, CodeDocument::removeListener
  34052. */
  34053. class JUCE_API Listener
  34054. {
  34055. public:
  34056. Listener() {}
  34057. virtual ~Listener() {}
  34058. /** Called by a CodeDocument when it is altered.
  34059. */
  34060. virtual void codeDocumentChanged (const Position& affectedTextStart,
  34061. const Position& affectedTextEnd) = 0;
  34062. };
  34063. /** Registers a listener object to receive callbacks when the document changes.
  34064. If the listener is already registered, this method has no effect.
  34065. @see removeListener
  34066. */
  34067. void addListener (Listener* listener) throw();
  34068. /** Deregisters a listener.
  34069. @see addListener
  34070. */
  34071. void removeListener (Listener* listener) throw();
  34072. /** Iterates the text in a CodeDocument.
  34073. This class lets you read characters from a CodeDocument. It's designed to be used
  34074. by a SyntaxAnalyser object.
  34075. @see CodeDocument, SyntaxAnalyser
  34076. */
  34077. class Iterator
  34078. {
  34079. public:
  34080. Iterator (CodeDocument* document);
  34081. Iterator (const Iterator& other);
  34082. Iterator& operator= (const Iterator& other) throw();
  34083. ~Iterator() throw();
  34084. /** Reads the next character and returns it.
  34085. @see peekNextChar
  34086. */
  34087. juce_wchar nextChar();
  34088. /** Reads the next character without advancing the current position. */
  34089. juce_wchar peekNextChar() const;
  34090. /** Advances the position by one character. */
  34091. void skip();
  34092. /** Returns the position of the next character as its position within the
  34093. whole document.
  34094. */
  34095. int getPosition() const throw() { return position; }
  34096. /** Skips over any whitespace characters until the next character is non-whitespace. */
  34097. void skipWhitespace();
  34098. /** Skips forward until the next character will be the first character on the next line */
  34099. void skipToEndOfLine();
  34100. /** Returns the line number of the next character. */
  34101. int getLine() const throw() { return line; }
  34102. /** Returns true if the iterator has reached the end of the document. */
  34103. bool isEOF() const throw();
  34104. private:
  34105. CodeDocument* document;
  34106. CodeDocumentLine* currentLine;
  34107. int line, position;
  34108. };
  34109. juce_UseDebuggingNewOperator
  34110. private:
  34111. friend class CodeDocumentInsertAction;
  34112. friend class CodeDocumentDeleteAction;
  34113. friend class Iterator;
  34114. friend class Position;
  34115. OwnedArray <CodeDocumentLine> lines;
  34116. Array <Position*> positionsToMaintain;
  34117. UndoManager undoManager;
  34118. int currentActionIndex, indexOfSavedState;
  34119. int maximumLineLength;
  34120. ListenerList <Listener> listeners;
  34121. String newLineChars;
  34122. void sendListenerChangeMessage (int startLine, int endLine);
  34123. void insert (const String& text, int insertPos, bool undoable);
  34124. void remove (int startPos, int endPos, bool undoable);
  34125. void checkLastLineStatus();
  34126. CodeDocument (const CodeDocument&);
  34127. CodeDocument& operator= (const CodeDocument&);
  34128. };
  34129. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  34130. /*** End of inlined file: juce_CodeDocument.h ***/
  34131. #endif
  34132. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34133. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  34134. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34135. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34136. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  34137. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34138. #define __JUCE_CODETOKENISER_JUCEHEADER__
  34139. /**
  34140. A base class for tokenising code so that the syntax can be displayed in a
  34141. code editor.
  34142. @see CodeDocument, CodeEditorComponent
  34143. */
  34144. class JUCE_API CodeTokeniser
  34145. {
  34146. public:
  34147. CodeTokeniser() {}
  34148. virtual ~CodeTokeniser() {}
  34149. /** Reads the next token from the source and returns its token type.
  34150. This must leave the source pointing to the first character in the
  34151. next token.
  34152. */
  34153. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  34154. /** Returns a list of the names of the token types this analyser uses.
  34155. The index in this list must match the token type numbers that are
  34156. returned by readNextToken().
  34157. */
  34158. virtual const StringArray getTokenTypes() = 0;
  34159. /** Returns a suggested syntax highlighting colour for a specified
  34160. token type.
  34161. */
  34162. virtual const Colour getDefaultColour (int tokenType) = 0;
  34163. juce_UseDebuggingNewOperator
  34164. };
  34165. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  34166. /*** End of inlined file: juce_CodeTokeniser.h ***/
  34167. /**
  34168. A text editor component designed specifically for source code.
  34169. This is designed to handle syntax highlighting and fast editing of very large
  34170. files.
  34171. */
  34172. class JUCE_API CodeEditorComponent : public Component,
  34173. public TextInputTarget,
  34174. public Timer,
  34175. public ScrollBar::Listener,
  34176. public CodeDocument::Listener,
  34177. public AsyncUpdater
  34178. {
  34179. public:
  34180. /** Creates an editor for a document.
  34181. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  34182. The object that you pass in is not owned or deleted by the editor - you must
  34183. make sure that it doesn't get deleted while this component is still using it.
  34184. @see CodeDocument
  34185. */
  34186. CodeEditorComponent (CodeDocument& document,
  34187. CodeTokeniser* codeTokeniser);
  34188. /** Destructor. */
  34189. ~CodeEditorComponent();
  34190. /** Returns the code document that this component is editing. */
  34191. CodeDocument& getDocument() const throw() { return document; }
  34192. /** Loads the given content into the document.
  34193. This will completely reset the CodeDocument object, clear its undo history,
  34194. and fill it with this text.
  34195. */
  34196. void loadContent (const String& newContent);
  34197. /** Returns the standard character width. */
  34198. float getCharWidth() const throw() { return charWidth; }
  34199. /** Returns the height of a line of text, in pixels. */
  34200. int getLineHeight() const throw() { return lineHeight; }
  34201. /** Returns the number of whole lines visible on the screen,
  34202. This doesn't include a cut-off line that might be visible at the bottom if the
  34203. component's height isn't an exact multiple of the line-height.
  34204. */
  34205. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  34206. /** Returns the number of whole columns visible on the screen.
  34207. This doesn't include any cut-off columns at the right-hand edge.
  34208. */
  34209. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  34210. /** Returns the current caret position. */
  34211. const CodeDocument::Position getCaretPos() const { return caretPos; }
  34212. /** Moves the caret.
  34213. If selecting is true, the section of the document between the current
  34214. caret position and the new one will become selected. If false, any currently
  34215. selected region will be deselected.
  34216. */
  34217. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  34218. /** Returns the on-screen position of a character in the document.
  34219. The rectangle returned is relative to this component's top-left origin.
  34220. */
  34221. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const throw();
  34222. /** Finds the character at a given on-screen position.
  34223. The co-ordinates are relative to this component's top-left origin.
  34224. */
  34225. const CodeDocument::Position getPositionAt (int x, int y);
  34226. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  34227. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  34228. void cursorDown (bool selecting);
  34229. void cursorUp (bool selecting);
  34230. void pageDown (bool selecting);
  34231. void pageUp (bool selecting);
  34232. void scrollDown();
  34233. void scrollUp();
  34234. void scrollToLine (int newFirstLineOnScreen);
  34235. void scrollBy (int deltaLines);
  34236. void scrollToColumn (int newFirstColumnOnScreen);
  34237. void scrollToKeepCaretOnScreen();
  34238. void goToStartOfDocument (bool selecting);
  34239. void goToStartOfLine (bool selecting);
  34240. void goToEndOfDocument (bool selecting);
  34241. void goToEndOfLine (bool selecting);
  34242. void deselectAll();
  34243. void selectAll();
  34244. void insertTextAtCaret (const String& textToInsert);
  34245. void insertTabAtCaret();
  34246. void cut();
  34247. void copy();
  34248. void copyThenCut();
  34249. void paste();
  34250. void backspace (bool moveInWholeWordSteps);
  34251. void deleteForward (bool moveInWholeWordSteps);
  34252. void undo();
  34253. void redo();
  34254. const Range<int> getHighlightedRegion() const;
  34255. void setHighlightedRegion (const Range<int>& newRange);
  34256. const String getTextInRange (const Range<int>& range) const;
  34257. /** Changes the current tab settings.
  34258. This lets you change the tab size and whether pressing the tab key inserts a
  34259. tab character, or its equivalent number of spaces.
  34260. */
  34261. void setTabSize (int numSpacesPerTab,
  34262. bool insertSpacesInsteadOfTabCharacters) throw();
  34263. /** Returns the current number of spaces per tab.
  34264. @see setTabSize
  34265. */
  34266. int getTabSize() const throw() { return spacesPerTab; }
  34267. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  34268. @see setTabSize
  34269. */
  34270. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  34271. /** Changes the font.
  34272. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  34273. */
  34274. void setFont (const Font& newFont);
  34275. /** Returns the font that the editor is using. */
  34276. const Font& getFont() const throw() { return font; }
  34277. /** Resets the syntax highlighting colours to the default ones provided by the
  34278. code tokeniser.
  34279. @see CodeTokeniser::getDefaultColour
  34280. */
  34281. void resetToDefaultColours();
  34282. /** Changes one of the syntax highlighting colours.
  34283. The token type values are dependent on the tokeniser being used - use
  34284. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34285. @see getColourForTokenType
  34286. */
  34287. void setColourForTokenType (int tokenType, const Colour& colour);
  34288. /** Returns one of the syntax highlighting colours.
  34289. The token type values are dependent on the tokeniser being used - use
  34290. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34291. @see setColourForTokenType
  34292. */
  34293. const Colour getColourForTokenType (int tokenType) const throw();
  34294. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  34295. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34296. methods.
  34297. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34298. */
  34299. enum ColourIds
  34300. {
  34301. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  34302. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  34303. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  34304. selected text. */
  34305. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  34306. enabled. */
  34307. };
  34308. /** Changes the size of the scrollbars. */
  34309. void setScrollbarThickness (int thickness) throw();
  34310. /** Returns the thickness of the scrollbars. */
  34311. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  34312. /** @internal */
  34313. void resized();
  34314. /** @internal */
  34315. void paint (Graphics& g);
  34316. /** @internal */
  34317. bool keyPressed (const KeyPress& key);
  34318. /** @internal */
  34319. void mouseDown (const MouseEvent& e);
  34320. /** @internal */
  34321. void mouseDrag (const MouseEvent& e);
  34322. /** @internal */
  34323. void mouseUp (const MouseEvent& e);
  34324. /** @internal */
  34325. void mouseDoubleClick (const MouseEvent& e);
  34326. /** @internal */
  34327. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34328. /** @internal */
  34329. void focusGained (FocusChangeType cause);
  34330. /** @internal */
  34331. void focusLost (FocusChangeType cause);
  34332. /** @internal */
  34333. void timerCallback();
  34334. /** @internal */
  34335. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  34336. /** @internal */
  34337. void handleAsyncUpdate();
  34338. /** @internal */
  34339. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  34340. const CodeDocument::Position& affectedTextEnd);
  34341. /** @internal */
  34342. bool isTextInputActive() const;
  34343. juce_UseDebuggingNewOperator
  34344. private:
  34345. CodeDocument& document;
  34346. Font font;
  34347. int firstLineOnScreen, gutter, spacesPerTab;
  34348. float charWidth;
  34349. int lineHeight, linesOnScreen, columnsOnScreen;
  34350. int scrollbarThickness, columnToTryToMaintain;
  34351. bool useSpacesForTabs;
  34352. double xOffset;
  34353. CodeDocument::Position caretPos;
  34354. CodeDocument::Position selectionStart, selectionEnd;
  34355. class CaretComponent;
  34356. CaretComponent* caret;
  34357. ScrollBar* verticalScrollBar;
  34358. ScrollBar* horizontalScrollBar;
  34359. enum DragType
  34360. {
  34361. notDragging,
  34362. draggingSelectionStart,
  34363. draggingSelectionEnd
  34364. };
  34365. DragType dragType;
  34366. CodeTokeniser* codeTokeniser;
  34367. Array <Colour> coloursForTokenCategories;
  34368. class CodeEditorLine;
  34369. OwnedArray <CodeEditorLine> lines;
  34370. void rebuildLineTokens();
  34371. OwnedArray <CodeDocument::Iterator> cachedIterators;
  34372. void clearCachedIterators (int firstLineToBeInvalid) throw();
  34373. void updateCachedIterators (int maxLineNum);
  34374. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  34375. void moveLineDelta (int delta, bool selecting);
  34376. void updateScrollBars();
  34377. void scrollToLineInternal (int line);
  34378. void scrollToColumnInternal (double column);
  34379. void newTransaction();
  34380. int indexToColumn (int line, int index) const throw();
  34381. int columnToIndex (int line, int column) const throw();
  34382. CodeEditorComponent (const CodeEditorComponent&);
  34383. CodeEditorComponent& operator= (const CodeEditorComponent&);
  34384. };
  34385. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34386. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  34387. #endif
  34388. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34389. #endif
  34390. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34391. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34392. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34393. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34394. /**
  34395. A simple lexical analyser for syntax colouring of C++ code.
  34396. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  34397. */
  34398. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  34399. {
  34400. public:
  34401. CPlusPlusCodeTokeniser();
  34402. ~CPlusPlusCodeTokeniser();
  34403. enum TokenType
  34404. {
  34405. tokenType_error = 0,
  34406. tokenType_comment,
  34407. tokenType_builtInKeyword,
  34408. tokenType_identifier,
  34409. tokenType_integerLiteral,
  34410. tokenType_floatLiteral,
  34411. tokenType_stringLiteral,
  34412. tokenType_operator,
  34413. tokenType_bracket,
  34414. tokenType_punctuation,
  34415. tokenType_preprocessor
  34416. };
  34417. int readNextToken (CodeDocument::Iterator& source);
  34418. const StringArray getTokenTypes();
  34419. const Colour getDefaultColour (int tokenType);
  34420. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  34421. static bool isReservedKeyword (const String& token) throw();
  34422. juce_UseDebuggingNewOperator
  34423. };
  34424. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34425. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34426. #endif
  34427. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34428. #endif
  34429. #ifndef __JUCE_LABEL_JUCEHEADER__
  34430. #endif
  34431. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34432. #endif
  34433. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34434. /*** Start of inlined file: juce_ProgressBar.h ***/
  34435. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34436. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34437. /**
  34438. A progress bar component.
  34439. To use this, just create one and make it visible. It'll run its own timer
  34440. to keep an eye on a variable that you give it, and will automatically
  34441. redraw itself when the variable changes.
  34442. For an easy way of running a background task with a dialog box showing its
  34443. progress, see the ThreadWithProgressWindow class.
  34444. @see ThreadWithProgressWindow
  34445. */
  34446. class JUCE_API ProgressBar : public Component,
  34447. public SettableTooltipClient,
  34448. private Timer
  34449. {
  34450. public:
  34451. /** Creates a ProgressBar.
  34452. @param progress pass in a reference to a double that you're going to
  34453. update with your task's progress. The ProgressBar will
  34454. monitor the value of this variable and will redraw itself
  34455. when the value changes. The range is from 0 to 1.0. Obviously
  34456. you'd better be careful not to delete this variable while the
  34457. ProgressBar still exists!
  34458. */
  34459. explicit ProgressBar (double& progress);
  34460. /** Destructor. */
  34461. ~ProgressBar();
  34462. /** Turns the percentage display on or off.
  34463. By default this is on, and the progress bar will display a text string showing
  34464. its current percentage.
  34465. */
  34466. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34467. /** Gives the progress bar a string to display inside it.
  34468. If you call this, it will turn off the percentage display.
  34469. @see setPercentageDisplay
  34470. */
  34471. void setTextToDisplay (const String& text);
  34472. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34473. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34474. methods.
  34475. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34476. */
  34477. enum ColourIds
  34478. {
  34479. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34480. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34481. classes will probably use variations on this colour. */
  34482. };
  34483. juce_UseDebuggingNewOperator
  34484. protected:
  34485. /** @internal */
  34486. void paint (Graphics& g);
  34487. /** @internal */
  34488. void lookAndFeelChanged();
  34489. /** @internal */
  34490. void visibilityChanged();
  34491. /** @internal */
  34492. void colourChanged();
  34493. private:
  34494. double& progress;
  34495. double currentValue;
  34496. bool displayPercentage;
  34497. String displayedMessage, currentMessage;
  34498. uint32 lastCallbackTime;
  34499. void timerCallback();
  34500. ProgressBar (const ProgressBar&);
  34501. ProgressBar& operator= (const ProgressBar&);
  34502. };
  34503. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34504. /*** End of inlined file: juce_ProgressBar.h ***/
  34505. #endif
  34506. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34507. /*** Start of inlined file: juce_Slider.h ***/
  34508. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34509. #define __JUCE_SLIDER_JUCEHEADER__
  34510. /**
  34511. A slider control for changing a value.
  34512. The slider can be horizontal, vertical, or rotary, and can optionally have
  34513. a text-box inside it to show an editable display of the current value.
  34514. To use it, create a Slider object and use the setSliderStyle() method
  34515. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34516. To define the values that it can be set to, see the setRange() and setValue() methods.
  34517. There are also lots of custom tweaks you can do by subclassing and overriding
  34518. some of the virtual methods, such as changing the scaling, changing the format of
  34519. the text display, custom ways of limiting the values, etc.
  34520. You can register Slider::Listener objects with a slider, and they'll be called when
  34521. the value changes.
  34522. @see Slider::Listener
  34523. */
  34524. class JUCE_API Slider : public Component,
  34525. public SettableTooltipClient,
  34526. private AsyncUpdater,
  34527. private Button::Listener,
  34528. private Label::Listener,
  34529. private Value::Listener
  34530. {
  34531. public:
  34532. /** Creates a slider.
  34533. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34534. setRange(), etc.
  34535. */
  34536. explicit Slider (const String& componentName = String::empty);
  34537. /** Destructor. */
  34538. ~Slider();
  34539. /** The types of slider available.
  34540. @see setSliderStyle, setRotaryParameters
  34541. */
  34542. enum SliderStyle
  34543. {
  34544. LinearHorizontal, /**< A traditional horizontal slider. */
  34545. LinearVertical, /**< A traditional vertical slider. */
  34546. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34547. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34548. @see setRotaryParameters */
  34549. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34550. @see setRotaryParameters */
  34551. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34552. @see setRotaryParameters */
  34553. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34554. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34555. @see setMinValue, setMaxValue */
  34556. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34557. @see setMinValue, setMaxValue */
  34558. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34559. value, with the current value being somewhere between them.
  34560. @see setMinValue, setMaxValue */
  34561. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34562. value, with the current value being somewhere between them.
  34563. @see setMinValue, setMaxValue */
  34564. };
  34565. /** Changes the type of slider interface being used.
  34566. @param newStyle the type of interface
  34567. @see setRotaryParameters, setVelocityBasedMode,
  34568. */
  34569. void setSliderStyle (SliderStyle newStyle);
  34570. /** Returns the slider's current style.
  34571. @see setSliderStyle
  34572. */
  34573. SliderStyle getSliderStyle() const { return style; }
  34574. /** Changes the properties of a rotary slider.
  34575. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34576. the slider's minimum value is represented
  34577. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34578. the slider's maximum value is represented. This must be
  34579. greater than startAngleRadians
  34580. @param stopAtEnd if true, then when the slider is dragged around past the
  34581. minimum or maximum, it'll stop there; if false, it'll wrap
  34582. back to the opposite value
  34583. */
  34584. void setRotaryParameters (float startAngleRadians,
  34585. float endAngleRadians,
  34586. bool stopAtEnd);
  34587. /** Sets the distance the mouse has to move to drag the slider across
  34588. the full extent of its range.
  34589. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34590. relative mouse movements to adjust the slider.
  34591. */
  34592. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  34593. /** Changes the way the the mouse is used when dragging the slider.
  34594. If true, this will turn on velocity-sensitive dragging, so that
  34595. the faster the mouse moves, the bigger the movement to the slider. This
  34596. helps when making accurate adjustments if the slider's range is quite large.
  34597. If false, the slider will just try to snap to wherever the mouse is.
  34598. */
  34599. void setVelocityBasedMode (bool isVelocityBased);
  34600. /** Returns true if velocity-based mode is active.
  34601. @see setVelocityBasedMode
  34602. */
  34603. bool getVelocityBasedMode() const { return isVelocityBased; }
  34604. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34605. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34606. or if you're holding down ctrl.
  34607. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34608. @param threshold the minimum number of pixels that the mouse needs to move for it
  34609. to be treated as a movement
  34610. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34611. the threshold is reached
  34612. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34613. key to toggle velocity-sensitive mode
  34614. */
  34615. void setVelocityModeParameters (double sensitivity = 1.0,
  34616. int threshold = 1,
  34617. double offset = 0.0,
  34618. bool userCanPressKeyToSwapMode = true);
  34619. /** Returns the velocity sensitivity setting.
  34620. @see setVelocityModeParameters
  34621. */
  34622. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  34623. /** Returns the velocity threshold setting.
  34624. @see setVelocityModeParameters
  34625. */
  34626. int getVelocityThreshold() const { return velocityModeThreshold; }
  34627. /** Returns the velocity offset setting.
  34628. @see setVelocityModeParameters
  34629. */
  34630. double getVelocityOffset() const { return velocityModeOffset; }
  34631. /** Returns the velocity user key setting.
  34632. @see setVelocityModeParameters
  34633. */
  34634. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  34635. /** Sets up a skew factor to alter the way values are distributed.
  34636. You may want to use a range of values on the slider where more accuracy
  34637. is required towards one end of the range, so this will logarithmically
  34638. spread the values across the length of the slider.
  34639. If the factor is < 1.0, the lower end of the range will fill more of the
  34640. slider's length; if the factor is > 1.0, the upper end of the range
  34641. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34642. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34643. method instead.
  34644. @see getSkewFactor, setSkewFactorFromMidPoint
  34645. */
  34646. void setSkewFactor (double factor);
  34647. /** Sets up a skew factor to alter the way values are distributed.
  34648. This allows you to specify the slider value that should appear in the
  34649. centre of the slider's visible range.
  34650. @see setSkewFactor, getSkewFactor
  34651. */
  34652. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  34653. /** Returns the current skew factor.
  34654. See setSkewFactor for more info.
  34655. @see setSkewFactor, setSkewFactorFromMidPoint
  34656. */
  34657. double getSkewFactor() const { return skewFactor; }
  34658. /** Used by setIncDecButtonsMode().
  34659. */
  34660. enum IncDecButtonMode
  34661. {
  34662. incDecButtonsNotDraggable,
  34663. incDecButtonsDraggable_AutoDirection,
  34664. incDecButtonsDraggable_Horizontal,
  34665. incDecButtonsDraggable_Vertical
  34666. };
  34667. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34668. can be dragged on the buttons to drag the values.
  34669. By default this is turned off. When enabled, clicking on the buttons still works
  34670. them as normal, but by holding down the mouse on a button and dragging it a little
  34671. distance, it flips into a mode where the value can be dragged. The drag direction can
  34672. either be set explicitly to be vertical or horizontal, or can be set to
  34673. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34674. are side-by-side or above each other.
  34675. */
  34676. void setIncDecButtonsMode (IncDecButtonMode mode);
  34677. /** The position of the slider's text-entry box.
  34678. @see setTextBoxStyle
  34679. */
  34680. enum TextEntryBoxPosition
  34681. {
  34682. NoTextBox, /**< Doesn't display a text box. */
  34683. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34684. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34685. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34686. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34687. };
  34688. /** Changes the location and properties of the text-entry box.
  34689. @param newPosition where it should go (or NoTextBox to not have one at all)
  34690. @param isReadOnly if true, it's a read-only display
  34691. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34692. room for the slider as well!
  34693. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34694. room for the slider as well!
  34695. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34696. */
  34697. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  34698. bool isReadOnly,
  34699. int textEntryBoxWidth,
  34700. int textEntryBoxHeight);
  34701. /** Returns the status of the text-box.
  34702. @see setTextBoxStyle
  34703. */
  34704. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  34705. /** Returns the width used for the text-box.
  34706. @see setTextBoxStyle
  34707. */
  34708. int getTextBoxWidth() const { return textBoxWidth; }
  34709. /** Returns the height used for the text-box.
  34710. @see setTextBoxStyle
  34711. */
  34712. int getTextBoxHeight() const { return textBoxHeight; }
  34713. /** Makes the text-box editable.
  34714. By default this is true, and the user can enter values into the textbox,
  34715. but it can be turned off if that's not suitable.
  34716. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34717. */
  34718. void setTextBoxIsEditable (bool shouldBeEditable);
  34719. /** Returns true if the text-box is read-only.
  34720. @see setTextBoxStyle
  34721. */
  34722. bool isTextBoxEditable() const { return editableText; }
  34723. /** If the text-box is editable, this will give it the focus so that the user can
  34724. type directly into it.
  34725. This is basically the effect as the user clicking on it.
  34726. */
  34727. void showTextBox();
  34728. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34729. focus away from it.
  34730. @param discardCurrentEditorContents if true, the slider's value will be left
  34731. unchanged; if false, the current contents of the
  34732. text editor will be used to set the slider position
  34733. before it is hidden.
  34734. */
  34735. void hideTextBox (bool discardCurrentEditorContents);
  34736. /** Changes the slider's current value.
  34737. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  34738. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34739. want to handle it.
  34740. @param newValue the new value to set - this will be restricted by the
  34741. minimum and maximum range, and will be snapped to the
  34742. nearest interval if one has been set
  34743. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34744. any Slider::Listeners or the valueChanged() method
  34745. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  34746. synchronously; if false, it will be asynchronous
  34747. */
  34748. void setValue (double newValue,
  34749. bool sendUpdateMessage = true,
  34750. bool sendMessageSynchronously = false);
  34751. /** Returns the slider's current value. */
  34752. double getValue() const;
  34753. /** Returns the Value object that represents the slider's current position.
  34754. You can use this Value object to connect the slider's position to external values or setters,
  34755. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34756. your own Value object.
  34757. @see Value, getMaxValue, getMinValueObject
  34758. */
  34759. Value& getValueObject() { return currentValue; }
  34760. /** Sets the limits that the slider's value can take.
  34761. @param newMinimum the lowest value allowed
  34762. @param newMaximum the highest value allowed
  34763. @param newInterval the steps in which the value is allowed to increase - if this
  34764. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34765. */
  34766. void setRange (double newMinimum,
  34767. double newMaximum,
  34768. double newInterval = 0);
  34769. /** Returns the current maximum value.
  34770. @see setRange
  34771. */
  34772. double getMaximum() const { return maximum; }
  34773. /** Returns the current minimum value.
  34774. @see setRange
  34775. */
  34776. double getMinimum() const { return minimum; }
  34777. /** Returns the current step-size for values.
  34778. @see setRange
  34779. */
  34780. double getInterval() const { return interval; }
  34781. /** For a slider with two or three thumbs, this returns the lower of its values.
  34782. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34783. A slider with three values also uses the normal getValue() and setValue() methods to
  34784. control the middle value.
  34785. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34786. */
  34787. double getMinValue() const;
  34788. /** For a slider with two or three thumbs, this returns the lower of its values.
  34789. You can use this Value object to connect the slider's position to external values or setters,
  34790. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34791. your own Value object.
  34792. @see Value, getMinValue, getMaxValueObject
  34793. */
  34794. Value& getMinValueObject() { return valueMin; }
  34795. /** For a slider with two or three thumbs, this sets the lower of its values.
  34796. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  34797. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34798. want to handle it.
  34799. @param newValue the new value to set - this will be restricted by the
  34800. minimum and maximum range, and will be snapped to the nearest
  34801. interval if one has been set.
  34802. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34803. any Slider::Listeners or the valueChanged() method
  34804. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  34805. synchronously; if false, it will be asynchronous
  34806. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34807. max value (in a two-value slider) or the mid value (in a three-value
  34808. slider). If false, then if this value goes beyond those values,
  34809. it will push them along with it.
  34810. @see getMinValue, setMaxValue, setValue
  34811. */
  34812. void setMinValue (double newValue,
  34813. bool sendUpdateMessage = true,
  34814. bool sendMessageSynchronously = false,
  34815. bool allowNudgingOfOtherValues = false);
  34816. /** For a slider with two or three thumbs, this returns the higher of its values.
  34817. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34818. A slider with three values also uses the normal getValue() and setValue() methods to
  34819. control the middle value.
  34820. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34821. */
  34822. double getMaxValue() const;
  34823. /** For a slider with two or three thumbs, this returns the higher of its values.
  34824. You can use this Value object to connect the slider's position to external values or setters,
  34825. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34826. your own Value object.
  34827. @see Value, getMaxValue, getMinValueObject
  34828. */
  34829. Value& getMaxValueObject() { return valueMax; }
  34830. /** For a slider with two or three thumbs, this sets the lower of its values.
  34831. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  34832. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34833. want to handle it.
  34834. @param newValue the new value to set - this will be restricted by the
  34835. minimum and maximum range, and will be snapped to the nearest
  34836. interval if one has been set.
  34837. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34838. any Slider::Listeners or the valueChanged() method
  34839. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  34840. synchronously; if false, it will be asynchronous
  34841. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34842. min value (in a two-value slider) or the mid value (in a three-value
  34843. slider). If false, then if this value goes beyond those values,
  34844. it will push them along with it.
  34845. @see getMaxValue, setMinValue, setValue
  34846. */
  34847. void setMaxValue (double newValue,
  34848. bool sendUpdateMessage = true,
  34849. bool sendMessageSynchronously = false,
  34850. bool allowNudgingOfOtherValues = false);
  34851. /** A class for receiving callbacks from a Slider.
  34852. To be told when a slider's value changes, you can register a Slider::Listener
  34853. object using Slider::addListener().
  34854. @see Slider::addListener, Slider::removeListener
  34855. */
  34856. class JUCE_API Listener
  34857. {
  34858. public:
  34859. /** Destructor. */
  34860. virtual ~Listener() {}
  34861. /** Called when the slider's value is changed.
  34862. This may be caused by dragging it, or by typing in its text entry box,
  34863. or by a call to Slider::setValue().
  34864. You can find out the new value using Slider::getValue().
  34865. @see Slider::valueChanged
  34866. */
  34867. virtual void sliderValueChanged (Slider* slider) = 0;
  34868. /** Called when the slider is about to be dragged.
  34869. This is called when a drag begins, then it's followed by multiple calls
  34870. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34871. user lets go.
  34872. @see sliderDragEnded, Slider::startedDragging
  34873. */
  34874. virtual void sliderDragStarted (Slider* slider);
  34875. /** Called after a drag operation has finished.
  34876. @see sliderDragStarted, Slider::stoppedDragging
  34877. */
  34878. virtual void sliderDragEnded (Slider* slider);
  34879. };
  34880. /** Adds a listener to be called when this slider's value changes. */
  34881. void addListener (Listener* listener);
  34882. /** Removes a previously-registered listener. */
  34883. void removeListener (Listener* listener);
  34884. /** This lets you choose whether double-clicking moves the slider to a given position.
  34885. By default this is turned off, but it's handy if you want a double-click to act
  34886. as a quick way of resetting a slider. Just pass in the value you want it to
  34887. go to when double-clicked.
  34888. @see getDoubleClickReturnValue
  34889. */
  34890. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  34891. double valueToSetOnDoubleClick);
  34892. /** Returns the values last set by setDoubleClickReturnValue() method.
  34893. Sets isEnabled to true if double-click is enabled, and returns the value
  34894. that was set.
  34895. @see setDoubleClickReturnValue
  34896. */
  34897. double getDoubleClickReturnValue (bool& isEnabled) const;
  34898. /** Tells the slider whether to keep sending change messages while the user
  34899. is dragging the slider.
  34900. If set to true, a change message will only be sent when the user has
  34901. dragged the slider and let go. If set to false (the default), then messages
  34902. will be continuously sent as they drag it while the mouse button is still
  34903. held down.
  34904. */
  34905. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  34906. /** This lets you change whether the slider thumb jumps to the mouse position
  34907. when you click.
  34908. By default, this is true. If it's false, then the slider moves with relative
  34909. motion when you drag it.
  34910. This only applies to linear bars, and won't affect two- or three- value
  34911. sliders.
  34912. */
  34913. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  34914. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34915. slider is being dragged.
  34916. This can be handy if your slider doesn't have a text-box, so that users can
  34917. see the value just when they're changing it.
  34918. If you pass a component as the parentComponentToUse parameter, the pop-up
  34919. bubble will be added as a child of that component when it's needed. If you
  34920. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34921. transparent window, so if you're using an OS that can't do transparent windows
  34922. you'll have to add it to a parent component instead).
  34923. */
  34924. void setPopupDisplayEnabled (bool isEnabled,
  34925. Component* parentComponentToUse);
  34926. /** If this is set to true, then right-clicking on the slider will pop-up
  34927. a menu to let the user change the way it works.
  34928. By default this is turned off, but when turned on, the menu will include
  34929. things like velocity sensitivity, and for rotary sliders, whether they
  34930. use a linear or rotary mouse-drag to move them.
  34931. */
  34932. void setPopupMenuEnabled (bool menuEnabled);
  34933. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34934. By default it's enabled.
  34935. */
  34936. void setScrollWheelEnabled (bool enabled);
  34937. /** Returns a number to indicate which thumb is currently being dragged by the
  34938. mouse.
  34939. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34940. the maximum-value thumb, or -1 if none is currently down.
  34941. */
  34942. int getThumbBeingDragged() const { return sliderBeingDragged; }
  34943. /** Callback to indicate that the user is about to start dragging the slider.
  34944. @see Slider::Listener::sliderDragStarted
  34945. */
  34946. virtual void startedDragging();
  34947. /** Callback to indicate that the user has just stopped dragging the slider.
  34948. @see Slider::Listener::sliderDragEnded
  34949. */
  34950. virtual void stoppedDragging();
  34951. /** Callback to indicate that the user has just moved the slider.
  34952. @see Slider::Listener::sliderValueChanged
  34953. */
  34954. virtual void valueChanged();
  34955. /** Subclasses can override this to convert a text string to a value.
  34956. When the user enters something into the text-entry box, this method is
  34957. called to convert it to a value.
  34958. The default routine just tries to convert it to a double.
  34959. @see getTextFromValue
  34960. */
  34961. virtual double getValueFromText (const String& text);
  34962. /** Turns the slider's current value into a text string.
  34963. Subclasses can override this to customise the formatting of the text-entry box.
  34964. The default implementation just turns the value into a string, using
  34965. a number of decimal places based on the range interval. If a suffix string
  34966. has been set using setTextValueSuffix(), this will be appended to the text.
  34967. @see getValueFromText
  34968. */
  34969. virtual const String getTextFromValue (double value);
  34970. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34971. a string.
  34972. This is used by the default implementation of getTextFromValue(), and is just
  34973. appended to the numeric value. For more advanced formatting, you can override
  34974. getTextFromValue() and do something else.
  34975. */
  34976. void setTextValueSuffix (const String& suffix);
  34977. /** Returns the suffix that was set by setTextValueSuffix(). */
  34978. const String getTextValueSuffix() const;
  34979. /** Allows a user-defined mapping of distance along the slider to its value.
  34980. The default implementation for this performs the skewing operation that
  34981. can be set up in the setSkewFactor() method. Override it if you need
  34982. some kind of custom mapping instead, but make sure you also implement the
  34983. inverse function in valueToProportionOfLength().
  34984. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34985. @returns the slider value that is represented by this position
  34986. @see valueToProportionOfLength
  34987. */
  34988. virtual double proportionOfLengthToValue (double proportion);
  34989. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34990. The default implementation for this performs the skewing operation that
  34991. can be set up in the setSkewFactor() method. Override it if you need
  34992. some kind of custom mapping instead, but make sure you also implement the
  34993. inverse function in proportionOfLengthToValue().
  34994. @param value a valid slider value, between the range of values specified in
  34995. setRange()
  34996. @returns a value 0 to 1.0 indicating the distance along the slider that
  34997. represents this value
  34998. @see proportionOfLengthToValue
  34999. */
  35000. virtual double valueToProportionOfLength (double value);
  35001. /** Returns the X or Y coordinate of a value along the slider's length.
  35002. If the slider is horizontal, this will be the X coordinate of the given
  35003. value, relative to the left of the slider. If it's vertical, then this will
  35004. be the Y coordinate, relative to the top of the slider.
  35005. If the slider is rotary, this will throw an assertion and return 0. If the
  35006. value is out-of-range, it will be constrained to the length of the slider.
  35007. */
  35008. float getPositionOfValue (double value);
  35009. /** This can be overridden to allow the slider to snap to user-definable values.
  35010. If overridden, it will be called when the user tries to move the slider to
  35011. a given position, and allows a subclass to sanity-check this value, possibly
  35012. returning a different value to use instead.
  35013. @param attemptedValue the value the user is trying to enter
  35014. @param userIsDragging true if the user is dragging with the mouse; false if
  35015. they are entering the value using the text box
  35016. @returns the value to use instead
  35017. */
  35018. virtual double snapValue (double attemptedValue, bool userIsDragging);
  35019. /** This can be called to force the text box to update its contents.
  35020. (Not normally needed, as this is done automatically).
  35021. */
  35022. void updateText();
  35023. /** True if the slider moves horizontally. */
  35024. bool isHorizontal() const;
  35025. /** True if the slider moves vertically. */
  35026. bool isVertical() const;
  35027. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  35028. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35029. methods.
  35030. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35031. */
  35032. enum ColourIds
  35033. {
  35034. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  35035. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  35036. and feel class how this is used. */
  35037. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  35038. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  35039. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  35040. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  35041. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  35042. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  35043. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  35044. };
  35045. juce_UseDebuggingNewOperator
  35046. protected:
  35047. /** @internal */
  35048. void labelTextChanged (Label*);
  35049. /** @internal */
  35050. void paint (Graphics& g);
  35051. /** @internal */
  35052. void resized();
  35053. /** @internal */
  35054. void mouseDown (const MouseEvent& e);
  35055. /** @internal */
  35056. void mouseUp (const MouseEvent& e);
  35057. /** @internal */
  35058. void mouseDrag (const MouseEvent& e);
  35059. /** @internal */
  35060. void mouseDoubleClick (const MouseEvent& e);
  35061. /** @internal */
  35062. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35063. /** @internal */
  35064. void modifierKeysChanged (const ModifierKeys& modifiers);
  35065. /** @internal */
  35066. void buttonClicked (Button* button);
  35067. /** @internal */
  35068. void lookAndFeelChanged();
  35069. /** @internal */
  35070. void enablementChanged();
  35071. /** @internal */
  35072. void focusOfChildComponentChanged (FocusChangeType cause);
  35073. /** @internal */
  35074. void handleAsyncUpdate();
  35075. /** @internal */
  35076. void colourChanged();
  35077. /** @internal */
  35078. void valueChanged (Value& value);
  35079. /** Returns the best number of decimal places to use when displaying numbers.
  35080. This is calculated from the slider's interval setting.
  35081. */
  35082. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  35083. private:
  35084. ListenerList <Listener> listeners;
  35085. Value currentValue, valueMin, valueMax;
  35086. double lastCurrentValue, lastValueMin, lastValueMax;
  35087. double minimum, maximum, interval, doubleClickReturnValue;
  35088. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  35089. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  35090. int velocityModeThreshold;
  35091. float rotaryStart, rotaryEnd;
  35092. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  35093. int mouseDragStartX, mouseDragStartY;
  35094. int sliderRegionStart, sliderRegionSize;
  35095. int sliderBeingDragged;
  35096. int pixelsForFullDragExtent;
  35097. Rectangle<int> sliderRect;
  35098. String textSuffix;
  35099. SliderStyle style;
  35100. TextEntryBoxPosition textBoxPos;
  35101. int textBoxWidth, textBoxHeight;
  35102. IncDecButtonMode incDecButtonMode;
  35103. bool editableText : 1, doubleClickToValue : 1;
  35104. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  35105. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  35106. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  35107. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  35108. Label* valueBox;
  35109. Button* incButton;
  35110. Button* decButton;
  35111. ScopedPointer <Component> popupDisplay;
  35112. Component* parentForPopupDisplay;
  35113. float getLinearSliderPos (double value);
  35114. void restoreMouseIfHidden();
  35115. void sendDragStart();
  35116. void sendDragEnd();
  35117. double constrainedValue (double value) const;
  35118. void triggerChangeMessage (bool synchronous);
  35119. bool incDecDragDirectionIsHorizontal() const;
  35120. Slider (const Slider&);
  35121. Slider& operator= (const Slider&);
  35122. };
  35123. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  35124. typedef Slider::Listener SliderListener;
  35125. #endif // __JUCE_SLIDER_JUCEHEADER__
  35126. /*** End of inlined file: juce_Slider.h ***/
  35127. #endif
  35128. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35129. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  35130. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35131. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35132. /**
  35133. A component that displays a strip of column headings for a table, and allows these
  35134. to be resized, dragged around, etc.
  35135. This is just the component that goes at the top of a table. You can use it
  35136. directly for custom components, or to create a simple table, use the
  35137. TableListBox class.
  35138. To use one of these, create it and use addColumn() to add all the columns that you need.
  35139. Each column must be given a unique ID number that's used to refer to it.
  35140. @see TableListBox, TableHeaderComponent::Listener
  35141. */
  35142. class JUCE_API TableHeaderComponent : public Component,
  35143. private AsyncUpdater
  35144. {
  35145. public:
  35146. /** Creates an empty table header.
  35147. */
  35148. TableHeaderComponent();
  35149. /** Destructor. */
  35150. ~TableHeaderComponent();
  35151. /** A combination of these flags are passed into the addColumn() method to specify
  35152. the properties of a column.
  35153. */
  35154. enum ColumnPropertyFlags
  35155. {
  35156. 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. */
  35157. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  35158. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  35159. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  35160. 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. */
  35161. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  35162. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  35163. /** This set of default flags is used as the default parameter value in addColumn(). */
  35164. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  35165. /** A quick way of combining flags for a column that's not resizable. */
  35166. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  35167. /** A quick way of combining flags for a column that's not resizable or sortable. */
  35168. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  35169. /** A quick way of combining flags for a column that's not sortable. */
  35170. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  35171. };
  35172. /** Adds a column to the table.
  35173. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  35174. registered listeners.
  35175. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  35176. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  35177. a unique ID. This is used to identify the column later on, after the user may have
  35178. changed the order that they appear in
  35179. @param width the initial width of the column, in pixels
  35180. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  35181. if the 'resizable' flag is specified for this column
  35182. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  35183. if the 'resizable' flag is specified for this column
  35184. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  35185. properties of this column
  35186. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  35187. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  35188. all columns, not just the index amongst those that are currently visible
  35189. */
  35190. void addColumn (const String& columnName,
  35191. int columnId,
  35192. int width,
  35193. int minimumWidth = 30,
  35194. int maximumWidth = -1,
  35195. int propertyFlags = defaultFlags,
  35196. int insertIndex = -1);
  35197. /** Removes a column with the given ID.
  35198. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  35199. registered listeners.
  35200. */
  35201. void removeColumn (int columnIdToRemove);
  35202. /** Deletes all columns from the table.
  35203. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  35204. registered listeners.
  35205. */
  35206. void removeAllColumns();
  35207. /** Returns the number of columns in the table.
  35208. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  35209. return the total number of columns, including hidden ones.
  35210. @see isColumnVisible
  35211. */
  35212. int getNumColumns (bool onlyCountVisibleColumns) const;
  35213. /** Returns the name for a column.
  35214. @see setColumnName
  35215. */
  35216. const String getColumnName (int columnId) const;
  35217. /** Changes the name of a column. */
  35218. void setColumnName (int columnId, const String& newName);
  35219. /** Moves a column to a different index in the table.
  35220. @param columnId the column to move
  35221. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  35222. */
  35223. void moveColumn (int columnId, int newVisibleIndex);
  35224. /** Returns the width of one of the columns.
  35225. */
  35226. int getColumnWidth (int columnId) const;
  35227. /** Changes the width of a column.
  35228. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  35229. */
  35230. void setColumnWidth (int columnId, int newWidth);
  35231. /** Shows or hides a column.
  35232. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  35233. @see isColumnVisible
  35234. */
  35235. void setColumnVisible (int columnId, bool shouldBeVisible);
  35236. /** Returns true if this column is currently visible.
  35237. @see setColumnVisible
  35238. */
  35239. bool isColumnVisible (int columnId) const;
  35240. /** Changes the column which is the sort column.
  35241. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  35242. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  35243. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  35244. @see getSortColumnId, isSortedForwards, reSortTable
  35245. */
  35246. void setSortColumnId (int columnId, bool sortForwards);
  35247. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  35248. @see setSortColumnId, isSortedForwards
  35249. */
  35250. int getSortColumnId() const;
  35251. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  35252. @see setSortColumnId
  35253. */
  35254. bool isSortedForwards() const;
  35255. /** Triggers a re-sort of the table according to the current sort-column.
  35256. If you modifiy the table's contents, you can call this to signal that the table needs
  35257. to be re-sorted.
  35258. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  35259. tableSortOrderChanged() method of any listeners).
  35260. */
  35261. void reSortTable();
  35262. /** Returns the total width of all the visible columns in the table.
  35263. */
  35264. int getTotalWidth() const;
  35265. /** Returns the index of a given column.
  35266. If there's no such column ID, this will return -1.
  35267. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  35268. otherwise it'll return the index amongst all the columns, including any hidden ones.
  35269. */
  35270. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  35271. /** Returns the ID of the column at a given index.
  35272. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  35273. otherwise it'll count it amongst all the columns, including any hidden ones.
  35274. If the index is out-of-range, it'll return 0.
  35275. */
  35276. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  35277. /** Returns the rectangle containing of one of the columns.
  35278. The index is an index from 0 to the number of columns that are currently visible (hidden
  35279. ones are not counted). It returns a rectangle showing the position of the column relative
  35280. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  35281. */
  35282. const Rectangle<int> getColumnPosition (int index) const;
  35283. /** Finds the column ID at a given x-position in the component.
  35284. If there is a column at this point this returns its ID, or if not, it will return 0.
  35285. */
  35286. int getColumnIdAtX (int xToFind) const;
  35287. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  35288. entire width of the component.
  35289. By default this is disabled. Turning it on also means that when resizing a column, those
  35290. on the right will be squashed to fit.
  35291. */
  35292. void setStretchToFitActive (bool shouldStretchToFit);
  35293. /** Returns true if stretch-to-fit has been enabled.
  35294. @see setStretchToFitActive
  35295. */
  35296. bool isStretchToFitActive() const;
  35297. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  35298. specified width, keeping their relative proportions the same.
  35299. If the minimum widths of the columns are too wide to fit into this space, it may
  35300. actually end up wider.
  35301. */
  35302. void resizeAllColumnsToFit (int targetTotalWidth);
  35303. /** Enables or disables the pop-up menu.
  35304. The default menu allows the user to show or hide columns. You can add custom
  35305. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  35306. By default the menu is enabled.
  35307. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  35308. */
  35309. void setPopupMenuActive (bool hasMenu);
  35310. /** Returns true if the pop-up menu is enabled.
  35311. @see setPopupMenuActive
  35312. */
  35313. bool isPopupMenuActive() const;
  35314. /** Returns a string that encapsulates the table's current layout.
  35315. This can be restored later using restoreFromString(). It saves the order of
  35316. the columns, the currently-sorted column, and the widths.
  35317. @see restoreFromString
  35318. */
  35319. const String toString() const;
  35320. /** Restores the state of the table, based on a string previously created with
  35321. toString().
  35322. @see toString
  35323. */
  35324. void restoreFromString (const String& storedVersion);
  35325. /**
  35326. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  35327. You can register one of these objects for table events using TableHeaderComponent::addListener()
  35328. and TableHeaderComponent::removeListener().
  35329. @see TableHeaderComponent
  35330. */
  35331. class JUCE_API Listener
  35332. {
  35333. public:
  35334. Listener() {}
  35335. /** Destructor. */
  35336. virtual ~Listener() {}
  35337. /** This is called when some of the table's columns are added, removed, hidden,
  35338. or rearranged.
  35339. */
  35340. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  35341. /** This is called when one or more of the table's columns are resized.
  35342. */
  35343. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  35344. /** This is called when the column by which the table should be sorted is changed.
  35345. */
  35346. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  35347. /** This is called when the user begins or ends dragging one of the columns around.
  35348. When the user starts dragging a column, this is called with the ID of that
  35349. column. When they finish dragging, it is called again with 0 as the ID.
  35350. */
  35351. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  35352. int columnIdNowBeingDragged);
  35353. };
  35354. /** Adds a listener to be informed about things that happen to the header. */
  35355. void addListener (Listener* newListener);
  35356. /** Removes a previously-registered listener. */
  35357. void removeListener (Listener* listenerToRemove);
  35358. /** This can be overridden to handle a mouse-click on one of the column headers.
  35359. The default implementation will use this click to call getSortColumnId() and
  35360. change the sort order.
  35361. */
  35362. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  35363. /** This can be overridden to add custom items to the pop-up menu.
  35364. If you override this, you should call the superclass's method to add its
  35365. column show/hide items, if you want them on the menu as well.
  35366. Then to handle the result, override reactToMenuItem().
  35367. @see reactToMenuItem
  35368. */
  35369. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  35370. /** Override this to handle any custom items that you have added to the
  35371. pop-up menu with an addMenuItems() override.
  35372. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35373. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35374. handle the items that it had added.
  35375. @see addMenuItems
  35376. */
  35377. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  35378. /** @internal */
  35379. void paint (Graphics& g);
  35380. /** @internal */
  35381. void resized();
  35382. /** @internal */
  35383. void mouseMove (const MouseEvent&);
  35384. /** @internal */
  35385. void mouseEnter (const MouseEvent&);
  35386. /** @internal */
  35387. void mouseExit (const MouseEvent&);
  35388. /** @internal */
  35389. void mouseDown (const MouseEvent&);
  35390. /** @internal */
  35391. void mouseDrag (const MouseEvent&);
  35392. /** @internal */
  35393. void mouseUp (const MouseEvent&);
  35394. /** @internal */
  35395. const MouseCursor getMouseCursor();
  35396. /** Can be overridden for more control over the pop-up menu behaviour. */
  35397. virtual void showColumnChooserMenu (int columnIdClicked);
  35398. juce_UseDebuggingNewOperator
  35399. private:
  35400. struct ColumnInfo
  35401. {
  35402. String name;
  35403. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35404. double lastDeliberateWidth;
  35405. bool isVisible() const;
  35406. };
  35407. OwnedArray <ColumnInfo> columns;
  35408. Array <Listener*> listeners;
  35409. ScopedPointer <Component> dragOverlayComp;
  35410. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35411. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35412. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35413. ColumnInfo* getInfoForId (int columnId) const;
  35414. int visibleIndexToTotalIndex (int visibleIndex) const;
  35415. void sendColumnsChanged();
  35416. void handleAsyncUpdate();
  35417. void beginDrag (const MouseEvent&);
  35418. void endDrag (int finalIndex);
  35419. int getResizeDraggerAt (int mouseX) const;
  35420. void updateColumnUnderMouse (int x, int y);
  35421. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35422. TableHeaderComponent (const TableHeaderComponent&);
  35423. TableHeaderComponent operator= (const TableHeaderComponent&);
  35424. };
  35425. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  35426. typedef TableHeaderComponent::Listener TableHeaderListener;
  35427. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35428. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  35429. #endif
  35430. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35431. /*** Start of inlined file: juce_TableListBox.h ***/
  35432. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35433. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35434. /**
  35435. One of these is used by a TableListBox as the data model for the table's contents.
  35436. The virtual methods that you override in this class take care of drawing the
  35437. table cells, and reacting to events.
  35438. @see TableListBox
  35439. */
  35440. class JUCE_API TableListBoxModel
  35441. {
  35442. public:
  35443. TableListBoxModel() {}
  35444. /** Destructor. */
  35445. virtual ~TableListBoxModel() {}
  35446. /** This must return the number of rows currently in the table.
  35447. If the number of rows changes, you must call TableListBox::updateContent() to
  35448. cause it to refresh the list.
  35449. */
  35450. virtual int getNumRows() = 0;
  35451. /** This must draw the background behind one of the rows in the table.
  35452. The graphics context has its origin at the row's top-left, and your method
  35453. should fill the area specified by the width and height parameters.
  35454. */
  35455. virtual void paintRowBackground (Graphics& g,
  35456. int rowNumber,
  35457. int width, int height,
  35458. bool rowIsSelected) = 0;
  35459. /** This must draw one of the cells.
  35460. The graphics context's origin will already be set to the top-left of the cell,
  35461. whose size is specified by (width, height).
  35462. */
  35463. virtual void paintCell (Graphics& g,
  35464. int rowNumber,
  35465. int columnId,
  35466. int width, int height,
  35467. bool rowIsSelected) = 0;
  35468. /** This is used to create or update a custom component to go in a cell.
  35469. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35470. and handle mouse clicks with cellClicked().
  35471. This method will be called whenever a custom component might need to be updated - e.g.
  35472. when the table is changed, or TableListBox::updateContent() is called.
  35473. If you don't need a custom component for the specified cell, then return 0.
  35474. If you do want a custom component, and the existingComponentToUpdate is null, then
  35475. this method must create a new component suitable for the cell, and return it.
  35476. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35477. by this method. In this case, the method must either update it to make sure it's correctly representing
  35478. the given cell (which may be different from the one that the component was created for), or it can
  35479. delete this component and return a new one.
  35480. */
  35481. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35482. Component* existingComponentToUpdate);
  35483. /** This callback is made when the user clicks on one of the cells in the table.
  35484. The mouse event's coordinates will be relative to the entire table row.
  35485. @see cellDoubleClicked, backgroundClicked
  35486. */
  35487. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35488. /** This callback is made when the user clicks on one of the cells in the table.
  35489. The mouse event's coordinates will be relative to the entire table row.
  35490. @see cellClicked, backgroundClicked
  35491. */
  35492. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35493. /** This can be overridden to react to the user double-clicking on a part of the list where
  35494. there are no rows.
  35495. @see cellClicked
  35496. */
  35497. virtual void backgroundClicked();
  35498. /** This callback is made when the table's sort order is changed.
  35499. This could be because the user has clicked a column header, or because the
  35500. TableHeaderComponent::setSortColumnId() method was called.
  35501. If you implement this, your method should re-sort the table using the given
  35502. column as the key.
  35503. */
  35504. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  35505. /** Returns the best width for one of the columns.
  35506. If you implement this method, you should measure the width of all the items
  35507. in this column, and return the best size.
  35508. Returning 0 means that the column shouldn't be changed.
  35509. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35510. */
  35511. virtual int getColumnAutoSizeWidth (int columnId);
  35512. /** Returns a tooltip for a particular cell in the table.
  35513. */
  35514. virtual const String getCellTooltip (int rowNumber, int columnId);
  35515. /** Override this to be informed when rows are selected or deselected.
  35516. @see ListBox::selectedRowsChanged()
  35517. */
  35518. virtual void selectedRowsChanged (int lastRowSelected);
  35519. /** Override this to be informed when the delete key is pressed.
  35520. @see ListBox::deleteKeyPressed()
  35521. */
  35522. virtual void deleteKeyPressed (int lastRowSelected);
  35523. /** Override this to be informed when the return key is pressed.
  35524. @see ListBox::returnKeyPressed()
  35525. */
  35526. virtual void returnKeyPressed (int lastRowSelected);
  35527. /** Override this to be informed when the list is scrolled.
  35528. This might be caused by the user moving the scrollbar, or by programmatic changes
  35529. to the list position.
  35530. */
  35531. virtual void listWasScrolled();
  35532. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35533. If this returns a non-empty name then when the user drags a row, the table will try to
  35534. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35535. drag-and-drop operation, using this string as the source description, and the listbox
  35536. itself as the source component.
  35537. @see DragAndDropContainer::startDragging
  35538. */
  35539. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35540. };
  35541. /**
  35542. A table of cells, using a TableHeaderComponent as its header.
  35543. This component makes it easy to create a table by providing a TableListBoxModel as
  35544. the data source.
  35545. @see TableListBoxModel, TableHeaderComponent
  35546. */
  35547. class JUCE_API TableListBox : public ListBox,
  35548. private ListBoxModel,
  35549. private TableHeaderComponent::Listener
  35550. {
  35551. public:
  35552. /** Creates a TableListBox.
  35553. The model pointer passed-in can be null, in which case you can set it later
  35554. with setModel().
  35555. */
  35556. TableListBox (const String& componentName,
  35557. TableListBoxModel* model);
  35558. /** Destructor. */
  35559. ~TableListBox();
  35560. /** Changes the TableListBoxModel that is being used for this table.
  35561. */
  35562. void setModel (TableListBoxModel* newModel);
  35563. /** Returns the model currently in use. */
  35564. TableListBoxModel* getModel() const { return model; }
  35565. /** Returns the header component being used in this table. */
  35566. TableHeaderComponent* getHeader() const { return header; }
  35567. /** Changes the height of the table header component.
  35568. @see getHeaderHeight
  35569. */
  35570. void setHeaderHeight (int newHeight);
  35571. /** Returns the height of the table header.
  35572. @see setHeaderHeight
  35573. */
  35574. int getHeaderHeight() const;
  35575. /** Resizes a column to fit its contents.
  35576. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35577. and applies that to the column.
  35578. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35579. */
  35580. void autoSizeColumn (int columnId);
  35581. /** Calls autoSizeColumn() for all columns in the table. */
  35582. void autoSizeAllColumns();
  35583. /** Enables or disables the auto size options on the popup menu.
  35584. By default, these are enabled.
  35585. */
  35586. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  35587. /** True if the auto-size options should be shown on the menu.
  35588. @see setAutoSizeMenuOptionsShown
  35589. */
  35590. bool isAutoSizeMenuOptionShown() const;
  35591. /** Returns the position of one of the cells in the table.
  35592. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35593. the table component's top-left. The row number isn't checked to see if it's
  35594. in-range, but the column ID must exist or this will return an empty rectangle.
  35595. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35596. top-left of the table's top-left cell.
  35597. */
  35598. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  35599. bool relativeToComponentTopLeft) const;
  35600. /** Returns the component that currently represents a given cell.
  35601. If the component for this cell is off-screen or if the position is out-of-range,
  35602. this may return 0.
  35603. @see getCellPosition
  35604. */
  35605. Component* getCellComponent (int columnId, int rowNumber) const;
  35606. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35607. @see ListBox::scrollToEnsureRowIsOnscreen
  35608. */
  35609. void scrollToEnsureColumnIsOnscreen (int columnId);
  35610. /** @internal */
  35611. int getNumRows();
  35612. /** @internal */
  35613. void paintListBoxItem (int, Graphics&, int, int, bool);
  35614. /** @internal */
  35615. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35616. /** @internal */
  35617. void selectedRowsChanged (int lastRowSelected);
  35618. /** @internal */
  35619. void deleteKeyPressed (int currentSelectedRow);
  35620. /** @internal */
  35621. void returnKeyPressed (int currentSelectedRow);
  35622. /** @internal */
  35623. void backgroundClicked();
  35624. /** @internal */
  35625. void listWasScrolled();
  35626. /** @internal */
  35627. void tableColumnsChanged (TableHeaderComponent*);
  35628. /** @internal */
  35629. void tableColumnsResized (TableHeaderComponent*);
  35630. /** @internal */
  35631. void tableSortOrderChanged (TableHeaderComponent*);
  35632. /** @internal */
  35633. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35634. /** @internal */
  35635. void resized();
  35636. juce_UseDebuggingNewOperator
  35637. private:
  35638. TableHeaderComponent* header;
  35639. TableListBoxModel* model;
  35640. int columnIdNowBeingDragged;
  35641. bool autoSizeOptionsShown;
  35642. void updateColumnComponents() const;
  35643. TableListBox (const TableListBox&);
  35644. TableListBox& operator= (const TableListBox&);
  35645. };
  35646. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35647. /*** End of inlined file: juce_TableListBox.h ***/
  35648. #endif
  35649. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35650. #endif
  35651. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35652. #endif
  35653. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35654. #endif
  35655. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35656. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  35657. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35658. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35659. /**
  35660. A factory object which can create ToolbarItemComponent objects.
  35661. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35662. that it can create.
  35663. Each type of item is identified by a unique ID, and multiple instances of an
  35664. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35665. bars).
  35666. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35667. */
  35668. class JUCE_API ToolbarItemFactory
  35669. {
  35670. public:
  35671. ToolbarItemFactory();
  35672. /** Destructor. */
  35673. virtual ~ToolbarItemFactory();
  35674. /** A set of reserved item ID values, used for the built-in item types.
  35675. */
  35676. enum SpecialItemIds
  35677. {
  35678. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35679. can be placed between sets of items to break them into groups. */
  35680. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35681. items.*/
  35682. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35683. either side of it, filling any available space. */
  35684. };
  35685. /** Must return a list of the IDs for all the item types that this factory can create.
  35686. The ids should be added to the array that is passed-in.
  35687. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35688. and the predefined IDs in the SpecialItemIds enum.
  35689. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35690. to this list if you want your toolbar to be able to contain those items.
  35691. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35692. of available items, and their order on the palette will reflect the order in which
  35693. they appear on this list.
  35694. @see ToolbarItemPalette
  35695. */
  35696. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35697. /** Must return the set of items that should be added to a toolbar as its default set.
  35698. This method is used by Toolbar::addDefaultItems() to determine which items to
  35699. create.
  35700. The items that your method adds to the array that is passed-in will be added to the
  35701. toolbar in the same order. Items can appear in the list more than once.
  35702. */
  35703. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35704. /** Must create an instance of one of the items that the factory lists in its
  35705. getAllToolbarItemIds() method.
  35706. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35707. method, except for the built-in item types from the SpecialItemIds enum, which
  35708. are created internally by the toolbar code.
  35709. Try not to keep a pointer to the object that is returned, as it will be deleted
  35710. automatically by the toolbar, and remember that multiple instances of the same
  35711. item type are likely to exist at the same time.
  35712. */
  35713. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  35714. };
  35715. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35716. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  35717. #endif
  35718. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35719. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  35720. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35721. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35722. /**
  35723. A component containing a list of toolbar items, which the user can drag onto
  35724. a toolbar to add them.
  35725. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35726. which automatically shows one of these in a dialog box with lots of extra controls.
  35727. @see Toolbar
  35728. */
  35729. class JUCE_API ToolbarItemPalette : public Component,
  35730. public DragAndDropContainer
  35731. {
  35732. public:
  35733. /** Creates a palette of items for a given factory, with the aim of adding them
  35734. to the specified toolbar.
  35735. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35736. set of items that are shown in this palette.
  35737. The toolbar and factory must not be deleted while this object exists.
  35738. */
  35739. ToolbarItemPalette (ToolbarItemFactory& factory,
  35740. Toolbar* toolbar);
  35741. /** Destructor. */
  35742. ~ToolbarItemPalette();
  35743. /** @internal */
  35744. void resized();
  35745. juce_UseDebuggingNewOperator
  35746. private:
  35747. ToolbarItemFactory& factory;
  35748. Toolbar* toolbar;
  35749. Viewport* viewport;
  35750. friend class Toolbar;
  35751. void replaceComponent (ToolbarItemComponent* comp);
  35752. ToolbarItemPalette (const ToolbarItemPalette&);
  35753. ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35754. };
  35755. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35756. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  35757. #endif
  35758. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35759. /*** Start of inlined file: juce_TreeView.h ***/
  35760. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35761. #define __JUCE_TREEVIEW_JUCEHEADER__
  35762. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  35763. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35764. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35765. /**
  35766. Components derived from this class can have files dropped onto them by an external application.
  35767. @see DragAndDropContainer
  35768. */
  35769. class JUCE_API FileDragAndDropTarget
  35770. {
  35771. public:
  35772. /** Destructor. */
  35773. virtual ~FileDragAndDropTarget() {}
  35774. /** Callback to check whether this target is interested in the set of files being offered.
  35775. Note that this will be called repeatedly when the user is dragging the mouse around over your
  35776. component, so don't do anything time-consuming in here, like opening the files to have a look
  35777. inside them!
  35778. @param files the set of (absolute) pathnames of the files that the user is dragging
  35779. @returns true if this component wants to receive the other callbacks regarging this
  35780. type of object; if it returns false, no other callbacks will be made.
  35781. */
  35782. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  35783. /** Callback to indicate that some files are being dragged over this component.
  35784. This gets called when the user moves the mouse into this component while dragging.
  35785. Use this callback as a trigger to make your component repaint itself to give the
  35786. user feedback about whether the files can be dropped here or not.
  35787. @param files the set of (absolute) pathnames of the files that the user is dragging
  35788. @param x the mouse x position, relative to this component
  35789. @param y the mouse y position, relative to this component
  35790. */
  35791. virtual void fileDragEnter (const StringArray& files, int x, int y);
  35792. /** Callback to indicate that the user is dragging some files over this component.
  35793. This gets called when the user moves the mouse over this component while dragging.
  35794. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  35795. this lets you know what happens in-between.
  35796. @param files the set of (absolute) pathnames of the files that the user is dragging
  35797. @param x the mouse x position, relative to this component
  35798. @param y the mouse y position, relative to this component
  35799. */
  35800. virtual void fileDragMove (const StringArray& files, int x, int y);
  35801. /** Callback to indicate that the mouse has moved away from this component.
  35802. This gets called when the user moves the mouse out of this component while dragging
  35803. the files.
  35804. If you've used fileDragEnter() to repaint your component and give feedback, use this
  35805. as a signal to repaint it in its normal state.
  35806. @param files the set of (absolute) pathnames of the files that the user is dragging
  35807. */
  35808. virtual void fileDragExit (const StringArray& files);
  35809. /** Callback to indicate that the user has dropped the files onto this component.
  35810. When the user drops the files, this get called, and you can use the files in whatever
  35811. way is appropriate.
  35812. Note that after this is called, the fileDragExit method may not be called, so you should
  35813. clean up in here if there's anything you need to do when the drag finishes.
  35814. @param files the set of (absolute) pathnames of the files that the user is dragging
  35815. @param x the mouse x position, relative to this component
  35816. @param y the mouse y position, relative to this component
  35817. */
  35818. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  35819. };
  35820. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35821. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  35822. class TreeView;
  35823. /**
  35824. An item in a treeview.
  35825. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  35826. own sub-items.
  35827. To implement an item that contains sub-items, override the itemOpennessChanged()
  35828. method so that when it is opened, it adds the new sub-items to itself using the
  35829. addSubItem method. Depending on the nature of the item it might choose to only
  35830. do this the first time it's opened, or it might want to refresh itself each time.
  35831. It also has the option of deleting its sub-items when it is closed, or leaving them
  35832. in place.
  35833. */
  35834. class JUCE_API TreeViewItem
  35835. {
  35836. public:
  35837. /** Constructor. */
  35838. TreeViewItem();
  35839. /** Destructor. */
  35840. virtual ~TreeViewItem();
  35841. /** Returns the number of sub-items that have been added to this item.
  35842. Note that this doesn't mean much if the node isn't open.
  35843. @see getSubItem, mightContainSubItems, addSubItem
  35844. */
  35845. int getNumSubItems() const throw();
  35846. /** Returns one of the item's sub-items.
  35847. Remember that the object returned might get deleted at any time when its parent
  35848. item is closed or refreshed, depending on the nature of the items you're using.
  35849. @see getNumSubItems
  35850. */
  35851. TreeViewItem* getSubItem (int index) const throw();
  35852. /** Removes any sub-items. */
  35853. void clearSubItems();
  35854. /** Adds a sub-item.
  35855. @param newItem the object to add to the item's sub-item list. Once added, these can be
  35856. found using getSubItem(). When the items are later removed with
  35857. removeSubItem() (or when this item is deleted), they will be deleted.
  35858. @param insertPosition the index which the new item should have when it's added. If this
  35859. value is less than 0, the item will be added to the end of the list.
  35860. */
  35861. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  35862. /** Removes one of the sub-items.
  35863. @param index the item to remove
  35864. @param deleteItem if true, the item that is removed will also be deleted.
  35865. */
  35866. void removeSubItem (int index, bool deleteItem = true);
  35867. /** Returns the TreeView to which this item belongs. */
  35868. TreeView* getOwnerView() const throw() { return ownerView; }
  35869. /** Returns the item within which this item is contained. */
  35870. TreeViewItem* getParentItem() const throw() { return parentItem; }
  35871. /** True if this item is currently open in the treeview. */
  35872. bool isOpen() const throw();
  35873. /** Opens or closes the item.
  35874. When opened or closed, the item's itemOpennessChanged() method will be called,
  35875. and a subclass should use this callback to create and add any sub-items that
  35876. it needs to.
  35877. @see itemOpennessChanged, mightContainSubItems
  35878. */
  35879. void setOpen (bool shouldBeOpen);
  35880. /** True if this item is currently selected.
  35881. Use this when painting the node, to decide whether to draw it as selected or not.
  35882. */
  35883. bool isSelected() const throw();
  35884. /** Selects or deselects the item.
  35885. This will cause a callback to itemSelectionChanged()
  35886. */
  35887. void setSelected (bool shouldBeSelected,
  35888. bool deselectOtherItemsFirst);
  35889. /** Returns the rectangle that this item occupies.
  35890. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  35891. top-left of the TreeView comp, so this will depend on the scroll-position of
  35892. the tree. If false, it is relative to the top-left of the topmost item in the
  35893. tree (so this would be unaffected by scrolling the view).
  35894. */
  35895. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  35896. /** Sends a signal to the treeview to make it refresh itself.
  35897. Call this if your items have changed and you want the tree to update to reflect
  35898. this.
  35899. */
  35900. void treeHasChanged() const throw();
  35901. /** Sends a repaint message to redraw just this item.
  35902. Note that you should only call this if you want to repaint a superficial change. If
  35903. you're altering the tree's nodes, you should instead call treeHasChanged().
  35904. */
  35905. void repaintItem() const;
  35906. /** Returns the row number of this item in the tree.
  35907. The row number of an item will change according to which items are open.
  35908. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  35909. */
  35910. int getRowNumberInTree() const throw();
  35911. /** Returns true if all the item's parent nodes are open.
  35912. This is useful to check whether the item might actually be visible or not.
  35913. */
  35914. bool areAllParentsOpen() const throw();
  35915. /** Changes whether lines are drawn to connect any sub-items to this item.
  35916. By default, line-drawing is turned on.
  35917. */
  35918. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  35919. /** Tells the tree whether this item can potentially be opened.
  35920. If your item could contain sub-items, this should return true; if it returns
  35921. false then the tree will not try to open the item. This determines whether or
  35922. not the item will be drawn with a 'plus' button next to it.
  35923. */
  35924. virtual bool mightContainSubItems() = 0;
  35925. /** Returns a string to uniquely identify this item.
  35926. If you're planning on using the TreeView::getOpennessState() method, then
  35927. these strings will be used to identify which nodes are open. The string
  35928. should be unique amongst the item's sibling items, but it's ok for there
  35929. to be duplicates at other levels of the tree.
  35930. If you're not going to store the state, then it's ok not to bother implementing
  35931. this method.
  35932. */
  35933. virtual const String getUniqueName() const;
  35934. /** Called when an item is opened or closed.
  35935. When setOpen() is called and the item has specified that it might
  35936. have sub-items with the mightContainSubItems() method, this method
  35937. is called to let the item create or manage its sub-items.
  35938. So when this is called with isNowOpen set to true (i.e. when the item is being
  35939. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  35940. refresh its sub-item list.
  35941. When this is called with isNowOpen set to false, the subclass might want
  35942. to use clearSubItems() to save on space, or it might choose to leave them,
  35943. depending on the nature of the tree.
  35944. You could also use this callback as a trigger to start a background process
  35945. which asynchronously creates sub-items and adds them, if that's more
  35946. appropriate for the task in hand.
  35947. @see mightContainSubItems
  35948. */
  35949. virtual void itemOpennessChanged (bool isNowOpen);
  35950. /** Must return the width required by this item.
  35951. If your item needs to have a particular width in pixels, return that value; if
  35952. you'd rather have it just fill whatever space is available in the treeview,
  35953. return -1.
  35954. If all your items return -1, no horizontal scrollbar will be shown, but if any
  35955. items have fixed widths and extend beyond the width of the treeview, a
  35956. scrollbar will appear.
  35957. Each item can be a different width, but if they change width, you should call
  35958. treeHasChanged() to update the tree.
  35959. */
  35960. virtual int getItemWidth() const { return -1; }
  35961. /** Must return the height required by this item.
  35962. This is the height in pixels that the item will take up. Items in the tree
  35963. can be different heights, but if they change height, you should call
  35964. treeHasChanged() to update the tree.
  35965. */
  35966. virtual int getItemHeight() const { return 20; }
  35967. /** You can override this method to return false if you don't want to allow the
  35968. user to select this item.
  35969. */
  35970. virtual bool canBeSelected() const { return true; }
  35971. /** Creates a component that will be used to represent this item.
  35972. You don't have to implement this method - if it returns 0 then no component
  35973. will be used for the item, and you can just draw it using the paintItem()
  35974. callback. But if you do return a component, it will be positioned in the
  35975. treeview so that it can be used to represent this item.
  35976. The component returned will be managed by the treeview, so always return
  35977. a new component, and don't keep a reference to it, as the treeview will
  35978. delete it later when it goes off the screen or is no longer needed. Also
  35979. bear in mind that if the component keeps a reference to the item that
  35980. created it, that item could be deleted before the component. Its position
  35981. and size will be completely managed by the tree, so don't attempt to move it
  35982. around.
  35983. Something you may want to do with your component is to give it a pointer to
  35984. the TreeView that created it. This is perfectly safe, and there's no danger
  35985. of it becoming a dangling pointer because the TreeView will always delete
  35986. the component before it is itself deleted.
  35987. As long as you stick to these rules you can return whatever kind of
  35988. component you like. It's most useful if you're doing things like drag-and-drop
  35989. of items, or want to use a Label component to edit item names, etc.
  35990. */
  35991. virtual Component* createItemComponent() { return 0; }
  35992. /** Draws the item's contents.
  35993. You can choose to either implement this method and draw each item, or you
  35994. can use createItemComponent() to create a component that will represent the
  35995. item.
  35996. If all you need in your tree is to be able to draw the items and detect when
  35997. the user selects or double-clicks one of them, it's probably enough to
  35998. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  35999. complicated interactions, you may need to use createItemComponent() instead.
  36000. @param g the graphics context to draw into
  36001. @param width the width of the area available for drawing
  36002. @param height the height of the area available for drawing
  36003. */
  36004. virtual void paintItem (Graphics& g, int width, int height);
  36005. /** Draws the item's open/close button.
  36006. If you don't implement this method, the default behaviour is to
  36007. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  36008. it for custom effects.
  36009. */
  36010. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  36011. /** Called when the user clicks on this item.
  36012. If you're using createItemComponent() to create a custom component for the
  36013. item, the mouse-clicks might not make it through to the treeview, but this
  36014. is how you find out about clicks when just drawing each item individually.
  36015. The associated mouse-event details are passed in, so you can find out about
  36016. which button, where it was, etc.
  36017. @see itemDoubleClicked
  36018. */
  36019. virtual void itemClicked (const MouseEvent& e);
  36020. /** Called when the user double-clicks on this item.
  36021. If you're using createItemComponent() to create a custom component for the
  36022. item, the mouse-clicks might not make it through to the treeview, but this
  36023. is how you find out about clicks when just drawing each item individually.
  36024. The associated mouse-event details are passed in, so you can find out about
  36025. which button, where it was, etc.
  36026. If not overridden, the base class method here will open or close the item as
  36027. if the 'plus' button had been clicked.
  36028. @see itemClicked
  36029. */
  36030. virtual void itemDoubleClicked (const MouseEvent& e);
  36031. /** Called when the item is selected or deselected.
  36032. Use this if you want to do something special when the item's selectedness
  36033. changes. By default it'll get repainted when this happens.
  36034. */
  36035. virtual void itemSelectionChanged (bool isNowSelected);
  36036. /** The item can return a tool tip string here if it wants to.
  36037. @see TooltipClient
  36038. */
  36039. virtual const String getTooltip();
  36040. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  36041. If this returns a non-empty name then when the user drags an item, the treeview will
  36042. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  36043. a drag-and-drop operation, using this string as the source description, with the treeview
  36044. itself as the source component.
  36045. If you need more complex drag-and-drop behaviour, you can use custom components for
  36046. the items, and use those to trigger the drag.
  36047. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  36048. isInterestedInFileDrag(), etc.
  36049. @see DragAndDropContainer::startDragging
  36050. */
  36051. virtual const String getDragSourceDescription();
  36052. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  36053. method and return true.
  36054. If you return true and allow some files to be dropped, you'll also need to implement the
  36055. filesDropped() method to do something with them.
  36056. Note that this will be called often, so make your implementation very quick! There's
  36057. certainly no time to try opening the files and having a think about what's inside them!
  36058. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  36059. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  36060. */
  36061. virtual bool isInterestedInFileDrag (const StringArray& files);
  36062. /** When files are dropped into this item, this callback is invoked.
  36063. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  36064. The insertIndex value indicates where in the list of sub-items the files were dropped.
  36065. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  36066. */
  36067. virtual void filesDropped (const StringArray& files, int insertIndex);
  36068. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  36069. If you implement this method, you'll also need to implement itemDropped() in order to handle
  36070. the items when they are dropped.
  36071. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  36072. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  36073. */
  36074. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  36075. /** When a things are dropped into this item, this callback is invoked.
  36076. For this to work, you need to have also implemented isInterestedInDragSource().
  36077. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  36078. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  36079. */
  36080. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  36081. /** Sets a flag to indicate that the item wants to be allowed
  36082. to draw all the way across to the left edge of the treeview.
  36083. By default this is false, which means that when the paintItem()
  36084. method is called, its graphics context is clipped to only allow
  36085. drawing within the item's rectangle. If this flag is set to true,
  36086. then the graphics context isn't clipped on its left side, so it
  36087. can draw all the way across to the left margin. Note that the
  36088. context will still have its origin in the same place though, so
  36089. the coordinates of anything to its left will be negative. It's
  36090. mostly useful if you want to draw a wider bar behind the
  36091. highlighted item.
  36092. */
  36093. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  36094. /** Saves the current state of open/closed nodes so it can be restored later.
  36095. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  36096. and records it as XML. To identify node objects it uses the
  36097. TreeViewItem::getUniqueName() method to create named paths. This
  36098. means that the same state of open/closed nodes can be restored to a
  36099. completely different instance of the tree, as long as it contains nodes
  36100. whose unique names are the same.
  36101. You'd normally want to use TreeView::getOpennessState() rather than call it
  36102. for a specific item, but this can be handy if you need to briefly save the state
  36103. for a section of the tree.
  36104. The caller is responsible for deleting the object that is returned.
  36105. @see TreeView::getOpennessState, restoreOpennessState
  36106. */
  36107. XmlElement* getOpennessState() const throw();
  36108. /** Restores the openness of this item and all its sub-items from a saved state.
  36109. See TreeView::restoreOpennessState for more details.
  36110. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  36111. for a specific item, but this can be handy if you need to briefly save the state
  36112. for a section of the tree.
  36113. @see TreeView::restoreOpennessState, getOpennessState
  36114. */
  36115. void restoreOpennessState (const XmlElement& xml) throw();
  36116. /** Returns the index of this item in its parent's sub-items. */
  36117. int getIndexInParent() const throw();
  36118. /** Returns true if this item is the last of its parent's sub-itens. */
  36119. bool isLastOfSiblings() const throw();
  36120. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  36121. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  36122. The string takes the form of a path, constructed from the getUniqueName() of this
  36123. item and all its parents, so these must all be correctly implemented for it to work.
  36124. @see TreeView::findItemFromIdentifierString, getUniqueName
  36125. */
  36126. const String getItemIdentifierString() const;
  36127. juce_UseDebuggingNewOperator
  36128. private:
  36129. TreeView* ownerView;
  36130. TreeViewItem* parentItem;
  36131. OwnedArray <TreeViewItem> subItems;
  36132. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  36133. int uid;
  36134. bool selected : 1;
  36135. bool redrawNeeded : 1;
  36136. bool drawLinesInside : 1;
  36137. bool drawsInLeftMargin : 1;
  36138. unsigned int openness : 2;
  36139. friend class TreeView;
  36140. friend class TreeViewContentComponent;
  36141. void updatePositions (int newY);
  36142. int getIndentX() const throw();
  36143. void setOwnerView (TreeView* newOwner) throw();
  36144. void paintRecursively (Graphics& g, int width);
  36145. TreeViewItem* getTopLevelItem() throw();
  36146. TreeViewItem* findItemRecursively (int y) throw();
  36147. TreeViewItem* getDeepestOpenParentItem() throw();
  36148. int getNumRows() const throw();
  36149. TreeViewItem* getItemOnRow (int index) throw();
  36150. void deselectAllRecursively();
  36151. int countSelectedItemsRecursively() const throw();
  36152. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  36153. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  36154. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  36155. TreeViewItem (const TreeViewItem&);
  36156. TreeViewItem& operator= (const TreeViewItem&);
  36157. };
  36158. /**
  36159. A tree-view component.
  36160. Use one of these to hold and display a structure of TreeViewItem objects.
  36161. */
  36162. class JUCE_API TreeView : public Component,
  36163. public SettableTooltipClient,
  36164. public FileDragAndDropTarget,
  36165. public DragAndDropTarget,
  36166. private AsyncUpdater
  36167. {
  36168. public:
  36169. /** Creates an empty treeview.
  36170. Once you've got a treeview component, you'll need to give it something to
  36171. display, using the setRootItem() method.
  36172. */
  36173. TreeView (const String& componentName = String::empty);
  36174. /** Destructor. */
  36175. ~TreeView();
  36176. /** Sets the item that is displayed in the treeview.
  36177. A tree has a single root item which contains as many sub-items as it needs. If
  36178. you want the tree to contain a number of root items, you should still use a single
  36179. root item above these, but hide it using setRootItemVisible().
  36180. You can pass in 0 to this method to clear the tree and remove its current root item.
  36181. The object passed in will not be deleted by the treeview, it's up to the caller
  36182. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  36183. this item until you've removed it from the tree, either by calling setRootItem (0),
  36184. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  36185. to delete it.
  36186. */
  36187. void setRootItem (TreeViewItem* newRootItem);
  36188. /** Returns the tree's root item.
  36189. This will be the last object passed to setRootItem(), or 0 if none has been set.
  36190. */
  36191. TreeViewItem* getRootItem() const throw() { return rootItem; }
  36192. /** This will remove and delete the current root item.
  36193. It's a convenient way of deleting the item and calling setRootItem (0).
  36194. */
  36195. void deleteRootItem();
  36196. /** Changes whether the tree's root item is shown or not.
  36197. If the root item is hidden, only its sub-items will be shown in the treeview - this
  36198. lets you make the tree look as if it's got many root items. If it's hidden, this call
  36199. will also make sure the root item is open (otherwise the treeview would look empty).
  36200. */
  36201. void setRootItemVisible (bool shouldBeVisible);
  36202. /** Returns true if the root item is visible.
  36203. @see setRootItemVisible
  36204. */
  36205. bool isRootItemVisible() const throw() { return rootItemVisible; }
  36206. /** Sets whether items are open or closed by default.
  36207. Normally, items are closed until the user opens them, but you can use this
  36208. to make them default to being open until explicitly closed.
  36209. @see areItemsOpenByDefault
  36210. */
  36211. void setDefaultOpenness (bool isOpenByDefault);
  36212. /** Returns true if the tree's items default to being open.
  36213. @see setDefaultOpenness
  36214. */
  36215. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  36216. /** This sets a flag to indicate that the tree can be used for multi-selection.
  36217. You can always select multiple items internally by calling the
  36218. TreeViewItem::setSelected() method, but this flag indicates whether the user
  36219. is allowed to multi-select by clicking on the tree.
  36220. By default it is disabled.
  36221. @see isMultiSelectEnabled
  36222. */
  36223. void setMultiSelectEnabled (bool canMultiSelect);
  36224. /** Returns whether multi-select has been enabled for the tree.
  36225. @see setMultiSelectEnabled
  36226. */
  36227. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  36228. /** Sets a flag to indicate whether to hide the open/close buttons.
  36229. @see areOpenCloseButtonsVisible
  36230. */
  36231. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  36232. /** Returns whether open/close buttons are shown.
  36233. @see setOpenCloseButtonsVisible
  36234. */
  36235. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  36236. /** Deselects any items that are currently selected. */
  36237. void clearSelectedItems();
  36238. /** Returns the number of items that are currently selected.
  36239. @see getSelectedItem, clearSelectedItems
  36240. */
  36241. int getNumSelectedItems() const throw();
  36242. /** Returns one of the selected items in the tree.
  36243. @param index the index, 0 to (getNumSelectedItems() - 1)
  36244. */
  36245. TreeViewItem* getSelectedItem (int index) const throw();
  36246. /** Returns the number of rows the tree is using.
  36247. This will depend on which items are open.
  36248. @see TreeViewItem::getRowNumberInTree()
  36249. */
  36250. int getNumRowsInTree() const;
  36251. /** Returns the item on a particular row of the tree.
  36252. If the index is out of range, this will return 0.
  36253. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  36254. */
  36255. TreeViewItem* getItemOnRow (int index) const;
  36256. /** Returns the item that contains a given y position.
  36257. The y is relative to the top of the TreeView component.
  36258. */
  36259. TreeViewItem* getItemAt (int yPosition) const throw();
  36260. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  36261. void scrollToKeepItemVisible (TreeViewItem* item);
  36262. /** Returns the treeview's Viewport object. */
  36263. Viewport* getViewport() const throw();
  36264. /** Returns the number of pixels by which each nested level of the tree is indented.
  36265. @see setIndentSize
  36266. */
  36267. int getIndentSize() const throw() { return indentSize; }
  36268. /** Changes the distance by which each nested level of the tree is indented.
  36269. @see getIndentSize
  36270. */
  36271. void setIndentSize (int newIndentSize);
  36272. /** Searches the tree for an item with the specified identifier.
  36273. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  36274. If no such item exists, this will return false. If the item is found, all of its items
  36275. will be automatically opened.
  36276. */
  36277. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  36278. /** Saves the current state of open/closed nodes so it can be restored later.
  36279. This takes a snapshot of which nodes have been explicitly opened or closed,
  36280. and records it as XML. To identify node objects it uses the
  36281. TreeViewItem::getUniqueName() method to create named paths. This
  36282. means that the same state of open/closed nodes can be restored to a
  36283. completely different instance of the tree, as long as it contains nodes
  36284. whose unique names are the same.
  36285. The caller is responsible for deleting the object that is returned.
  36286. @param alsoIncludeScrollPosition if this is true, the state will also
  36287. include information about where the
  36288. tree has been scrolled to vertically,
  36289. so this can also be restored
  36290. @see restoreOpennessState
  36291. */
  36292. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  36293. /** Restores a previously saved arrangement of open/closed nodes.
  36294. This will try to restore a snapshot of the tree's state that was created by
  36295. the getOpennessState() method. If any of the nodes named in the original
  36296. XML aren't present in this tree, they will be ignored.
  36297. @see getOpennessState
  36298. */
  36299. void restoreOpennessState (const XmlElement& newState);
  36300. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  36301. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36302. methods.
  36303. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36304. */
  36305. enum ColourIds
  36306. {
  36307. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  36308. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  36309. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  36310. };
  36311. /** @internal */
  36312. void paint (Graphics& g);
  36313. /** @internal */
  36314. void resized();
  36315. /** @internal */
  36316. bool keyPressed (const KeyPress& key);
  36317. /** @internal */
  36318. void colourChanged();
  36319. /** @internal */
  36320. void enablementChanged();
  36321. /** @internal */
  36322. bool isInterestedInFileDrag (const StringArray& files);
  36323. /** @internal */
  36324. void fileDragEnter (const StringArray& files, int x, int y);
  36325. /** @internal */
  36326. void fileDragMove (const StringArray& files, int x, int y);
  36327. /** @internal */
  36328. void fileDragExit (const StringArray& files);
  36329. /** @internal */
  36330. void filesDropped (const StringArray& files, int x, int y);
  36331. /** @internal */
  36332. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  36333. /** @internal */
  36334. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36335. /** @internal */
  36336. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36337. /** @internal */
  36338. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  36339. /** @internal */
  36340. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36341. juce_UseDebuggingNewOperator
  36342. private:
  36343. friend class TreeViewItem;
  36344. friend class TreeViewContentComponent;
  36345. class TreeViewport;
  36346. class InsertPointHighlight;
  36347. class TargetGroupHighlight;
  36348. friend class ScopedPointer<TreeViewport>;
  36349. friend class ScopedPointer<InsertPointHighlight>;
  36350. friend class ScopedPointer<TargetGroupHighlight>;
  36351. ScopedPointer<TreeViewport> viewport;
  36352. CriticalSection nodeAlterationLock;
  36353. TreeViewItem* rootItem;
  36354. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  36355. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  36356. int indentSize;
  36357. bool defaultOpenness : 1;
  36358. bool needsRecalculating : 1;
  36359. bool rootItemVisible : 1;
  36360. bool multiSelectEnabled : 1;
  36361. bool openCloseButtonsVisible : 1;
  36362. void itemsChanged() throw();
  36363. void handleAsyncUpdate();
  36364. void moveSelectedRow (int delta);
  36365. void updateButtonUnderMouse (const MouseEvent& e);
  36366. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  36367. void hideDragHighlight() throw();
  36368. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  36369. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  36370. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  36371. const StringArray& files, const String& sourceDescription,
  36372. Component* sourceComponent) const throw();
  36373. TreeView (const TreeView&);
  36374. TreeView& operator= (const TreeView&);
  36375. };
  36376. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  36377. /*** End of inlined file: juce_TreeView.h ***/
  36378. #endif
  36379. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36380. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36381. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36382. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36383. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  36384. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36385. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36386. /*** Start of inlined file: juce_FileFilter.h ***/
  36387. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36388. #define __JUCE_FILEFILTER_JUCEHEADER__
  36389. /**
  36390. Interface for deciding which files are suitable for something.
  36391. For example, this is used by DirectoryContentsList to select which files
  36392. go into the list.
  36393. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36394. */
  36395. class JUCE_API FileFilter
  36396. {
  36397. public:
  36398. /** Creates a filter with the given description.
  36399. The description can be returned later with the getDescription() method.
  36400. */
  36401. FileFilter (const String& filterDescription);
  36402. /** Destructor. */
  36403. virtual ~FileFilter();
  36404. /** Returns the description that the filter was created with. */
  36405. const String& getDescription() const throw();
  36406. /** Should return true if this file is suitable for inclusion in whatever context
  36407. the object is being used.
  36408. */
  36409. virtual bool isFileSuitable (const File& file) const = 0;
  36410. /** Should return true if this directory is suitable for inclusion in whatever context
  36411. the object is being used.
  36412. */
  36413. virtual bool isDirectorySuitable (const File& file) const = 0;
  36414. protected:
  36415. String description;
  36416. };
  36417. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36418. /*** End of inlined file: juce_FileFilter.h ***/
  36419. /**
  36420. A class to asynchronously scan for details about the files in a directory.
  36421. This keeps a list of files and some information about them, using a background
  36422. thread to scan for more files. As files are found, it broadcasts change messages
  36423. to tell any listeners.
  36424. @see FileListComponent, FileBrowserComponent
  36425. */
  36426. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36427. public TimeSliceClient
  36428. {
  36429. public:
  36430. /** Creates a directory list.
  36431. To set the directory it should point to, use setDirectory(), which will
  36432. also start it scanning for files on the background thread.
  36433. When the background thread finds and adds new files to this list, the
  36434. ChangeBroadcaster class will send a change message, so you can register
  36435. listeners and update them when the list changes.
  36436. @param fileFilter an optional filter to select which files are
  36437. included in the list. If this is 0, then all files
  36438. and directories are included. Make sure that the
  36439. filter doesn't get deleted during the lifetime of this
  36440. object
  36441. @param threadToUse a thread object that this list can use
  36442. to scan for files as a background task. Make sure
  36443. that the thread you give it has been started, or you
  36444. won't get any files!
  36445. */
  36446. DirectoryContentsList (const FileFilter* fileFilter,
  36447. TimeSliceThread& threadToUse);
  36448. /** Destructor. */
  36449. ~DirectoryContentsList();
  36450. /** Sets the directory to look in for files.
  36451. If the directory that's passed in is different to the current one, this will
  36452. also start the background thread scanning it for files.
  36453. */
  36454. void setDirectory (const File& directory,
  36455. bool includeDirectories,
  36456. bool includeFiles);
  36457. /** Returns the directory that's currently being used. */
  36458. const File& getDirectory() const;
  36459. /** Clears the list, and stops the thread scanning for files. */
  36460. void clear();
  36461. /** Clears the list and restarts scanning the directory for files. */
  36462. void refresh();
  36463. /** True if the background thread hasn't yet finished scanning for files. */
  36464. bool isStillLoading() const;
  36465. /** Tells the list whether or not to ignore hidden files.
  36466. By default these are ignored.
  36467. */
  36468. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  36469. /** Returns true if hidden files are ignored.
  36470. @see setIgnoresHiddenFiles
  36471. */
  36472. bool ignoresHiddenFiles() const;
  36473. /** Contains cached information about one of the files in a DirectoryContentsList.
  36474. */
  36475. struct FileInfo
  36476. {
  36477. /** The filename.
  36478. This isn't a full pathname, it's just the last part of the path, same as you'd
  36479. get from File::getFileName().
  36480. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36481. */
  36482. String filename;
  36483. /** File size in bytes. */
  36484. int64 fileSize;
  36485. /** File modification time.
  36486. As supplied by File::getLastModificationTime().
  36487. */
  36488. Time modificationTime;
  36489. /** File creation time.
  36490. As supplied by File::getCreationTime().
  36491. */
  36492. Time creationTime;
  36493. /** True if the file is a directory. */
  36494. bool isDirectory;
  36495. /** True if the file is read-only. */
  36496. bool isReadOnly;
  36497. };
  36498. /** Returns the number of files currently available in the list.
  36499. The info about one of these files can be retrieved with getFileInfo() or
  36500. getFile().
  36501. Obviously as the background thread runs and scans the directory for files, this
  36502. number will change.
  36503. @see getFileInfo, getFile
  36504. */
  36505. int getNumFiles() const;
  36506. /** Returns the cached information about one of the files in the list.
  36507. If the index is in-range, this will return true and will copy the file's details
  36508. to the structure that is passed-in.
  36509. If it returns false, then the index wasn't in range, and the structure won't
  36510. be affected.
  36511. @see getNumFiles, getFile
  36512. */
  36513. bool getFileInfo (int index, FileInfo& resultInfo) const;
  36514. /** Returns one of the files in the list.
  36515. @param index should be less than getNumFiles(). If this is out-of-range, the
  36516. return value will be File::nonexistent
  36517. @see getNumFiles, getFileInfo
  36518. */
  36519. const File getFile (int index) const;
  36520. /** Returns the file filter being used.
  36521. The filter is specified in the constructor.
  36522. */
  36523. const FileFilter* getFilter() const { return fileFilter; }
  36524. /** @internal */
  36525. bool useTimeSlice();
  36526. /** @internal */
  36527. TimeSliceThread& getTimeSliceThread() { return thread; }
  36528. /** @internal */
  36529. static int compareElements (const DirectoryContentsList::FileInfo* first,
  36530. const DirectoryContentsList::FileInfo* second);
  36531. juce_UseDebuggingNewOperator
  36532. private:
  36533. File root;
  36534. const FileFilter* fileFilter;
  36535. TimeSliceThread& thread;
  36536. int fileTypeFlags;
  36537. CriticalSection fileListLock;
  36538. OwnedArray <FileInfo> files;
  36539. ScopedPointer <DirectoryIterator> fileFindHandle;
  36540. bool volatile shouldStop;
  36541. void changed();
  36542. bool checkNextFile (bool& hasChanged);
  36543. bool addFile (const File& file, bool isDir,
  36544. const int64 fileSize, const Time& modTime,
  36545. const Time& creationTime, bool isReadOnly);
  36546. void setTypeFlags (int newFlags);
  36547. DirectoryContentsList (const DirectoryContentsList&);
  36548. DirectoryContentsList& operator= (const DirectoryContentsList&);
  36549. };
  36550. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36551. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  36552. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  36553. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36554. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36555. /**
  36556. A listener for user selection events in a file browser.
  36557. This is used by a FileBrowserComponent or FileListComponent.
  36558. */
  36559. class JUCE_API FileBrowserListener
  36560. {
  36561. public:
  36562. /** Destructor. */
  36563. virtual ~FileBrowserListener();
  36564. /** Callback when the user selects a different file in the browser. */
  36565. virtual void selectionChanged() = 0;
  36566. /** Callback when the user clicks on a file in the browser. */
  36567. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36568. /** Callback when the user double-clicks on a file in the browser. */
  36569. virtual void fileDoubleClicked (const File& file) = 0;
  36570. };
  36571. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36572. /*** End of inlined file: juce_FileBrowserListener.h ***/
  36573. /**
  36574. A base class for components that display a list of the files in a directory.
  36575. @see DirectoryContentsList
  36576. */
  36577. class JUCE_API DirectoryContentsDisplayComponent
  36578. {
  36579. public:
  36580. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  36581. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36582. /** Destructor. */
  36583. virtual ~DirectoryContentsDisplayComponent();
  36584. /** Returns the number of files the user has got selected.
  36585. @see getSelectedFile
  36586. */
  36587. virtual int getNumSelectedFiles() const = 0;
  36588. /** Returns one of the files that the user has currently selected.
  36589. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  36590. @see getNumSelectedFiles
  36591. */
  36592. virtual const File getSelectedFile (int index) const = 0;
  36593. /** Deselects any selected files. */
  36594. virtual void deselectAllFiles() = 0;
  36595. /** Scrolls this view to the top. */
  36596. virtual void scrollToTop() = 0;
  36597. /** Adds a listener to be told when files are selected or clicked.
  36598. @see removeListener
  36599. */
  36600. void addListener (FileBrowserListener* listener);
  36601. /** Removes a listener.
  36602. @see addListener
  36603. */
  36604. void removeListener (FileBrowserListener* listener);
  36605. /** A set of colour IDs to use to change the colour of various aspects of the list.
  36606. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36607. methods.
  36608. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36609. */
  36610. enum ColourIds
  36611. {
  36612. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36613. textColourId = 0x1000541, /**< The colour for the text. */
  36614. };
  36615. /** @internal */
  36616. void sendSelectionChangeMessage();
  36617. /** @internal */
  36618. void sendDoubleClickMessage (const File& file);
  36619. /** @internal */
  36620. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36621. juce_UseDebuggingNewOperator
  36622. protected:
  36623. DirectoryContentsList& fileList;
  36624. ListenerList <FileBrowserListener> listeners;
  36625. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36626. DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36627. };
  36628. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36629. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36630. #endif
  36631. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36632. #endif
  36633. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36634. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  36635. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36636. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36637. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  36638. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36639. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36640. /**
  36641. Base class for components that live inside a file chooser dialog box and
  36642. show previews of the files that get selected.
  36643. One of these allows special extra information to be displayed for files
  36644. in a dialog box as the user selects them. Each time the current file or
  36645. directory is changed, the selectedFileChanged() method will be called
  36646. to allow it to update itself appropriately.
  36647. @see FileChooser, ImagePreviewComponent
  36648. */
  36649. class JUCE_API FilePreviewComponent : public Component
  36650. {
  36651. public:
  36652. /** Creates a FilePreviewComponent. */
  36653. FilePreviewComponent();
  36654. /** Destructor. */
  36655. ~FilePreviewComponent();
  36656. /** Called to indicate that the user's currently selected file has changed.
  36657. @param newSelectedFile the newly selected file or directory, which may be
  36658. File::nonexistent if none is selected.
  36659. */
  36660. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36661. juce_UseDebuggingNewOperator
  36662. private:
  36663. FilePreviewComponent (const FilePreviewComponent&);
  36664. FilePreviewComponent& operator= (const FilePreviewComponent&);
  36665. };
  36666. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36667. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  36668. /**
  36669. A component for browsing and selecting a file or directory to open or save.
  36670. This contains a FileListComponent and adds various boxes and controls for
  36671. navigating and selecting a file. It can work in different modes so that it can
  36672. be used for loading or saving a file, or for choosing a directory.
  36673. @see FileChooserDialogBox, FileChooser, FileListComponent
  36674. */
  36675. class JUCE_API FileBrowserComponent : public Component,
  36676. public ChangeBroadcaster,
  36677. private FileBrowserListener,
  36678. private TextEditor::Listener,
  36679. private Button::Listener,
  36680. private ComboBox::Listener,
  36681. private FileFilter
  36682. {
  36683. public:
  36684. /** Various options for the browser.
  36685. A combination of these is passed into the FileBrowserComponent constructor.
  36686. */
  36687. enum FileChooserFlags
  36688. {
  36689. openMode = 1, /**< specifies that the component should allow the user to
  36690. choose an existing file with the intention of opening it. */
  36691. saveMode = 2, /**< specifies that the component should allow the user to specify
  36692. the name of a file that will be used to save something. */
  36693. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  36694. conjunction with canSelectDirectories). */
  36695. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  36696. conjuction with canSelectFiles). */
  36697. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  36698. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  36699. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  36700. };
  36701. /** Creates a FileBrowserComponent.
  36702. @param flags A combination of flags from the FileChooserFlags enumeration,
  36703. used to specify the component's behaviour. The flags must contain
  36704. either openMode or saveMode, and canSelectFiles and/or
  36705. canSelectDirectories.
  36706. @param initialFileOrDirectory The file or directory that should be selected when
  36707. the component begins. If this is File::nonexistent,
  36708. a default directory will be chosen.
  36709. @param fileFilter an optional filter to use to determine which files
  36710. are shown. If this is 0 then all files are displayed. Note
  36711. that a pointer is kept internally to this object, so
  36712. make sure that it is not deleted before the browser object
  36713. is deleted.
  36714. @param previewComp an optional preview component that will be used to
  36715. show previews of files that the user selects
  36716. */
  36717. FileBrowserComponent (int flags,
  36718. const File& initialFileOrDirectory,
  36719. const FileFilter* fileFilter,
  36720. FilePreviewComponent* previewComp);
  36721. /** Destructor. */
  36722. ~FileBrowserComponent();
  36723. /** Returns the number of files that the user has got selected.
  36724. If multiple select isn't active, this will only be 0 or 1. To get the complete
  36725. list of files they've chosen, pass an index to getCurrentFile().
  36726. */
  36727. int getNumSelectedFiles() const throw();
  36728. /** Returns one of the files that the user has chosen.
  36729. If the box has multi-select enabled, the index lets you specify which of the files
  36730. to get - see getNumSelectedFiles() to find out how many files were chosen.
  36731. @see getHighlightedFile
  36732. */
  36733. const File getSelectedFile (int index) const throw();
  36734. /** Deselects any files that are currently selected.
  36735. */
  36736. void deselectAllFiles();
  36737. /** Returns true if the currently selected file(s) are usable.
  36738. This can be used to decide whether the user can press "ok" for the
  36739. current file. What it does depends on the mode, so for example in an "open"
  36740. mode, this only returns true if a file has been selected and if it exists.
  36741. In a "save" mode, a non-existent file would also be valid.
  36742. */
  36743. bool currentFileIsValid() const;
  36744. /** This returns the last item in the view that the user has highlighted.
  36745. This may be different from getCurrentFile(), which returns the value
  36746. that is shown in the filename box, and if there are multiple selections,
  36747. this will only return one of them.
  36748. @see getSelectedFile
  36749. */
  36750. const File getHighlightedFile() const throw();
  36751. /** Returns the directory whose contents are currently being shown in the listbox. */
  36752. const File getRoot() const;
  36753. /** Changes the directory that's being shown in the listbox. */
  36754. void setRoot (const File& newRootDirectory);
  36755. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36756. void goUp();
  36757. /** Refreshes the directory that's currently being listed. */
  36758. void refresh();
  36759. /** Returns a verb to describe what should happen when the file is accepted.
  36760. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36761. mode, it'll be "Save", etc.
  36762. */
  36763. virtual const String getActionVerb() const;
  36764. /** Returns true if the saveMode flag was set when this component was created.
  36765. */
  36766. bool isSaveMode() const throw();
  36767. /** Adds a listener to be told when the user selects and clicks on files.
  36768. @see removeListener
  36769. */
  36770. void addListener (FileBrowserListener* listener);
  36771. /** Removes a listener.
  36772. @see addListener
  36773. */
  36774. void removeListener (FileBrowserListener* listener);
  36775. /** @internal */
  36776. void resized();
  36777. /** @internal */
  36778. void buttonClicked (Button* b);
  36779. /** @internal */
  36780. void comboBoxChanged (ComboBox*);
  36781. /** @internal */
  36782. void textEditorTextChanged (TextEditor& editor);
  36783. /** @internal */
  36784. void textEditorReturnKeyPressed (TextEditor& editor);
  36785. /** @internal */
  36786. void textEditorEscapeKeyPressed (TextEditor& editor);
  36787. /** @internal */
  36788. void textEditorFocusLost (TextEditor& editor);
  36789. /** @internal */
  36790. bool keyPressed (const KeyPress& key);
  36791. /** @internal */
  36792. void selectionChanged();
  36793. /** @internal */
  36794. void fileClicked (const File& f, const MouseEvent& e);
  36795. /** @internal */
  36796. void fileDoubleClicked (const File& f);
  36797. /** @internal */
  36798. bool isFileSuitable (const File& file) const;
  36799. /** @internal */
  36800. bool isDirectorySuitable (const File&) const;
  36801. /** @internal */
  36802. FilePreviewComponent* getPreviewComponent() const throw();
  36803. juce_UseDebuggingNewOperator
  36804. protected:
  36805. virtual const BigInteger getRoots (StringArray& rootNames, StringArray& rootPaths);
  36806. private:
  36807. ScopedPointer <DirectoryContentsList> fileList;
  36808. const FileFilter* fileFilter;
  36809. int flags;
  36810. File currentRoot;
  36811. Array<File> chosenFiles;
  36812. ListenerList <FileBrowserListener> listeners;
  36813. DirectoryContentsDisplayComponent* fileListComponent;
  36814. FilePreviewComponent* previewComp;
  36815. ComboBox* currentPathBox;
  36816. TextEditor* filenameBox;
  36817. Button* goUpButton;
  36818. TimeSliceThread thread;
  36819. void sendListenerChangeMessage();
  36820. bool isFileOrDirSuitable (const File& f) const;
  36821. FileBrowserComponent (const FileBrowserComponent&);
  36822. FileBrowserComponent& operator= (const FileBrowserComponent&);
  36823. };
  36824. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36825. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  36826. #endif
  36827. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36828. #endif
  36829. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36830. /*** Start of inlined file: juce_FileChooser.h ***/
  36831. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36832. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36833. /**
  36834. Creates a dialog box to choose a file or directory to load or save.
  36835. To use a FileChooser:
  36836. - create one (as a local stack variable is the neatest way)
  36837. - call one of its browseFor.. methods
  36838. - if this returns true, the user has selected a file, so you can retrieve it
  36839. with the getResult() method.
  36840. e.g. @code
  36841. void loadMooseFile()
  36842. {
  36843. FileChooser myChooser ("Please select the moose you want to load...",
  36844. File::getSpecialLocation (File::userHomeDirectory),
  36845. "*.moose");
  36846. if (myChooser.browseForFileToOpen())
  36847. {
  36848. File mooseFile (myChooser.getResult());
  36849. loadMoose (mooseFile);
  36850. }
  36851. }
  36852. @endcode
  36853. */
  36854. class JUCE_API FileChooser
  36855. {
  36856. public:
  36857. /** Creates a FileChooser.
  36858. After creating one of these, use one of the browseFor... methods to display it.
  36859. @param dialogBoxTitle a text string to display in the dialog box to
  36860. tell the user what's going on
  36861. @param initialFileOrDirectory the file or directory that should be selected when
  36862. the dialog box opens. If this parameter is set to
  36863. File::nonexistent, a sensible default directory
  36864. will be used instead.
  36865. @param filePatternsAllowed a set of file patterns to specify which files can be
  36866. selected - each pattern should be separated by a
  36867. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36868. empty string means that all files are allowed
  36869. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36870. possible; if false, then a Juce-based browser dialog
  36871. box will always be used
  36872. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36873. */
  36874. FileChooser (const String& dialogBoxTitle,
  36875. const File& initialFileOrDirectory = File::nonexistent,
  36876. const String& filePatternsAllowed = String::empty,
  36877. bool useOSNativeDialogBox = true);
  36878. /** Destructor. */
  36879. ~FileChooser();
  36880. /** Shows a dialog box to choose a file to open.
  36881. This will display the dialog box modally, using an "open file" mode, so that
  36882. it won't allow non-existent files or directories to be chosen.
  36883. @param previewComponent an optional component to display inside the dialog
  36884. box to show special info about the files that the user
  36885. is browsing. The component will not be deleted by this
  36886. object, so the caller must take care of it.
  36887. @returns true if the user selected a file, in which case, use the getResult()
  36888. method to find out what it was. Returns false if they cancelled instead.
  36889. @see browseForFileToSave, browseForDirectory
  36890. */
  36891. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36892. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36893. The files that are returned can be obtained by calling getResults(). See
  36894. browseForFileToOpen() for more info about the behaviour of this method.
  36895. */
  36896. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36897. /** Shows a dialog box to choose a file to save.
  36898. This will display the dialog box modally, using an "save file" mode, so it
  36899. will allow non-existent files to be chosen, but not directories.
  36900. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36901. the user if they're sure they want to overwrite a file that already
  36902. exists
  36903. @returns true if the user chose a file and pressed 'ok', in which case, use
  36904. the getResult() method to find out what the file was. Returns false
  36905. if they cancelled instead.
  36906. @see browseForFileToOpen, browseForDirectory
  36907. */
  36908. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  36909. /** Shows a dialog box to choose a directory.
  36910. This will display the dialog box modally, using an "open directory" mode, so it
  36911. will only allow directories to be returned, not files.
  36912. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36913. the getResult() method to find out what they chose. Returns false
  36914. if they cancelled instead.
  36915. @see browseForFileToOpen, browseForFileToSave
  36916. */
  36917. bool browseForDirectory();
  36918. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  36919. The files that are returned can be obtained by calling getResults(). See
  36920. browseForFileToOpen() for more info about the behaviour of this method.
  36921. */
  36922. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  36923. /** Returns the last file that was chosen by one of the browseFor methods.
  36924. After calling the appropriate browseFor... method, this method lets you
  36925. find out what file or directory they chose.
  36926. Note that the file returned is only valid if the browse method returned true (i.e.
  36927. if the user pressed 'ok' rather than cancelling).
  36928. If you're using a multiple-file select, then use the getResults() method instead,
  36929. to obtain the list of all files chosen.
  36930. @see getResults
  36931. */
  36932. const File getResult() const;
  36933. /** Returns a list of all the files that were chosen during the last call to a
  36934. browse method.
  36935. This array may be empty if no files were chosen, or can contain multiple entries
  36936. if multiple files were chosen.
  36937. @see getResult
  36938. */
  36939. const Array<File>& getResults() const;
  36940. juce_UseDebuggingNewOperator
  36941. private:
  36942. String title, filters;
  36943. File startingFile;
  36944. Array<File> results;
  36945. bool useNativeDialogBox;
  36946. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  36947. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36948. FilePreviewComponent* previewComponent);
  36949. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  36950. const String& filters, bool selectsDirectories, bool selectsFiles,
  36951. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36952. FilePreviewComponent* previewComponent);
  36953. };
  36954. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36955. /*** End of inlined file: juce_FileChooser.h ***/
  36956. #endif
  36957. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36958. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  36959. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36960. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36961. /*** Start of inlined file: juce_ResizableWindow.h ***/
  36962. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36963. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36964. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  36965. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36966. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36967. /*** Start of inlined file: juce_DropShadower.h ***/
  36968. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36969. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36970. /**
  36971. Adds a drop-shadow to a component.
  36972. This object creates and manages a set of components which sit around a
  36973. component, creating a gaussian shadow around it. The components will track
  36974. the position of the component and if it's brought to the front they'll also
  36975. follow this.
  36976. For desktop windows you don't need to use this class directly - just
  36977. set the Component::windowHasDropShadow flag when calling
  36978. Component::addToDesktop(), and the system will create one of these if it's
  36979. needed (which it obviously isn't on the Mac, for example).
  36980. */
  36981. class JUCE_API DropShadower : public ComponentListener
  36982. {
  36983. public:
  36984. /** Creates a DropShadower.
  36985. @param alpha the opacity of the shadows, from 0 to 1.0
  36986. @param xOffset the horizontal displacement of the shadow, in pixels
  36987. @param yOffset the vertical displacement of the shadow, in pixels
  36988. @param blurRadius the radius of the blur to use for creating the shadow
  36989. */
  36990. DropShadower (float alpha = 0.5f,
  36991. int xOffset = 1,
  36992. int yOffset = 5,
  36993. float blurRadius = 10.0f);
  36994. /** Destructor. */
  36995. virtual ~DropShadower();
  36996. /** Attaches the DropShadower to the component you want to shadow. */
  36997. void setOwner (Component* componentToFollow);
  36998. /** @internal */
  36999. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  37000. /** @internal */
  37001. void componentBroughtToFront (Component& component);
  37002. /** @internal */
  37003. void componentChildrenChanged (Component& component);
  37004. /** @internal */
  37005. void componentParentHierarchyChanged (Component& component);
  37006. /** @internal */
  37007. void componentVisibilityChanged (Component& component);
  37008. juce_UseDebuggingNewOperator
  37009. private:
  37010. Component* owner;
  37011. int numShadows;
  37012. Component* shadowWindows[4];
  37013. Image shadowImageSections[12];
  37014. const int shadowEdge, xOffset, yOffset;
  37015. const float alpha, blurRadius;
  37016. bool inDestructor, reentrant;
  37017. void updateShadows();
  37018. void setShadowImage (const Image& src,
  37019. const int num,
  37020. const int w, const int h,
  37021. const int sx, const int sy);
  37022. void bringShadowWindowsToFront();
  37023. void deleteShadowWindows();
  37024. DropShadower (const DropShadower&);
  37025. DropShadower& operator= (const DropShadower&);
  37026. };
  37027. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  37028. /*** End of inlined file: juce_DropShadower.h ***/
  37029. /**
  37030. A base class for top-level windows.
  37031. This class is used for components that are considered a major part of your
  37032. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  37033. etc. Things like menus that pop up briefly aren't derived from it.
  37034. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  37035. could itself be the child of another component.
  37036. The class manages a list of all instances of top-level windows that are in use,
  37037. and each one is also given the concept of being "active". The active window is
  37038. one that is actively being used by the user. This isn't quite the same as the
  37039. component with the keyboard focus, because there may be a popup menu or other
  37040. temporary window which gets keyboard focus while the active top level window is
  37041. unchanged.
  37042. A top-level window also has an optional drop-shadow.
  37043. @see ResizableWindow, DocumentWindow, DialogWindow
  37044. */
  37045. class JUCE_API TopLevelWindow : public Component
  37046. {
  37047. public:
  37048. /** Creates a TopLevelWindow.
  37049. @param name the name to give the component
  37050. @param addToDesktop if true, the window will be automatically added to the
  37051. desktop; if false, you can use it as a child component
  37052. */
  37053. TopLevelWindow (const String& name, bool addToDesktop);
  37054. /** Destructor. */
  37055. ~TopLevelWindow();
  37056. /** True if this is currently the TopLevelWindow that is actively being used.
  37057. This isn't quite the same as having keyboard focus, because the focus may be
  37058. on a child component or a temporary pop-up menu, etc, while this window is
  37059. still considered to be active.
  37060. @see activeWindowStatusChanged
  37061. */
  37062. bool isActiveWindow() const throw() { return windowIsActive_; }
  37063. /** This will set the bounds of the window so that it's centred in front of another
  37064. window.
  37065. If your app has a few windows open and want to pop up a dialog box for one of
  37066. them, you can use this to show it in front of the relevent parent window, which
  37067. is a bit neater than just having it appear in the middle of the screen.
  37068. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  37069. be used instead. If no window is focused, it'll just default to the middle of the
  37070. screen.
  37071. */
  37072. void centreAroundComponent (Component* componentToCentreAround,
  37073. int width, int height);
  37074. /** Turns the drop-shadow on and off. */
  37075. void setDropShadowEnabled (bool useShadow);
  37076. /** Sets whether an OS-native title bar will be used, or a Juce one.
  37077. @see isUsingNativeTitleBar
  37078. */
  37079. void setUsingNativeTitleBar (bool useNativeTitleBar);
  37080. /** Returns true if the window is currently using an OS-native title bar.
  37081. @see setUsingNativeTitleBar
  37082. */
  37083. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  37084. /** Returns the number of TopLevelWindow objects currently in use.
  37085. @see getTopLevelWindow
  37086. */
  37087. static int getNumTopLevelWindows() throw();
  37088. /** Returns one of the TopLevelWindow objects currently in use.
  37089. The index is 0 to (getNumTopLevelWindows() - 1).
  37090. */
  37091. static TopLevelWindow* getTopLevelWindow (int index) throw();
  37092. /** Returns the currently-active top level window.
  37093. There might not be one, of course, so this can return 0.
  37094. */
  37095. static TopLevelWindow* getActiveTopLevelWindow() throw();
  37096. juce_UseDebuggingNewOperator
  37097. /** @internal */
  37098. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  37099. protected:
  37100. /** This callback happens when this window becomes active or inactive.
  37101. @see isActiveWindow
  37102. */
  37103. virtual void activeWindowStatusChanged();
  37104. /** @internal */
  37105. void focusOfChildComponentChanged (FocusChangeType cause);
  37106. /** @internal */
  37107. void parentHierarchyChanged();
  37108. /** @internal */
  37109. void visibilityChanged();
  37110. /** @internal */
  37111. virtual int getDesktopWindowStyleFlags() const;
  37112. /** @internal */
  37113. void recreateDesktopWindow();
  37114. private:
  37115. friend class TopLevelWindowManager;
  37116. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  37117. ScopedPointer <DropShadower> shadower;
  37118. void setWindowActive (bool isNowActive);
  37119. TopLevelWindow (const TopLevelWindow&);
  37120. TopLevelWindow& operator= (const TopLevelWindow&);
  37121. };
  37122. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37123. /*** End of inlined file: juce_TopLevelWindow.h ***/
  37124. /*** Start of inlined file: juce_ComponentDragger.h ***/
  37125. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37126. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37127. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  37128. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37129. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37130. /**
  37131. A class that imposes restrictions on a Component's size or position.
  37132. This is used by classes such as ResizableCornerComponent,
  37133. ResizableBorderComponent and ResizableWindow.
  37134. The base class can impose some basic size and position limits, but you can
  37135. also subclass this for custom uses.
  37136. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  37137. */
  37138. class JUCE_API ComponentBoundsConstrainer
  37139. {
  37140. public:
  37141. /** When first created, the object will not impose any restrictions on the components. */
  37142. ComponentBoundsConstrainer() throw();
  37143. /** Destructor. */
  37144. virtual ~ComponentBoundsConstrainer();
  37145. /** Imposes a minimum width limit. */
  37146. void setMinimumWidth (int minimumWidth) throw();
  37147. /** Returns the current minimum width. */
  37148. int getMinimumWidth() const throw() { return minW; }
  37149. /** Imposes a maximum width limit. */
  37150. void setMaximumWidth (int maximumWidth) throw();
  37151. /** Returns the current maximum width. */
  37152. int getMaximumWidth() const throw() { return maxW; }
  37153. /** Imposes a minimum height limit. */
  37154. void setMinimumHeight (int minimumHeight) throw();
  37155. /** Returns the current minimum height. */
  37156. int getMinimumHeight() const throw() { return minH; }
  37157. /** Imposes a maximum height limit. */
  37158. void setMaximumHeight (int maximumHeight) throw();
  37159. /** Returns the current maximum height. */
  37160. int getMaximumHeight() const throw() { return maxH; }
  37161. /** Imposes a minimum width and height limit. */
  37162. void setMinimumSize (int minimumWidth,
  37163. int minimumHeight) throw();
  37164. /** Imposes a maximum width and height limit. */
  37165. void setMaximumSize (int maximumWidth,
  37166. int maximumHeight) throw();
  37167. /** Set all the maximum and minimum dimensions. */
  37168. void setSizeLimits (int minimumWidth,
  37169. int minimumHeight,
  37170. int maximumWidth,
  37171. int maximumHeight) throw();
  37172. /** Sets the amount by which the component is allowed to go off-screen.
  37173. The values indicate how many pixels must remain on-screen when dragged off
  37174. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  37175. when the component goes off the top of the screen, its y-position will be
  37176. clipped so that there are always at least 10 pixels on-screen. In other words,
  37177. the lowest y-position it can take would be (10 - the component's height).
  37178. If you pass 0 or less for one of these amounts, the component is allowed
  37179. to move beyond that edge completely, with no restrictions at all.
  37180. If you pass a very large number (i.e. larger that the dimensions of the
  37181. component itself), then the component won't be allowed to overlap that
  37182. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  37183. the component will bump into the left side of the screen and go no further.
  37184. */
  37185. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  37186. int minimumWhenOffTheLeft,
  37187. int minimumWhenOffTheBottom,
  37188. int minimumWhenOffTheRight) throw();
  37189. /** Specifies a width-to-height ratio that the resizer should always maintain.
  37190. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  37191. will always be maintained as this multiple of the height.
  37192. @see setResizeLimits
  37193. */
  37194. void setFixedAspectRatio (double widthOverHeight) throw();
  37195. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  37196. If no aspect ratio is being enforced, this will return 0.
  37197. */
  37198. double getFixedAspectRatio() const throw();
  37199. /** This callback changes the given co-ordinates to impose whatever the current
  37200. constraints are set to be.
  37201. @param bounds the target position that should be examined and adjusted
  37202. @param previousBounds the component's current size
  37203. @param limits the region in which the component can be positioned
  37204. @param isStretchingTop whether the top edge of the component is being resized
  37205. @param isStretchingLeft whether the left edge of the component is being resized
  37206. @param isStretchingBottom whether the bottom edge of the component is being resized
  37207. @param isStretchingRight whether the right edge of the component is being resized
  37208. */
  37209. virtual void checkBounds (Rectangle<int>& bounds,
  37210. const Rectangle<int>& previousBounds,
  37211. const Rectangle<int>& limits,
  37212. bool isStretchingTop,
  37213. bool isStretchingLeft,
  37214. bool isStretchingBottom,
  37215. bool isStretchingRight);
  37216. /** This callback happens when the resizer is about to start dragging. */
  37217. virtual void resizeStart();
  37218. /** This callback happens when the resizer has finished dragging. */
  37219. virtual void resizeEnd();
  37220. /** Checks the given bounds, and then sets the component to the corrected size. */
  37221. void setBoundsForComponent (Component* const component,
  37222. const Rectangle<int>& bounds,
  37223. bool isStretchingTop,
  37224. bool isStretchingLeft,
  37225. bool isStretchingBottom,
  37226. bool isStretchingRight);
  37227. /** Performs a check on the current size of a component, and moves or resizes
  37228. it if it fails the constraints.
  37229. */
  37230. void checkComponentBounds (Component* component);
  37231. /** Called by setBoundsForComponent() to apply a new constrained size to a
  37232. component.
  37233. By default this just calls setBounds(), but it virtual in case it's needed for
  37234. extremely cunning purposes.
  37235. */
  37236. virtual void applyBoundsToComponent (Component* component,
  37237. const Rectangle<int>& bounds);
  37238. juce_UseDebuggingNewOperator
  37239. private:
  37240. int minW, maxW, minH, maxH;
  37241. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  37242. double aspectRatio;
  37243. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  37244. ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  37245. };
  37246. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37247. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  37248. /**
  37249. An object to take care of the logic for dragging components around with the mouse.
  37250. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  37251. then in your mouseDrag() callback, call dragComponent().
  37252. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  37253. to limit the component's position and keep it on-screen.
  37254. e.g. @code
  37255. class MyDraggableComp
  37256. {
  37257. ComponentDragger myDragger;
  37258. void mouseDown (const MouseEvent& e)
  37259. {
  37260. myDragger.startDraggingComponent (this, 0);
  37261. }
  37262. void mouseDrag (const MouseEvent& e)
  37263. {
  37264. myDragger.dragComponent (this, e);
  37265. }
  37266. };
  37267. @endcode
  37268. */
  37269. class JUCE_API ComponentDragger
  37270. {
  37271. public:
  37272. /** Creates a ComponentDragger. */
  37273. ComponentDragger();
  37274. /** Destructor. */
  37275. virtual ~ComponentDragger();
  37276. /** Call this from your component's mouseDown() method, to prepare for dragging.
  37277. @param componentToDrag the component that you want to drag
  37278. @param constrainer a constrainer object to use to keep the component
  37279. from going offscreen
  37280. @see dragComponent
  37281. */
  37282. void startDraggingComponent (Component* const componentToDrag,
  37283. ComponentBoundsConstrainer* constrainer);
  37284. /** Call this from your mouseDrag() callback to move the component.
  37285. This will move the component, but will first check the validity of the
  37286. component's new position using the checkPosition() method, which you
  37287. can override if you need to enforce special positioning limits on the
  37288. component.
  37289. @param componentToDrag the component that you want to drag
  37290. @param e the current mouse-drag event
  37291. @see dragComponent
  37292. */
  37293. void dragComponent (Component* const componentToDrag,
  37294. const MouseEvent& e);
  37295. juce_UseDebuggingNewOperator
  37296. private:
  37297. ComponentBoundsConstrainer* constrainer;
  37298. Point<int> originalPos;
  37299. ComponentDragger (const ComponentDragger&);
  37300. ComponentDragger& operator= (const ComponentDragger&);
  37301. };
  37302. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37303. /*** End of inlined file: juce_ComponentDragger.h ***/
  37304. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  37305. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37306. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37307. /**
  37308. A component that resizes its parent window when dragged.
  37309. This component forms a frame around the edge of a component, allowing it to
  37310. be dragged by the edges or corners to resize it - like the way windows are
  37311. resized in MSWindows or Linux.
  37312. To use it, just add it to your component, making it fill the entire parent component
  37313. (there's a mouse hit-test that only traps mouse-events which land around the
  37314. edge of the component, so it's even ok to put it on top of any other components
  37315. you're using). Make sure you rescale the resizer component to fill the parent
  37316. each time the parent's size changes.
  37317. @see ResizableCornerComponent
  37318. */
  37319. class JUCE_API ResizableBorderComponent : public Component
  37320. {
  37321. public:
  37322. /** Creates a resizer.
  37323. Pass in the target component which you want to be resized when this one is
  37324. dragged.
  37325. The target component will usually be a parent of the resizer component, but this
  37326. isn't mandatory.
  37327. Remember that when the target component is resized, it'll need to move and
  37328. resize this component to keep it in place, as this won't happen automatically.
  37329. If the constrainer parameter is non-zero, then this object will be used to enforce
  37330. limits on the size and position that the component can be stretched to. Make sure
  37331. that the constrainer isn't deleted while still in use by this object.
  37332. @see ComponentBoundsConstrainer
  37333. */
  37334. ResizableBorderComponent (Component* componentToResize,
  37335. ComponentBoundsConstrainer* constrainer);
  37336. /** Destructor. */
  37337. ~ResizableBorderComponent();
  37338. /** Specifies how many pixels wide the draggable edges of this component are.
  37339. @see getBorderThickness
  37340. */
  37341. void setBorderThickness (const BorderSize& newBorderSize);
  37342. /** Returns the number of pixels wide that the draggable edges of this component are.
  37343. @see setBorderThickness
  37344. */
  37345. const BorderSize getBorderThickness() const;
  37346. /** Represents the different sections of a resizable border, which allow it to
  37347. resized in different ways.
  37348. */
  37349. class Zone
  37350. {
  37351. public:
  37352. enum Zones
  37353. {
  37354. centre = 0,
  37355. left = 1,
  37356. top = 2,
  37357. right = 4,
  37358. bottom = 8
  37359. };
  37360. /** Creates a Zone from a combination of the flags in \enum Zones. */
  37361. explicit Zone (int zoneFlags = 0) throw();
  37362. Zone (const Zone& other) throw();
  37363. Zone& operator= (const Zone& other) throw();
  37364. bool operator== (const Zone& other) const throw();
  37365. bool operator!= (const Zone& other) const throw();
  37366. /** Given a point within a rectangle with a resizable border, this returns the
  37367. zone that the point lies within.
  37368. */
  37369. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  37370. const BorderSize& border,
  37371. const Point<int>& position);
  37372. /** Returns an appropriate mouse-cursor for this resize zone. */
  37373. const MouseCursor getMouseCursor() const throw();
  37374. /** Returns true if dragging this zone will move the enire object without resizing it. */
  37375. bool isDraggingWholeObject() const throw() { return zone == centre; }
  37376. /** Returns true if dragging this zone will move the object's left edge. */
  37377. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  37378. /** Returns true if dragging this zone will move the object's right edge. */
  37379. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  37380. /** Returns true if dragging this zone will move the object's top edge. */
  37381. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  37382. /** Returns true if dragging this zone will move the object's bottom edge. */
  37383. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  37384. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  37385. applies to.
  37386. */
  37387. const Rectangle<int> resizeRectangleBy (Rectangle<int> original,
  37388. const Point<int>& distance) const throw();
  37389. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  37390. applies to.
  37391. */
  37392. const Rectangle<float> resizeRectangleBy (Rectangle<float> original,
  37393. const Point<float>& distance) const throw();
  37394. /** Returns the raw flags for this zone. */
  37395. int getZoneFlags() const throw() { return zone; }
  37396. private:
  37397. int zone;
  37398. };
  37399. juce_UseDebuggingNewOperator
  37400. protected:
  37401. /** @internal */
  37402. void paint (Graphics& g);
  37403. /** @internal */
  37404. void mouseEnter (const MouseEvent& e);
  37405. /** @internal */
  37406. void mouseMove (const MouseEvent& e);
  37407. /** @internal */
  37408. void mouseDown (const MouseEvent& e);
  37409. /** @internal */
  37410. void mouseDrag (const MouseEvent& e);
  37411. /** @internal */
  37412. void mouseUp (const MouseEvent& e);
  37413. /** @internal */
  37414. bool hitTest (int x, int y);
  37415. private:
  37416. Component::SafePointer<Component> component;
  37417. ComponentBoundsConstrainer* constrainer;
  37418. BorderSize borderSize;
  37419. Rectangle<int> originalBounds;
  37420. Zone mouseZone;
  37421. void updateMouseZone (const MouseEvent& e);
  37422. ResizableBorderComponent (const ResizableBorderComponent&);
  37423. ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  37424. };
  37425. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37426. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  37427. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  37428. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37429. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37430. /** A component that resizes a parent window when dragged.
  37431. This is the small triangular stripey resizer component you get in the bottom-right
  37432. of windows (more commonly on the Mac than Windows). Put one in the corner of
  37433. a larger component and it will automatically resize its parent when it gets dragged
  37434. around.
  37435. @see ResizableFrameComponent
  37436. */
  37437. class JUCE_API ResizableCornerComponent : public Component
  37438. {
  37439. public:
  37440. /** Creates a resizer.
  37441. Pass in the target component which you want to be resized when this one is
  37442. dragged.
  37443. The target component will usually be a parent of the resizer component, but this
  37444. isn't mandatory.
  37445. Remember that when the target component is resized, it'll need to move and
  37446. resize this component to keep it in place, as this won't happen automatically.
  37447. If the constrainer parameter is non-zero, then this object will be used to enforce
  37448. limits on the size and position that the component can be stretched to. Make sure
  37449. that the constrainer isn't deleted while still in use by this object. If you
  37450. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  37451. @see ComponentBoundsConstrainer
  37452. */
  37453. ResizableCornerComponent (Component* componentToResize,
  37454. ComponentBoundsConstrainer* constrainer);
  37455. /** Destructor. */
  37456. ~ResizableCornerComponent();
  37457. juce_UseDebuggingNewOperator
  37458. protected:
  37459. /** @internal */
  37460. void paint (Graphics& g);
  37461. /** @internal */
  37462. void mouseDown (const MouseEvent& e);
  37463. /** @internal */
  37464. void mouseDrag (const MouseEvent& e);
  37465. /** @internal */
  37466. void mouseUp (const MouseEvent& e);
  37467. /** @internal */
  37468. bool hitTest (int x, int y);
  37469. private:
  37470. Component::SafePointer<Component> component;
  37471. ComponentBoundsConstrainer* constrainer;
  37472. Rectangle<int> originalBounds;
  37473. ResizableCornerComponent (const ResizableCornerComponent&);
  37474. ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  37475. };
  37476. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37477. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  37478. /**
  37479. A base class for top-level windows that can be dragged around and resized.
  37480. To add content to the window, use its setContentComponent() method to
  37481. give it a component that will remain positioned inside it (leaving a gap around
  37482. the edges for a border).
  37483. It's not advisable to add child components directly to a ResizableWindow: put them
  37484. inside your content component instead. And overriding methods like resized(), moved(), etc
  37485. is also not recommended - instead override these methods for your content component.
  37486. (If for some obscure reason you do need to override these methods, always remember to
  37487. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37488. decorations correctly).
  37489. By default resizing isn't enabled - use the setResizable() method to enable it and
  37490. to choose the style of resizing to use.
  37491. @see TopLevelWindow
  37492. */
  37493. class JUCE_API ResizableWindow : public TopLevelWindow
  37494. {
  37495. public:
  37496. /** Creates a ResizableWindow.
  37497. This constructor doesn't specify a background colour, so the LookAndFeel's default
  37498. background colour will be used.
  37499. @param name the name to give the component
  37500. @param addToDesktop if true, the window will be automatically added to the
  37501. desktop; if false, you can use it as a child component
  37502. */
  37503. ResizableWindow (const String& name,
  37504. bool addToDesktop);
  37505. /** Creates a ResizableWindow.
  37506. @param name the name to give the component
  37507. @param backgroundColour the colour to use for filling the window's background.
  37508. @param addToDesktop if true, the window will be automatically added to the
  37509. desktop; if false, you can use it as a child component
  37510. */
  37511. ResizableWindow (const String& name,
  37512. const Colour& backgroundColour,
  37513. bool addToDesktop);
  37514. /** Destructor.
  37515. If a content component has been set with setContentComponent(), it
  37516. will be deleted.
  37517. */
  37518. ~ResizableWindow();
  37519. /** Returns the colour currently being used for the window's background.
  37520. As a convenience the window will fill itself with this colour, but you
  37521. can override the paint() method if you need more customised behaviour.
  37522. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  37523. @see setBackgroundColour
  37524. */
  37525. const Colour getBackgroundColour() const throw();
  37526. /** Changes the colour currently being used for the window's background.
  37527. As a convenience the window will fill itself with this colour, but you
  37528. can override the paint() method if you need more customised behaviour.
  37529. Note that the opaque state of this window is altered by this call to reflect
  37530. the opacity of the colour passed-in. On window systems which can't support
  37531. semi-transparent windows this might cause problems, (though it's unlikely you'll
  37532. be using this class as a base for a semi-transparent component anyway).
  37533. You can also use the ResizableWindow::backgroundColourId colour id to set
  37534. this colour.
  37535. @see getBackgroundColour
  37536. */
  37537. void setBackgroundColour (const Colour& newColour);
  37538. /** Make the window resizable or fixed.
  37539. @param shouldBeResizable whether it's resizable at all
  37540. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  37541. bottom-right; if false, it'll use a ResizableBorderComponent
  37542. around the edge
  37543. @see setResizeLimits, isResizable
  37544. */
  37545. void setResizable (bool shouldBeResizable,
  37546. bool useBottomRightCornerResizer);
  37547. /** True if resizing is enabled.
  37548. @see setResizable
  37549. */
  37550. bool isResizable() const throw();
  37551. /** This sets the maximum and minimum sizes for the window.
  37552. If the window's current size is outside these limits, it will be resized to
  37553. make sure it's within them.
  37554. Calling setBounds() on the component will bypass any size checking - it's only when
  37555. the window is being resized by the user that these values are enforced.
  37556. @see setResizable, setFixedAspectRatio
  37557. */
  37558. void setResizeLimits (int newMinimumWidth,
  37559. int newMinimumHeight,
  37560. int newMaximumWidth,
  37561. int newMaximumHeight) throw();
  37562. /** Returns the bounds constrainer object that this window is using.
  37563. You can access this to change its properties.
  37564. */
  37565. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  37566. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  37567. A pointer to the object you pass in will be kept, but it won't be deleted
  37568. by this object, so it's the caller's responsiblity to manage it.
  37569. If you pass 0, then no contraints will be placed on the positioning of the window.
  37570. */
  37571. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  37572. /** Calls the window's setBounds method, after first checking these bounds
  37573. with the current constrainer.
  37574. @see setConstrainer
  37575. */
  37576. void setBoundsConstrained (const Rectangle<int>& bounds);
  37577. /** Returns true if the window is currently in full-screen mode.
  37578. @see setFullScreen
  37579. */
  37580. bool isFullScreen() const;
  37581. /** Puts the window into full-screen mode, or restores it to its normal size.
  37582. If true, the window will become full-screen; if false, it will return to the
  37583. last size it was before being made full-screen.
  37584. @see isFullScreen
  37585. */
  37586. void setFullScreen (bool shouldBeFullScreen);
  37587. /** Returns true if the window is currently minimised.
  37588. @see setMinimised
  37589. */
  37590. bool isMinimised() const;
  37591. /** Minimises the window, or restores it to its previous position and size.
  37592. When being un-minimised, it'll return to the last position and size it
  37593. was in before being minimised.
  37594. @see isMinimised
  37595. */
  37596. void setMinimised (bool shouldMinimise);
  37597. /** Returns a string which encodes the window's current size and position.
  37598. This string will encapsulate the window's size, position, and whether it's
  37599. in full-screen mode. It's intended for letting your application save and
  37600. restore a window's position.
  37601. Use the restoreWindowStateFromString() to restore from a saved state.
  37602. @see restoreWindowStateFromString
  37603. */
  37604. const String getWindowStateAsString();
  37605. /** Restores the window to a previously-saved size and position.
  37606. This restores the window's size, positon and full-screen status from an
  37607. string that was previously created with the getWindowStateAsString()
  37608. method.
  37609. @returns false if the string wasn't a valid window state
  37610. @see getWindowStateAsString
  37611. */
  37612. bool restoreWindowStateFromString (const String& previousState);
  37613. /** Returns the current content component.
  37614. This will be the component set by setContentComponent(), or 0 if none
  37615. has yet been specified.
  37616. @see setContentComponent
  37617. */
  37618. Component* getContentComponent() const throw() { return contentComponent; }
  37619. /** Changes the current content component.
  37620. This sets a component that will be placed in the centre of the ResizableWindow,
  37621. (leaving a space around the edge for the border).
  37622. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37623. with addChildComponent(). Instead, add them to the content component.
  37624. @param newContentComponent the new component to use (or null to not use one) - this
  37625. component will be deleted either when replaced by another call
  37626. to this method, or when the ResizableWindow is deleted.
  37627. To remove a content component without deleting it, use
  37628. setContentComponent (0, false).
  37629. @param deleteOldOne if true, the previous content component will be deleted; if
  37630. false, the previous component will just be removed without
  37631. deleting it.
  37632. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37633. it always fits around the size of the content component. If false, the
  37634. new content will be resized to fit the current space available.
  37635. */
  37636. void setContentComponent (Component* newContentComponent,
  37637. bool deleteOldOne = true,
  37638. bool resizeToFit = false);
  37639. /** Changes the window so that the content component ends up with the specified size.
  37640. This is basically a setSize call on the window, but which adds on the borders,
  37641. so you can specify the content component's target size.
  37642. */
  37643. void setContentComponentSize (int width, int height);
  37644. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37645. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37646. methods.
  37647. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37648. */
  37649. enum ColourIds
  37650. {
  37651. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37652. };
  37653. juce_UseDebuggingNewOperator
  37654. protected:
  37655. /** @internal */
  37656. void paint (Graphics& g);
  37657. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37658. void moved();
  37659. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37660. void resized();
  37661. /** @internal */
  37662. void mouseDown (const MouseEvent& e);
  37663. /** @internal */
  37664. void mouseDrag (const MouseEvent& e);
  37665. /** @internal */
  37666. void lookAndFeelChanged();
  37667. /** @internal */
  37668. void childBoundsChanged (Component* child);
  37669. /** @internal */
  37670. void parentSizeChanged();
  37671. /** @internal */
  37672. void visibilityChanged();
  37673. /** @internal */
  37674. void activeWindowStatusChanged();
  37675. /** @internal */
  37676. int getDesktopWindowStyleFlags() const;
  37677. /** Returns the width of the border to use around the window.
  37678. @see getContentComponentBorder
  37679. */
  37680. virtual const BorderSize getBorderThickness();
  37681. /** Returns the insets to use when positioning the content component.
  37682. @see getBorderThickness
  37683. */
  37684. virtual const BorderSize getContentComponentBorder();
  37685. #if JUCE_DEBUG
  37686. /** Overridden to warn people about adding components directly to this component
  37687. instead of using setContentComponent().
  37688. If you know what you're doing and are sure you really want to add a component, specify
  37689. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37690. */
  37691. void addChildComponent (Component* child, int zOrder = -1);
  37692. /** Overridden to warn people about adding components directly to this component
  37693. instead of using setContentComponent().
  37694. If you know what you're doing and are sure you really want to add a component, specify
  37695. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37696. */
  37697. void addAndMakeVisible (Component* child, int zOrder = -1);
  37698. #endif
  37699. ScopedPointer <ResizableCornerComponent> resizableCorner;
  37700. ScopedPointer <ResizableBorderComponent> resizableBorder;
  37701. private:
  37702. Component::SafePointer <Component> contentComponent;
  37703. bool resizeToFitContent, fullscreen;
  37704. ComponentDragger dragger;
  37705. Rectangle<int> lastNonFullScreenPos;
  37706. ComponentBoundsConstrainer defaultConstrainer;
  37707. ComponentBoundsConstrainer* constrainer;
  37708. #if JUCE_DEBUG
  37709. bool hasBeenResized;
  37710. #endif
  37711. void updateLastPos();
  37712. ResizableWindow (const ResizableWindow&);
  37713. ResizableWindow& operator= (const ResizableWindow&);
  37714. // (xxx remove these eventually)
  37715. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37716. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37717. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37718. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37719. };
  37720. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37721. /*** End of inlined file: juce_ResizableWindow.h ***/
  37722. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  37723. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37724. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37725. /**
  37726. A glyph from a particular font, with a particular size, style,
  37727. typeface and position.
  37728. @see GlyphArrangement, Font
  37729. */
  37730. class JUCE_API PositionedGlyph
  37731. {
  37732. public:
  37733. PositionedGlyph (const PositionedGlyph& other);
  37734. /** Returns the character the glyph represents. */
  37735. juce_wchar getCharacter() const { return character; }
  37736. /** Checks whether the glyph is actually empty. */
  37737. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  37738. /** Returns the position of the glyph's left-hand edge. */
  37739. float getLeft() const { return x; }
  37740. /** Returns the position of the glyph's right-hand edge. */
  37741. float getRight() const { return x + w; }
  37742. /** Returns the y position of the glyph's baseline. */
  37743. float getBaselineY() const { return y; }
  37744. /** Returns the y position of the top of the glyph. */
  37745. float getTop() const { return y - font.getAscent(); }
  37746. /** Returns the y position of the bottom of the glyph. */
  37747. float getBottom() const { return y + font.getDescent(); }
  37748. /** Returns the bounds of the glyph. */
  37749. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  37750. /** Shifts the glyph's position by a relative amount. */
  37751. void moveBy (float deltaX, float deltaY);
  37752. /** Draws the glyph into a graphics context. */
  37753. void draw (const Graphics& g) const;
  37754. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  37755. void draw (const Graphics& g, const AffineTransform& transform) const;
  37756. /** Returns the path for this glyph.
  37757. @param path the glyph's outline will be appended to this path
  37758. */
  37759. void createPath (Path& path) const;
  37760. /** Checks to see if a point lies within this glyph. */
  37761. bool hitTest (float x, float y) const;
  37762. juce_UseDebuggingNewOperator
  37763. private:
  37764. friend class GlyphArrangement;
  37765. float x, y, w;
  37766. Font font;
  37767. juce_wchar character;
  37768. int glyph;
  37769. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  37770. };
  37771. /**
  37772. A set of glyphs, each with a position.
  37773. You can create a GlyphArrangement, text to it and then draw it onto a
  37774. graphics context. It's used internally by the text methods in the
  37775. Graphics class, but can be used directly if more control is needed.
  37776. @see Font, PositionedGlyph
  37777. */
  37778. class JUCE_API GlyphArrangement
  37779. {
  37780. public:
  37781. /** Creates an empty arrangement. */
  37782. GlyphArrangement();
  37783. /** Takes a copy of another arrangement. */
  37784. GlyphArrangement (const GlyphArrangement& other);
  37785. /** Copies another arrangement onto this one.
  37786. To add another arrangement without clearing this one, use addGlyphArrangement().
  37787. */
  37788. GlyphArrangement& operator= (const GlyphArrangement& other);
  37789. /** Destructor. */
  37790. ~GlyphArrangement();
  37791. /** Returns the total number of glyphs in the arrangement. */
  37792. int getNumGlyphs() const throw() { return glyphs.size(); }
  37793. /** Returns one of the glyphs from the arrangement.
  37794. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  37795. careful not to pass an out-of-range index here, as it
  37796. doesn't do any bounds-checking.
  37797. */
  37798. PositionedGlyph& getGlyph (int index) const;
  37799. /** Clears all text from the arrangement and resets it.
  37800. */
  37801. void clear();
  37802. /** Appends a line of text to the arrangement.
  37803. This will add the text as a single line, where x is the left-hand edge of the
  37804. first character, and y is the position for the text's baseline.
  37805. If the text contains new-lines or carriage-returns, this will ignore them - use
  37806. addJustifiedText() to add multi-line arrangements.
  37807. */
  37808. void addLineOfText (const Font& font,
  37809. const String& text,
  37810. float x, float y);
  37811. /** Adds a line of text, truncating it if it's wider than a specified size.
  37812. This is the same as addLineOfText(), but if the line's width exceeds the value
  37813. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  37814. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  37815. */
  37816. void addCurtailedLineOfText (const Font& font,
  37817. const String& text,
  37818. float x, float y,
  37819. float maxWidthPixels,
  37820. bool useEllipsis);
  37821. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  37822. This will add text to the arrangement, breaking it into new lines either where there
  37823. is a new-line or carriage-return character in the text, or where a line's width
  37824. exceeds the value set in maxLineWidth.
  37825. Each line that is added will be laid out using the flags set in horizontalLayout, so
  37826. the lines can be left- or right-justified, or centred horizontally in the space
  37827. between x and (x + maxLineWidth).
  37828. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  37829. lines will be placed below it, separated by a distance of font.getHeight().
  37830. */
  37831. void addJustifiedText (const Font& font,
  37832. const String& text,
  37833. float x, float y,
  37834. float maxLineWidth,
  37835. const Justification& horizontalLayout);
  37836. /** Tries to fit some text withing a given space.
  37837. This does its best to make the given text readable within the specified rectangle,
  37838. so it useful for labelling things.
  37839. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  37840. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  37841. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  37842. it's been truncated.
  37843. A Justification parameter lets you specify how the text is laid out within the rectangle,
  37844. both horizontally and vertically.
  37845. @see Graphics::drawFittedText
  37846. */
  37847. void addFittedText (const Font& font,
  37848. const String& text,
  37849. float x, float y, float width, float height,
  37850. const Justification& layout,
  37851. int maximumLinesToUse,
  37852. float minimumHorizontalScale = 0.7f);
  37853. /** Appends another glyph arrangement to this one. */
  37854. void addGlyphArrangement (const GlyphArrangement& other);
  37855. /** Draws this glyph arrangement to a graphics context.
  37856. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  37857. method, which renders the glyphs as filled vectors.
  37858. */
  37859. void draw (const Graphics& g) const;
  37860. /** Draws this glyph arrangement to a graphics context.
  37861. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  37862. method for non-transformed arrangements.
  37863. */
  37864. void draw (const Graphics& g, const AffineTransform& transform) const;
  37865. /** Converts the set of glyphs into a path.
  37866. @param path the glyphs' outlines will be appended to this path
  37867. */
  37868. void createPath (Path& path) const;
  37869. /** Looks for a glyph that contains the given co-ordinate.
  37870. @returns the index of the glyph, or -1 if none were found.
  37871. */
  37872. int findGlyphIndexAt (float x, float y) const;
  37873. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  37874. @param startIndex the first glyph to test
  37875. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  37876. startIndex will be included
  37877. @param includeWhitespace if true, the extent of any whitespace characters will also
  37878. be taken into account
  37879. */
  37880. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  37881. /** Shifts a set of glyphs by a given amount.
  37882. @param startIndex the first glyph to transform
  37883. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  37884. startIndex will be used
  37885. @param deltaX the amount to add to their x-positions
  37886. @param deltaY the amount to add to their y-positions
  37887. */
  37888. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  37889. float deltaX, float deltaY);
  37890. /** Removes a set of glyphs from the arrangement.
  37891. @param startIndex the first glyph to remove
  37892. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  37893. startIndex will be deleted
  37894. */
  37895. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  37896. /** Expands or compresses a set of glyphs horizontally.
  37897. @param startIndex the first glyph to transform
  37898. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  37899. startIndex will be used
  37900. @param horizontalScaleFactor how much to scale their horizontal width by
  37901. */
  37902. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  37903. float horizontalScaleFactor);
  37904. /** Justifies a set of glyphs within a given space.
  37905. This moves the glyphs as a block so that the whole thing is located within the
  37906. given rectangle with the specified layout.
  37907. If the Justification::horizontallyJustified flag is specified, each line will
  37908. be stretched out to fill the specified width.
  37909. */
  37910. void justifyGlyphs (int startIndex, int numGlyphs,
  37911. float x, float y, float width, float height,
  37912. const Justification& justification);
  37913. juce_UseDebuggingNewOperator
  37914. private:
  37915. OwnedArray <PositionedGlyph> glyphs;
  37916. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  37917. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  37918. const Justification& justification, float minimumHorizontalScale);
  37919. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  37920. };
  37921. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37922. /*** End of inlined file: juce_GlyphArrangement.h ***/
  37923. /**
  37924. A file open/save dialog box.
  37925. This is a Juce-based file dialog box; to use a native file chooser, see the
  37926. FileChooser class.
  37927. To use one of these, create it and call its show() method. e.g.
  37928. @code
  37929. {
  37930. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  37931. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37932. File::nonexistent,
  37933. &wildcardFilter,
  37934. 0);
  37935. FileChooserDialogBox dialogBox ("Open some kind of file",
  37936. "Please choose some kind of file that you want to open...",
  37937. browser,
  37938. getLookAndFeel().alertWindowBackground);
  37939. if (dialogBox.show())
  37940. {
  37941. File selectedFile = browser.getCurrentFile();
  37942. ...
  37943. }
  37944. }
  37945. @endcode
  37946. @see FileChooser
  37947. */
  37948. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37949. public Button::Listener,
  37950. public FileBrowserListener
  37951. {
  37952. public:
  37953. /** Creates a file chooser box.
  37954. @param title the main title to show at the top of the box
  37955. @param instructions an optional longer piece of text to show below the title in
  37956. a smaller font, describing in more detail what's required.
  37957. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37958. box. Make sure you delete this after (but not before!) the
  37959. dialog box has been deleted.
  37960. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37961. if they try to select a file that already exists. (This
  37962. flag is only used when saving files)
  37963. @param backgroundColour the background colour for the top level window
  37964. @see FileBrowserComponent, FilePreviewComponent
  37965. */
  37966. FileChooserDialogBox (const String& title,
  37967. const String& instructions,
  37968. FileBrowserComponent& browserComponent,
  37969. bool warnAboutOverwritingExistingFiles,
  37970. const Colour& backgroundColour);
  37971. /** Destructor. */
  37972. ~FileChooserDialogBox();
  37973. /** Displays and runs the dialog box modally.
  37974. This will show the box with the specified size, returning true if the user
  37975. pressed 'ok', or false if they cancelled.
  37976. Leave the width or height as 0 to use the default size
  37977. */
  37978. bool show (int width = 0, int height = 0);
  37979. /** Displays and runs the dialog box modally.
  37980. This will show the box with the specified size at the specified location,
  37981. returning true if the user pressed 'ok', or false if they cancelled.
  37982. Leave the width or height as 0 to use the default size.
  37983. */
  37984. bool showAt (int x, int y, int width, int height);
  37985. /** A set of colour IDs to use to change the colour of various aspects of the box.
  37986. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37987. methods.
  37988. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37989. */
  37990. enum ColourIds
  37991. {
  37992. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  37993. };
  37994. /** @internal */
  37995. void buttonClicked (Button* button);
  37996. /** @internal */
  37997. void closeButtonPressed();
  37998. /** @internal */
  37999. void selectionChanged();
  38000. /** @internal */
  38001. void fileClicked (const File& file, const MouseEvent& e);
  38002. /** @internal */
  38003. void fileDoubleClicked (const File& file);
  38004. juce_UseDebuggingNewOperator
  38005. private:
  38006. class ContentComponent : public Component
  38007. {
  38008. public:
  38009. ContentComponent();
  38010. ~ContentComponent();
  38011. void paint (Graphics& g);
  38012. void resized();
  38013. String instructions;
  38014. GlyphArrangement text;
  38015. FileBrowserComponent* chooserComponent;
  38016. FilePreviewComponent* previewComponent;
  38017. TextButton* okButton;
  38018. TextButton* cancelButton;
  38019. };
  38020. ContentComponent* content;
  38021. const bool warnAboutOverwritingExistingFiles;
  38022. FileChooserDialogBox (const FileChooserDialogBox&);
  38023. FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  38024. };
  38025. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38026. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  38027. #endif
  38028. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  38029. #endif
  38030. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38031. /*** Start of inlined file: juce_FileListComponent.h ***/
  38032. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38033. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38034. /**
  38035. A component that displays the files in a directory as a listbox.
  38036. This implements the DirectoryContentsDisplayComponent base class so that
  38037. it can be used in a FileBrowserComponent.
  38038. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38039. class and the FileBrowserListener class.
  38040. @see DirectoryContentsList, FileTreeComponent
  38041. */
  38042. class JUCE_API FileListComponent : public ListBox,
  38043. public DirectoryContentsDisplayComponent,
  38044. private ListBoxModel,
  38045. private ChangeListener
  38046. {
  38047. public:
  38048. /** Creates a listbox to show the contents of a specified directory.
  38049. */
  38050. FileListComponent (DirectoryContentsList& listToShow);
  38051. /** Destructor. */
  38052. ~FileListComponent();
  38053. /** Returns the number of files the user has got selected.
  38054. @see getSelectedFile
  38055. */
  38056. int getNumSelectedFiles() const;
  38057. /** Returns one of the files that the user has currently selected.
  38058. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38059. @see getNumSelectedFiles
  38060. */
  38061. const File getSelectedFile (int index = 0) const;
  38062. /** Deselects any files that are currently selected. */
  38063. void deselectAllFiles();
  38064. /** Scrolls to the top of the list. */
  38065. void scrollToTop();
  38066. /** @internal */
  38067. void changeListenerCallback (void*);
  38068. /** @internal */
  38069. int getNumRows();
  38070. /** @internal */
  38071. void paintListBoxItem (int, Graphics&, int, int, bool);
  38072. /** @internal */
  38073. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  38074. /** @internal */
  38075. void selectedRowsChanged (int lastRowSelected);
  38076. /** @internal */
  38077. void deleteKeyPressed (int currentSelectedRow);
  38078. /** @internal */
  38079. void returnKeyPressed (int currentSelectedRow);
  38080. juce_UseDebuggingNewOperator
  38081. private:
  38082. FileListComponent (const FileListComponent&);
  38083. FileListComponent& operator= (const FileListComponent&);
  38084. File lastDirectory;
  38085. };
  38086. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38087. /*** End of inlined file: juce_FileListComponent.h ***/
  38088. #endif
  38089. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38090. /*** Start of inlined file: juce_FilenameComponent.h ***/
  38091. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38092. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38093. class FilenameComponent;
  38094. /**
  38095. Listens for events happening to a FilenameComponent.
  38096. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  38097. register one of these objects for event callbacks when the filename is changed.
  38098. @see FilenameComponent
  38099. */
  38100. class JUCE_API FilenameComponentListener
  38101. {
  38102. public:
  38103. /** Destructor. */
  38104. virtual ~FilenameComponentListener() {}
  38105. /** This method is called after the FilenameComponent's file has been changed. */
  38106. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  38107. };
  38108. /**
  38109. Shows a filename as an editable text box, with a 'browse' button and a
  38110. drop-down list for recently selected files.
  38111. A handy component for dialogue boxes where you want the user to be able to
  38112. select a file or directory.
  38113. Attach an FilenameComponentListener using the addListener() method, and it will
  38114. get called each time the user changes the filename, either by browsing for a file
  38115. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38116. @see FileChooser, ComboBox
  38117. */
  38118. class JUCE_API FilenameComponent : public Component,
  38119. public SettableTooltipClient,
  38120. public FileDragAndDropTarget,
  38121. private AsyncUpdater,
  38122. private Button::Listener,
  38123. private ComboBox::Listener
  38124. {
  38125. public:
  38126. /** Creates a FilenameComponent.
  38127. @param name the name for this component.
  38128. @param currentFile the file to initially show in the box
  38129. @param canEditFilename if true, the user can manually edit the filename; if false,
  38130. they can only change it by browsing for a new file
  38131. @param isDirectory if true, the file will be treated as a directory, and
  38132. an appropriate directory browser used
  38133. @param isForSaving if true, the file browser will allow non-existent files to
  38134. be picked, as the file is assumed to be used for saving rather
  38135. than loading
  38136. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38137. If an empty string is passed in, then the pattern is assumed to be "*"
  38138. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38139. to any filenames that are entered or chosen
  38140. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38141. will only appear if the initial file isn't valid)
  38142. */
  38143. FilenameComponent (const String& name,
  38144. const File& currentFile,
  38145. bool canEditFilename,
  38146. bool isDirectory,
  38147. bool isForSaving,
  38148. const String& fileBrowserWildcard,
  38149. const String& enforcedSuffix,
  38150. const String& textWhenNothingSelected);
  38151. /** Destructor. */
  38152. ~FilenameComponent();
  38153. /** Returns the currently displayed filename. */
  38154. const File getCurrentFile() const;
  38155. /** Changes the current filename.
  38156. If addToRecentlyUsedList is true, the filename will also be added to the
  38157. drop-down list of recent files.
  38158. If sendChangeNotification is false, then the listeners won't be told of the
  38159. change.
  38160. */
  38161. void setCurrentFile (File newFile,
  38162. bool addToRecentlyUsedList,
  38163. bool sendChangeNotification = true);
  38164. /** Changes whether the use can type into the filename box.
  38165. */
  38166. void setFilenameIsEditable (bool shouldBeEditable);
  38167. /** Sets a file or directory to be the default starting point for the browser to show.
  38168. This is only used if the current file hasn't been set.
  38169. */
  38170. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  38171. /** Returns all the entries on the recent files list.
  38172. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  38173. state of this list.
  38174. @see setRecentlyUsedFilenames
  38175. */
  38176. const StringArray getRecentlyUsedFilenames() const;
  38177. /** Sets all the entries on the recent files list.
  38178. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  38179. state of this list.
  38180. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  38181. */
  38182. void setRecentlyUsedFilenames (const StringArray& filenames);
  38183. /** Adds an entry to the recently-used files dropdown list.
  38184. If the file is already in the list, it will be moved to the top. A limit
  38185. is also placed on the number of items that are kept in the list.
  38186. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  38187. */
  38188. void addRecentlyUsedFile (const File& file);
  38189. /** Changes the limit for the number of files that will be stored in the recent-file list.
  38190. */
  38191. void setMaxNumberOfRecentFiles (int newMaximum);
  38192. /** Changes the text shown on the 'browse' button.
  38193. By default this button just says "..." but you can change it. The button itself
  38194. can be changed using the look-and-feel classes, so it might not actually have any
  38195. text on it.
  38196. */
  38197. void setBrowseButtonText (const String& browseButtonText);
  38198. /** Adds a listener that will be called when the selected file is changed. */
  38199. void addListener (FilenameComponentListener* listener);
  38200. /** Removes a previously-registered listener. */
  38201. void removeListener (FilenameComponentListener* listener);
  38202. /** Gives the component a tooltip. */
  38203. void setTooltip (const String& newTooltip);
  38204. /** @internal */
  38205. void paintOverChildren (Graphics& g);
  38206. /** @internal */
  38207. void resized();
  38208. /** @internal */
  38209. void lookAndFeelChanged();
  38210. /** @internal */
  38211. bool isInterestedInFileDrag (const StringArray& files);
  38212. /** @internal */
  38213. void filesDropped (const StringArray& files, int, int);
  38214. /** @internal */
  38215. void fileDragEnter (const StringArray& files, int, int);
  38216. /** @internal */
  38217. void fileDragExit (const StringArray& files);
  38218. juce_UseDebuggingNewOperator
  38219. private:
  38220. ComboBox filenameBox;
  38221. String lastFilename;
  38222. ScopedPointer<Button> browseButton;
  38223. int maxRecentFiles;
  38224. bool isDir, isSaving, isFileDragOver;
  38225. String wildcard, enforcedSuffix, browseButtonText;
  38226. ListenerList <FilenameComponentListener> listeners;
  38227. File defaultBrowseFile;
  38228. void comboBoxChanged (ComboBox*);
  38229. void buttonClicked (Button* button);
  38230. void handleAsyncUpdate();
  38231. FilenameComponent (const FilenameComponent&);
  38232. FilenameComponent& operator= (const FilenameComponent&);
  38233. };
  38234. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38235. /*** End of inlined file: juce_FilenameComponent.h ***/
  38236. #endif
  38237. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38238. #endif
  38239. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38240. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  38241. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38242. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38243. /**
  38244. Shows a set of file paths in a list, allowing them to be added, removed or
  38245. re-ordered.
  38246. @see FileSearchPath
  38247. */
  38248. class JUCE_API FileSearchPathListComponent : public Component,
  38249. public SettableTooltipClient,
  38250. public FileDragAndDropTarget,
  38251. private Button::Listener,
  38252. private ListBoxModel
  38253. {
  38254. public:
  38255. /** Creates an empty FileSearchPathListComponent.
  38256. */
  38257. FileSearchPathListComponent();
  38258. /** Destructor. */
  38259. ~FileSearchPathListComponent();
  38260. /** Returns the path as it is currently shown. */
  38261. const FileSearchPath& getPath() const throw() { return path; }
  38262. /** Changes the current path. */
  38263. void setPath (const FileSearchPath& newPath);
  38264. /** Sets a file or directory to be the default starting point for the browser to show.
  38265. This is only used if the current file hasn't been set.
  38266. */
  38267. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  38268. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38269. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38270. methods.
  38271. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38272. */
  38273. enum ColourIds
  38274. {
  38275. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  38276. Make this transparent if you don't want the background to be filled. */
  38277. };
  38278. /** @internal */
  38279. int getNumRows();
  38280. /** @internal */
  38281. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  38282. /** @internal */
  38283. void deleteKeyPressed (int lastRowSelected);
  38284. /** @internal */
  38285. void returnKeyPressed (int lastRowSelected);
  38286. /** @internal */
  38287. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  38288. /** @internal */
  38289. void selectedRowsChanged (int lastRowSelected);
  38290. /** @internal */
  38291. void resized();
  38292. /** @internal */
  38293. void paint (Graphics& g);
  38294. /** @internal */
  38295. bool isInterestedInFileDrag (const StringArray& files);
  38296. /** @internal */
  38297. void filesDropped (const StringArray& files, int, int);
  38298. /** @internal */
  38299. void buttonClicked (Button* button);
  38300. juce_UseDebuggingNewOperator
  38301. private:
  38302. FileSearchPath path;
  38303. File defaultBrowseTarget;
  38304. ListBox* listBox;
  38305. Button* addButton;
  38306. Button* removeButton;
  38307. TextButton* changeButton;
  38308. DrawableButton* upButton;
  38309. DrawableButton* downButton;
  38310. void changed();
  38311. void updateButtons();
  38312. FileSearchPathListComponent (const FileSearchPathListComponent&);
  38313. FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  38314. };
  38315. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38316. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  38317. #endif
  38318. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38319. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  38320. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38321. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38322. /**
  38323. A component that displays the files in a directory as a treeview.
  38324. This implements the DirectoryContentsDisplayComponent base class so that
  38325. it can be used in a FileBrowserComponent.
  38326. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38327. class and the FileBrowserListener class.
  38328. @see DirectoryContentsList, FileListComponent
  38329. */
  38330. class JUCE_API FileTreeComponent : public TreeView,
  38331. public DirectoryContentsDisplayComponent
  38332. {
  38333. public:
  38334. /** Creates a listbox to show the contents of a specified directory.
  38335. */
  38336. FileTreeComponent (DirectoryContentsList& listToShow);
  38337. /** Destructor. */
  38338. ~FileTreeComponent();
  38339. /** Returns the number of files the user has got selected.
  38340. @see getSelectedFile
  38341. */
  38342. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  38343. /** Returns one of the files that the user has currently selected.
  38344. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38345. @see getNumSelectedFiles
  38346. */
  38347. const File getSelectedFile (int index = 0) const;
  38348. /** Deselects any files that are currently selected. */
  38349. void deselectAllFiles();
  38350. /** Scrolls the list to the top. */
  38351. void scrollToTop();
  38352. /** Setting a name for this allows tree items to be dragged.
  38353. The string that you pass in here will be returned by the getDragSourceDescription()
  38354. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38355. */
  38356. void setDragAndDropDescription (const String& description);
  38357. /** Returns the last value that was set by setDragAndDropDescription().
  38358. */
  38359. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38360. juce_UseDebuggingNewOperator
  38361. private:
  38362. String dragAndDropDescription;
  38363. FileTreeComponent (const FileTreeComponent&);
  38364. FileTreeComponent& operator= (const FileTreeComponent&);
  38365. };
  38366. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38367. /*** End of inlined file: juce_FileTreeComponent.h ***/
  38368. #endif
  38369. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38370. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  38371. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38372. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38373. /**
  38374. A simple preview component that shows thumbnails of image files.
  38375. @see FileChooserDialogBox, FilePreviewComponent
  38376. */
  38377. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  38378. private Timer
  38379. {
  38380. public:
  38381. /** Creates an ImagePreviewComponent. */
  38382. ImagePreviewComponent();
  38383. /** Destructor. */
  38384. ~ImagePreviewComponent();
  38385. /** @internal */
  38386. void selectedFileChanged (const File& newSelectedFile);
  38387. /** @internal */
  38388. void paint (Graphics& g);
  38389. /** @internal */
  38390. void timerCallback();
  38391. juce_UseDebuggingNewOperator
  38392. private:
  38393. File fileToLoad;
  38394. Image currentThumbnail;
  38395. String currentDetails;
  38396. void getThumbSize (int& w, int& h) const;
  38397. ImagePreviewComponent (const ImagePreviewComponent&);
  38398. ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  38399. };
  38400. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38401. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  38402. #endif
  38403. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38404. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  38405. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38406. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38407. /**
  38408. A type of FileFilter that works by wildcard pattern matching.
  38409. This filter only allows files that match one of the specified patterns, but
  38410. allows all directories through.
  38411. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38412. */
  38413. class JUCE_API WildcardFileFilter : public FileFilter
  38414. {
  38415. public:
  38416. /**
  38417. Creates a wildcard filter for one or more patterns.
  38418. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38419. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38420. or .aiff.
  38421. The description is a name to show the user in a list of possible patterns, so
  38422. for the wav/aiff example, your description might be "audio files".
  38423. */
  38424. WildcardFileFilter (const String& fileWildcardPatterns,
  38425. const String& directoryWildcardPatterns,
  38426. const String& description);
  38427. /** Destructor. */
  38428. ~WildcardFileFilter();
  38429. /** Returns true if the filename matches one of the patterns specified. */
  38430. bool isFileSuitable (const File& file) const;
  38431. /** This always returns true. */
  38432. bool isDirectorySuitable (const File& file) const;
  38433. juce_UseDebuggingNewOperator
  38434. private:
  38435. StringArray fileWildcards, directoryWildcards;
  38436. static void parse (const String& pattern, StringArray& result);
  38437. static bool match (const File& file, const StringArray& wildcards);
  38438. };
  38439. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38440. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  38441. #endif
  38442. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  38443. #endif
  38444. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  38445. #endif
  38446. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  38447. #endif
  38448. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  38449. #endif
  38450. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  38451. #endif
  38452. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  38453. #endif
  38454. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38455. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  38456. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38457. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38458. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  38459. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38460. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38461. /**
  38462. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  38463. command in a ApplicationCommandManager.
  38464. Normally, you won't actually create a KeyPressMappingSet directly, because
  38465. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  38466. you'd create yourself an ApplicationCommandManager, and call its
  38467. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  38468. KeyPressMappingSet.
  38469. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  38470. to the top-level component for which you want to handle keystrokes. So for example:
  38471. @code
  38472. class MyMainWindow : public Component
  38473. {
  38474. ApplicationCommandManager* myCommandManager;
  38475. public:
  38476. MyMainWindow()
  38477. {
  38478. myCommandManager = new ApplicationCommandManager();
  38479. // first, make sure the command manager has registered all the commands that its
  38480. // targets can perform..
  38481. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  38482. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  38483. // this will use the command manager to initialise the KeyPressMappingSet with
  38484. // the default keypresses that were specified when the targets added their commands
  38485. // to the manager.
  38486. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  38487. // having set up the default key-mappings, you might now want to load the last set
  38488. // of mappings that the user configured.
  38489. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  38490. // Now tell our top-level window to send any keypresses that arrive to the
  38491. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  38492. addKeyListener (myCommandManager->getKeyMappings());
  38493. }
  38494. ...
  38495. }
  38496. @endcode
  38497. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  38498. register to be told when a command or mapping is added, removed, etc.
  38499. There's also a UI component called KeyMappingEditorComponent that can be used
  38500. to easily edit the key mappings.
  38501. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  38502. */
  38503. class JUCE_API KeyPressMappingSet : public KeyListener,
  38504. public ChangeBroadcaster,
  38505. public FocusChangeListener
  38506. {
  38507. public:
  38508. /** Creates a KeyPressMappingSet for a given command manager.
  38509. Normally, you won't actually create a KeyPressMappingSet directly, because
  38510. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  38511. best thing to do is to create your ApplicationCommandManager, and use the
  38512. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  38513. When a suitable keypress happens, the manager's invoke() method will be
  38514. used to invoke the appropriate command.
  38515. @see ApplicationCommandManager
  38516. */
  38517. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  38518. /** Creates an copy of a KeyPressMappingSet. */
  38519. KeyPressMappingSet (const KeyPressMappingSet& other);
  38520. /** Destructor. */
  38521. ~KeyPressMappingSet();
  38522. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  38523. /** Returns a list of keypresses that are assigned to a particular command.
  38524. @param commandID the command's ID
  38525. */
  38526. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  38527. /** Assigns a keypress to a command.
  38528. If the keypress is already assigned to a different command, it will first be
  38529. removed from that command, to avoid it triggering multiple functions.
  38530. @param commandID the ID of the command that you want to add a keypress to. If
  38531. this is 0, the keypress will be removed from anything that it
  38532. was previously assigned to, but not re-assigned
  38533. @param newKeyPress the new key-press
  38534. @param insertIndex if this is less than zero, the key will be appended to the
  38535. end of the list of keypresses; otherwise the new keypress will
  38536. be inserted into the existing list at this index
  38537. */
  38538. void addKeyPress (CommandID commandID,
  38539. const KeyPress& newKeyPress,
  38540. int insertIndex = -1);
  38541. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  38542. @see resetToDefaultMapping
  38543. */
  38544. void resetToDefaultMappings();
  38545. /** Resets all key-mappings to the defaults for a particular command.
  38546. @see resetToDefaultMappings
  38547. */
  38548. void resetToDefaultMapping (CommandID commandID);
  38549. /** Removes all keypresses that are assigned to any commands. */
  38550. void clearAllKeyPresses();
  38551. /** Removes all keypresses that are assigned to a particular command. */
  38552. void clearAllKeyPresses (CommandID commandID);
  38553. /** Removes one of the keypresses that are assigned to a command.
  38554. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  38555. which the keyPressIndex refers.
  38556. */
  38557. void removeKeyPress (CommandID commandID, int keyPressIndex);
  38558. /** Removes a keypress from any command that it may be assigned to.
  38559. */
  38560. void removeKeyPress (const KeyPress& keypress);
  38561. /** Returns true if the given command is linked to this key. */
  38562. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  38563. /** Looks for a command that corresponds to a keypress.
  38564. @returns the UID of the command or 0 if none was found
  38565. */
  38566. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  38567. /** Tries to recreate the mappings from a previously stored state.
  38568. The XML passed in must have been created by the createXml() method.
  38569. If the stored state makes any reference to commands that aren't
  38570. currently available, these will be ignored.
  38571. If the set of mappings being loaded was a set of differences (using createXml (true)),
  38572. then this will call resetToDefaultMappings() and then merge the saved mappings
  38573. on top. If the saved set was created with createXml (false), then this method
  38574. will first clear all existing mappings and load the saved ones as a complete set.
  38575. @returns true if it manages to load the XML correctly
  38576. @see createXml
  38577. */
  38578. bool restoreFromXml (const XmlElement& xmlVersion);
  38579. /** Creates an XML representation of the current mappings.
  38580. This will produce a lump of XML that can be later reloaded using
  38581. restoreFromXml() to recreate the current mapping state.
  38582. The object that is returned must be deleted by the caller.
  38583. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  38584. will be saved into the XML. If it's true, then the XML will
  38585. only store the differences between the current mappings and
  38586. the default mappings you'd get from calling resetToDefaultMappings().
  38587. The advantage of saving a set of differences from the default is that
  38588. if you change the default mappings (in a new version of your app, for
  38589. example), then these will be merged into a user's saved preferences.
  38590. @see restoreFromXml
  38591. */
  38592. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  38593. /** @internal */
  38594. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  38595. /** @internal */
  38596. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  38597. /** @internal */
  38598. void globalFocusChanged (Component* focusedComponent);
  38599. juce_UseDebuggingNewOperator
  38600. private:
  38601. ApplicationCommandManager* commandManager;
  38602. struct CommandMapping
  38603. {
  38604. CommandID commandID;
  38605. Array <KeyPress> keypresses;
  38606. bool wantsKeyUpDownCallbacks;
  38607. };
  38608. OwnedArray <CommandMapping> mappings;
  38609. struct KeyPressTime
  38610. {
  38611. KeyPress key;
  38612. uint32 timeWhenPressed;
  38613. };
  38614. OwnedArray <KeyPressTime> keysDown;
  38615. void handleMessage (const Message& message);
  38616. void invokeCommand (const CommandID commandID,
  38617. const KeyPress& keyPress,
  38618. const bool isKeyDown,
  38619. const int millisecsSinceKeyPressed,
  38620. Component* const originatingComponent) const;
  38621. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  38622. };
  38623. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38624. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  38625. /**
  38626. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  38627. object.
  38628. @see KeyPressMappingSet
  38629. */
  38630. class JUCE_API KeyMappingEditorComponent : public Component,
  38631. public TreeViewItem,
  38632. public ChangeListener,
  38633. private Button::Listener
  38634. {
  38635. public:
  38636. /** Creates a KeyMappingEditorComponent.
  38637. @param mappingSet this is the set of mappings to display and
  38638. edit. Make sure the mappings object is not
  38639. deleted before this component!
  38640. @param showResetToDefaultButton if true, then at the bottom of the
  38641. list, the component will include a 'reset to
  38642. defaults' button.
  38643. */
  38644. KeyMappingEditorComponent (KeyPressMappingSet* mappingSet,
  38645. bool showResetToDefaultButton);
  38646. /** Destructor. */
  38647. virtual ~KeyMappingEditorComponent();
  38648. /** Sets up the colours to use for parts of the component.
  38649. @param mainBackground colour to use for most of the background
  38650. @param textColour colour to use for the text
  38651. */
  38652. void setColours (const Colour& mainBackground,
  38653. const Colour& textColour);
  38654. /** Returns the KeyPressMappingSet that this component is acting upon.
  38655. */
  38656. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  38657. /** Can be overridden if some commands need to be excluded from the list.
  38658. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  38659. method to decide what to return, but you can override it to handle special cases.
  38660. */
  38661. virtual bool shouldCommandBeIncluded (CommandID commandID);
  38662. /** Can be overridden to indicate that some commands are shown as read-only.
  38663. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  38664. method to decide what to return, but you can override it to handle special cases.
  38665. */
  38666. virtual bool isCommandReadOnly (CommandID commandID);
  38667. /** This can be overridden to let you change the format of the string used
  38668. to describe a keypress.
  38669. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  38670. keys that are triggered by something else externally. If you override the
  38671. method, be sure to let the base class's method handle keys you're not
  38672. interested in.
  38673. */
  38674. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  38675. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38676. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38677. methods.
  38678. To change the colours of the menu that pops up
  38679. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38680. */
  38681. enum ColourIds
  38682. {
  38683. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  38684. textColourId = 0x100ad01, /**< The colour for the text. */
  38685. };
  38686. /** @internal */
  38687. void parentHierarchyChanged();
  38688. /** @internal */
  38689. void resized();
  38690. /** @internal */
  38691. void changeListenerCallback (void*);
  38692. /** @internal */
  38693. bool mightContainSubItems();
  38694. /** @internal */
  38695. const String getUniqueName() const;
  38696. /** @internal */
  38697. void buttonClicked (Button* button);
  38698. juce_UseDebuggingNewOperator
  38699. private:
  38700. KeyPressMappingSet* mappings;
  38701. TreeView* tree;
  38702. friend class KeyMappingTreeViewItem;
  38703. friend class KeyCategoryTreeViewItem;
  38704. friend class KeyMappingItemComponent;
  38705. friend class KeyMappingChangeButton;
  38706. TextButton* resetButton;
  38707. void assignNewKey (CommandID commandID, int index);
  38708. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  38709. KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  38710. };
  38711. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38712. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  38713. #endif
  38714. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  38715. #endif
  38716. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38717. #endif
  38718. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  38719. #endif
  38720. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38721. #endif
  38722. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  38723. #endif
  38724. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  38725. #endif
  38726. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38727. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  38728. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38729. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38730. /** An object that watches for any movement of a component or any of its parent components.
  38731. This makes it easy to check when a component is moved relative to its top-level
  38732. peer window. The normal Component::moved() method is only called when a component
  38733. moves relative to its immediate parent, and sometimes you want to know if any of
  38734. components higher up the tree have moved (which of course will affect the overall
  38735. position of all their sub-components).
  38736. It also includes a callback that lets you know when the top-level peer is changed.
  38737. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  38738. because they need to keep their custom windows in the right place and respond to
  38739. changes in the peer.
  38740. */
  38741. class JUCE_API ComponentMovementWatcher : public ComponentListener
  38742. {
  38743. public:
  38744. /** Creates a ComponentMovementWatcher to watch a given target component. */
  38745. ComponentMovementWatcher (Component* component);
  38746. /** Destructor. */
  38747. ~ComponentMovementWatcher();
  38748. /** This callback happens when the component that is being watched is moved
  38749. relative to its top-level peer window, or when it is resized.
  38750. */
  38751. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  38752. /** This callback happens when the component's top-level peer is changed.
  38753. */
  38754. virtual void componentPeerChanged() = 0;
  38755. juce_UseDebuggingNewOperator
  38756. /** @internal */
  38757. void componentParentHierarchyChanged (Component& component);
  38758. /** @internal */
  38759. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  38760. private:
  38761. Component::SafePointer<Component> component;
  38762. ComponentPeer* lastPeer;
  38763. Array <Component*> registeredParentComps;
  38764. bool reentrant;
  38765. Rectangle<int> lastBounds;
  38766. void unregister();
  38767. void registerWithParentComps();
  38768. ComponentMovementWatcher (const ComponentMovementWatcher&);
  38769. ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  38770. };
  38771. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38772. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  38773. #endif
  38774. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38775. /*** Start of inlined file: juce_GroupComponent.h ***/
  38776. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38777. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38778. /**
  38779. A component that draws an outline around itself and has an optional title at
  38780. the top, for drawing an outline around a group of controls.
  38781. */
  38782. class JUCE_API GroupComponent : public Component
  38783. {
  38784. public:
  38785. /** Creates a GroupComponent.
  38786. @param componentName the name to give the component
  38787. @param labelText the text to show at the top of the outline
  38788. */
  38789. GroupComponent (const String& componentName = String::empty,
  38790. const String& labelText = String::empty);
  38791. /** Destructor. */
  38792. ~GroupComponent();
  38793. /** Changes the text that's shown at the top of the component. */
  38794. void setText (const String& newText);
  38795. /** Returns the currently displayed text label. */
  38796. const String getText() const;
  38797. /** Sets the positioning of the text label.
  38798. (The default is Justification::left)
  38799. @see getTextLabelPosition
  38800. */
  38801. void setTextLabelPosition (const Justification& justification);
  38802. /** Returns the current text label position.
  38803. @see setTextLabelPosition
  38804. */
  38805. const Justification getTextLabelPosition() const throw() { return justification; }
  38806. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38807. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38808. methods.
  38809. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38810. */
  38811. enum ColourIds
  38812. {
  38813. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  38814. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  38815. };
  38816. /** @internal */
  38817. void paint (Graphics& g);
  38818. /** @internal */
  38819. void enablementChanged();
  38820. /** @internal */
  38821. void colourChanged();
  38822. private:
  38823. String text;
  38824. Justification justification;
  38825. GroupComponent (const GroupComponent&);
  38826. GroupComponent& operator= (const GroupComponent&);
  38827. };
  38828. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38829. /*** End of inlined file: juce_GroupComponent.h ***/
  38830. #endif
  38831. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38832. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  38833. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38834. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38835. /*** Start of inlined file: juce_TabbedComponent.h ***/
  38836. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38837. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38838. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  38839. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38840. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38841. class TabbedButtonBar;
  38842. /** In a TabbedButtonBar, this component is used for each of the buttons.
  38843. If you want to create a TabbedButtonBar with custom tab components, derive
  38844. your component from this class, and override the TabbedButtonBar::createTabButton()
  38845. method to create it instead of the default one.
  38846. @see TabbedButtonBar
  38847. */
  38848. class JUCE_API TabBarButton : public Button
  38849. {
  38850. public:
  38851. /** Creates the tab button. */
  38852. TabBarButton (const String& name,
  38853. TabbedButtonBar* ownerBar,
  38854. int tabIndex);
  38855. /** Destructor. */
  38856. ~TabBarButton();
  38857. /** Chooses the best length for the tab, given the specified depth.
  38858. If the tab is horizontal, this should return its width, and the depth
  38859. specifies its height. If it's vertical, it should return the height, and
  38860. the depth is actually its width.
  38861. */
  38862. virtual int getBestTabLength (int depth);
  38863. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  38864. void clicked (const ModifierKeys& mods);
  38865. bool hitTest (int x, int y);
  38866. juce_UseDebuggingNewOperator
  38867. protected:
  38868. friend class TabbedButtonBar;
  38869. TabbedButtonBar* const owner;
  38870. int tabIndex, overlapPixels;
  38871. DropShadowEffect shadow;
  38872. /** Returns an area of the component that's safe to draw in.
  38873. This deals with the orientation of the tabs, which affects which side is
  38874. touching the tabbed box's content component.
  38875. */
  38876. void getActiveArea (int& x, int& y, int& w, int& h);
  38877. private:
  38878. TabBarButton (const TabBarButton&);
  38879. TabBarButton& operator= (const TabBarButton&);
  38880. };
  38881. /**
  38882. A vertical or horizontal bar containing tabs that you can select.
  38883. You can use one of these to generate things like a dialog box that has
  38884. tabbed pages you can flip between. Attach a ChangeListener to the
  38885. button bar to be told when the user changes the page.
  38886. An easier method than doing this is to use a TabbedComponent, which
  38887. contains its own TabbedButtonBar and which takes care of the layout
  38888. and other housekeeping.
  38889. @see TabbedComponent
  38890. */
  38891. class JUCE_API TabbedButtonBar : public Component,
  38892. public ChangeBroadcaster,
  38893. public Button::Listener
  38894. {
  38895. public:
  38896. /** The placement of the tab-bar
  38897. @see setOrientation, getOrientation
  38898. */
  38899. enum Orientation
  38900. {
  38901. TabsAtTop,
  38902. TabsAtBottom,
  38903. TabsAtLeft,
  38904. TabsAtRight
  38905. };
  38906. /** Creates a TabbedButtonBar with a given placement.
  38907. You can change the orientation later if you need to.
  38908. */
  38909. TabbedButtonBar (Orientation orientation);
  38910. /** Destructor. */
  38911. ~TabbedButtonBar();
  38912. /** Changes the bar's orientation.
  38913. This won't change the bar's actual size - you'll need to do that yourself,
  38914. but this determines which direction the tabs go in, and which side they're
  38915. stuck to.
  38916. */
  38917. void setOrientation (Orientation orientation);
  38918. /** Returns the current orientation.
  38919. @see setOrientation
  38920. */
  38921. Orientation getOrientation() const throw() { return orientation; }
  38922. /** Deletes all the tabs from the bar.
  38923. @see addTab
  38924. */
  38925. void clearTabs();
  38926. /** Adds a tab to the bar.
  38927. Tabs are added in left-to-right reading order.
  38928. If this is the first tab added, it'll also be automatically selected.
  38929. */
  38930. void addTab (const String& tabName,
  38931. const Colour& tabBackgroundColour,
  38932. int insertIndex = -1);
  38933. /** Changes the name of one of the tabs. */
  38934. void setTabName (int tabIndex,
  38935. const String& newName);
  38936. /** Gets rid of one of the tabs. */
  38937. void removeTab (int tabIndex);
  38938. /** Moves a tab to a new index in the list.
  38939. Pass -1 as the index to move it to the end of the list.
  38940. */
  38941. void moveTab (int currentIndex, int newIndex);
  38942. /** Returns the number of tabs in the bar. */
  38943. int getNumTabs() const;
  38944. /** Returns a list of all the tab names in the bar. */
  38945. const StringArray getTabNames() const;
  38946. /** Changes the currently selected tab.
  38947. This will send a change message and cause a synchronous callback to
  38948. the currentTabChanged() method. (But if the given tab is already selected,
  38949. nothing will be done).
  38950. To deselect all the tabs, use an index of -1.
  38951. */
  38952. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38953. /** Returns the name of the currently selected tab.
  38954. This could be an empty string if none are selected.
  38955. */
  38956. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  38957. /** Returns the index of the currently selected tab.
  38958. This could return -1 if none are selected.
  38959. */
  38960. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  38961. /** Returns the button for a specific tab.
  38962. The button that is returned may be deleted later by this component, so don't hang
  38963. on to the pointer that is returned. A null pointer may be returned if the index is
  38964. out of range.
  38965. */
  38966. TabBarButton* getTabButton (int index) const;
  38967. /** Callback method to indicate the selected tab has been changed.
  38968. @see setCurrentTabIndex
  38969. */
  38970. virtual void currentTabChanged (int newCurrentTabIndex,
  38971. const String& newCurrentTabName);
  38972. /** Callback method to indicate that the user has right-clicked on a tab.
  38973. (Or ctrl-clicked on the Mac)
  38974. */
  38975. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  38976. /** Returns the colour of a tab.
  38977. This is the colour that was specified in addTab().
  38978. */
  38979. const Colour getTabBackgroundColour (int tabIndex);
  38980. /** Changes the background colour of a tab.
  38981. @see addTab, getTabBackgroundColour
  38982. */
  38983. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38984. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38985. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38986. methods.
  38987. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38988. */
  38989. enum ColourIds
  38990. {
  38991. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  38992. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  38993. the look and feel will choose an appropriate colour. */
  38994. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  38995. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  38996. this isn't specified, the look and feel will choose an appropriate
  38997. colour. */
  38998. };
  38999. /** @internal */
  39000. void resized();
  39001. /** @internal */
  39002. void buttonClicked (Button* button);
  39003. /** @internal */
  39004. void lookAndFeelChanged();
  39005. juce_UseDebuggingNewOperator
  39006. protected:
  39007. /** This creates one of the tabs.
  39008. If you need to use custom tab components, you can override this method and
  39009. return your own class instead of the default.
  39010. */
  39011. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  39012. private:
  39013. Orientation orientation;
  39014. StringArray tabs;
  39015. Array <Colour> tabColours;
  39016. int currentTabIndex;
  39017. Component* behindFrontTab;
  39018. ScopedPointer<Button> extraTabsButton;
  39019. TabbedButtonBar (const TabbedButtonBar&);
  39020. TabbedButtonBar& operator= (const TabbedButtonBar&);
  39021. };
  39022. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  39023. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  39024. /**
  39025. A component with a TabbedButtonBar along one of its sides.
  39026. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  39027. with addTab(), and this will take care of showing the pages for you when the
  39028. user clicks on a different tab.
  39029. @see TabbedButtonBar
  39030. */
  39031. class JUCE_API TabbedComponent : public Component
  39032. {
  39033. public:
  39034. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  39035. Once created, add some tabs with the addTab() method.
  39036. */
  39037. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  39038. /** Destructor. */
  39039. ~TabbedComponent();
  39040. /** Changes the placement of the tabs.
  39041. This will rearrange the layout to place the tabs along the appropriate
  39042. side of this component, and will shift the content component accordingly.
  39043. @see TabbedButtonBar::setOrientation
  39044. */
  39045. void setOrientation (TabbedButtonBar::Orientation orientation);
  39046. /** Returns the current tab placement.
  39047. @see setOrientation, TabbedButtonBar::getOrientation
  39048. */
  39049. TabbedButtonBar::Orientation getOrientation() const throw();
  39050. /** Specifies how many pixels wide or high the tab-bar should be.
  39051. If the tabs are placed along the top or bottom, this specified the height
  39052. of the bar; if they're along the left or right edges, it'll be the width
  39053. of the bar.
  39054. */
  39055. void setTabBarDepth (int newDepth);
  39056. /** Returns the current thickness of the tab bar.
  39057. @see setTabBarDepth
  39058. */
  39059. int getTabBarDepth() const throw() { return tabDepth; }
  39060. /** Specifies the thickness of an outline that should be drawn around the content component.
  39061. If this thickness is > 0, a line will be drawn around the three sides of the content
  39062. component which don't touch the tab-bar, and the content component will be inset by this amount.
  39063. To set the colour of the line, use setColour (outlineColourId, ...).
  39064. */
  39065. void setOutline (int newThickness);
  39066. /** Specifies a gap to leave around the edge of the content component.
  39067. Each edge of the content component will be indented by the given number of pixels.
  39068. */
  39069. void setIndent (int indentThickness);
  39070. /** Removes all the tabs from the bar.
  39071. @see TabbedButtonBar::clearTabs
  39072. */
  39073. void clearTabs();
  39074. /** Adds a tab to the tab-bar.
  39075. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  39076. is true, it will be deleted when the tab is removed or when this object is
  39077. deleted.
  39078. @see TabbedButtonBar::addTab
  39079. */
  39080. void addTab (const String& tabName,
  39081. const Colour& tabBackgroundColour,
  39082. Component* contentComponent,
  39083. bool deleteComponentWhenNotNeeded,
  39084. int insertIndex = -1);
  39085. /** Changes the name of one of the tabs. */
  39086. void setTabName (int tabIndex, const String& newName);
  39087. /** Gets rid of one of the tabs. */
  39088. void removeTab (int tabIndex);
  39089. /** Returns the number of tabs in the bar. */
  39090. int getNumTabs() const;
  39091. /** Returns a list of all the tab names in the bar. */
  39092. const StringArray getTabNames() const;
  39093. /** Returns the content component that was added for the given index.
  39094. Be sure not to use or delete the components that are returned, as this may interfere
  39095. with the TabbedComponent's use of them.
  39096. */
  39097. Component* getTabContentComponent (int tabIndex) const throw();
  39098. /** Returns the colour of one of the tabs. */
  39099. const Colour getTabBackgroundColour (int tabIndex) const throw();
  39100. /** Changes the background colour of one of the tabs. */
  39101. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  39102. /** Changes the currently-selected tab.
  39103. To deselect all the tabs, pass -1 as the index.
  39104. @see TabbedButtonBar::setCurrentTabIndex
  39105. */
  39106. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  39107. /** Returns the index of the currently selected tab.
  39108. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  39109. */
  39110. int getCurrentTabIndex() const;
  39111. /** Returns the name of the currently selected tab.
  39112. @see addTab, TabbedButtonBar::getCurrentTabName()
  39113. */
  39114. const String& getCurrentTabName() const;
  39115. /** Returns the current component that's filling the panel.
  39116. This will return 0 if there isn't one.
  39117. */
  39118. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  39119. /** Callback method to indicate the selected tab has been changed.
  39120. @see setCurrentTabIndex
  39121. */
  39122. virtual void currentTabChanged (int newCurrentTabIndex,
  39123. const String& newCurrentTabName);
  39124. /** Callback method to indicate that the user has right-clicked on a tab.
  39125. (Or ctrl-clicked on the Mac)
  39126. */
  39127. virtual void popupMenuClickOnTab (int tabIndex,
  39128. const String& tabName);
  39129. /** Returns the tab button bar component that is being used.
  39130. */
  39131. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  39132. /** A set of colour IDs to use to change the colour of various aspects of the component.
  39133. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39134. methods.
  39135. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39136. */
  39137. enum ColourIds
  39138. {
  39139. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  39140. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  39141. (See setOutline) */
  39142. };
  39143. /** @internal */
  39144. void paint (Graphics& g);
  39145. /** @internal */
  39146. void resized();
  39147. /** @internal */
  39148. void lookAndFeelChanged();
  39149. juce_UseDebuggingNewOperator
  39150. protected:
  39151. TabbedButtonBar* tabs;
  39152. /** This creates one of the tab buttons.
  39153. If you need to use custom tab components, you can override this method and
  39154. return your own class instead of the default.
  39155. */
  39156. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  39157. private:
  39158. Array <Component*> contentComponents;
  39159. Component* panelComponent;
  39160. int tabDepth;
  39161. int outlineThickness, edgeIndent;
  39162. static const Identifier deleteComponentId;
  39163. friend class TabCompButtonBar;
  39164. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  39165. TabbedComponent (const TabbedComponent&);
  39166. TabbedComponent& operator= (const TabbedComponent&);
  39167. };
  39168. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39169. /*** End of inlined file: juce_TabbedComponent.h ***/
  39170. /*** Start of inlined file: juce_DocumentWindow.h ***/
  39171. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39172. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39173. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  39174. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39175. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39176. /*** Start of inlined file: juce_MenuBarModel.h ***/
  39177. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  39178. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  39179. /**
  39180. A class for controlling MenuBar components.
  39181. This class is used to tell a MenuBar what menus to show, and to respond
  39182. to a menu being selected.
  39183. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  39184. */
  39185. class JUCE_API MenuBarModel : private AsyncUpdater,
  39186. private ApplicationCommandManagerListener
  39187. {
  39188. public:
  39189. MenuBarModel() throw();
  39190. /** Destructor. */
  39191. virtual ~MenuBarModel();
  39192. /** Call this when some of your menu items have changed.
  39193. This method will cause a callback to any MenuBarListener objects that
  39194. are registered with this model.
  39195. If this model is displaying items from an ApplicationCommandManager, you
  39196. can use the setApplicationCommandManagerToWatch() method to cause
  39197. change messages to be sent automatically when the ApplicationCommandManager
  39198. is changed.
  39199. @see addListener, removeListener, MenuBarListener
  39200. */
  39201. void menuItemsChanged();
  39202. /** Tells the menu bar to listen to the specified command manager, and to update
  39203. itself when the commands change.
  39204. This will also allow it to flash a menu name when a command from that menu
  39205. is invoked using a keystroke.
  39206. */
  39207. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  39208. /** A class to receive callbacks when a MenuBarModel changes.
  39209. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  39210. */
  39211. class JUCE_API Listener
  39212. {
  39213. public:
  39214. /** Destructor. */
  39215. virtual ~Listener() {}
  39216. /** This callback is made when items are changed in the menu bar model.
  39217. */
  39218. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  39219. /** This callback is made when an application command is invoked that
  39220. is represented by one of the items in the menu bar model.
  39221. */
  39222. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  39223. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  39224. };
  39225. /** Registers a listener for callbacks when the menu items in this model change.
  39226. The listener object will get callbacks when this object's menuItemsChanged()
  39227. method is called.
  39228. @see removeListener
  39229. */
  39230. void addListener (Listener* listenerToAdd) throw();
  39231. /** Removes a listener.
  39232. @see addListener
  39233. */
  39234. void removeListener (Listener* listenerToRemove) throw();
  39235. /** This method must return a list of the names of the menus. */
  39236. virtual const StringArray getMenuBarNames() = 0;
  39237. /** This should return the popup menu to display for a given top-level menu.
  39238. @param topLevelMenuIndex the index of the top-level menu to show
  39239. @param menuName the name of the top-level menu item to show
  39240. */
  39241. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  39242. const String& menuName) = 0;
  39243. /** This is called when a menu item has been clicked on.
  39244. @param menuItemID the item ID of the PopupMenu item that was selected
  39245. @param topLevelMenuIndex the index of the top-level menu from which the item was
  39246. chosen (just in case you've used duplicate ID numbers
  39247. on more than one of the popup menus)
  39248. */
  39249. virtual void menuItemSelected (int menuItemID,
  39250. int topLevelMenuIndex) = 0;
  39251. #if JUCE_MAC || DOXYGEN
  39252. /** MAC ONLY - Sets the model that is currently being shown as the main
  39253. menu bar at the top of the screen on the Mac.
  39254. You can pass 0 to stop the current model being displayed. Be careful
  39255. not to delete a model while it is being used.
  39256. An optional extra menu can be specified, containing items to add to the top of
  39257. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  39258. an apple, it's the one next to it, with your application's name at the top
  39259. and the services menu etc on it). When one of these items is selected, the
  39260. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  39261. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  39262. object then newMenuBarModel must be non-null.
  39263. */
  39264. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  39265. const PopupMenu* extraAppleMenuItems = 0);
  39266. /** MAC ONLY - Returns the menu model that is currently being shown as
  39267. the main menu bar.
  39268. */
  39269. static MenuBarModel* getMacMainMenu();
  39270. #endif
  39271. /** @internal */
  39272. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  39273. /** @internal */
  39274. void applicationCommandListChanged();
  39275. /** @internal */
  39276. void handleAsyncUpdate();
  39277. juce_UseDebuggingNewOperator
  39278. private:
  39279. ApplicationCommandManager* manager;
  39280. ListenerList <Listener> listeners;
  39281. MenuBarModel (const MenuBarModel&);
  39282. MenuBarModel& operator= (const MenuBarModel&);
  39283. };
  39284. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  39285. typedef MenuBarModel::Listener MenuBarModelListener;
  39286. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  39287. /*** End of inlined file: juce_MenuBarModel.h ***/
  39288. /**
  39289. A menu bar component.
  39290. @see MenuBarModel
  39291. */
  39292. class JUCE_API MenuBarComponent : public Component,
  39293. private MenuBarModel::Listener,
  39294. private Timer
  39295. {
  39296. public:
  39297. /** Creates a menu bar.
  39298. @param model the model object to use to control this bar. You can
  39299. pass 0 into this if you like, and set the model later
  39300. using the setModel() method
  39301. */
  39302. MenuBarComponent (MenuBarModel* model);
  39303. /** Destructor. */
  39304. ~MenuBarComponent();
  39305. /** Changes the model object to use to control the bar.
  39306. This can be 0, in which case the bar will be empty. Don't delete the object
  39307. that is passed-in while it's still being used by this MenuBar.
  39308. */
  39309. void setModel (MenuBarModel* newModel);
  39310. /** Returns the current menu bar model being used.
  39311. */
  39312. MenuBarModel* getModel() const throw();
  39313. /** Pops up one of the menu items.
  39314. This lets you manually open one of the menus - it could be triggered by a
  39315. key shortcut, for example.
  39316. */
  39317. void showMenu (int menuIndex);
  39318. /** @internal */
  39319. void paint (Graphics& g);
  39320. /** @internal */
  39321. void resized();
  39322. /** @internal */
  39323. void mouseEnter (const MouseEvent& e);
  39324. /** @internal */
  39325. void mouseExit (const MouseEvent& e);
  39326. /** @internal */
  39327. void mouseDown (const MouseEvent& e);
  39328. /** @internal */
  39329. void mouseDrag (const MouseEvent& e);
  39330. /** @internal */
  39331. void mouseUp (const MouseEvent& e);
  39332. /** @internal */
  39333. void mouseMove (const MouseEvent& e);
  39334. /** @internal */
  39335. void handleCommandMessage (int commandId);
  39336. /** @internal */
  39337. bool keyPressed (const KeyPress& key);
  39338. /** @internal */
  39339. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  39340. /** @internal */
  39341. void menuCommandInvoked (MenuBarModel* menuBarModel,
  39342. const ApplicationCommandTarget::InvocationInfo& info);
  39343. juce_UseDebuggingNewOperator
  39344. private:
  39345. class AsyncCallback;
  39346. friend class AsyncCallback;
  39347. MenuBarModel* model;
  39348. StringArray menuNames;
  39349. Array <int> xPositions;
  39350. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  39351. int lastMouseX, lastMouseY;
  39352. int getItemAt (int x, int y);
  39353. void setItemUnderMouse (int index);
  39354. void setOpenItem (int index);
  39355. void updateItemUnderMouse (int x, int y);
  39356. void timerCallback();
  39357. void repaintMenuItem (int index);
  39358. void menuDismissed (int topLevelIndex, int itemId);
  39359. MenuBarComponent (const MenuBarComponent&);
  39360. MenuBarComponent& operator= (const MenuBarComponent&);
  39361. };
  39362. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39363. /*** End of inlined file: juce_MenuBarComponent.h ***/
  39364. /**
  39365. A resizable window with a title bar and maximise, minimise and close buttons.
  39366. This subclass of ResizableWindow creates a fairly standard type of window with
  39367. a title bar and various buttons. The name of the component is shown in the
  39368. title bar, and an icon can optionally be specified with setIcon().
  39369. All the methods available to a ResizableWindow are also available to this,
  39370. so it can easily be made resizable, minimised, maximised, etc.
  39371. It's not advisable to add child components directly to a DocumentWindow: put them
  39372. inside your content component instead. And overriding methods like resized(), moved(), etc
  39373. is also not recommended - instead override these methods for your content component.
  39374. (If for some obscure reason you do need to override these methods, always remember to
  39375. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  39376. decorations correctly).
  39377. You can also automatically add a menu bar to the window, using the setMenuBar()
  39378. method.
  39379. @see ResizableWindow, DialogWindow
  39380. */
  39381. class JUCE_API DocumentWindow : public ResizableWindow
  39382. {
  39383. public:
  39384. /** The set of available button-types that can be put on the title bar.
  39385. @see setTitleBarButtonsRequired
  39386. */
  39387. enum TitleBarButtons
  39388. {
  39389. minimiseButton = 1,
  39390. maximiseButton = 2,
  39391. closeButton = 4,
  39392. /** A combination of all the buttons above. */
  39393. allButtons = 7
  39394. };
  39395. /** Creates a DocumentWindow.
  39396. @param name the name to give the component - this is also
  39397. the title shown at the top of the window. To change
  39398. this later, use setName()
  39399. @param backgroundColour the colour to use for filling the window's background.
  39400. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39401. should be shown on the title bar. This value is a bitwise
  39402. combination of values from the TitleBarButtons enum. Note
  39403. that it can be "allButtons" to get them all. You
  39404. can change this later with the setTitleBarButtonsRequired()
  39405. method, which can also specify where they are positioned.
  39406. @param addToDesktop if true, the window will be automatically added to the
  39407. desktop; if false, you can use it as a child component
  39408. @see TitleBarButtons
  39409. */
  39410. DocumentWindow (const String& name,
  39411. const Colour& backgroundColour,
  39412. int requiredButtons,
  39413. bool addToDesktop = true);
  39414. /** Destructor.
  39415. If a content component has been set with setContentComponent(), it
  39416. will be deleted.
  39417. */
  39418. ~DocumentWindow();
  39419. /** Changes the component's name.
  39420. (This is overridden from Component::setName() to cause a repaint, as
  39421. the name is what gets drawn across the window's title bar).
  39422. */
  39423. void setName (const String& newName);
  39424. /** Sets an icon to show in the title bar, next to the title.
  39425. A copy is made internally of the image, so the caller can delete the
  39426. image after calling this. If 0 is passed-in, any existing icon will be
  39427. removed.
  39428. */
  39429. void setIcon (const Image& imageToUse);
  39430. /** Changes the height of the title-bar. */
  39431. void setTitleBarHeight (int newHeight);
  39432. /** Returns the current title bar height. */
  39433. int getTitleBarHeight() const;
  39434. /** Changes the set of title-bar buttons being shown.
  39435. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39436. should be shown on the title bar. This value is a bitwise
  39437. combination of values from the TitleBarButtons enum. Note
  39438. that it can be "allButtons" to get them all.
  39439. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  39440. left side of the bar; if false, they'll be placed at the right
  39441. */
  39442. void setTitleBarButtonsRequired (int requiredButtons,
  39443. bool positionTitleBarButtonsOnLeft);
  39444. /** Sets whether the title should be centred within the window.
  39445. If true, the title text is shown in the middle of the title-bar; if false,
  39446. it'll be shown at the left of the bar.
  39447. */
  39448. void setTitleBarTextCentred (bool textShouldBeCentred);
  39449. /** Creates a menu inside this window.
  39450. @param menuBarModel this specifies a MenuBarModel that should be used to
  39451. generate the contents of a menu bar that will be placed
  39452. just below the title bar, and just above any content
  39453. component. If this value is zero, any existing menu bar
  39454. will be removed from the component; if non-zero, one will
  39455. be added if it's required.
  39456. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  39457. or less to use the look-and-feel's default size.
  39458. */
  39459. void setMenuBar (MenuBarModel* menuBarModel,
  39460. int menuBarHeight = 0);
  39461. /** This method is called when the user tries to close the window.
  39462. This is triggered by the user clicking the close button, or using some other
  39463. OS-specific key shortcut or OS menu for getting rid of a window.
  39464. If the window is just a pop-up, you should override this closeButtonPressed()
  39465. method and make it delete the window in whatever way is appropriate for your
  39466. app. E.g. you might just want to call "delete this".
  39467. If your app is centred around this window such that the whole app should quit when
  39468. the window is closed, then you will probably want to use this method as an opportunity
  39469. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  39470. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  39471. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  39472. or closing it via the taskbar icon on Windows).
  39473. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  39474. redirects it to call this method, so any methods of closing the window that are
  39475. caught by userTriedToCloseWindow() will also end up here).
  39476. */
  39477. virtual void closeButtonPressed();
  39478. /** Callback that is triggered when the minimise button is pressed.
  39479. The default implementation of this calls ResizableWindow::setMinimised(), but
  39480. you can override it to do more customised behaviour.
  39481. */
  39482. virtual void minimiseButtonPressed();
  39483. /** Callback that is triggered when the maximise button is pressed, or when the
  39484. title-bar is double-clicked.
  39485. The default implementation of this calls ResizableWindow::setFullScreen(), but
  39486. you can override it to do more customised behaviour.
  39487. */
  39488. virtual void maximiseButtonPressed();
  39489. /** Returns the close button, (or 0 if there isn't one). */
  39490. Button* getCloseButton() const throw();
  39491. /** Returns the minimise button, (or 0 if there isn't one). */
  39492. Button* getMinimiseButton() const throw();
  39493. /** Returns the maximise button, (or 0 if there isn't one). */
  39494. Button* getMaximiseButton() const throw();
  39495. /** A set of colour IDs to use to change the colour of various aspects of the window.
  39496. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39497. methods.
  39498. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39499. */
  39500. enum ColourIds
  39501. {
  39502. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  39503. and feel class how this is used. */
  39504. };
  39505. /** @internal */
  39506. void paint (Graphics& g);
  39507. /** @internal */
  39508. void resized();
  39509. /** @internal */
  39510. void lookAndFeelChanged();
  39511. /** @internal */
  39512. const BorderSize getBorderThickness();
  39513. /** @internal */
  39514. const BorderSize getContentComponentBorder();
  39515. /** @internal */
  39516. void mouseDoubleClick (const MouseEvent& e);
  39517. /** @internal */
  39518. void userTriedToCloseWindow();
  39519. /** @internal */
  39520. void activeWindowStatusChanged();
  39521. /** @internal */
  39522. int getDesktopWindowStyleFlags() const;
  39523. /** @internal */
  39524. void parentHierarchyChanged();
  39525. /** @internal */
  39526. const Rectangle<int> getTitleBarArea();
  39527. juce_UseDebuggingNewOperator
  39528. private:
  39529. int titleBarHeight, menuBarHeight, requiredButtons;
  39530. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  39531. ScopedPointer <Button> titleBarButtons [3];
  39532. Image titleBarIcon;
  39533. ScopedPointer <MenuBarComponent> menuBar;
  39534. MenuBarModel* menuBarModel;
  39535. class ButtonListenerProxy;
  39536. friend class ScopedPointer <ButtonListenerProxy>;
  39537. ScopedPointer <ButtonListenerProxy> buttonListener;
  39538. void repaintTitleBar();
  39539. DocumentWindow (const DocumentWindow&);
  39540. DocumentWindow& operator= (const DocumentWindow&);
  39541. };
  39542. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39543. /*** End of inlined file: juce_DocumentWindow.h ***/
  39544. class MultiDocumentPanel;
  39545. class MDITabbedComponentInternal;
  39546. /**
  39547. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  39548. component.
  39549. It's like a normal DocumentWindow but has some extra functionality to make sure
  39550. everything works nicely inside a MultiDocumentPanel.
  39551. @see MultiDocumentPanel
  39552. */
  39553. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  39554. {
  39555. public:
  39556. /**
  39557. */
  39558. MultiDocumentPanelWindow (const Colour& backgroundColour);
  39559. /** Destructor. */
  39560. ~MultiDocumentPanelWindow();
  39561. /** @internal */
  39562. void maximiseButtonPressed();
  39563. /** @internal */
  39564. void closeButtonPressed();
  39565. /** @internal */
  39566. void activeWindowStatusChanged();
  39567. /** @internal */
  39568. void broughtToFront();
  39569. juce_UseDebuggingNewOperator
  39570. private:
  39571. void updateOrder();
  39572. MultiDocumentPanel* getOwner() const throw();
  39573. };
  39574. /**
  39575. A component that contains a set of other components either in floating windows
  39576. or tabs.
  39577. This acts as a panel that can be used to hold a set of open document windows, with
  39578. different layout modes.
  39579. Use addDocument() and closeDocument() to add or remove components from the
  39580. panel - never use any of the Component methods to access the panel's child
  39581. components directly, as these are managed internally.
  39582. */
  39583. class JUCE_API MultiDocumentPanel : public Component,
  39584. private ComponentListener
  39585. {
  39586. public:
  39587. /** Creates an empty panel.
  39588. Use addDocument() and closeDocument() to add or remove components from the
  39589. panel - never use any of the Component methods to access the panel's child
  39590. components directly, as these are managed internally.
  39591. */
  39592. MultiDocumentPanel();
  39593. /** Destructor.
  39594. When deleted, this will call closeAllDocuments (false) to make sure all its
  39595. components are deleted. If you need to make sure all documents are saved
  39596. before closing, then you should call closeAllDocuments (true) and check that
  39597. it returns true before deleting the panel.
  39598. */
  39599. ~MultiDocumentPanel();
  39600. /** Tries to close all the documents.
  39601. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39602. be called for each open document, and any of these calls fails, this method
  39603. will stop and return false, leaving some documents still open.
  39604. If checkItsOkToCloseFirst is false, then all documents will be closed
  39605. unconditionally.
  39606. @see closeDocument
  39607. */
  39608. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  39609. /** Adds a document component to the panel.
  39610. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  39611. this will fail and return false. (If it does fail, the component passed-in will not be
  39612. deleted, even if deleteWhenRemoved was set to true).
  39613. The MultiDocumentPanel will deal with creating a window border to go around your component,
  39614. so just pass in the bare content component here, no need to give it a ResizableWindow
  39615. or DocumentWindow.
  39616. @param component the component to add
  39617. @param backgroundColour the background colour to use to fill the component's
  39618. window or tab
  39619. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  39620. or closeAllDocuments(), then it will be deleted. If false, then
  39621. the caller must handle the component's deletion
  39622. */
  39623. bool addDocument (Component* component,
  39624. const Colour& backgroundColour,
  39625. bool deleteWhenRemoved);
  39626. /** Closes one of the documents.
  39627. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39628. be called, and if it fails, this method will return false without closing the
  39629. document.
  39630. If checkItsOkToCloseFirst is false, then the documents will be closed
  39631. unconditionally.
  39632. The component will be deleted if the deleteWhenRemoved parameter was set to
  39633. true when it was added with addDocument.
  39634. @see addDocument, closeAllDocuments
  39635. */
  39636. bool closeDocument (Component* component,
  39637. bool checkItsOkToCloseFirst);
  39638. /** Returns the number of open document windows.
  39639. @see getDocument
  39640. */
  39641. int getNumDocuments() const throw();
  39642. /** Returns one of the open documents.
  39643. The order of the documents in this array may change when they are added, removed
  39644. or moved around.
  39645. @see getNumDocuments
  39646. */
  39647. Component* getDocument (int index) const throw();
  39648. /** Returns the document component that is currently focused or on top.
  39649. If currently using floating windows, then this will be the component in the currently
  39650. active window, or the top component if none are active.
  39651. If it's currently in tabbed mode, then it'll return the component in the active tab.
  39652. @see setActiveDocument
  39653. */
  39654. Component* getActiveDocument() const throw();
  39655. /** Makes one of the components active and brings it to the top.
  39656. @see getActiveDocument
  39657. */
  39658. void setActiveDocument (Component* component);
  39659. /** Callback which gets invoked when the currently-active document changes. */
  39660. virtual void activeDocumentChanged();
  39661. /** Sets a limit on how many windows can be open at once.
  39662. If this is zero or less there's no limit (the default). addDocument() will fail
  39663. if this number is exceeded.
  39664. */
  39665. void setMaximumNumDocuments (int maximumNumDocuments);
  39666. /** Sets an option to make the document fullscreen if there's only one document open.
  39667. If set to true, then if there's only one document, it'll fill the whole of this
  39668. component without tabs or a window border. If false, then tabs or a window
  39669. will always be shown, even if there's only one document. If there's more than
  39670. one document open, then this option makes no difference.
  39671. */
  39672. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  39673. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  39674. */
  39675. bool isFullscreenWhenOneDocument() const throw();
  39676. /** The different layout modes available. */
  39677. enum LayoutMode
  39678. {
  39679. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  39680. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  39681. };
  39682. /** Changes the panel's mode.
  39683. @see LayoutMode, getLayoutMode
  39684. */
  39685. void setLayoutMode (LayoutMode newLayoutMode);
  39686. /** Returns the current layout mode. */
  39687. LayoutMode getLayoutMode() const throw() { return mode; }
  39688. /** Sets the background colour for the whole panel.
  39689. Each document has its own background colour, but this is the one used to fill the areas
  39690. behind them.
  39691. */
  39692. void setBackgroundColour (const Colour& newBackgroundColour);
  39693. /** Returns the current background colour.
  39694. @see setBackgroundColour
  39695. */
  39696. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  39697. /** A subclass must override this to say whether its currently ok for a document
  39698. to be closed.
  39699. This method is called by closeDocument() and closeAllDocuments() to indicate that
  39700. a document should be saved if possible, ready for it to be closed.
  39701. If this method returns true, then it means the document is ok and can be closed.
  39702. If it returns false, then it means that the closeDocument() method should stop
  39703. and not close.
  39704. Normally, you'd use this method to ask the user if they want to save any changes,
  39705. then return true if the save operation went ok. If the user cancelled the save
  39706. operation you could return false here to abort the close operation.
  39707. If your component is based on the FileBasedDocument class, then you'd probably want
  39708. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  39709. FileBasedDocument::savedOk
  39710. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  39711. */
  39712. virtual bool tryToCloseDocument (Component* component) = 0;
  39713. /** Creates a new window to be used for a document.
  39714. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  39715. but you might want to override it to return a custom component.
  39716. */
  39717. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  39718. /** @internal */
  39719. void paint (Graphics& g);
  39720. /** @internal */
  39721. void resized();
  39722. /** @internal */
  39723. void componentNameChanged (Component&);
  39724. juce_UseDebuggingNewOperator
  39725. private:
  39726. LayoutMode mode;
  39727. Array <Component*> components;
  39728. TabbedComponent* tabComponent;
  39729. Colour backgroundColour;
  39730. int maximumNumDocuments, numDocsBeforeTabsUsed;
  39731. friend class MultiDocumentPanelWindow;
  39732. friend class MDITabbedComponentInternal;
  39733. Component* getContainerComp (Component* c) const;
  39734. void updateOrder();
  39735. void addWindow (Component* component);
  39736. };
  39737. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  39738. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  39739. #endif
  39740. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39741. #endif
  39742. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39743. #endif
  39744. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  39745. #endif
  39746. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39747. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  39748. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39749. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39750. /**
  39751. For laying out a set of components, where the components have preferred sizes
  39752. and size limits, but where they are allowed to stretch to fill the available
  39753. space.
  39754. For example, if you have a component containing several other components, and
  39755. each one should be given a share of the total size, you could use one of these
  39756. to resize the child components when the parent component is resized. Then
  39757. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  39758. A StretchableLayoutManager operates only in one dimension, so if you have a set
  39759. of components stacked vertically on top of each other, you'd use one to manage their
  39760. heights. To build up complex arrangements of components, e.g. for applications
  39761. with multiple nested panels, you would use more than one StretchableLayoutManager.
  39762. E.g. by using two (one vertical, one horizontal), you could create a resizable
  39763. spreadsheet-style table.
  39764. E.g.
  39765. @code
  39766. class MyComp : public Component
  39767. {
  39768. StretchableLayoutManager myLayout;
  39769. MyComp()
  39770. {
  39771. myLayout.setItemLayout (0, // for item 0
  39772. 50, 100, // must be between 50 and 100 pixels in size
  39773. -0.6); // and its preferred size is 60% of the total available space
  39774. myLayout.setItemLayout (1, // for item 1
  39775. -0.2, -0.6, // size must be between 20% and 60% of the available space
  39776. 50); // and its preferred size is 50 pixels
  39777. }
  39778. void resized()
  39779. {
  39780. // make a list of two of our child components that we want to reposition
  39781. Component* comps[] = { myComp1, myComp2 };
  39782. // this will position the 2 components, one above the other, to fit
  39783. // vertically into the rectangle provided.
  39784. myLayout.layOutComponents (comps, 2,
  39785. 0, 0, getWidth(), getHeight(),
  39786. true);
  39787. }
  39788. };
  39789. @endcode
  39790. @see StretchableLayoutResizerBar
  39791. */
  39792. class JUCE_API StretchableLayoutManager
  39793. {
  39794. public:
  39795. /** Creates an empty layout.
  39796. You'll need to add some item properties to the layout before it can be used
  39797. to resize things - see setItemLayout().
  39798. */
  39799. StretchableLayoutManager();
  39800. /** Destructor. */
  39801. ~StretchableLayoutManager();
  39802. /** For a numbered item, this sets its size limits and preferred size.
  39803. @param itemIndex the index of the item to change.
  39804. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39805. indicates an absolute size in pixels. A negative number indicates a
  39806. proportion of the available space (e.g -0.5 is 50%)
  39807. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39808. indicates an absolute size in pixels. A negative number indicates a
  39809. proportion of the available space
  39810. @param preferredSize the size that this item would like to be, if there's enough room. A
  39811. positive number indicates an absolute size in pixels. A negative number
  39812. indicates a proportion of the available space
  39813. @see getItemLayout
  39814. */
  39815. void setItemLayout (int itemIndex,
  39816. double minimumSize,
  39817. double maximumSize,
  39818. double preferredSize);
  39819. /** For a numbered item, this returns its size limits and preferred size.
  39820. @param itemIndex the index of the item.
  39821. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39822. indicates an absolute size in pixels. A negative number indicates a
  39823. proportion of the available space (e.g -0.5 is 50%)
  39824. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39825. indicates an absolute size in pixels. A negative number indicates a
  39826. proportion of the available space
  39827. @param preferredSize the size that this item would like to be, if there's enough room. A
  39828. positive number indicates an absolute size in pixels. A negative number
  39829. indicates a proportion of the available space
  39830. @returns false if the item's properties hadn't been set
  39831. @see setItemLayout
  39832. */
  39833. bool getItemLayout (int itemIndex,
  39834. double& minimumSize,
  39835. double& maximumSize,
  39836. double& preferredSize) const;
  39837. /** Clears all the properties that have been set with setItemLayout() and resets
  39838. this object to its initial state.
  39839. */
  39840. void clearAllItems();
  39841. /** Takes a set of components that correspond to the layout's items, and positions
  39842. them to fill a space.
  39843. This will try to give each item its preferred size, whether that's a relative size
  39844. or an absolute one.
  39845. @param components an array of components that correspond to each of the
  39846. numbered items that the StretchableLayoutManager object
  39847. has been told about with setItemLayout()
  39848. @param numComponents the number of components in the array that is passed-in. This
  39849. should be the same as the number of items this object has been
  39850. told about.
  39851. @param x the left of the rectangle in which the components should
  39852. be laid out
  39853. @param y the top of the rectangle in which the components should
  39854. be laid out
  39855. @param width the width of the rectangle in which the components should
  39856. be laid out
  39857. @param height the height of the rectangle in which the components should
  39858. be laid out
  39859. @param vertically if true, the components will be positioned in a vertical stack,
  39860. so that they fill the height of the rectangle. If false, they
  39861. will be placed side-by-side in a horizontal line, filling the
  39862. available width
  39863. @param resizeOtherDimension if true, this means that the components will have their
  39864. other dimension resized to fit the space - i.e. if the 'vertically'
  39865. parameter is true, their x-positions and widths are adjusted to fit
  39866. the x and width parameters; if 'vertically' is false, their y-positions
  39867. and heights are adjusted to fit the y and height parameters.
  39868. */
  39869. void layOutComponents (Component** components,
  39870. int numComponents,
  39871. int x, int y, int width, int height,
  39872. bool vertically,
  39873. bool resizeOtherDimension);
  39874. /** Returns the current position of one of the items.
  39875. This is only a valid call after layOutComponents() has been called, as it
  39876. returns the last position that this item was placed at. If the layout was
  39877. vertical, the value returned will be the y position of the top of the item,
  39878. relative to the top of the rectangle in which the items were placed (so for
  39879. example, item 0 will always have position of 0, even in the rectangle passed
  39880. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  39881. the position returned is the item's left-hand position, again relative to the
  39882. x position of the rectangle used.
  39883. @see getItemCurrentSize, setItemPosition
  39884. */
  39885. int getItemCurrentPosition (int itemIndex) const;
  39886. /** Returns the current size of one of the items.
  39887. This is only meaningful after layOutComponents() has been called, as it
  39888. returns the last size that this item was given. If the layout was done
  39889. vertically, it'll return the item's height in pixels; if it was horizontal,
  39890. it'll return its width.
  39891. @see getItemCurrentRelativeSize
  39892. */
  39893. int getItemCurrentAbsoluteSize (int itemIndex) const;
  39894. /** Returns the current size of one of the items.
  39895. This is only meaningful after layOutComponents() has been called, as it
  39896. returns the last size that this item was given. If the layout was done
  39897. vertically, it'll return a negative value representing the item's height relative
  39898. to the last size used for laying the components out; if the layout was done
  39899. horizontally it'll be the proportion of its width.
  39900. @see getItemCurrentAbsoluteSize
  39901. */
  39902. double getItemCurrentRelativeSize (int itemIndex) const;
  39903. /** Moves one of the items, shifting along any other items as necessary in
  39904. order to get it to the desired position.
  39905. Calling this method will also update the preferred sizes of the items it
  39906. shuffles along, so that they reflect their new positions.
  39907. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  39908. about when it's dragged).
  39909. @param itemIndex the item to move
  39910. @param newPosition the absolute position that you'd like this item to move
  39911. to. The item might not be able to always reach exactly this position,
  39912. because other items may have minimum sizes that constrain how
  39913. far it can go
  39914. */
  39915. void setItemPosition (int itemIndex,
  39916. int newPosition);
  39917. juce_UseDebuggingNewOperator
  39918. private:
  39919. struct ItemLayoutProperties
  39920. {
  39921. int itemIndex;
  39922. int currentSize;
  39923. double minSize, maxSize, preferredSize;
  39924. };
  39925. OwnedArray <ItemLayoutProperties> items;
  39926. int totalSize;
  39927. static int sizeToRealSize (double size, int totalSpace);
  39928. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  39929. void setTotalSize (int newTotalSize);
  39930. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  39931. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  39932. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  39933. void updatePrefSizesToMatchCurrentPositions();
  39934. StretchableLayoutManager (const StretchableLayoutManager&);
  39935. StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  39936. };
  39937. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39938. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  39939. #endif
  39940. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39941. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39942. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39943. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39944. /**
  39945. A component that acts as one of the vertical or horizontal bars you see being
  39946. used to resize panels in a window.
  39947. One of these acts with a StretchableLayoutManager to resize the other components.
  39948. @see StretchableLayoutManager
  39949. */
  39950. class JUCE_API StretchableLayoutResizerBar : public Component
  39951. {
  39952. public:
  39953. /** Creates a resizer bar for use on a specified layout.
  39954. @param layoutToUse the layout that will be affected when this bar
  39955. is dragged
  39956. @param itemIndexInLayout the item index in the layout that corresponds to
  39957. this bar component. You'll need to set up the item
  39958. properties in a suitable way for a divider bar, e.g.
  39959. for an 8-pixel wide bar which, you could call
  39960. myLayout->setItemLayout (barIndex, 8, 8, 8)
  39961. @param isBarVertical true if it's an upright bar that you drag left and
  39962. right; false for a horizontal one that you drag up and
  39963. down
  39964. */
  39965. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  39966. int itemIndexInLayout,
  39967. bool isBarVertical);
  39968. /** Destructor. */
  39969. ~StretchableLayoutResizerBar();
  39970. /** This is called when the bar is dragged.
  39971. This method must update the positions of any components whose position is
  39972. determined by the StretchableLayoutManager, because they might have just
  39973. moved.
  39974. The default implementation calls the resized() method of this component's
  39975. parent component, because that's often where you're likely to apply the
  39976. layout, but it can be overridden for more specific needs.
  39977. */
  39978. virtual void hasBeenMoved();
  39979. /** @internal */
  39980. void paint (Graphics& g);
  39981. /** @internal */
  39982. void mouseDown (const MouseEvent& e);
  39983. /** @internal */
  39984. void mouseDrag (const MouseEvent& e);
  39985. juce_UseDebuggingNewOperator
  39986. private:
  39987. StretchableLayoutManager* layout;
  39988. int itemIndex, mouseDownPos;
  39989. bool isVertical;
  39990. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  39991. StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  39992. };
  39993. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39994. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39995. #endif
  39996. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39997. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  39998. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39999. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  40000. /**
  40001. A utility class for fitting a set of objects whose sizes can vary between
  40002. a minimum and maximum size, into a space.
  40003. This is a trickier algorithm than it would first seem, so I've put it in this
  40004. class to allow it to be shared by various bits of code.
  40005. To use it, create one of these objects, call addItem() to add the list of items
  40006. you need, then call resizeToFit(), which will change all their sizes. You can
  40007. then retrieve the new sizes with getItemSize() and getNumItems().
  40008. It's currently used by the TableHeaderComponent for stretching out the table
  40009. headings to fill the table's width.
  40010. */
  40011. class StretchableObjectResizer
  40012. {
  40013. public:
  40014. /** Creates an empty object resizer. */
  40015. StretchableObjectResizer();
  40016. /** Destructor. */
  40017. ~StretchableObjectResizer();
  40018. /** Adds an item to the list.
  40019. The order parameter lets you specify groups of items that are resized first when some
  40020. space needs to be found. Those items with an order of 0 will be the first ones to be
  40021. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  40022. will then try resizing the items with an order of 1, then 2, and so on.
  40023. */
  40024. void addItem (double currentSize,
  40025. double minSize,
  40026. double maxSize,
  40027. int order = 0);
  40028. /** Resizes all the items to fit this amount of space.
  40029. This will attempt to fit them in without exceeding each item's miniumum and
  40030. maximum sizes. In cases where none of the items can be expanded or enlarged any
  40031. further, the final size may be greater or less than the size passed in.
  40032. After calling this method, you can retrieve the new sizes with the getItemSize()
  40033. method.
  40034. */
  40035. void resizeToFit (double targetSize);
  40036. /** Returns the number of items that have been added. */
  40037. int getNumItems() const throw() { return items.size(); }
  40038. /** Returns the size of one of the items. */
  40039. double getItemSize (int index) const throw();
  40040. juce_UseDebuggingNewOperator
  40041. private:
  40042. struct Item
  40043. {
  40044. double size;
  40045. double minSize;
  40046. double maxSize;
  40047. int order;
  40048. };
  40049. OwnedArray <Item> items;
  40050. StretchableObjectResizer (const StretchableObjectResizer&);
  40051. StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  40052. };
  40053. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  40054. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  40055. #endif
  40056. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  40057. #endif
  40058. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  40059. #endif
  40060. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  40061. #endif
  40062. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40063. /*** Start of inlined file: juce_LookAndFeel.h ***/
  40064. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40065. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  40066. /*** Start of inlined file: juce_AlertWindow.h ***/
  40067. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  40068. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  40069. /*** Start of inlined file: juce_TextLayout.h ***/
  40070. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  40071. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  40072. class Graphics;
  40073. /**
  40074. A laid-out arrangement of text.
  40075. You can add text in different fonts to a TextLayout object, then call its
  40076. layout() method to word-wrap it into lines. The layout can then be drawn
  40077. using a graphics context.
  40078. It's handy if you've got a message to display, because you can format it,
  40079. measure the extent of the layout, and then create a suitably-sized window
  40080. to show it in.
  40081. @see Font, Graphics::drawFittedText, GlyphArrangement
  40082. */
  40083. class JUCE_API TextLayout
  40084. {
  40085. public:
  40086. /** Creates an empty text layout.
  40087. Text can then be appended using the appendText() method.
  40088. */
  40089. TextLayout();
  40090. /** Creates a copy of another layout object. */
  40091. TextLayout (const TextLayout& other);
  40092. /** Creates a text layout from an initial string and font. */
  40093. TextLayout (const String& text, const Font& font);
  40094. /** Destructor. */
  40095. ~TextLayout();
  40096. /** Copies another layout onto this one. */
  40097. TextLayout& operator= (const TextLayout& layoutToCopy);
  40098. /** Clears the layout, removing all its text. */
  40099. void clear();
  40100. /** Adds a string to the end of the arrangement.
  40101. The string will be broken onto new lines wherever it contains
  40102. carriage-returns or linefeeds. After adding it, you can call layout()
  40103. to wrap long lines into a paragraph and justify it.
  40104. */
  40105. void appendText (const String& textToAppend,
  40106. const Font& fontToUse);
  40107. /** Replaces all the text with a new string.
  40108. This is equivalent to calling clear() followed by appendText().
  40109. */
  40110. void setText (const String& newText,
  40111. const Font& fontToUse);
  40112. /** Breaks the text up to form a paragraph with the given width.
  40113. @param maximumWidth any text wider than this will be split
  40114. across multiple lines
  40115. @param justification how the lines are to be laid-out horizontally
  40116. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  40117. width that keeps all the lines of text at a
  40118. similar length - this is good when you're displaying
  40119. a short message and don't want it to get split
  40120. onto two lines with only a couple of words on
  40121. the second line, which looks untidy.
  40122. */
  40123. void layout (int maximumWidth,
  40124. const Justification& justification,
  40125. bool attemptToBalanceLineLengths);
  40126. /** Returns the overall width of the entire text layout. */
  40127. int getWidth() const;
  40128. /** Returns the overall height of the entire text layout. */
  40129. int getHeight() const;
  40130. /** Returns the total number of lines of text. */
  40131. int getNumLines() const { return totalLines; }
  40132. /** Returns the width of a particular line of text.
  40133. @param lineNumber the line, from 0 to (getNumLines() - 1)
  40134. */
  40135. int getLineWidth (int lineNumber) const;
  40136. /** Renders the text at a specified position using a graphics context.
  40137. */
  40138. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  40139. /** Renders the text within a specified rectangle using a graphics context.
  40140. The justification flags dictate how the block of text should be positioned
  40141. within the rectangle.
  40142. */
  40143. void drawWithin (Graphics& g,
  40144. int x, int y, int w, int h,
  40145. const Justification& layoutFlags) const;
  40146. juce_UseDebuggingNewOperator
  40147. private:
  40148. class Token;
  40149. friend class OwnedArray <Token>;
  40150. OwnedArray <Token> tokens;
  40151. int totalLines;
  40152. };
  40153. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  40154. /*** End of inlined file: juce_TextLayout.h ***/
  40155. /** A window that displays a message and has buttons for the user to react to it.
  40156. For simple dialog boxes with just a couple of buttons on them, there are
  40157. some static methods for running these.
  40158. For more complex dialogs, an AlertWindow can be created, then it can have some
  40159. buttons and components added to it, and its runModalLoop() method is then used to
  40160. show it. The value returned by runModalLoop() shows which button the
  40161. user pressed to dismiss the box.
  40162. @see ThreadWithProgressWindow
  40163. */
  40164. class JUCE_API AlertWindow : public TopLevelWindow,
  40165. private Button::Listener
  40166. {
  40167. public:
  40168. /** The type of icon to show in the dialog box. */
  40169. enum AlertIconType
  40170. {
  40171. NoIcon, /**< No icon will be shown on the dialog box. */
  40172. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  40173. user to answer a question. */
  40174. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  40175. warning about something and shouldn't be ignored. */
  40176. InfoIcon /**< An icon that indicates that the dialog box is just
  40177. giving the user some information, which doesn't require
  40178. a response from them. */
  40179. };
  40180. /** Creates an AlertWindow.
  40181. @param title the headline to show at the top of the dialog box
  40182. @param message a longer, more descriptive message to show underneath the
  40183. headline
  40184. @param iconType the type of icon to display
  40185. @param associatedComponent if this is non-zero, it specifies the component that the
  40186. alert window should be associated with. Depending on the look
  40187. and feel, this might be used for positioning of the alert window.
  40188. */
  40189. AlertWindow (const String& title,
  40190. const String& message,
  40191. AlertIconType iconType,
  40192. Component* associatedComponent = 0);
  40193. /** Destroys the AlertWindow */
  40194. ~AlertWindow();
  40195. /** Returns the type of alert icon that was specified when the window
  40196. was created. */
  40197. AlertIconType getAlertType() const throw() { return alertIconType; }
  40198. /** Changes the dialog box's message.
  40199. This will also resize the window to fit the new message if required.
  40200. */
  40201. void setMessage (const String& message);
  40202. /** Adds a button to the window.
  40203. @param name the text to show on the button
  40204. @param returnValue the value that should be returned from runModalLoop()
  40205. if this is the button that the user presses.
  40206. @param shortcutKey1 an optional key that can be pressed to trigger this button
  40207. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  40208. */
  40209. void addButton (const String& name,
  40210. int returnValue,
  40211. const KeyPress& shortcutKey1 = KeyPress(),
  40212. const KeyPress& shortcutKey2 = KeyPress());
  40213. /** Returns the number of buttons that the window currently has. */
  40214. int getNumButtons() const;
  40215. /** Invokes a click of one of the buttons. */
  40216. void triggerButtonClick (const String& buttonName);
  40217. /** Adds a textbox to the window for entering strings.
  40218. @param name an internal name for the text-box. This is the name to pass to
  40219. the getTextEditorContents() method to find out what the
  40220. user typed-in.
  40221. @param initialContents a string to show in the text box when it's first shown
  40222. @param onScreenLabel if this is non-empty, it will be displayed next to the
  40223. text-box to label it.
  40224. @param isPasswordBox if true, the text editor will display asterisks instead of
  40225. the actual text
  40226. @see getTextEditorContents
  40227. */
  40228. void addTextEditor (const String& name,
  40229. const String& initialContents,
  40230. const String& onScreenLabel = String::empty,
  40231. bool isPasswordBox = false);
  40232. /** Returns the contents of a named textbox.
  40233. After showing an AlertWindow that contains a text editor, this can be
  40234. used to find out what the user has typed into it.
  40235. @param nameOfTextEditor the name of the text box that you're interested in
  40236. @see addTextEditor
  40237. */
  40238. const String getTextEditorContents (const String& nameOfTextEditor) const;
  40239. /** Adds a drop-down list of choices to the box.
  40240. After the box has been shown, the getComboBoxComponent() method can
  40241. be used to find out which item the user picked.
  40242. @param name the label to use for the drop-down list
  40243. @param items the list of items to show in it
  40244. @param onScreenLabel if this is non-empty, it will be displayed next to the
  40245. combo-box to label it.
  40246. @see getComboBoxComponent
  40247. */
  40248. void addComboBox (const String& name,
  40249. const StringArray& items,
  40250. const String& onScreenLabel = String::empty);
  40251. /** Returns a drop-down list that was added to the AlertWindow.
  40252. @param nameOfList the name that was passed into the addComboBox() method
  40253. when creating the drop-down
  40254. @returns the ComboBox component, or 0 if none was found for the given name.
  40255. */
  40256. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  40257. /** Adds a block of text.
  40258. This is handy for adding a multi-line note next to a textbox or combo-box,
  40259. to provide more details about what's going on.
  40260. */
  40261. void addTextBlock (const String& text);
  40262. /** Adds a progress-bar to the window.
  40263. @param progressValue a variable that will be repeatedly checked while the
  40264. dialog box is visible, to see how far the process has
  40265. got. The value should be in the range 0 to 1.0
  40266. */
  40267. void addProgressBarComponent (double& progressValue);
  40268. /** Adds a user-defined component to the dialog box.
  40269. @param component the component to add - its size should be set up correctly
  40270. before it is passed in. The caller is responsible for deleting
  40271. the component later on - the AlertWindow won't delete it.
  40272. */
  40273. void addCustomComponent (Component* component);
  40274. /** Returns the number of custom components in the dialog box.
  40275. @see getCustomComponent, addCustomComponent
  40276. */
  40277. int getNumCustomComponents() const;
  40278. /** Returns one of the custom components in the dialog box.
  40279. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  40280. will return 0
  40281. @see getNumCustomComponents, addCustomComponent
  40282. */
  40283. Component* getCustomComponent (int index) const;
  40284. /** Removes one of the custom components in the dialog box.
  40285. Note that this won't delete it, it just removes the component from the window
  40286. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  40287. will return 0
  40288. @returns the component that was removed (or zero)
  40289. @see getNumCustomComponents, addCustomComponent
  40290. */
  40291. Component* removeCustomComponent (int index);
  40292. /** Returns true if the window contains any components other than just buttons.*/
  40293. bool containsAnyExtraComponents() const;
  40294. // easy-to-use message box functions:
  40295. /** Shows a dialog box that just has a message and a single button to get rid of it.
  40296. The box is shown modally, and the method returns after the user
  40297. has clicked the button (or pressed the escape or return keys).
  40298. @param iconType the type of icon to show
  40299. @param title the headline to show at the top of the box
  40300. @param message a longer, more descriptive message to show underneath the
  40301. headline
  40302. @param buttonText the text to show in the button - if this string is empty, the
  40303. default string "ok" (or a localised version) will be used.
  40304. @param associatedComponent if this is non-zero, it specifies the component that the
  40305. alert window should be associated with. Depending on the look
  40306. and feel, this might be used for positioning of the alert window.
  40307. */
  40308. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  40309. const String& title,
  40310. const String& message,
  40311. const String& buttonText = String::empty,
  40312. Component* associatedComponent = 0);
  40313. /** Shows a dialog box with two buttons.
  40314. Ideal for ok/cancel or yes/no choices. The return key can also be used
  40315. to trigger the first button, and the escape key for the second button.
  40316. @param iconType the type of icon to show
  40317. @param title the headline to show at the top of the box
  40318. @param message a longer, more descriptive message to show underneath the
  40319. headline
  40320. @param button1Text the text to show in the first button - if this string is
  40321. empty, the default string "ok" (or a localised version of it)
  40322. will be used.
  40323. @param button2Text the text to show in the second button - if this string is
  40324. empty, the default string "cancel" (or a localised version of it)
  40325. will be used.
  40326. @param associatedComponent if this is non-zero, it specifies the component that the
  40327. alert window should be associated with. Depending on the look
  40328. and feel, this might be used for positioning of the alert window.
  40329. @returns true if button 1 was clicked, false if it was button 2
  40330. */
  40331. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  40332. const String& title,
  40333. const String& message,
  40334. const String& button1Text = String::empty,
  40335. const String& button2Text = String::empty,
  40336. Component* associatedComponent = 0);
  40337. /** Shows a dialog box with three buttons.
  40338. Ideal for yes/no/cancel boxes.
  40339. The escape key can be used to trigger the third button.
  40340. @param iconType the type of icon to show
  40341. @param title the headline to show at the top of the box
  40342. @param message a longer, more descriptive message to show underneath the
  40343. headline
  40344. @param button1Text the text to show in the first button - if an empty string, then
  40345. "yes" will be used (or a localised version of it)
  40346. @param button2Text the text to show in the first button - if an empty string, then
  40347. "no" will be used (or a localised version of it)
  40348. @param button3Text the text to show in the first button - if an empty string, then
  40349. "cancel" will be used (or a localised version of it)
  40350. @param associatedComponent if this is non-zero, it specifies the component that the
  40351. alert window should be associated with. Depending on the look
  40352. and feel, this might be used for positioning of the alert window.
  40353. @returns one of the following values:
  40354. - 0 if the third button was pressed (normally used for 'cancel')
  40355. - 1 if the first button was pressed (normally used for 'yes')
  40356. - 2 if the middle button was pressed (normally used for 'no')
  40357. */
  40358. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  40359. const String& title,
  40360. const String& message,
  40361. const String& button1Text = String::empty,
  40362. const String& button2Text = String::empty,
  40363. const String& button3Text = String::empty,
  40364. Component* associatedComponent = 0);
  40365. /** Shows an operating-system native dialog box.
  40366. @param title the title to use at the top
  40367. @param bodyText the longer message to show
  40368. @param isOkCancel if true, this will show an ok/cancel box, if false,
  40369. it'll show a box with just an ok button
  40370. @returns true if the ok button was pressed, false if they pressed cancel.
  40371. */
  40372. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  40373. const String& bodyText,
  40374. bool isOkCancel);
  40375. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  40376. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40377. methods.
  40378. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40379. */
  40380. enum ColourIds
  40381. {
  40382. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  40383. textColourId = 0x1001810, /**< The colour for the text. */
  40384. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  40385. };
  40386. juce_UseDebuggingNewOperator
  40387. protected:
  40388. /** @internal */
  40389. void paint (Graphics& g);
  40390. /** @internal */
  40391. void mouseDown (const MouseEvent& e);
  40392. /** @internal */
  40393. void mouseDrag (const MouseEvent& e);
  40394. /** @internal */
  40395. bool keyPressed (const KeyPress& key);
  40396. /** @internal */
  40397. void buttonClicked (Button* button);
  40398. /** @internal */
  40399. void lookAndFeelChanged();
  40400. /** @internal */
  40401. void userTriedToCloseWindow();
  40402. /** @internal */
  40403. int getDesktopWindowStyleFlags() const;
  40404. private:
  40405. String text;
  40406. TextLayout textLayout;
  40407. AlertIconType alertIconType;
  40408. ComponentBoundsConstrainer constrainer;
  40409. ComponentDragger dragger;
  40410. Rectangle<int> textArea;
  40411. Array<void*> buttons, textBoxes, comboBoxes;
  40412. Array<void*> progressBars, customComps, textBlocks, allComps;
  40413. StringArray textboxNames, comboBoxNames;
  40414. Font font;
  40415. Component* associatedComponent;
  40416. void updateLayout (bool onlyIncreaseSize);
  40417. // disable copy constructor
  40418. AlertWindow (const AlertWindow&);
  40419. AlertWindow& operator= (const AlertWindow&);
  40420. };
  40421. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  40422. /*** End of inlined file: juce_AlertWindow.h ***/
  40423. class ToggleButton;
  40424. class TextButton;
  40425. class AlertWindow;
  40426. class TextLayout;
  40427. class ScrollBar;
  40428. class BubbleComponent;
  40429. class ComboBox;
  40430. class Button;
  40431. class FilenameComponent;
  40432. class DocumentWindow;
  40433. class ResizableWindow;
  40434. class GroupComponent;
  40435. class MenuBarComponent;
  40436. class DropShadower;
  40437. class GlyphArrangement;
  40438. class PropertyComponent;
  40439. class TableHeaderComponent;
  40440. class Toolbar;
  40441. class ToolbarItemComponent;
  40442. class PopupMenu;
  40443. class ProgressBar;
  40444. class FileBrowserComponent;
  40445. class DirectoryContentsDisplayComponent;
  40446. class FilePreviewComponent;
  40447. class ImageButton;
  40448. class CallOutBox;
  40449. /**
  40450. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40451. can be used to apply different 'skins' to the application.
  40452. */
  40453. class JUCE_API LookAndFeel
  40454. {
  40455. public:
  40456. /** Creates the default JUCE look and feel. */
  40457. LookAndFeel();
  40458. /** Destructor. */
  40459. virtual ~LookAndFeel();
  40460. /** Returns the current default look-and-feel for a component to use when it
  40461. hasn't got one explicitly set.
  40462. @see setDefaultLookAndFeel
  40463. */
  40464. static LookAndFeel& getDefaultLookAndFeel() throw();
  40465. /** Changes the default look-and-feel.
  40466. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40467. set to 0, it will revert to using the default one. The
  40468. object passed-in must be deleted by the caller when
  40469. it's no longer needed.
  40470. @see getDefaultLookAndFeel
  40471. */
  40472. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40473. /** Looks for a colour that has been registered with the given colour ID number.
  40474. If a colour has been set for this ID number using setColour(), then it is
  40475. returned. If none has been set, it will just return Colours::black.
  40476. The colour IDs for various purposes are stored as enums in the components that
  40477. they are relevent to - for an example, see Slider::ColourIds,
  40478. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40479. If you're looking up a colour for use in drawing a component, it's usually
  40480. best not to call this directly, but to use the Component::findColour() method
  40481. instead. That will first check whether a suitable colour has been registered
  40482. directly with the component, and will fall-back on calling the component's
  40483. LookAndFeel's findColour() method if none is found.
  40484. @see setColour, Component::findColour, Component::setColour
  40485. */
  40486. const Colour findColour (int colourId) const throw();
  40487. /** Registers a colour to be used for a particular purpose.
  40488. For more details, see the comments for findColour().
  40489. @see findColour, Component::findColour, Component::setColour
  40490. */
  40491. void setColour (int colourId, const Colour& colour) throw();
  40492. /** Returns true if the specified colour ID has been explicitly set using the
  40493. setColour() method.
  40494. */
  40495. bool isColourSpecified (int colourId) const throw();
  40496. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40497. /** Allows you to change the default sans-serif font.
  40498. If you need to supply your own Typeface object for any of the default fonts, rather
  40499. than just supplying the name (e.g. if you want to use an embedded font), then
  40500. you should instead override getTypefaceForFont() to create and return the typeface.
  40501. */
  40502. void setDefaultSansSerifTypefaceName (const String& newName);
  40503. /** Override this to get the chance to swap a component's mouse cursor for a
  40504. customised one.
  40505. */
  40506. virtual const MouseCursor getMouseCursorFor (Component& component);
  40507. /** Draws the lozenge-shaped background for a standard button. */
  40508. virtual void drawButtonBackground (Graphics& g,
  40509. Button& button,
  40510. const Colour& backgroundColour,
  40511. bool isMouseOverButton,
  40512. bool isButtonDown);
  40513. virtual const Font getFontForTextButton (TextButton& button);
  40514. /** Draws the text for a TextButton. */
  40515. virtual void drawButtonText (Graphics& g,
  40516. TextButton& button,
  40517. bool isMouseOverButton,
  40518. bool isButtonDown);
  40519. /** Draws the contents of a standard ToggleButton. */
  40520. virtual void drawToggleButton (Graphics& g,
  40521. ToggleButton& button,
  40522. bool isMouseOverButton,
  40523. bool isButtonDown);
  40524. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40525. virtual void drawTickBox (Graphics& g,
  40526. Component& component,
  40527. float x, float y, float w, float h,
  40528. bool ticked,
  40529. bool isEnabled,
  40530. bool isMouseOverButton,
  40531. bool isButtonDown);
  40532. /* AlertWindow handling..
  40533. */
  40534. virtual AlertWindow* createAlertWindow (const String& title,
  40535. const String& message,
  40536. const String& button1,
  40537. const String& button2,
  40538. const String& button3,
  40539. AlertWindow::AlertIconType iconType,
  40540. int numButtons,
  40541. Component* associatedComponent);
  40542. virtual void drawAlertBox (Graphics& g,
  40543. AlertWindow& alert,
  40544. const Rectangle<int>& textArea,
  40545. TextLayout& textLayout);
  40546. virtual int getAlertBoxWindowFlags();
  40547. virtual int getAlertWindowButtonHeight();
  40548. virtual const Font getAlertWindowFont();
  40549. /** Draws a progress bar.
  40550. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40551. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40552. isn't known). It can use the current time as a basis for playing an animation.
  40553. (Used by progress bars in AlertWindow).
  40554. */
  40555. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40556. int width, int height,
  40557. double progress, const String& textToShow);
  40558. // Draws a small image that spins to indicate that something's happening..
  40559. // This method should use the current time to animate itself, so just keep
  40560. // repainting it every so often.
  40561. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  40562. int x, int y, int w, int h);
  40563. /** Draws one of the buttons on a scrollbar.
  40564. @param g the context to draw into
  40565. @param scrollbar the bar itself
  40566. @param width the width of the button
  40567. @param height the height of the button
  40568. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40569. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40570. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40571. @param isButtonDown whether the mouse button's held down
  40572. */
  40573. virtual void drawScrollbarButton (Graphics& g,
  40574. ScrollBar& scrollbar,
  40575. int width, int height,
  40576. int buttonDirection,
  40577. bool isScrollbarVertical,
  40578. bool isMouseOverButton,
  40579. bool isButtonDown);
  40580. /** Draws the thumb area of a scrollbar.
  40581. @param g the context to draw into
  40582. @param scrollbar the bar itself
  40583. @param x the x position of the left edge of the thumb area to draw in
  40584. @param y the y position of the top edge of the thumb area to draw in
  40585. @param width the width of the thumb area to draw in
  40586. @param height the height of the thumb area to draw in
  40587. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40588. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40589. thumb, or its x position for horizontal bars
  40590. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40591. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40592. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40593. currently dragging the thumb
  40594. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40595. */
  40596. virtual void drawScrollbar (Graphics& g,
  40597. ScrollBar& scrollbar,
  40598. int x, int y,
  40599. int width, int height,
  40600. bool isScrollbarVertical,
  40601. int thumbStartPosition,
  40602. int thumbSize,
  40603. bool isMouseOver,
  40604. bool isMouseDown);
  40605. /** Returns the component effect to use for a scrollbar */
  40606. virtual ImageEffectFilter* getScrollbarEffect();
  40607. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40608. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40609. /** Returns the default thickness to use for a scrollbar. */
  40610. virtual int getDefaultScrollbarWidth();
  40611. /** Returns the length in pixels to use for a scrollbar button. */
  40612. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40613. /** Returns a tick shape for use in yes/no boxes, etc. */
  40614. virtual const Path getTickShape (float height);
  40615. /** Returns a cross shape for use in yes/no boxes, etc. */
  40616. virtual const Path getCrossShape (float height);
  40617. /** Draws the + or - box in a treeview. */
  40618. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40619. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40620. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40621. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40622. virtual const Image getDefaultFolderImage();
  40623. virtual const Image getDefaultDocumentFileImage();
  40624. virtual void createFileChooserHeaderText (const String& title,
  40625. const String& instructions,
  40626. GlyphArrangement& destArrangement,
  40627. int width);
  40628. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40629. const String& filename, Image* icon,
  40630. const String& fileSizeDescription,
  40631. const String& fileTimeDescription,
  40632. bool isDirectory,
  40633. bool isItemSelected,
  40634. int itemIndex);
  40635. virtual Button* createFileBrowserGoUpButton();
  40636. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40637. DirectoryContentsDisplayComponent* fileListComponent,
  40638. FilePreviewComponent* previewComp,
  40639. ComboBox* currentPathBox,
  40640. TextEditor* filenameBox,
  40641. Button* goUpButton);
  40642. virtual void drawBubble (Graphics& g,
  40643. float tipX, float tipY,
  40644. float boxX, float boxY, float boxW, float boxH);
  40645. /** Fills the background of a popup menu component. */
  40646. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40647. /** Draws one of the items in a popup menu. */
  40648. virtual void drawPopupMenuItem (Graphics& g,
  40649. int width, int height,
  40650. bool isSeparator,
  40651. bool isActive,
  40652. bool isHighlighted,
  40653. bool isTicked,
  40654. bool hasSubMenu,
  40655. const String& text,
  40656. const String& shortcutKeyText,
  40657. Image* image,
  40658. const Colour* const textColour);
  40659. /** Returns the size and style of font to use in popup menus. */
  40660. virtual const Font getPopupMenuFont();
  40661. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40662. int width, int height,
  40663. bool isScrollUpArrow);
  40664. /** Finds the best size for an item in a popup menu. */
  40665. virtual void getIdealPopupMenuItemSize (const String& text,
  40666. bool isSeparator,
  40667. int standardMenuItemHeight,
  40668. int& idealWidth,
  40669. int& idealHeight);
  40670. virtual int getMenuWindowFlags();
  40671. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40672. bool isMouseOverBar,
  40673. MenuBarComponent& menuBar);
  40674. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40675. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40676. virtual void drawMenuBarItem (Graphics& g,
  40677. int width, int height,
  40678. int itemIndex,
  40679. const String& itemText,
  40680. bool isMouseOverItem,
  40681. bool isMenuOpen,
  40682. bool isMouseOverBar,
  40683. MenuBarComponent& menuBar);
  40684. virtual void drawComboBox (Graphics& g, int width, int height,
  40685. bool isButtonDown,
  40686. int buttonX, int buttonY,
  40687. int buttonW, int buttonH,
  40688. ComboBox& box);
  40689. virtual const Font getComboBoxFont (ComboBox& box);
  40690. virtual Label* createComboBoxTextBox (ComboBox& box);
  40691. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40692. virtual void drawLabel (Graphics& g, Label& label);
  40693. virtual void drawLinearSlider (Graphics& g,
  40694. int x, int y,
  40695. int width, int height,
  40696. float sliderPos,
  40697. float minSliderPos,
  40698. float maxSliderPos,
  40699. const Slider::SliderStyle style,
  40700. Slider& slider);
  40701. virtual void drawLinearSliderBackground (Graphics& g,
  40702. int x, int y,
  40703. int width, int height,
  40704. float sliderPos,
  40705. float minSliderPos,
  40706. float maxSliderPos,
  40707. const Slider::SliderStyle style,
  40708. Slider& slider);
  40709. virtual void drawLinearSliderThumb (Graphics& g,
  40710. int x, int y,
  40711. int width, int height,
  40712. float sliderPos,
  40713. float minSliderPos,
  40714. float maxSliderPos,
  40715. const Slider::SliderStyle style,
  40716. Slider& slider);
  40717. virtual int getSliderThumbRadius (Slider& slider);
  40718. virtual void drawRotarySlider (Graphics& g,
  40719. int x, int y,
  40720. int width, int height,
  40721. float sliderPosProportional,
  40722. float rotaryStartAngle,
  40723. float rotaryEndAngle,
  40724. Slider& slider);
  40725. virtual Button* createSliderButton (bool isIncrement);
  40726. virtual Label* createSliderTextBox (Slider& slider);
  40727. virtual ImageEffectFilter* getSliderEffect();
  40728. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40729. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40730. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40731. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40732. ComboBox* filenameBox, Button* browseButton);
  40733. virtual void drawCornerResizer (Graphics& g,
  40734. int w, int h,
  40735. bool isMouseOver,
  40736. bool isMouseDragging);
  40737. virtual void drawResizableFrame (Graphics& g,
  40738. int w, int h,
  40739. const BorderSize& borders);
  40740. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40741. const BorderSize& border,
  40742. ResizableWindow& window);
  40743. virtual void drawResizableWindowBorder (Graphics& g,
  40744. int w, int h,
  40745. const BorderSize& border,
  40746. ResizableWindow& window);
  40747. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40748. Graphics& g, int w, int h,
  40749. int titleSpaceX, int titleSpaceW,
  40750. const Image* icon,
  40751. bool drawTitleTextOnLeft);
  40752. virtual Button* createDocumentWindowButton (int buttonType);
  40753. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40754. int titleBarX, int titleBarY,
  40755. int titleBarW, int titleBarH,
  40756. Button* minimiseButton,
  40757. Button* maximiseButton,
  40758. Button* closeButton,
  40759. bool positionTitleBarButtonsOnLeft);
  40760. virtual int getDefaultMenuBarHeight();
  40761. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40762. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40763. int w, int h,
  40764. bool isVerticalBar,
  40765. bool isMouseOver,
  40766. bool isMouseDragging);
  40767. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40768. const String& text,
  40769. const Justification& position,
  40770. GroupComponent& group);
  40771. virtual void createTabButtonShape (Path& p,
  40772. int width, int height,
  40773. int tabIndex,
  40774. const String& text,
  40775. Button& button,
  40776. TabbedButtonBar::Orientation orientation,
  40777. bool isMouseOver,
  40778. bool isMouseDown,
  40779. bool isFrontTab);
  40780. virtual void fillTabButtonShape (Graphics& g,
  40781. const Path& path,
  40782. const Colour& preferredBackgroundColour,
  40783. int tabIndex,
  40784. const String& text,
  40785. Button& button,
  40786. TabbedButtonBar::Orientation orientation,
  40787. bool isMouseOver,
  40788. bool isMouseDown,
  40789. bool isFrontTab);
  40790. virtual void drawTabButtonText (Graphics& g,
  40791. int x, int y, int w, int h,
  40792. const Colour& preferredBackgroundColour,
  40793. int tabIndex,
  40794. const String& text,
  40795. Button& button,
  40796. TabbedButtonBar::Orientation orientation,
  40797. bool isMouseOver,
  40798. bool isMouseDown,
  40799. bool isFrontTab);
  40800. virtual int getTabButtonOverlap (int tabDepth);
  40801. virtual int getTabButtonSpaceAroundImage();
  40802. virtual int getTabButtonBestWidth (int tabIndex,
  40803. const String& text,
  40804. int tabDepth,
  40805. Button& button);
  40806. virtual void drawTabButton (Graphics& g,
  40807. int w, int h,
  40808. const Colour& preferredColour,
  40809. int tabIndex,
  40810. const String& text,
  40811. Button& button,
  40812. TabbedButtonBar::Orientation orientation,
  40813. bool isMouseOver,
  40814. bool isMouseDown,
  40815. bool isFrontTab);
  40816. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40817. int w, int h,
  40818. TabbedButtonBar& tabBar,
  40819. TabbedButtonBar::Orientation orientation);
  40820. virtual Button* createTabBarExtrasButton();
  40821. virtual void drawImageButton (Graphics& g, Image* image,
  40822. int imageX, int imageY, int imageW, int imageH,
  40823. const Colour& overlayColour,
  40824. float imageOpacity,
  40825. ImageButton& button);
  40826. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40827. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40828. int width, int height,
  40829. bool isMouseOver, bool isMouseDown,
  40830. int columnFlags);
  40831. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40832. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40833. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40834. bool isMouseOver, bool isMouseDown,
  40835. ToolbarItemComponent& component);
  40836. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40837. const String& text, ToolbarItemComponent& component);
  40838. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40839. bool isOpen, int width, int height);
  40840. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40841. PropertyComponent& component);
  40842. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40843. PropertyComponent& component);
  40844. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  40845. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  40846. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40847. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  40848. /**
  40849. */
  40850. virtual void playAlertSound();
  40851. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40852. static void drawGlassSphere (Graphics& g,
  40853. float x, float y,
  40854. float diameter,
  40855. const Colour& colour,
  40856. float outlineThickness) throw();
  40857. static void drawGlassPointer (Graphics& g,
  40858. float x, float y,
  40859. float diameter,
  40860. const Colour& colour, float outlineThickness,
  40861. int direction) throw();
  40862. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40863. static void drawGlassLozenge (Graphics& g,
  40864. float x, float y,
  40865. float width, float height,
  40866. const Colour& colour,
  40867. float outlineThickness,
  40868. float cornerSize,
  40869. bool flatOnLeft, bool flatOnRight,
  40870. bool flatOnTop, bool flatOnBottom) throw();
  40871. juce_UseDebuggingNewOperator
  40872. private:
  40873. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40874. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40875. Array <int> colourIds;
  40876. Array <Colour> colours;
  40877. // default typeface names
  40878. String defaultSans, defaultSerif, defaultFixed;
  40879. void drawShinyButtonShape (Graphics& g,
  40880. float x, float y, float w, float h, float maxCornerSize,
  40881. const Colour& baseColour,
  40882. float strokeWidth,
  40883. bool flatOnLeft,
  40884. bool flatOnRight,
  40885. bool flatOnTop,
  40886. bool flatOnBottom) throw();
  40887. LookAndFeel (const LookAndFeel&);
  40888. LookAndFeel& operator= (const LookAndFeel&);
  40889. };
  40890. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40891. /*** End of inlined file: juce_LookAndFeel.h ***/
  40892. #endif
  40893. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40894. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40895. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40896. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40897. /**
  40898. The original Juce look-and-feel.
  40899. */
  40900. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40901. {
  40902. public:
  40903. /** Creates the default JUCE look and feel. */
  40904. OldSchoolLookAndFeel();
  40905. /** Destructor. */
  40906. virtual ~OldSchoolLookAndFeel();
  40907. /** Draws the lozenge-shaped background for a standard button. */
  40908. virtual void drawButtonBackground (Graphics& g,
  40909. Button& button,
  40910. const Colour& backgroundColour,
  40911. bool isMouseOverButton,
  40912. bool isButtonDown);
  40913. /** Draws the contents of a standard ToggleButton. */
  40914. virtual void drawToggleButton (Graphics& g,
  40915. ToggleButton& button,
  40916. bool isMouseOverButton,
  40917. bool isButtonDown);
  40918. virtual void drawTickBox (Graphics& g,
  40919. Component& component,
  40920. float x, float y, float w, float h,
  40921. bool ticked,
  40922. bool isEnabled,
  40923. bool isMouseOverButton,
  40924. bool isButtonDown);
  40925. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40926. int width, int height,
  40927. double progress, const String& textToShow);
  40928. virtual void drawScrollbarButton (Graphics& g,
  40929. ScrollBar& scrollbar,
  40930. int width, int height,
  40931. int buttonDirection,
  40932. bool isScrollbarVertical,
  40933. bool isMouseOverButton,
  40934. bool isButtonDown);
  40935. virtual void drawScrollbar (Graphics& g,
  40936. ScrollBar& scrollbar,
  40937. int x, int y,
  40938. int width, int height,
  40939. bool isScrollbarVertical,
  40940. int thumbStartPosition,
  40941. int thumbSize,
  40942. bool isMouseOver,
  40943. bool isMouseDown);
  40944. virtual ImageEffectFilter* getScrollbarEffect();
  40945. virtual void drawTextEditorOutline (Graphics& g,
  40946. int width, int height,
  40947. TextEditor& textEditor);
  40948. /** Fills the background of a popup menu component. */
  40949. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40950. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40951. bool isMouseOverBar,
  40952. MenuBarComponent& menuBar);
  40953. virtual void drawComboBox (Graphics& g, int width, int height,
  40954. bool isButtonDown,
  40955. int buttonX, int buttonY,
  40956. int buttonW, int buttonH,
  40957. ComboBox& box);
  40958. virtual const Font getComboBoxFont (ComboBox& box);
  40959. virtual void drawLinearSlider (Graphics& g,
  40960. int x, int y,
  40961. int width, int height,
  40962. float sliderPos,
  40963. float minSliderPos,
  40964. float maxSliderPos,
  40965. const Slider::SliderStyle style,
  40966. Slider& slider);
  40967. virtual int getSliderThumbRadius (Slider& slider);
  40968. virtual Button* createSliderButton (bool isIncrement);
  40969. virtual ImageEffectFilter* getSliderEffect();
  40970. virtual void drawCornerResizer (Graphics& g,
  40971. int w, int h,
  40972. bool isMouseOver,
  40973. bool isMouseDragging);
  40974. virtual Button* createDocumentWindowButton (int buttonType);
  40975. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40976. int titleBarX, int titleBarY,
  40977. int titleBarW, int titleBarH,
  40978. Button* minimiseButton,
  40979. Button* maximiseButton,
  40980. Button* closeButton,
  40981. bool positionTitleBarButtonsOnLeft);
  40982. juce_UseDebuggingNewOperator
  40983. private:
  40984. DropShadowEffect scrollbarShadow;
  40985. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40986. OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40987. };
  40988. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40989. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40990. #endif
  40991. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  40992. #endif
  40993. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  40994. #endif
  40995. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  40996. #endif
  40997. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40998. /*** Start of inlined file: juce_PopupMenuCustomComponent.h ***/
  40999. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  41000. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  41001. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  41002. @see PopupMenu::addCustomItem
  41003. */
  41004. class JUCE_API PopupMenuCustomComponent : public Component,
  41005. public ReferenceCountedObject
  41006. {
  41007. public:
  41008. /** Destructor. */
  41009. ~PopupMenuCustomComponent();
  41010. /** Chooses the size that this component would like to have.
  41011. Note that the size which this method returns isn't necessarily the one that
  41012. the menu will give it, as it will be stretched to fit the other items in
  41013. the menu.
  41014. */
  41015. virtual void getIdealSize (int& idealWidth,
  41016. int& idealHeight) = 0;
  41017. /** Dismisses the menu indicating that this item has been chosen.
  41018. This will cause the menu to exit from its modal state, returning
  41019. this item's id as the result.
  41020. */
  41021. void triggerMenuItem();
  41022. /** Returns true if this item should be highlighted because the mouse is
  41023. over it.
  41024. You can call this method in your paint() method to find out whether
  41025. to draw a highlight.
  41026. */
  41027. bool isItemHighlighted() const throw() { return isHighlighted; }
  41028. protected:
  41029. /** Constructor.
  41030. If isTriggeredAutomatically is true, then the menu will automatically detect
  41031. a click on this component and use that to trigger it. If it's false, then it's
  41032. up to your class to manually trigger the item if it wants to.
  41033. */
  41034. PopupMenuCustomComponent (bool isTriggeredAutomatically = true);
  41035. private:
  41036. friend class PopupMenu;
  41037. friend class PopupMenu::ItemComponent;
  41038. friend class PopupMenu::Window;
  41039. bool isHighlighted, isTriggeredAutomatically;
  41040. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  41041. PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  41042. };
  41043. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  41044. /*** End of inlined file: juce_PopupMenuCustomComponent.h ***/
  41045. #endif
  41046. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41047. #endif
  41048. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  41049. #endif
  41050. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  41051. #endif
  41052. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41053. #endif
  41054. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41055. /*** Start of inlined file: juce_LassoComponent.h ***/
  41056. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41057. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41058. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  41059. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41060. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41061. /** Manages a list of selectable items.
  41062. Use one of these to keep a track of things that the user has highlighted, like
  41063. icons or things in a list.
  41064. The class is templated so that you can use it to hold either a set of pointers
  41065. to objects, or a set of ID numbers or handles, for cases where each item may
  41066. not always have a corresponding object.
  41067. To be informed when items are selected/deselected, register a ChangeListener with
  41068. this object.
  41069. @see SelectableObject
  41070. */
  41071. template <class SelectableItemType>
  41072. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  41073. {
  41074. public:
  41075. typedef SelectableItemType ItemType;
  41076. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  41077. /** Creates an empty set. */
  41078. SelectedItemSet()
  41079. {
  41080. }
  41081. /** Creates a set based on an array of items. */
  41082. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  41083. : selectedItems (items)
  41084. {
  41085. }
  41086. /** Creates a copy of another set. */
  41087. SelectedItemSet (const SelectedItemSet& other)
  41088. : selectedItems (other.selectedItems)
  41089. {
  41090. }
  41091. /** Creates a copy of another set. */
  41092. SelectedItemSet& operator= (const SelectedItemSet& other)
  41093. {
  41094. if (selectedItems != other.selectedItems)
  41095. {
  41096. selectedItems = other.selectedItems;
  41097. changed();
  41098. }
  41099. return *this;
  41100. }
  41101. /** Destructor. */
  41102. ~SelectedItemSet()
  41103. {
  41104. }
  41105. /** Clears any other currently selected items, and selects this item.
  41106. If this item is already the only thing selected, no change notification
  41107. will be sent out.
  41108. @see addToSelection, addToSelectionBasedOnModifiers
  41109. */
  41110. void selectOnly (ParameterType item)
  41111. {
  41112. if (isSelected (item))
  41113. {
  41114. for (int i = selectedItems.size(); --i >= 0;)
  41115. {
  41116. if (selectedItems.getUnchecked(i) != item)
  41117. {
  41118. deselect (selectedItems.getUnchecked(i));
  41119. i = jmin (i, selectedItems.size());
  41120. }
  41121. }
  41122. }
  41123. else
  41124. {
  41125. deselectAll();
  41126. changed();
  41127. selectedItems.add (item);
  41128. itemSelected (item);
  41129. }
  41130. }
  41131. /** Selects an item.
  41132. If the item is already selected, no change notification will be sent out.
  41133. @see selectOnly, addToSelectionBasedOnModifiers
  41134. */
  41135. void addToSelection (ParameterType item)
  41136. {
  41137. if (! isSelected (item))
  41138. {
  41139. changed();
  41140. selectedItems.add (item);
  41141. itemSelected (item);
  41142. }
  41143. }
  41144. /** Selects or deselects an item.
  41145. This will use the modifier keys to decide whether to deselect other items
  41146. first.
  41147. So if the shift key is held down, the item will be added without deselecting
  41148. anything (same as calling addToSelection() )
  41149. If no modifiers are down, the current selection will be cleared first (same
  41150. as calling selectOnly() )
  41151. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  41152. so it'll be added to the set unless it's already there, in which case it'll be
  41153. deselected.
  41154. If the items that you're selecting can also be dragged, you may need to use the
  41155. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  41156. subtleties of this kind of usage.
  41157. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  41158. */
  41159. void addToSelectionBasedOnModifiers (ParameterType item,
  41160. const ModifierKeys& modifiers)
  41161. {
  41162. if (modifiers.isShiftDown())
  41163. {
  41164. addToSelection (item);
  41165. }
  41166. else if (modifiers.isCommandDown())
  41167. {
  41168. if (isSelected (item))
  41169. deselect (item);
  41170. else
  41171. addToSelection (item);
  41172. }
  41173. else
  41174. {
  41175. selectOnly (item);
  41176. }
  41177. }
  41178. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  41179. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  41180. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  41181. makes it easy to handle multiple-selection of sets of objects that can also
  41182. be dragged.
  41183. For example, if you have several items already selected, and you click on
  41184. one of them (without dragging), then you'd expect this to deselect the other, and
  41185. just select the item you clicked on. But if you had clicked on this item and
  41186. dragged it, you'd have expected them all to stay selected.
  41187. When you call this method, you'll need to store the boolean result, because the
  41188. addToSelectionOnMouseUp() method will need to be know this value.
  41189. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  41190. */
  41191. bool addToSelectionOnMouseDown (ParameterType item,
  41192. const ModifierKeys& modifiers)
  41193. {
  41194. if (isSelected (item))
  41195. {
  41196. return ! modifiers.isPopupMenu();
  41197. }
  41198. else
  41199. {
  41200. addToSelectionBasedOnModifiers (item, modifiers);
  41201. return false;
  41202. }
  41203. }
  41204. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  41205. Call this during a mouseUp callback, when you have previously called the
  41206. addToSelectionOnMouseDown() method during your mouseDown event.
  41207. See addToSelectionOnMouseDown() for more info
  41208. @param item the item to select (or deselect)
  41209. @param modifiers the modifiers from the mouse-up event
  41210. @param wasItemDragged true if your item was dragged during the mouse click
  41211. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  41212. back from the addToSelectionOnMouseDown() call that you
  41213. should have made during the matching mouseDown event
  41214. */
  41215. void addToSelectionOnMouseUp (ParameterType item,
  41216. const ModifierKeys& modifiers,
  41217. const bool wasItemDragged,
  41218. const bool resultOfMouseDownSelectMethod)
  41219. {
  41220. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  41221. addToSelectionBasedOnModifiers (item, modifiers);
  41222. }
  41223. /** Deselects an item. */
  41224. void deselect (ParameterType item)
  41225. {
  41226. const int i = selectedItems.indexOf (item);
  41227. if (i >= 0)
  41228. {
  41229. changed();
  41230. itemDeselected (selectedItems.remove (i));
  41231. }
  41232. }
  41233. /** Deselects all items. */
  41234. void deselectAll()
  41235. {
  41236. if (selectedItems.size() > 0)
  41237. {
  41238. changed();
  41239. for (int i = selectedItems.size(); --i >= 0;)
  41240. {
  41241. itemDeselected (selectedItems.remove (i));
  41242. i = jmin (i, selectedItems.size());
  41243. }
  41244. }
  41245. }
  41246. /** Returns the number of currently selected items.
  41247. @see getSelectedItem
  41248. */
  41249. int getNumSelected() const throw()
  41250. {
  41251. return selectedItems.size();
  41252. }
  41253. /** Returns one of the currently selected items.
  41254. Returns 0 if the index is out-of-range.
  41255. @see getNumSelected
  41256. */
  41257. SelectableItemType getSelectedItem (const int index) const throw()
  41258. {
  41259. return selectedItems [index];
  41260. }
  41261. /** True if this item is currently selected. */
  41262. bool isSelected (ParameterType item) const throw()
  41263. {
  41264. return selectedItems.contains (item);
  41265. }
  41266. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  41267. /** Can be overridden to do special handling when an item is selected.
  41268. For example, if the item is an object, you might want to call it and tell
  41269. it that it's being selected.
  41270. */
  41271. virtual void itemSelected (SelectableItemType item) { (void) item; }
  41272. /** Can be overridden to do special handling when an item is deselected.
  41273. For example, if the item is an object, you might want to call it and tell
  41274. it that it's being deselected.
  41275. */
  41276. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  41277. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  41278. */
  41279. void changed (const bool synchronous = false)
  41280. {
  41281. if (synchronous)
  41282. sendSynchronousChangeMessage (this);
  41283. else
  41284. sendChangeMessage (this);
  41285. }
  41286. juce_UseDebuggingNewOperator
  41287. private:
  41288. Array <SelectableItemType> selectedItems;
  41289. };
  41290. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41291. /*** End of inlined file: juce_SelectedItemSet.h ***/
  41292. /**
  41293. A class used by the LassoComponent to manage the things that it selects.
  41294. This allows the LassoComponent to find out which items are within the lasso,
  41295. and to change the list of selected items.
  41296. @see LassoComponent, SelectedItemSet
  41297. */
  41298. template <class SelectableItemType>
  41299. class LassoSource
  41300. {
  41301. public:
  41302. /** Destructor. */
  41303. virtual ~LassoSource() {}
  41304. /** Returns the set of items that lie within a given lassoable region.
  41305. Your implementation of this method must find all the relevent items that lie
  41306. within the given rectangle. and add them to the itemsFound array.
  41307. The co-ordinates are relative to the top-left of the lasso component's parent
  41308. component. (i.e. they are the same as the size and position of the lasso
  41309. component itself).
  41310. */
  41311. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  41312. const Rectangle<int>& area) = 0;
  41313. /** Returns the SelectedItemSet that the lasso should update.
  41314. This set will be continuously updated by the LassoComponent as it gets
  41315. dragged around, so make sure that you've got a ChangeListener attached to
  41316. the set so that your UI objects will know when the selection changes and
  41317. be able to update themselves appropriately.
  41318. */
  41319. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  41320. };
  41321. /**
  41322. A component that acts as a rectangular selection region, which you drag with
  41323. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  41324. To use one of these:
  41325. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  41326. component, and call its beginLasso() method, giving it a
  41327. suitable LassoSource object that it can use to find out which items are in
  41328. the active area.
  41329. - Each time your parent component gets a mouseDrag event, call dragLasso()
  41330. to update the lasso's position - it will use its LassoSource to calculate and
  41331. update the current selection.
  41332. - After the drag has finished and you get a mouseUp callback, you should call
  41333. endLasso() to clean up. This will make the lasso component invisible, and you
  41334. can remove it from the parent component, or delete it.
  41335. The class takes into account the modifier keys that are being held down while
  41336. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  41337. be added to the original selection; if ctrl or command is pressed, they will be
  41338. xor'ed with any previously selected items.
  41339. @see LassoSource, SelectedItemSet
  41340. */
  41341. template <class SelectableItemType>
  41342. class LassoComponent : public Component
  41343. {
  41344. public:
  41345. /** Creates a Lasso component.
  41346. The fill colour is used to fill the lasso'ed rectangle, and the outline
  41347. colour is used to draw a line around its edge.
  41348. */
  41349. explicit LassoComponent (const int outlineThickness_ = 1)
  41350. : source (0),
  41351. outlineThickness (outlineThickness_)
  41352. {
  41353. }
  41354. /** Destructor. */
  41355. ~LassoComponent()
  41356. {
  41357. }
  41358. /** Call this in your mouseDown event, to initialise a drag.
  41359. Pass in a suitable LassoSource object which the lasso will use to find
  41360. the items and change the selection.
  41361. After using this method to initialise the lasso, repeatedly call dragLasso()
  41362. in your component's mouseDrag callback.
  41363. @see dragLasso, endLasso, LassoSource
  41364. */
  41365. void beginLasso (const MouseEvent& e,
  41366. LassoSource <SelectableItemType>* const lassoSource)
  41367. {
  41368. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  41369. jassert (lassoSource != 0); // the source can't be null!
  41370. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  41371. source = lassoSource;
  41372. if (lassoSource != 0)
  41373. originalSelection = lassoSource->getLassoSelection().getItemArray();
  41374. setSize (0, 0);
  41375. dragStartPos = e.getMouseDownPosition();
  41376. }
  41377. /** Call this in your mouseDrag event, to update the lasso's position.
  41378. This must be repeatedly calling when the mouse is dragged, after you've
  41379. first initialised the lasso with beginLasso().
  41380. This method takes into account the modifier keys that are being held down, so
  41381. if shift is pressed, then the lassoed items will be added to any that were
  41382. previously selected; if ctrl or command is pressed, then they will be xor'ed
  41383. with previously selected items.
  41384. @see beginLasso, endLasso
  41385. */
  41386. void dragLasso (const MouseEvent& e)
  41387. {
  41388. if (source != 0)
  41389. {
  41390. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  41391. setVisible (true);
  41392. Array <SelectableItemType> itemsInLasso;
  41393. source->findLassoItemsInArea (itemsInLasso, getBounds());
  41394. if (e.mods.isShiftDown())
  41395. {
  41396. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  41397. itemsInLasso.addArray (originalSelection);
  41398. }
  41399. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  41400. {
  41401. Array <SelectableItemType> originalMinusNew (originalSelection);
  41402. originalMinusNew.removeValuesIn (itemsInLasso);
  41403. itemsInLasso.removeValuesIn (originalSelection);
  41404. itemsInLasso.addArray (originalMinusNew);
  41405. }
  41406. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  41407. }
  41408. }
  41409. /** Call this in your mouseUp event, after the lasso has been dragged.
  41410. @see beginLasso, dragLasso
  41411. */
  41412. void endLasso()
  41413. {
  41414. source = 0;
  41415. originalSelection.clear();
  41416. setVisible (false);
  41417. }
  41418. /** A set of colour IDs to use to change the colour of various aspects of the label.
  41419. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41420. methods.
  41421. Note that you can also use the constants from TextEditor::ColourIds to change the
  41422. colour of the text editor that is opened when a label is editable.
  41423. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41424. */
  41425. enum ColourIds
  41426. {
  41427. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  41428. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  41429. };
  41430. /** @internal */
  41431. void paint (Graphics& g)
  41432. {
  41433. g.fillAll (findColour (lassoFillColourId));
  41434. g.setColour (findColour (lassoOutlineColourId));
  41435. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  41436. // this suggests that you've left a lasso comp lying around after the
  41437. // mouse drag has finished.. Be careful to call endLasso() when you get a
  41438. // mouse-up event.
  41439. jassert (isMouseButtonDownAnywhere());
  41440. }
  41441. /** @internal */
  41442. bool hitTest (int, int) { return false; }
  41443. juce_UseDebuggingNewOperator
  41444. private:
  41445. Array <SelectableItemType> originalSelection;
  41446. LassoSource <SelectableItemType>* source;
  41447. int outlineThickness;
  41448. Point<int> dragStartPos;
  41449. };
  41450. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41451. /*** End of inlined file: juce_LassoComponent.h ***/
  41452. #endif
  41453. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  41454. #endif
  41455. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  41456. #endif
  41457. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41458. /*** Start of inlined file: juce_MouseHoverDetector.h ***/
  41459. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41460. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41461. /**
  41462. Monitors a component for mouse activity, and triggers a callback
  41463. when the mouse hovers in one place for a specified length of time.
  41464. To use a hover-detector, just create one and call its setHoverComponent()
  41465. method to start it watching a component. You can call setHoverComponent (0)
  41466. to make it inactive.
  41467. (Be careful not to delete a component that's being monitored without first
  41468. stopping or deleting the hover detector).
  41469. */
  41470. class JUCE_API MouseHoverDetector
  41471. {
  41472. public:
  41473. /** Creates a hover detector.
  41474. Initially the object is inactive, and you need to tell it which component
  41475. to monitor, using the setHoverComponent() method.
  41476. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  41477. needs to stay still before the mouseHovered() method
  41478. is invoked. You can change this setting later with
  41479. the setHoverTimeMillisecs() method
  41480. */
  41481. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  41482. /** Destructor. */
  41483. virtual ~MouseHoverDetector();
  41484. /** Changes the time for which the mouse has to stay still before it's considered
  41485. to be hovering.
  41486. */
  41487. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  41488. /** Changes the component that's being monitored for hovering.
  41489. Be careful not to delete a component that's being monitored without first
  41490. stopping or deleting the hover detector.
  41491. */
  41492. void setHoverComponent (Component* const newSourceComponent);
  41493. protected:
  41494. /** Called back when the mouse hovers.
  41495. After the mouse has stayed still over the component for the length of time
  41496. specified by setHoverTimeMillisecs(), this method will be invoked.
  41497. When the mouse is first moved after this callback has occurred, the
  41498. mouseMovedAfterHover() method will be called.
  41499. @param mouseX the mouse's X position relative to the component being monitored
  41500. @param mouseY the mouse's Y position relative to the component being monitored
  41501. */
  41502. virtual void mouseHovered (int mouseX,
  41503. int mouseY) = 0;
  41504. /** Called when the mouse is moved away after just having hovered. */
  41505. virtual void mouseMovedAfterHover() = 0;
  41506. private:
  41507. class JUCE_API HoverDetectorInternal : public MouseListener,
  41508. public Timer
  41509. {
  41510. public:
  41511. MouseHoverDetector* owner;
  41512. int lastX, lastY;
  41513. void timerCallback();
  41514. void mouseEnter (const MouseEvent&);
  41515. void mouseExit (const MouseEvent&);
  41516. void mouseDown (const MouseEvent&);
  41517. void mouseUp (const MouseEvent&);
  41518. void mouseMove (const MouseEvent&);
  41519. void mouseWheelMove (const MouseEvent&, float, float);
  41520. } internalTimer;
  41521. friend class HoverDetectorInternal;
  41522. Component* source;
  41523. int hoverTimeMillisecs;
  41524. bool hasJustHovered;
  41525. void hoverTimerCallback();
  41526. void checkJustHoveredCallback();
  41527. MouseHoverDetector (const MouseHoverDetector&);
  41528. MouseHoverDetector& operator= (const MouseHoverDetector&);
  41529. };
  41530. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41531. /*** End of inlined file: juce_MouseHoverDetector.h ***/
  41532. #endif
  41533. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41534. /*** Start of inlined file: juce_MouseInputSource.h ***/
  41535. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41536. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41537. class Component;
  41538. class ComponentPeer;
  41539. class MouseInputSourceInternal;
  41540. /**
  41541. Represents a linear source of mouse events from a mouse device or individual finger
  41542. in a multi-touch environment.
  41543. Each MouseEvent object contains a reference to the MouseInputSource that generated
  41544. it. In an environment with a single mouse for input, all events will come from the
  41545. same source, but in a multi-touch system, there may be multiple MouseInputSource
  41546. obects active, each representing a stream of events coming from a particular finger.
  41547. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  41548. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  41549. the only events that can happen between a mouseDown and its corresponding mouseUp are
  41550. mouseDrags, etc.
  41551. When there are multiple touches arriving from multiple MouseInputSources, their
  41552. event streams may arrive in an interleaved order, so you should use the getIndex()
  41553. method to find out which finger each event came from.
  41554. @see MouseEvent
  41555. */
  41556. class JUCE_API MouseInputSource
  41557. {
  41558. public:
  41559. /** Creates a MouseInputSource.
  41560. You should never actually create a MouseInputSource in your own code - the
  41561. library takes care of managing these objects.
  41562. */
  41563. MouseInputSource (int index, bool isMouseDevice);
  41564. /** Destructor. */
  41565. ~MouseInputSource();
  41566. /** Returns true if this object represents a normal desk-based mouse device. */
  41567. bool isMouse() const;
  41568. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  41569. bool isTouch() const;
  41570. /** Returns true if this source has an on-screen pointer that can hover over
  41571. items without clicking them.
  41572. */
  41573. bool canHover() const;
  41574. /** Returns true if this source may have a scroll wheel. */
  41575. bool hasMouseWheel() const;
  41576. /** Returns this source's index in the global list of possible sources.
  41577. If the system only has a single mouse, there will only be a single MouseInputSource
  41578. with an index of 0.
  41579. If the system supports multi-touch input, then the index will represent a finger
  41580. number, starting from 0. When the first touch event begins, it will have finger
  41581. number 0, and then if a second touch happens while the first is still down, it
  41582. will have index 1, etc.
  41583. */
  41584. int getIndex() const;
  41585. /** Returns true if this device is currently being pressed. */
  41586. bool isDragging() const;
  41587. /** Returns the last-known screen position of this source. */
  41588. const Point<int> getScreenPosition() const;
  41589. /** Returns a set of modifiers that indicate which buttons are currently
  41590. held down on this device.
  41591. */
  41592. const ModifierKeys getCurrentModifiers() const;
  41593. /** Returns the component that was last known to be under this pointer. */
  41594. Component* getComponentUnderMouse() const;
  41595. /** Tells the device to dispatch a mouse-move event.
  41596. This is asynchronous - the event will occur on the message thread.
  41597. */
  41598. void triggerFakeMove() const;
  41599. /** Returns the number of clicks that should be counted as belonging to the
  41600. current mouse event.
  41601. So the mouse is currently down and it's the second click of a double-click, this
  41602. will return 2.
  41603. */
  41604. int getNumberOfMultipleClicks() const throw();
  41605. /** Returns the time at which the last mouse-down occurred. */
  41606. const Time getLastMouseDownTime() const throw();
  41607. /** Returns the screen position at which the last mouse-down occurred. */
  41608. const Point<int> getLastMouseDownPosition() const throw();
  41609. /** Returns true if this mouse is currently down, and if it has been dragged more
  41610. than a couple of pixels from the place it was pressed.
  41611. */
  41612. bool hasMouseMovedSignificantlySincePressed() const throw();
  41613. bool hasMouseCursor() const throw();
  41614. void showMouseCursor (const MouseCursor& cursor);
  41615. void hideCursor();
  41616. void revealCursor();
  41617. void forceMouseCursorUpdate();
  41618. bool canDoUnboundedMovement() const throw();
  41619. /** Allows the mouse to move beyond the edges of the screen.
  41620. Calling this method when the mouse button is currently pressed will remove the cursor
  41621. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  41622. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  41623. can be used for things like custom slider controls or dragging objects around, where
  41624. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  41625. The unbounded mode is automatically turned off when the mouse button is released, or
  41626. it can be turned off explicitly by calling this method again.
  41627. @param isEnabled whether to turn this mode on or off
  41628. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  41629. hidden; if true, it will only be hidden when it
  41630. is moved beyond the edge of the screen
  41631. */
  41632. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  41633. juce_UseDebuggingNewOperator
  41634. /** @internal */
  41635. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  41636. /** @internal */
  41637. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  41638. private:
  41639. friend class Desktop;
  41640. friend class ComponentPeer;
  41641. friend class MouseInputSourceInternal;
  41642. ScopedPointer<MouseInputSourceInternal> pimpl;
  41643. MouseInputSource (const MouseInputSource&);
  41644. MouseInputSource& operator= (const MouseInputSource&);
  41645. };
  41646. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41647. /*** End of inlined file: juce_MouseInputSource.h ***/
  41648. #endif
  41649. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  41650. #endif
  41651. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  41652. #endif
  41653. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41654. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  41655. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41656. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41657. /**
  41658. A PropertyComponent that contains an on/off toggle button.
  41659. This type of property component can be used if you have a boolean value to
  41660. toggle on/off.
  41661. @see PropertyComponent
  41662. */
  41663. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  41664. private Button::Listener
  41665. {
  41666. protected:
  41667. /** Creates a button component.
  41668. If you use this constructor, you must override the getState() and setState()
  41669. methods.
  41670. @param propertyName the property name to be passed to the PropertyComponent
  41671. @param buttonTextWhenTrue the text shown in the button when the value is true
  41672. @param buttonTextWhenFalse the text shown in the button when the value is false
  41673. */
  41674. BooleanPropertyComponent (const String& propertyName,
  41675. const String& buttonTextWhenTrue,
  41676. const String& buttonTextWhenFalse);
  41677. public:
  41678. /** Creates a button component.
  41679. @param valueToControl a Value object that this property should refer to.
  41680. @param propertyName the property name to be passed to the PropertyComponent
  41681. @param buttonText the text shown in the ToggleButton component
  41682. */
  41683. BooleanPropertyComponent (const Value& valueToControl,
  41684. const String& propertyName,
  41685. const String& buttonText);
  41686. /** Destructor. */
  41687. ~BooleanPropertyComponent();
  41688. /** Called to change the state of the boolean value. */
  41689. virtual void setState (bool newState);
  41690. /** Must return the current value of the property. */
  41691. virtual bool getState() const;
  41692. /** @internal */
  41693. void paint (Graphics& g);
  41694. /** @internal */
  41695. void refresh();
  41696. /** @internal */
  41697. void buttonClicked (Button*);
  41698. juce_UseDebuggingNewOperator
  41699. private:
  41700. ToggleButton button;
  41701. String onText, offText;
  41702. BooleanPropertyComponent (const BooleanPropertyComponent&);
  41703. BooleanPropertyComponent& operator= (const BooleanPropertyComponent&);
  41704. };
  41705. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41706. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  41707. #endif
  41708. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41709. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  41710. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41711. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41712. /**
  41713. A PropertyComponent that contains a button.
  41714. This type of property component can be used if you need a button to trigger some
  41715. kind of action.
  41716. @see PropertyComponent
  41717. */
  41718. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  41719. private Button::Listener
  41720. {
  41721. public:
  41722. /** Creates a button component.
  41723. @param propertyName the property name to be passed to the PropertyComponent
  41724. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  41725. */
  41726. ButtonPropertyComponent (const String& propertyName,
  41727. bool triggerOnMouseDown);
  41728. /** Destructor. */
  41729. ~ButtonPropertyComponent();
  41730. /** Called when the user clicks the button.
  41731. */
  41732. virtual void buttonClicked() = 0;
  41733. /** Returns the string that should be displayed in the button.
  41734. If you need to change this string, call refresh() to update the component.
  41735. */
  41736. virtual const String getButtonText() const = 0;
  41737. /** @internal */
  41738. void refresh();
  41739. /** @internal */
  41740. void buttonClicked (Button*);
  41741. juce_UseDebuggingNewOperator
  41742. private:
  41743. TextButton button;
  41744. ButtonPropertyComponent (const ButtonPropertyComponent&);
  41745. ButtonPropertyComponent& operator= (const ButtonPropertyComponent&);
  41746. };
  41747. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41748. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  41749. #endif
  41750. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41751. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  41752. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41753. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41754. /**
  41755. A PropertyComponent that shows its value as a combo box.
  41756. This type of property component contains a list of options and has a
  41757. combo box to choose one.
  41758. Your subclass's constructor must add some strings to the choices StringArray
  41759. and these are shown in the list.
  41760. The getIndex() method will be called to find out which option is the currently
  41761. selected one. If you call refresh() it will call getIndex() to check whether
  41762. the value has changed, and will update the combo box if needed.
  41763. If the user selects a different item from the list, setIndex() will be
  41764. called to let your class process this.
  41765. @see PropertyComponent, PropertyPanel
  41766. */
  41767. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  41768. private ComboBox::Listener
  41769. {
  41770. protected:
  41771. /** Creates the component.
  41772. Your subclass's constructor must add a list of options to the choices
  41773. member variable.
  41774. */
  41775. ChoicePropertyComponent (const String& propertyName);
  41776. public:
  41777. /** Creates the component.
  41778. @param valueToControl the value that the combo box will read and control
  41779. @param propertyName the name of the property
  41780. @param choices the list of possible values that the drop-down list will contain
  41781. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  41782. These are the values that will be read and written to the
  41783. valueToControl value. This array must contain the same number of items
  41784. as the choices array
  41785. */
  41786. ChoicePropertyComponent (const Value& valueToControl,
  41787. const String& propertyName,
  41788. const StringArray& choices,
  41789. const Array <var>& correspondingValues);
  41790. /** Destructor. */
  41791. ~ChoicePropertyComponent();
  41792. /** Called when the user selects an item from the combo box.
  41793. Your subclass must use this callback to update the value that this component
  41794. represents. The index is the index of the chosen item in the choices
  41795. StringArray.
  41796. */
  41797. virtual void setIndex (int newIndex);
  41798. /** Returns the index of the item that should currently be shown.
  41799. This is the index of the item in the choices StringArray that will be
  41800. shown.
  41801. */
  41802. virtual int getIndex() const;
  41803. /** Returns the list of options. */
  41804. const StringArray& getChoices() const;
  41805. /** @internal */
  41806. void refresh();
  41807. /** @internal */
  41808. void comboBoxChanged (ComboBox*);
  41809. juce_UseDebuggingNewOperator
  41810. protected:
  41811. /** The list of options that will be shown in the combo box.
  41812. Your subclass must populate this array in its constructor. If any empty
  41813. strings are added, these will be replaced with horizontal separators (see
  41814. ComboBox::addSeparator() for more info).
  41815. */
  41816. StringArray choices;
  41817. private:
  41818. ComboBox comboBox;
  41819. bool isCustomClass;
  41820. class RemapperValueSource;
  41821. void createComboBox();
  41822. ChoicePropertyComponent (const ChoicePropertyComponent&);
  41823. ChoicePropertyComponent& operator= (const ChoicePropertyComponent&);
  41824. };
  41825. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41826. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  41827. #endif
  41828. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  41829. #endif
  41830. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  41831. #endif
  41832. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41833. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  41834. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41835. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41836. /**
  41837. A PropertyComponent that shows its value as a slider.
  41838. @see PropertyComponent, Slider
  41839. */
  41840. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  41841. private Slider::Listener
  41842. {
  41843. protected:
  41844. /** Creates the property component.
  41845. The ranges, interval and skew factor are passed to the Slider component.
  41846. If you need to customise the slider in other ways, your constructor can
  41847. access the slider member variable and change it directly.
  41848. */
  41849. SliderPropertyComponent (const String& propertyName,
  41850. double rangeMin,
  41851. double rangeMax,
  41852. double interval,
  41853. double skewFactor = 1.0);
  41854. public:
  41855. /** Creates the property component.
  41856. The ranges, interval and skew factor are passed to the Slider component.
  41857. If you need to customise the slider in other ways, your constructor can
  41858. access the slider member variable and change it directly.
  41859. */
  41860. SliderPropertyComponent (const Value& valueToControl,
  41861. const String& propertyName,
  41862. double rangeMin,
  41863. double rangeMax,
  41864. double interval,
  41865. double skewFactor = 1.0);
  41866. /** Destructor. */
  41867. ~SliderPropertyComponent();
  41868. /** Called when the user moves the slider to change its value.
  41869. Your subclass must use this method to update whatever item this property
  41870. represents.
  41871. */
  41872. virtual void setValue (double newValue);
  41873. /** Returns the value that the slider should show. */
  41874. virtual double getValue() const;
  41875. /** @internal */
  41876. void refresh();
  41877. /** @internal */
  41878. void changeListenerCallback (void*);
  41879. /** @internal */
  41880. void sliderValueChanged (Slider*);
  41881. juce_UseDebuggingNewOperator
  41882. protected:
  41883. /** The slider component being used in this component.
  41884. Your subclass has access to this in case it needs to customise it in some way.
  41885. */
  41886. Slider slider;
  41887. SliderPropertyComponent (const SliderPropertyComponent&);
  41888. SliderPropertyComponent& operator= (const SliderPropertyComponent&);
  41889. };
  41890. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41891. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  41892. #endif
  41893. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41894. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  41895. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41896. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41897. /**
  41898. A PropertyComponent that shows its value as editable text.
  41899. @see PropertyComponent
  41900. */
  41901. class JUCE_API TextPropertyComponent : public PropertyComponent
  41902. {
  41903. protected:
  41904. /** Creates a text property component.
  41905. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41906. sets whether the text editor allows carriage returns.
  41907. @see TextEditor
  41908. */
  41909. TextPropertyComponent (const String& propertyName,
  41910. int maxNumChars,
  41911. bool isMultiLine);
  41912. public:
  41913. /** Creates a text property component.
  41914. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41915. sets whether the text editor allows carriage returns.
  41916. @see TextEditor
  41917. */
  41918. TextPropertyComponent (const Value& valueToControl,
  41919. const String& propertyName,
  41920. int maxNumChars,
  41921. bool isMultiLine);
  41922. /** Destructor. */
  41923. ~TextPropertyComponent();
  41924. /** Called when the user edits the text.
  41925. Your subclass must use this callback to change the value of whatever item
  41926. this property component represents.
  41927. */
  41928. virtual void setText (const String& newText);
  41929. /** Returns the text that should be shown in the text editor.
  41930. */
  41931. virtual const String getText() const;
  41932. /** @internal */
  41933. void refresh();
  41934. /** @internal */
  41935. void textWasEdited();
  41936. juce_UseDebuggingNewOperator
  41937. private:
  41938. Label* textEditor;
  41939. void createEditor (int maxNumChars, bool isMultiLine);
  41940. TextPropertyComponent (const TextPropertyComponent&);
  41941. TextPropertyComponent& operator= (const TextPropertyComponent&);
  41942. };
  41943. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41944. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  41945. #endif
  41946. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41947. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  41948. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41949. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41950. #if JUCE_WINDOWS || DOXYGEN
  41951. /**
  41952. A Windows-specific class that can create and embed an ActiveX control inside
  41953. itself.
  41954. To use it, create one of these, put it in place and make sure it's visible in a
  41955. window, then use createControl() to instantiate an ActiveX control. The control
  41956. will then be moved and resized to follow the movements of this component.
  41957. Of course, since the control is a heavyweight window, it'll obliterate any
  41958. juce components that may overlap this component, but that's life.
  41959. */
  41960. class JUCE_API ActiveXControlComponent : public Component
  41961. {
  41962. public:
  41963. /** Create an initially-empty container. */
  41964. ActiveXControlComponent();
  41965. /** Destructor. */
  41966. ~ActiveXControlComponent();
  41967. /** Tries to create an ActiveX control and embed it in this peer.
  41968. The peer controlIID is a pointer to an IID structure - it's treated
  41969. as a void* because when including the Juce headers, you might not always
  41970. have included windows.h first, in which case IID wouldn't be defined.
  41971. e.g. @code
  41972. const IID myIID = __uuidof (QTControl);
  41973. myControlComp->createControl (&myIID);
  41974. @endcode
  41975. */
  41976. bool createControl (const void* controlIID);
  41977. /** Deletes the ActiveX control, if one has been created.
  41978. */
  41979. void deleteControl();
  41980. /** Returns true if a control is currently in use. */
  41981. bool isControlOpen() const throw() { return control != 0; }
  41982. /** Does a QueryInterface call on the embedded control object.
  41983. This allows you to cast the control to whatever type of COM object you need.
  41984. The iid parameter is a pointer to an IID structure - it's treated
  41985. as a void* because when including the Juce headers, you might not always
  41986. have included windows.h first, in which case IID wouldn't be defined, but
  41987. you should just pass a pointer to an IID.
  41988. e.g. @code
  41989. const IID iid = __uuidof (IOleWindow);
  41990. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  41991. if (oleWindow != 0)
  41992. {
  41993. HWND hwnd;
  41994. oleWindow->GetWindow (&hwnd);
  41995. ...
  41996. oleWindow->Release();
  41997. }
  41998. @endcode
  41999. */
  42000. void* queryInterface (const void* iid) const;
  42001. /** Set this to false to stop mouse events being allowed through to the control.
  42002. */
  42003. void setMouseEventsAllowed (bool eventsCanReachControl);
  42004. /** Returns true if mouse events are allowed to get through to the control.
  42005. */
  42006. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  42007. /** @internal */
  42008. void paint (Graphics& g);
  42009. /** @internal */
  42010. void* originalWndProc;
  42011. juce_UseDebuggingNewOperator
  42012. private:
  42013. class Pimpl;
  42014. friend class Pimpl;
  42015. friend class ScopedPointer <Pimpl>;
  42016. ScopedPointer <Pimpl> control;
  42017. bool mouseEventsAllowed;
  42018. void setControlBounds (const Rectangle<int>& bounds) const;
  42019. void setControlVisible (bool b) const;
  42020. ActiveXControlComponent (const ActiveXControlComponent&);
  42021. ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  42022. };
  42023. #endif
  42024. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  42025. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  42026. #endif
  42027. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  42028. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  42029. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  42030. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  42031. /**
  42032. A component containing controls to let the user change the audio settings of
  42033. an AudioDeviceManager object.
  42034. Very easy to use - just create one of these and show it to the user.
  42035. @see AudioDeviceManager
  42036. */
  42037. class JUCE_API AudioDeviceSelectorComponent : public Component,
  42038. public ComboBox::Listener,
  42039. public Button::Listener,
  42040. public ChangeListener
  42041. {
  42042. public:
  42043. /** Creates the component.
  42044. If your app needs only output channels, you might ask for a maximum of 0 input
  42045. channels, and the component won't display any options for choosing the input
  42046. channels. And likewise if you're doing an input-only app.
  42047. @param deviceManager the device manager that this component should control
  42048. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  42049. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  42050. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  42051. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  42052. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  42053. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  42054. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  42055. treated as a set of separate mono channels.
  42056. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  42057. are shown, with an "advanced" button that shows the rest of them
  42058. */
  42059. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  42060. const int minAudioInputChannels,
  42061. const int maxAudioInputChannels,
  42062. const int minAudioOutputChannels,
  42063. const int maxAudioOutputChannels,
  42064. const bool showMidiInputOptions,
  42065. const bool showMidiOutputSelector,
  42066. const bool showChannelsAsStereoPairs,
  42067. const bool hideAdvancedOptionsWithButton);
  42068. /** Destructor */
  42069. ~AudioDeviceSelectorComponent();
  42070. /** @internal */
  42071. void resized();
  42072. /** @internal */
  42073. void comboBoxChanged (ComboBox*);
  42074. /** @internal */
  42075. void buttonClicked (Button*);
  42076. /** @internal */
  42077. void changeListenerCallback (void*);
  42078. /** @internal */
  42079. void childBoundsChanged (Component*);
  42080. juce_UseDebuggingNewOperator
  42081. private:
  42082. AudioDeviceManager& deviceManager;
  42083. ScopedPointer<ComboBox> deviceTypeDropDown;
  42084. ScopedPointer<Label> deviceTypeDropDownLabel;
  42085. ScopedPointer<Component> audioDeviceSettingsComp;
  42086. String audioDeviceSettingsCompType;
  42087. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  42088. const bool showChannelsAsStereoPairs;
  42089. const bool hideAdvancedOptionsWithButton;
  42090. class MidiInputSelectorComponentListBox;
  42091. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  42092. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  42093. ScopedPointer<ComboBox> midiOutputSelector;
  42094. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  42095. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  42096. AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  42097. };
  42098. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  42099. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  42100. #endif
  42101. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42102. /*** Start of inlined file: juce_BubbleComponent.h ***/
  42103. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42104. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42105. /**
  42106. A component for showing a message or other graphics inside a speech-bubble-shaped
  42107. outline, pointing at a location on the screen.
  42108. This is a base class that just draws and positions the bubble shape, but leaves
  42109. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  42110. that draws a text message.
  42111. To use it, create your subclass, then either add it to a parent component or
  42112. put it on the desktop with addToDesktop (0), use setPosition() to
  42113. resize and position it, then make it visible.
  42114. @see BubbleMessageComponent
  42115. */
  42116. class JUCE_API BubbleComponent : public Component
  42117. {
  42118. protected:
  42119. /** Creates a BubbleComponent.
  42120. Your subclass will need to implement the getContentSize() and paintContent()
  42121. methods to draw the bubble's contents.
  42122. */
  42123. BubbleComponent();
  42124. public:
  42125. /** Destructor. */
  42126. ~BubbleComponent();
  42127. /** A list of permitted placements for the bubble, relative to the co-ordinates
  42128. at which it should be pointing.
  42129. @see setAllowedPlacement
  42130. */
  42131. enum BubblePlacement
  42132. {
  42133. above = 1,
  42134. below = 2,
  42135. left = 4,
  42136. right = 8
  42137. };
  42138. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  42139. point at which it's pointing.
  42140. By default when setPosition() is called, the bubble will place itself either
  42141. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  42142. the values in BubblePlacement to restrict this choice.
  42143. E.g. if you only want your bubble to appear above or below the target area,
  42144. use setAllowedPlacement (above | below);
  42145. @see BubblePlacement
  42146. */
  42147. void setAllowedPlacement (int newPlacement);
  42148. /** Moves and resizes the bubble to point at a given component.
  42149. This will resize the bubble to fit its content, then find a position for it
  42150. so that it's next to, but doesn't overlap the given component.
  42151. It'll put itself either above, below, or to the side of the component depending
  42152. on where there's the most space, honouring any restrictions that were set
  42153. with setAllowedPlacement().
  42154. */
  42155. void setPosition (Component* componentToPointTo);
  42156. /** Moves and resizes the bubble to point at a given point.
  42157. This will resize the bubble to fit its content, then position it
  42158. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  42159. are relative to either the bubble component's parent component if it has one, or
  42160. they are screen co-ordinates if not.
  42161. It'll put itself either above, below, or to the side of this point, depending
  42162. on where there's the most space, honouring any restrictions that were set
  42163. with setAllowedPlacement().
  42164. */
  42165. void setPosition (int arrowTipX,
  42166. int arrowTipY);
  42167. /** Moves and resizes the bubble to point at a given rectangle.
  42168. This will resize the bubble to fit its content, then find a position for it
  42169. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  42170. co-ordinates are relative to either the bubble component's parent component
  42171. if it has one, or they are screen co-ordinates if not.
  42172. It'll put itself either above, below, or to the side of the component depending
  42173. on where there's the most space, honouring any restrictions that were set
  42174. with setAllowedPlacement().
  42175. */
  42176. void setPosition (const Rectangle<int>& rectangleToPointTo);
  42177. protected:
  42178. /** Subclasses should override this to return the size of the content they
  42179. want to draw inside the bubble.
  42180. */
  42181. virtual void getContentSize (int& width, int& height) = 0;
  42182. /** Subclasses should override this to draw their bubble's contents.
  42183. The graphics object's clip region and the dimensions passed in here are
  42184. set up to paint just the rectangle inside the bubble.
  42185. */
  42186. virtual void paintContent (Graphics& g, int width, int height) = 0;
  42187. public:
  42188. /** @internal */
  42189. void paint (Graphics& g);
  42190. juce_UseDebuggingNewOperator
  42191. private:
  42192. Rectangle<int> content;
  42193. int side, allowablePlacements;
  42194. float arrowTipX, arrowTipY;
  42195. DropShadowEffect shadow;
  42196. BubbleComponent (const BubbleComponent&);
  42197. BubbleComponent& operator= (const BubbleComponent&);
  42198. };
  42199. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42200. /*** End of inlined file: juce_BubbleComponent.h ***/
  42201. #endif
  42202. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42203. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  42204. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42205. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42206. /**
  42207. A speech-bubble component that displays a short message.
  42208. This can be used to show a message with the tail of the speech bubble
  42209. pointing to a particular component or location on the screen.
  42210. @see BubbleComponent
  42211. */
  42212. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  42213. private Timer
  42214. {
  42215. public:
  42216. /** Creates a bubble component.
  42217. After creating one a BubbleComponent, do the following:
  42218. - add it to an appropriate parent component, or put it on the
  42219. desktop with Component::addToDesktop (0).
  42220. - use the showAt() method to show a message.
  42221. - it will make itself invisible after it times-out (and can optionally
  42222. also delete itself), or you can reuse it somewhere else by calling
  42223. showAt() again.
  42224. */
  42225. BubbleMessageComponent (int fadeOutLengthMs = 150);
  42226. /** Destructor. */
  42227. ~BubbleMessageComponent();
  42228. /** Shows a message bubble at a particular position.
  42229. This shows the bubble with its stem pointing to the given location
  42230. (co-ordinates being relative to its parent component).
  42231. For details about exactly how it decides where to position itself, see
  42232. BubbleComponent::updatePosition().
  42233. @param x the x co-ordinate of end of the bubble's tail
  42234. @param y the y co-ordinate of end of the bubble's tail
  42235. @param message the text to display
  42236. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  42237. from its parent compnent. If this is 0 or less, it
  42238. will stay there until manually removed.
  42239. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  42240. mouse button is pressed (anywhere on the screen)
  42241. @param deleteSelfAfterUse if true, then the component will delete itself after
  42242. it becomes invisible
  42243. */
  42244. void showAt (int x, int y,
  42245. const String& message,
  42246. int numMillisecondsBeforeRemoving,
  42247. bool removeWhenMouseClicked = true,
  42248. bool deleteSelfAfterUse = false);
  42249. /** Shows a message bubble next to a particular component.
  42250. This shows the bubble with its stem pointing at the given component.
  42251. For details about exactly how it decides where to position itself, see
  42252. BubbleComponent::updatePosition().
  42253. @param component the component that you want to point at
  42254. @param message the text to display
  42255. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  42256. from its parent compnent. If this is 0 or less, it
  42257. will stay there until manually removed.
  42258. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  42259. mouse button is pressed (anywhere on the screen)
  42260. @param deleteSelfAfterUse if true, then the component will delete itself after
  42261. it becomes invisible
  42262. */
  42263. void showAt (Component* component,
  42264. const String& message,
  42265. int numMillisecondsBeforeRemoving,
  42266. bool removeWhenMouseClicked = true,
  42267. bool deleteSelfAfterUse = false);
  42268. /** @internal */
  42269. void getContentSize (int& w, int& h);
  42270. /** @internal */
  42271. void paintContent (Graphics& g, int w, int h);
  42272. /** @internal */
  42273. void timerCallback();
  42274. juce_UseDebuggingNewOperator
  42275. private:
  42276. int fadeOutLength, mouseClickCounter;
  42277. TextLayout textLayout;
  42278. int64 expiryTime;
  42279. bool deleteAfterUse;
  42280. void init (int numMillisecondsBeforeRemoving,
  42281. bool removeWhenMouseClicked,
  42282. bool deleteSelfAfterUse);
  42283. BubbleMessageComponent (const BubbleMessageComponent&);
  42284. BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  42285. };
  42286. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42287. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  42288. #endif
  42289. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  42290. /*** Start of inlined file: juce_ColourSelector.h ***/
  42291. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  42292. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  42293. /**
  42294. A component that lets the user choose a colour.
  42295. This shows RGB sliders and a colourspace that the user can pick colours from.
  42296. This class is also a ChangeBroadcaster, so listeners can register to be told
  42297. when the colour changes.
  42298. */
  42299. class JUCE_API ColourSelector : public Component,
  42300. public ChangeBroadcaster,
  42301. protected Slider::Listener
  42302. {
  42303. public:
  42304. /** Options for the type of selector to show. These are passed into the constructor. */
  42305. enum ColourSelectorOptions
  42306. {
  42307. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  42308. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  42309. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  42310. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  42311. };
  42312. /** Creates a ColourSelector object.
  42313. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  42314. which of the selector's features should be visible.
  42315. The edgeGap value specifies the amount of space to leave around the edge.
  42316. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  42317. colourspace and hue selector components.
  42318. */
  42319. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  42320. int edgeGap = 4,
  42321. int gapAroundColourSpaceComponent = 7);
  42322. /** Destructor. */
  42323. ~ColourSelector();
  42324. /** Returns the colour that the user has currently selected.
  42325. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  42326. register to be told when the colour changes.
  42327. @see setCurrentColour
  42328. */
  42329. const Colour getCurrentColour() const;
  42330. /** Changes the colour that is currently being shown.
  42331. */
  42332. void setCurrentColour (const Colour& newColour);
  42333. /** Tells the selector how many preset colour swatches you want to have on the component.
  42334. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42335. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42336. their values.
  42337. */
  42338. virtual int getNumSwatches() const;
  42339. /** Called by the selector to find out the colour of one of the swatches.
  42340. Your subclass should return the colour of the swatch with the given index.
  42341. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42342. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42343. their values.
  42344. */
  42345. virtual const Colour getSwatchColour (int index) const;
  42346. /** Called by the selector when the user puts a new colour into one of the swatches.
  42347. Your subclass should change the colour of the swatch with the given index.
  42348. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42349. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42350. their values.
  42351. */
  42352. virtual void setSwatchColour (int index, const Colour& newColour) const;
  42353. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42354. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42355. methods.
  42356. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42357. */
  42358. enum ColourIds
  42359. {
  42360. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  42361. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  42362. };
  42363. juce_UseDebuggingNewOperator
  42364. private:
  42365. class ColourSpaceView;
  42366. class HueSelectorComp;
  42367. class SwatchComponent;
  42368. friend class ColourSpaceView;
  42369. friend class HueSelectorComp;
  42370. Colour colour;
  42371. float h, s, v;
  42372. Slider* sliders[4];
  42373. ColourSpaceView* colourSpace;
  42374. HueSelectorComp* hueSelector;
  42375. OwnedArray <SwatchComponent> swatchComponents;
  42376. const int flags;
  42377. int edgeGap;
  42378. Rectangle<int> previewArea;
  42379. void setHue (float newH);
  42380. void setSV (float newS, float newV);
  42381. void updateHSV();
  42382. void update();
  42383. void sliderValueChanged (Slider*);
  42384. void paint (Graphics& g);
  42385. void resized();
  42386. ColourSelector (const ColourSelector&);
  42387. ColourSelector& operator= (const ColourSelector&);
  42388. // this constructor is here temporarily to prevent old code compiling, because the parameters
  42389. // have changed - if you get an error here, update your code to use the new constructor instead..
  42390. // (xxx - note to self: remember to remove this at some point in the future)
  42391. ColourSelector (bool);
  42392. };
  42393. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  42394. /*** End of inlined file: juce_ColourSelector.h ***/
  42395. #endif
  42396. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42397. #endif
  42398. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42399. /*** Start of inlined file: juce_MagnifierComponent.h ***/
  42400. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42401. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42402. /**
  42403. A component that contains another component, and can magnify or shrink it.
  42404. This component will continually update its size so that it fits the zoomed
  42405. version of the content component that you put inside it, so don't try to
  42406. change the size of this component directly - instead change that of the
  42407. content component.
  42408. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  42409. to remap mouse events correctly. This means that the content component won't
  42410. appear to be a direct child of this component, and instead will think its
  42411. on the desktop.
  42412. */
  42413. class JUCE_API MagnifierComponent : public Component
  42414. {
  42415. public:
  42416. /** Creates a MagnifierComponent.
  42417. This component will continually update its size so that it fits the zoomed
  42418. version of the content component that you put inside it, so don't try to
  42419. change the size of this component directly - instead change that of the
  42420. content component.
  42421. @param contentComponent the component to add as the magnified one
  42422. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  42423. be deleted when this component is deleted. If false,
  42424. it's the caller's responsibility to delete it later.
  42425. */
  42426. MagnifierComponent (Component* contentComponent,
  42427. bool deleteContentCompWhenNoLongerNeeded);
  42428. /** Destructor. */
  42429. ~MagnifierComponent();
  42430. /** Returns the current content component. */
  42431. Component* getContentComponent() const { return content; }
  42432. /** Changes the zoom level.
  42433. The scale factor must be greater than zero. Values less than 1 will shrink the
  42434. image; values greater than 1 will multiply its size by this amount.
  42435. When this is called, this component will change its size to fit the full extent
  42436. of the newly zoomed content.
  42437. */
  42438. void setScaleFactor (double newScaleFactor);
  42439. /** Returns the current zoom factor. */
  42440. double getScaleFactor() const { return scaleFactor; }
  42441. /** Changes the quality setting used to rescale the graphics.
  42442. */
  42443. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  42444. juce_UseDebuggingNewOperator
  42445. /** @internal */
  42446. void childBoundsChanged (Component*);
  42447. private:
  42448. Component* content;
  42449. Component* holderComp;
  42450. double scaleFactor;
  42451. ComponentPeer* peer;
  42452. bool deleteContent;
  42453. Graphics::ResamplingQuality quality;
  42454. MouseInputSource mouseSource;
  42455. void paint (Graphics& g);
  42456. void mouseDown (const MouseEvent& e);
  42457. void mouseUp (const MouseEvent& e);
  42458. void mouseDrag (const MouseEvent& e);
  42459. void mouseMove (const MouseEvent& e);
  42460. void mouseEnter (const MouseEvent& e);
  42461. void mouseExit (const MouseEvent& e);
  42462. void mouseWheelMove (const MouseEvent& e, float, float);
  42463. void passOnMouseEventToPeer (const MouseEvent& e);
  42464. int scaleInt (int n) const;
  42465. MagnifierComponent (const MagnifierComponent&);
  42466. MagnifierComponent& operator= (const MagnifierComponent&);
  42467. };
  42468. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42469. /*** End of inlined file: juce_MagnifierComponent.h ***/
  42470. #endif
  42471. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42472. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  42473. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42474. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42475. /**
  42476. A component that displays a piano keyboard, whose notes can be clicked on.
  42477. This component will mimic a physical midi keyboard, showing the current state of
  42478. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  42479. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  42480. Another feature is that the computer keyboard can also be used to play notes. By
  42481. default it maps the top two rows of a standard querty keyboard to the notes, but
  42482. these can be remapped if needed. It will only respond to keypresses when it has
  42483. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  42484. The component is also a ChangeBroadcaster, so if you want to be informed when the
  42485. keyboard is scrolled, you can register a ChangeListener for callbacks.
  42486. @see MidiKeyboardState
  42487. */
  42488. class JUCE_API MidiKeyboardComponent : public Component,
  42489. public MidiKeyboardStateListener,
  42490. public ChangeBroadcaster,
  42491. private Timer,
  42492. private AsyncUpdater
  42493. {
  42494. public:
  42495. /** The direction of the keyboard.
  42496. @see setOrientation
  42497. */
  42498. enum Orientation
  42499. {
  42500. horizontalKeyboard,
  42501. verticalKeyboardFacingLeft,
  42502. verticalKeyboardFacingRight,
  42503. };
  42504. /** Creates a MidiKeyboardComponent.
  42505. @param state the midi keyboard model that this component will represent
  42506. @param orientation whether the keyboard is horizonal or vertical
  42507. */
  42508. MidiKeyboardComponent (MidiKeyboardState& state,
  42509. Orientation orientation);
  42510. /** Destructor. */
  42511. ~MidiKeyboardComponent();
  42512. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  42513. on the component.
  42514. Values are 0 to 1.0, where 1.0 is the heaviest.
  42515. @see setMidiChannel
  42516. */
  42517. void setVelocity (float velocity, bool useMousePositionForVelocity);
  42518. /** Changes the midi channel number that will be used for events triggered by clicking
  42519. on the component.
  42520. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  42521. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  42522. Although this is the channel used for outgoing events, the component can display
  42523. incoming events from more than one channel - see setMidiChannelsToDisplay()
  42524. @see setVelocity
  42525. */
  42526. void setMidiChannel (int midiChannelNumber);
  42527. /** Returns the midi channel that the keyboard is using for midi messages.
  42528. @see setMidiChannel
  42529. */
  42530. int getMidiChannel() const throw() { return midiChannel; }
  42531. /** Sets a mask to indicate which incoming midi channels should be represented by
  42532. key movements.
  42533. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  42534. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  42535. in this mask, the on-screen keys will also go down.
  42536. By default, this mask is set to 0xffff (all channels displayed).
  42537. @see setMidiChannel
  42538. */
  42539. void setMidiChannelsToDisplay (int midiChannelMask);
  42540. /** Returns the current set of midi channels represented by the component.
  42541. This is the value that was set with setMidiChannelsToDisplay().
  42542. */
  42543. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  42544. /** Changes the width used to draw the white keys. */
  42545. void setKeyWidth (float widthInPixels);
  42546. /** Returns the width that was set by setKeyWidth(). */
  42547. float getKeyWidth() const throw() { return keyWidth; }
  42548. /** Changes the keyboard's current direction. */
  42549. void setOrientation (Orientation newOrientation);
  42550. /** Returns the keyboard's current direction. */
  42551. const Orientation getOrientation() const throw() { return orientation; }
  42552. /** Sets the range of midi notes that the keyboard will be limited to.
  42553. By default the range is 0 to 127 (inclusive), but you can limit this if you
  42554. only want a restricted set of the keys to be shown.
  42555. Note that the values here are inclusive and must be between 0 and 127.
  42556. */
  42557. void setAvailableRange (int lowestNote,
  42558. int highestNote);
  42559. /** Returns the first note in the available range.
  42560. @see setAvailableRange
  42561. */
  42562. int getRangeStart() const throw() { return rangeStart; }
  42563. /** Returns the last note in the available range.
  42564. @see setAvailableRange
  42565. */
  42566. int getRangeEnd() const throw() { return rangeEnd; }
  42567. /** If the keyboard extends beyond the size of the component, this will scroll
  42568. it to show the given key at the start.
  42569. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  42570. base class to send a callback to any ChangeListeners that have been registered.
  42571. */
  42572. void setLowestVisibleKey (int noteNumber);
  42573. /** Returns the number of the first key shown in the component.
  42574. @see setLowestVisibleKey
  42575. */
  42576. int getLowestVisibleKey() const throw() { return firstKey; }
  42577. /** Returns the length of the black notes.
  42578. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  42579. */
  42580. int getBlackNoteLength() const throw() { return blackNoteLength; }
  42581. /** If set to true, then scroll buttons will appear at either end of the keyboard
  42582. if there are too many notes to fit them all in the component at once.
  42583. */
  42584. void setScrollButtonsVisible (bool canScroll);
  42585. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42586. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42587. methods.
  42588. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42589. */
  42590. enum ColourIds
  42591. {
  42592. whiteNoteColourId = 0x1005000,
  42593. blackNoteColourId = 0x1005001,
  42594. keySeparatorLineColourId = 0x1005002,
  42595. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  42596. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  42597. textLabelColourId = 0x1005005,
  42598. upDownButtonBackgroundColourId = 0x1005006,
  42599. upDownButtonArrowColourId = 0x1005007
  42600. };
  42601. /** Returns the position within the component of the left-hand edge of a key.
  42602. Depending on the keyboard's orientation, this may be a horizontal or vertical
  42603. distance, in either direction.
  42604. */
  42605. int getKeyStartPosition (const int midiNoteNumber) const;
  42606. /** Deletes all key-mappings.
  42607. @see setKeyPressForNote
  42608. */
  42609. void clearKeyMappings();
  42610. /** Maps a key-press to a given note.
  42611. @param key the key that should trigger the note
  42612. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  42613. be. The actual midi note that gets played will be
  42614. this value + (12 * the current base octave). To change
  42615. the base octave, see setKeyPressBaseOctave()
  42616. */
  42617. void setKeyPressForNote (const KeyPress& key,
  42618. int midiNoteOffsetFromC);
  42619. /** Removes any key-mappings for a given note.
  42620. For a description of what the note number means, see setKeyPressForNote().
  42621. */
  42622. void removeKeyPressForNote (int midiNoteOffsetFromC);
  42623. /** Changes the base note above which key-press-triggered notes are played.
  42624. The set of key-mappings that trigger notes can be moved up and down to cover
  42625. the entire scale using this method.
  42626. The value passed in is an octave number between 0 and 10 (inclusive), and
  42627. indicates which C is the base note to which the key-mapped notes are
  42628. relative.
  42629. */
  42630. void setKeyPressBaseOctave (int newOctaveNumber);
  42631. /** This sets the octave number which is shown as the octave number for middle C.
  42632. This affects only the default implementation of getWhiteNoteText(), which
  42633. passes this octave number to MidiMessage::getMidiNoteName() in order to
  42634. get the note text. See MidiMessage::getMidiNoteName() for more info about
  42635. the parameter.
  42636. By default this value is set to 3.
  42637. @see getOctaveForMiddleC
  42638. */
  42639. void setOctaveForMiddleC (int octaveNumForMiddleC);
  42640. /** This returns the value set by setOctaveForMiddleC().
  42641. @see setOctaveForMiddleC
  42642. */
  42643. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  42644. /** @internal */
  42645. void paint (Graphics& g);
  42646. /** @internal */
  42647. void resized();
  42648. /** @internal */
  42649. void mouseMove (const MouseEvent& e);
  42650. /** @internal */
  42651. void mouseDrag (const MouseEvent& e);
  42652. /** @internal */
  42653. void mouseDown (const MouseEvent& e);
  42654. /** @internal */
  42655. void mouseUp (const MouseEvent& e);
  42656. /** @internal */
  42657. void mouseEnter (const MouseEvent& e);
  42658. /** @internal */
  42659. void mouseExit (const MouseEvent& e);
  42660. /** @internal */
  42661. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  42662. /** @internal */
  42663. void timerCallback();
  42664. /** @internal */
  42665. bool keyStateChanged (bool isKeyDown);
  42666. /** @internal */
  42667. void focusLost (FocusChangeType cause);
  42668. /** @internal */
  42669. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  42670. /** @internal */
  42671. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  42672. /** @internal */
  42673. void handleAsyncUpdate();
  42674. /** @internal */
  42675. void colourChanged();
  42676. juce_UseDebuggingNewOperator
  42677. protected:
  42678. friend class MidiKeyboardUpDownButton;
  42679. /** Draws a white note in the given rectangle.
  42680. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42681. currently pressed down.
  42682. When doing this, be sure to note the keyboard's orientation.
  42683. */
  42684. virtual void drawWhiteNote (int midiNoteNumber,
  42685. Graphics& g,
  42686. int x, int y, int w, int h,
  42687. bool isDown, bool isOver,
  42688. const Colour& lineColour,
  42689. const Colour& textColour);
  42690. /** Draws a black note in the given rectangle.
  42691. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42692. currently pressed down.
  42693. When doing this, be sure to note the keyboard's orientation.
  42694. */
  42695. virtual void drawBlackNote (int midiNoteNumber,
  42696. Graphics& g,
  42697. int x, int y, int w, int h,
  42698. bool isDown, bool isOver,
  42699. const Colour& noteFillColour);
  42700. /** Allows text to be drawn on the white notes.
  42701. By default this is used to label the C in each octave, but could be used for other things.
  42702. @see setOctaveForMiddleC
  42703. */
  42704. virtual const String getWhiteNoteText (const int midiNoteNumber);
  42705. /** Draws the up and down buttons that change the base note. */
  42706. virtual void drawUpDownButton (Graphics& g, int w, int h,
  42707. const bool isMouseOver,
  42708. const bool isButtonPressed,
  42709. const bool movesOctavesUp);
  42710. /** Callback when the mouse is clicked on a key.
  42711. You could use this to do things like handle right-clicks on keys, etc.
  42712. Return true if you want the click to trigger the note, or false if you
  42713. want to handle it yourself and not have the note played.
  42714. @see mouseDraggedToKey
  42715. */
  42716. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  42717. /** Callback when the mouse is dragged from one key onto another.
  42718. @see mouseDownOnKey
  42719. */
  42720. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  42721. /** Calculates the positon of a given midi-note.
  42722. This can be overridden to create layouts with custom key-widths.
  42723. @param midiNoteNumber the note to find
  42724. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  42725. @param x the x position of the left-hand edge of the key (this method
  42726. always works in terms of a horizontal keyboard)
  42727. @param w the width of the key
  42728. */
  42729. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  42730. int& x, int& w) const;
  42731. private:
  42732. MidiKeyboardState& state;
  42733. int xOffset, blackNoteLength;
  42734. float keyWidth;
  42735. Orientation orientation;
  42736. int midiChannel, midiInChannelMask;
  42737. float velocity;
  42738. int noteUnderMouse, mouseDownNote;
  42739. BigInteger keysPressed, keysCurrentlyDrawnDown;
  42740. int rangeStart, rangeEnd, firstKey;
  42741. bool canScroll, mouseDragging, useMousePositionForVelocity;
  42742. Button* scrollDown;
  42743. Button* scrollUp;
  42744. Array <KeyPress> keyPresses;
  42745. Array <int> keyPressNotes;
  42746. int keyMappingOctave;
  42747. int octaveNumForMiddleC;
  42748. static const uint8 whiteNotes[];
  42749. static const uint8 blackNotes[];
  42750. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  42751. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  42752. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  42753. void resetAnyKeysInUse();
  42754. void updateNoteUnderMouse (const Point<int>& pos);
  42755. void repaintNote (const int midiNoteNumber);
  42756. MidiKeyboardComponent (const MidiKeyboardComponent&);
  42757. MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  42758. };
  42759. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42760. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  42761. #endif
  42762. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42763. /*** Start of inlined file: juce_NSViewComponent.h ***/
  42764. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42765. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42766. #if ! DOXYGEN
  42767. class NSViewComponentInternal;
  42768. #endif
  42769. #if JUCE_MAC || DOXYGEN
  42770. /**
  42771. A Mac-specific class that can create and embed an NSView inside itself.
  42772. To use it, create one of these, put it in place and make sure it's visible in a
  42773. window, then use setView() to assign an NSView to it. The view will then be
  42774. moved and resized to follow the movements of this component.
  42775. Of course, since the view is a native object, it'll obliterate any
  42776. juce components that may overlap this component, but that's life.
  42777. */
  42778. class JUCE_API NSViewComponent : public Component
  42779. {
  42780. public:
  42781. /** Create an initially-empty container. */
  42782. NSViewComponent();
  42783. /** Destructor. */
  42784. ~NSViewComponent();
  42785. /** Assigns an NSView to this peer.
  42786. The view will be retained and released by this component for as long as
  42787. it is needed. To remove the current view, just call setView (0).
  42788. Note: a void* is used here to avoid including the cocoa headers as
  42789. part of the juce.h, but the method expects an NSView*.
  42790. */
  42791. void setView (void* nsView);
  42792. /** Returns the current NSView.
  42793. Note: a void* is returned here to avoid including the cocoa headers as
  42794. a requirement of juce.h, so you should just cast the object to an NSView*.
  42795. */
  42796. void* getView() const;
  42797. /** @internal */
  42798. void paint (Graphics& g);
  42799. juce_UseDebuggingNewOperator
  42800. private:
  42801. friend class NSViewComponentInternal;
  42802. ScopedPointer <NSViewComponentInternal> info;
  42803. NSViewComponent (const NSViewComponent&);
  42804. NSViewComponent& operator= (const NSViewComponent&);
  42805. };
  42806. #endif
  42807. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42808. /*** End of inlined file: juce_NSViewComponent.h ***/
  42809. #endif
  42810. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42811. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  42812. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42813. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42814. // this is used to disable OpenGL, and is defined in juce_Config.h
  42815. #if JUCE_OPENGL || DOXYGEN
  42816. /**
  42817. Represents the various properties of an OpenGL bitmap format.
  42818. @see OpenGLComponent::setPixelFormat
  42819. */
  42820. class JUCE_API OpenGLPixelFormat
  42821. {
  42822. public:
  42823. /** Creates an OpenGLPixelFormat.
  42824. The default constructor just initialises the object as a simple 8-bit
  42825. RGBA format.
  42826. */
  42827. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  42828. int alphaBits = 8,
  42829. int depthBufferBits = 16,
  42830. int stencilBufferBits = 0);
  42831. OpenGLPixelFormat (const OpenGLPixelFormat&);
  42832. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  42833. bool operator== (const OpenGLPixelFormat&) const;
  42834. int redBits; /**< The number of bits per pixel to use for the red channel. */
  42835. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  42836. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  42837. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  42838. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  42839. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  42840. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  42841. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  42842. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  42843. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  42844. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  42845. /** Returns a list of all the pixel formats that can be used in this system.
  42846. A reference component is needed in case there are multiple screens with different
  42847. capabilities - in which case, the one that the component is on will be used.
  42848. */
  42849. static void getAvailablePixelFormats (Component* component,
  42850. OwnedArray <OpenGLPixelFormat>& results);
  42851. juce_UseDebuggingNewOperator
  42852. };
  42853. /**
  42854. A base class for types of OpenGL context.
  42855. An OpenGLComponent will supply its own context for drawing in its window.
  42856. */
  42857. class JUCE_API OpenGLContext
  42858. {
  42859. public:
  42860. /** Destructor. */
  42861. virtual ~OpenGLContext();
  42862. /** Makes this context the currently active one. */
  42863. virtual bool makeActive() const throw() = 0;
  42864. /** If this context is currently active, it is disactivated. */
  42865. virtual bool makeInactive() const throw() = 0;
  42866. /** Returns true if this context is currently active. */
  42867. virtual bool isActive() const throw() = 0;
  42868. /** Swaps the buffers (if the context can do this). */
  42869. virtual void swapBuffers() = 0;
  42870. /** Sets whether the context checks the vertical sync before swapping.
  42871. The value is the number of frames to allow between buffer-swapping. This is
  42872. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  42873. and greater numbers indicate that it should swap less often.
  42874. Returns true if it sets the value successfully.
  42875. */
  42876. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  42877. /** Returns the current swap-sync interval.
  42878. See setSwapInterval() for info about the value returned.
  42879. */
  42880. virtual int getSwapInterval() const = 0;
  42881. /** Returns the pixel format being used by this context. */
  42882. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  42883. /** For windowed contexts, this moves the context within the bounds of
  42884. its parent window.
  42885. */
  42886. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  42887. /** For windowed contexts, this triggers a repaint of the window.
  42888. (Not relevent on all platforms).
  42889. */
  42890. virtual void repaint() = 0;
  42891. /** Returns an OS-dependent handle to the raw GL context.
  42892. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  42893. a GLXContext.
  42894. */
  42895. virtual void* getRawContext() const throw() = 0;
  42896. /** Deletes the context.
  42897. This must only be called on the message thread, or will deadlock.
  42898. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  42899. to call any other OpenGL function afterwards.
  42900. This doesn't touch other resources, such as window handles, etc.
  42901. You'll probably never have to call this method directly.
  42902. */
  42903. virtual void deleteContext() = 0;
  42904. /** Returns the context that's currently in active use by the calling thread.
  42905. Returns 0 if there isn't an active context.
  42906. */
  42907. static OpenGLContext* getCurrentContext();
  42908. juce_UseDebuggingNewOperator
  42909. protected:
  42910. OpenGLContext() throw();
  42911. };
  42912. /**
  42913. A component that contains an OpenGL canvas.
  42914. Override this, add it to whatever component you want to, and use the renderOpenGL()
  42915. method to draw its contents.
  42916. */
  42917. class JUCE_API OpenGLComponent : public Component
  42918. {
  42919. public:
  42920. /** Used to select the type of openGL API to use, if more than one choice is available
  42921. on a particular platform.
  42922. */
  42923. enum OpenGLType
  42924. {
  42925. openGLDefault = 0,
  42926. #if JUCE_IOS
  42927. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  42928. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  42929. #endif
  42930. };
  42931. /** Creates an OpenGLComponent. */
  42932. OpenGLComponent (OpenGLType type = openGLDefault);
  42933. /** Destructor. */
  42934. ~OpenGLComponent();
  42935. /** Changes the pixel format used by this component.
  42936. @see OpenGLPixelFormat::getAvailablePixelFormats()
  42937. */
  42938. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  42939. /** Returns the pixel format that this component is currently using. */
  42940. const OpenGLPixelFormat getPixelFormat() const;
  42941. /** Specifies an OpenGL context which should be shared with the one that this
  42942. component is using.
  42943. This is an OpenGL feature that lets two contexts share their texture data.
  42944. Note that this pointer is stored by the component, and when the component
  42945. needs to recreate its internal context for some reason, the same context
  42946. will be used again to share lists. So if you pass a context in here,
  42947. don't delete the context while this component is still using it! You can
  42948. call shareWith (0) to stop this component from sharing with it.
  42949. */
  42950. void shareWith (OpenGLContext* contextToShareListsWith);
  42951. /** Returns the context that this component is sharing with.
  42952. @see shareWith
  42953. */
  42954. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  42955. /** Flips the openGL buffers over. */
  42956. void swapBuffers();
  42957. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  42958. When this is called, makeCurrentContextActive() will already have been called
  42959. for you, so you just need to draw.
  42960. */
  42961. virtual void renderOpenGL() = 0;
  42962. /** This method is called when the component creates a new OpenGL context.
  42963. A new context may be created when the component is first used, or when it
  42964. is moved to a different window, or when the window is hidden and re-shown,
  42965. etc.
  42966. You can use this callback as an opportunity to set up things like textures
  42967. that your context needs.
  42968. New contexts are created on-demand by the makeCurrentContextActive() method - so
  42969. if the context is deleted, e.g. by changing the pixel format or window, no context
  42970. will be created until the next call to makeCurrentContextActive(), which will
  42971. synchronously create one and call this method. This means that if you're using
  42972. a non-GUI thread for rendering, you can make sure this method is be called by
  42973. your renderer thread.
  42974. When this callback happens, the context will already have been made current
  42975. using the makeCurrentContextActive() method, so there's no need to call it
  42976. again in your code.
  42977. */
  42978. virtual void newOpenGLContextCreated() = 0;
  42979. /** Returns the context that will draw into this component.
  42980. This may return 0 if the component is currently invisible or hasn't currently
  42981. got a context. The context object can be deleted and a new one created during
  42982. the lifetime of this component, and there may be times when it doesn't have one.
  42983. @see newOpenGLContextCreated()
  42984. */
  42985. OpenGLContext* getCurrentContext() const throw() { return context; }
  42986. /** Makes this component the current openGL context.
  42987. You might want to use this in things like your resize() method, before calling
  42988. GL commands.
  42989. If this returns false, then the context isn't active, so you should avoid
  42990. making any calls.
  42991. This call may actually create a context if one isn't currently initialised. If
  42992. it does this, it will also synchronously call the newOpenGLContextCreated()
  42993. method to let you initialise it as necessary.
  42994. @see OpenGLContext::makeActive
  42995. */
  42996. bool makeCurrentContextActive();
  42997. /** Stops the current component being the active OpenGL context.
  42998. This is the opposite of makeCurrentContextActive()
  42999. @see OpenGLContext::makeInactive
  43000. */
  43001. void makeCurrentContextInactive();
  43002. /** Returns true if this component is the active openGL context for the
  43003. current thread.
  43004. @see OpenGLContext::isActive
  43005. */
  43006. bool isActiveContext() const throw();
  43007. /** Calls the rendering callback, and swaps the buffers afterwards.
  43008. This is called automatically by paint() when the component needs to be rendered.
  43009. It can be overridden if you need to decouple the rendering from the paint callback
  43010. and render with a custom thread.
  43011. Returns true if the operation succeeded.
  43012. */
  43013. virtual bool renderAndSwapBuffers();
  43014. /** This returns a critical section that can be used to lock the current context.
  43015. Because the context that is used by this component can change, e.g. when the
  43016. component is shown or hidden, then if you're rendering to it on a background
  43017. thread, this allows you to lock the context for the duration of your rendering
  43018. routine.
  43019. */
  43020. CriticalSection& getContextLock() throw() { return contextLock; }
  43021. /** @internal */
  43022. void paint (Graphics& g);
  43023. /** Returns the native handle of an embedded heavyweight window, if there is one.
  43024. E.g. On windows, this will return the HWND of the sub-window containing
  43025. the opengl context, on the mac it'll be the NSOpenGLView.
  43026. */
  43027. void* getNativeWindowHandle() const;
  43028. /** Delete the context.
  43029. This can be called back on the same thread that created the context. */
  43030. void deleteContext();
  43031. juce_UseDebuggingNewOperator
  43032. private:
  43033. const OpenGLType type;
  43034. class OpenGLComponentWatcher;
  43035. friend class OpenGLComponentWatcher;
  43036. friend class ScopedPointer <OpenGLComponentWatcher>;
  43037. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  43038. ScopedPointer <OpenGLContext> context;
  43039. OpenGLContext* contextToShareListsWith;
  43040. CriticalSection contextLock;
  43041. OpenGLPixelFormat preferredPixelFormat;
  43042. bool needToUpdateViewport;
  43043. OpenGLContext* createContext();
  43044. void updateContextPosition();
  43045. void internalRepaint (int x, int y, int w, int h);
  43046. OpenGLComponent (const OpenGLComponent&);
  43047. OpenGLComponent& operator= (const OpenGLComponent&);
  43048. };
  43049. #endif
  43050. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  43051. /*** End of inlined file: juce_OpenGLComponent.h ***/
  43052. #endif
  43053. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  43054. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  43055. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  43056. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  43057. /**
  43058. A component with a set of buttons at the top for changing between pages of
  43059. preferences.
  43060. This is just a handy way of writing a Mac-style preferences panel where you
  43061. have a row of buttons along the top for the different preference categories,
  43062. each button having an icon above its name. Clicking these will show an
  43063. appropriate prefs page below it.
  43064. You can either put one of these inside your own component, or just use the
  43065. showInDialogBox() method to show it in a window and run it modally.
  43066. To use it, just add a set of named pages with the addSettingsPage() method,
  43067. and implement the createComponentForPage() method to create suitable components
  43068. for each of these pages.
  43069. */
  43070. class JUCE_API PreferencesPanel : public Component,
  43071. private Button::Listener
  43072. {
  43073. public:
  43074. /** Creates an empty panel.
  43075. Use addSettingsPage() to add some pages to it in your constructor.
  43076. */
  43077. PreferencesPanel();
  43078. /** Destructor. */
  43079. ~PreferencesPanel();
  43080. /** Creates a page using a set of drawables to define the page's icon.
  43081. Note that the other version of this method is much easier if you're using
  43082. an image instead of a custom drawable.
  43083. @param pageTitle the name of this preferences page - you'll need to
  43084. make sure your createComponentForPage() method creates
  43085. a suitable component when it is passed this name
  43086. @param normalIcon the drawable to display in the page's button normally
  43087. @param overIcon the drawable to display in the page's button when the mouse is over
  43088. @param downIcon the drawable to display in the page's button when the button is down
  43089. @see DrawableButton
  43090. */
  43091. void addSettingsPage (const String& pageTitle,
  43092. const Drawable* normalIcon,
  43093. const Drawable* overIcon,
  43094. const Drawable* downIcon);
  43095. /** Creates a page using a set of drawables to define the page's icon.
  43096. The other version of this method gives you more control over the icon, but this
  43097. one is much easier if you're just loading it from a file.
  43098. @param pageTitle the name of this preferences page - you'll need to
  43099. make sure your createComponentForPage() method creates
  43100. a suitable component when it is passed this name
  43101. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  43102. For this to look good, you'll probably want to use a nice
  43103. transparent png file.
  43104. @param imageDataSize the size of the image data, in bytes
  43105. */
  43106. void addSettingsPage (const String& pageTitle,
  43107. const void* imageData,
  43108. int imageDataSize);
  43109. /** Utility method to display this panel in a DialogWindow.
  43110. Calling this will create a DialogWindow containing this panel with the
  43111. given size and title, and will run it modally, returning when the user
  43112. closes the dialog box.
  43113. */
  43114. void showInDialogBox (const String& dialogtitle,
  43115. int dialogWidth,
  43116. int dialogHeight,
  43117. const Colour& backgroundColour = Colours::white);
  43118. /** Subclasses must override this to return a component for each preferences page.
  43119. The subclass should return a pointer to a new component representing the named
  43120. page, which the panel will then display.
  43121. The panel will delete the component later when the user goes to another page
  43122. or deletes the panel.
  43123. */
  43124. virtual Component* createComponentForPage (const String& pageName) = 0;
  43125. /** Changes the current page being displayed. */
  43126. void setCurrentPage (const String& pageName);
  43127. /** @internal */
  43128. void resized();
  43129. /** @internal */
  43130. void paint (Graphics& g);
  43131. /** @internal */
  43132. void buttonClicked (Button* button);
  43133. juce_UseDebuggingNewOperator
  43134. private:
  43135. String currentPageName;
  43136. ScopedPointer <Component> currentPage;
  43137. int buttonSize;
  43138. PreferencesPanel (const PreferencesPanel&);
  43139. PreferencesPanel& operator= (const PreferencesPanel&);
  43140. };
  43141. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  43142. /*** End of inlined file: juce_PreferencesPanel.h ***/
  43143. #endif
  43144. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43145. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  43146. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43147. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43148. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  43149. // amalgamated build)
  43150. #if JUCE_WINDOWS
  43151. typedef ActiveXControlComponent QTCompBaseClass;
  43152. #elif JUCE_MAC
  43153. typedef NSViewComponent QTCompBaseClass;
  43154. #endif
  43155. // this is used to disable QuickTime, and is defined in juce_Config.h
  43156. #if JUCE_QUICKTIME || DOXYGEN
  43157. /**
  43158. A window that can play back a QuickTime movie.
  43159. */
  43160. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  43161. {
  43162. public:
  43163. /** Creates a QuickTimeMovieComponent, initially blank.
  43164. Use the loadMovie() method to load a movie once you've added the
  43165. component to a window, (or put it on the desktop as a heavyweight window).
  43166. Loading a movie when the component isn't visible can cause problems, as
  43167. QuickTime needs a window handle to initialise properly.
  43168. */
  43169. QuickTimeMovieComponent();
  43170. /** Destructor. */
  43171. ~QuickTimeMovieComponent();
  43172. /** Returns true if QT is installed and working on this machine.
  43173. */
  43174. static bool isQuickTimeAvailable() throw();
  43175. /** Tries to load a QuickTime movie from a file into the player.
  43176. It's best to call this function once you've added the component to a window,
  43177. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43178. component isn't visible can cause problems, because QuickTime needs a window
  43179. handle to do its stuff.
  43180. @param movieFile the .mov file to open
  43181. @param isControllerVisible whether to show a controller bar at the bottom
  43182. @returns true if the movie opens successfully
  43183. */
  43184. bool loadMovie (const File& movieFile,
  43185. bool isControllerVisible);
  43186. /** Tries to load a QuickTime movie from a URL into the player.
  43187. It's best to call this function once you've added the component to a window,
  43188. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43189. component isn't visible can cause problems, because QuickTime needs a window
  43190. handle to do its stuff.
  43191. @param movieURL the .mov file to open
  43192. @param isControllerVisible whether to show a controller bar at the bottom
  43193. @returns true if the movie opens successfully
  43194. */
  43195. bool loadMovie (const URL& movieURL,
  43196. bool isControllerVisible);
  43197. /** Tries to load a QuickTime movie from a stream into the player.
  43198. It's best to call this function once you've added the component to a window,
  43199. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43200. component isn't visible can cause problems, because QuickTime needs a window
  43201. handle to do its stuff.
  43202. @param movieStream a stream containing a .mov file. The component may try
  43203. to read the whole stream before playing, rather than
  43204. streaming from it.
  43205. @param isControllerVisible whether to show a controller bar at the bottom
  43206. @returns true if the movie opens successfully
  43207. */
  43208. bool loadMovie (InputStream* movieStream,
  43209. bool isControllerVisible);
  43210. /** Closes the movie, if one is open. */
  43211. void closeMovie();
  43212. /** Returns the movie file that is currently open.
  43213. If there isn't one, this returns File::nonexistent
  43214. */
  43215. const File getCurrentMovieFile() const;
  43216. /** Returns true if there's currently a movie open. */
  43217. bool isMovieOpen() const;
  43218. /** Returns the length of the movie, in seconds. */
  43219. double getMovieDuration() const;
  43220. /** Returns the movie's natural size, in pixels.
  43221. You can use this to resize the component to show the movie at its preferred
  43222. scale.
  43223. If no movie is loaded, the size returned will be 0 x 0.
  43224. */
  43225. void getMovieNormalSize (int& width, int& height) const;
  43226. /** This will position the component within a given area, keeping its aspect
  43227. ratio correct according to the movie's normal size.
  43228. The component will be made as large as it can go within the space, and will
  43229. be aligned according to the justification value if this means there are gaps at
  43230. the top or sides.
  43231. */
  43232. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  43233. const RectanglePlacement& placement);
  43234. /** Starts the movie playing. */
  43235. void play();
  43236. /** Stops the movie playing. */
  43237. void stop();
  43238. /** Returns true if the movie is currently playing. */
  43239. bool isPlaying() const;
  43240. /** Moves the movie's position back to the start. */
  43241. void goToStart();
  43242. /** Sets the movie's position to a given time. */
  43243. void setPosition (double seconds);
  43244. /** Returns the current play position of the movie. */
  43245. double getPosition() const;
  43246. /** Changes the movie playback rate.
  43247. A value of 1 is normal speed, greater values play it proportionately faster,
  43248. smaller values play it slower.
  43249. */
  43250. void setSpeed (float newSpeed);
  43251. /** Changes the movie's playback volume.
  43252. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  43253. */
  43254. void setMovieVolume (float newVolume);
  43255. /** Returns the movie's playback volume.
  43256. @returns the volume in the range 0 (silent) to 1.0 (full)
  43257. */
  43258. float getMovieVolume() const;
  43259. /** Tells the movie whether it should loop. */
  43260. void setLooping (bool shouldLoop);
  43261. /** Returns true if the movie is currently looping.
  43262. @see setLooping
  43263. */
  43264. bool isLooping() const;
  43265. /** True if the native QuickTime controller bar is shown in the window.
  43266. @see loadMovie
  43267. */
  43268. bool isControllerVisible() const;
  43269. /** @internal */
  43270. void paint (Graphics& g);
  43271. juce_UseDebuggingNewOperator
  43272. private:
  43273. File movieFile;
  43274. bool movieLoaded, controllerVisible, looping;
  43275. #if JUCE_WINDOWS
  43276. void parentHierarchyChanged();
  43277. void visibilityChanged();
  43278. void createControlIfNeeded();
  43279. bool isControlCreated() const;
  43280. class Pimpl;
  43281. friend class ScopedPointer <Pimpl>;
  43282. ScopedPointer <Pimpl> pimpl;
  43283. #else
  43284. void* movie;
  43285. #endif
  43286. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  43287. QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  43288. };
  43289. #endif
  43290. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43291. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  43292. #endif
  43293. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43294. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  43295. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43296. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43297. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  43298. /**
  43299. On Windows only, this component sits in the taskbar tray as a small icon.
  43300. To use it, just create one of these components, but don't attempt to make it
  43301. visible, add it to a parent, or put it on the desktop.
  43302. You can then call setIconImage() to create an icon for it in the taskbar.
  43303. To change the icon's tooltip, you can use setIconTooltip().
  43304. To respond to mouse-events, you can override the normal mouseDown(),
  43305. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  43306. position will not be valid, you can use this to respond to clicks. Traditionally
  43307. you'd use a left-click to show your application's window, and a right-click
  43308. to show a pop-up menu.
  43309. */
  43310. class JUCE_API SystemTrayIconComponent : public Component
  43311. {
  43312. public:
  43313. SystemTrayIconComponent();
  43314. /** Destructor. */
  43315. ~SystemTrayIconComponent();
  43316. /** Changes the image shown in the taskbar.
  43317. */
  43318. void setIconImage (const Image& newImage);
  43319. /** Changes the tooltip that Windows shows above the icon. */
  43320. void setIconTooltip (const String& tooltip);
  43321. #if JUCE_LINUX
  43322. /** @internal */
  43323. void paint (Graphics& g);
  43324. #endif
  43325. juce_UseDebuggingNewOperator
  43326. private:
  43327. SystemTrayIconComponent (const SystemTrayIconComponent&);
  43328. SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  43329. };
  43330. #endif
  43331. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43332. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  43333. #endif
  43334. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43335. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  43336. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43337. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43338. #if JUCE_WEB_BROWSER || DOXYGEN
  43339. #if ! DOXYGEN
  43340. class WebBrowserComponentInternal;
  43341. #endif
  43342. /**
  43343. A component that displays an embedded web browser.
  43344. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  43345. Windows, probably IE.
  43346. */
  43347. class JUCE_API WebBrowserComponent : public Component
  43348. {
  43349. public:
  43350. /** Creates a WebBrowserComponent.
  43351. Once it's created and visible, send the browser to a URL using goToURL().
  43352. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  43353. component is taken offscreen, it'll clear the current page
  43354. and replace it with a blank page - this can be handy to stop
  43355. the browser using resources in the background when it's not
  43356. actually being used.
  43357. */
  43358. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  43359. /** Destructor. */
  43360. ~WebBrowserComponent();
  43361. /** Sends the browser to a particular URL.
  43362. @param url the URL to go to.
  43363. @param headers an optional set of parameters to put in the HTTP header. If
  43364. you supply this, it should be a set of string in the form
  43365. "HeaderKey: HeaderValue"
  43366. @param postData an optional block of data that will be attached to the HTTP
  43367. POST request
  43368. */
  43369. void goToURL (const String& url,
  43370. const StringArray* headers = 0,
  43371. const MemoryBlock* postData = 0);
  43372. /** Stops the current page loading.
  43373. */
  43374. void stop();
  43375. /** Sends the browser back one page.
  43376. */
  43377. void goBack();
  43378. /** Sends the browser forward one page.
  43379. */
  43380. void goForward();
  43381. /** Refreshes the browser.
  43382. */
  43383. void refresh();
  43384. /** This callback is called when the browser is about to navigate
  43385. to a new location.
  43386. You can override this method to perform some action when the user
  43387. tries to go to a particular URL. To allow the operation to carry on,
  43388. return true, or return false to stop the navigation happening.
  43389. */
  43390. virtual bool pageAboutToLoad (const String& newURL);
  43391. /** @internal */
  43392. void paint (Graphics& g);
  43393. /** @internal */
  43394. void resized();
  43395. /** @internal */
  43396. void parentHierarchyChanged();
  43397. /** @internal */
  43398. void visibilityChanged();
  43399. juce_UseDebuggingNewOperator
  43400. private:
  43401. WebBrowserComponentInternal* browser;
  43402. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  43403. String lastURL;
  43404. StringArray lastHeaders;
  43405. MemoryBlock lastPostData;
  43406. void reloadLastURL();
  43407. void checkWindowAssociation();
  43408. WebBrowserComponent (const WebBrowserComponent&);
  43409. WebBrowserComponent& operator= (const WebBrowserComponent&);
  43410. };
  43411. #endif
  43412. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43413. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  43414. #endif
  43415. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43416. #endif
  43417. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  43418. /*** Start of inlined file: juce_CallOutBox.h ***/
  43419. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  43420. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  43421. /**
  43422. A box with a small arrow that can be used as a temporary pop-up window to show
  43423. extra controls when a button or other component is clicked.
  43424. Using one of these is similar to having a popup menu attached to a button or
  43425. other component - but it looks fancier, and has an arrow that can indicate the
  43426. object that it applies to.
  43427. Normally, you'd create one of these on the stack and run it modally, e.g.
  43428. @code
  43429. void mouseUp (const MouseEvent& e)
  43430. {
  43431. MyContentComponent content;
  43432. content.setSize (300, 300);
  43433. CallOutBox callOut (content, *this, 0);
  43434. callOut.runModalLoop();
  43435. }
  43436. @endcode
  43437. The call-out will resize and position itself when the content changes size.
  43438. */
  43439. class JUCE_API CallOutBox : public Component
  43440. {
  43441. public:
  43442. /** Creates a CallOutBox.
  43443. @param contentComponent the component to display inside the call-out. This should
  43444. already have a size set (although the call-out will also
  43445. update itself when the component's size is changed later).
  43446. Obviously this component must not be deleted until the
  43447. call-out box has been deleted.
  43448. @param componentToPointTo the component that the call-out's arrow should point towards
  43449. @param parentComponent if non-zero, this is the component to add the call-out to. If
  43450. this is zero, the call-out will be added to the desktop.
  43451. */
  43452. CallOutBox (Component& contentComponent,
  43453. Component& componentToPointTo,
  43454. Component* parentComponent);
  43455. /** Destructor. */
  43456. ~CallOutBox();
  43457. /** Changes the length of the arrow. */
  43458. void setArrowSize (float newSize);
  43459. /** Updates the position and size of the box.
  43460. You shouldn't normally need to call this, unless you need more precise control over the
  43461. layout.
  43462. @param newAreaToPointTo the rectangle to make the box's arrow point to
  43463. @param newAreaToFitIn the area within which the box's position should be constrained
  43464. */
  43465. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  43466. const Rectangle<int>& newAreaToFitIn);
  43467. /** @internal */
  43468. void paint (Graphics& g);
  43469. /** @internal */
  43470. void resized();
  43471. /** @internal */
  43472. void moved();
  43473. /** @internal */
  43474. void childBoundsChanged (Component*);
  43475. /** @internal */
  43476. bool hitTest (int x, int y);
  43477. /** @internal */
  43478. void inputAttemptWhenModal();
  43479. /** @internal */
  43480. bool keyPressed (const KeyPress& key);
  43481. /** @internal */
  43482. void handleCommandMessage (int commandId);
  43483. juce_UseDebuggingNewOperator
  43484. private:
  43485. int borderSpace;
  43486. float arrowSize;
  43487. Component& content;
  43488. Path outline;
  43489. Point<float> targetPoint;
  43490. Rectangle<int> availableArea, targetArea;
  43491. Image background;
  43492. void refreshPath();
  43493. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  43494. CallOutBox (const CallOutBox&);
  43495. CallOutBox& operator= (const CallOutBox&);
  43496. };
  43497. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  43498. /*** End of inlined file: juce_CallOutBox.h ***/
  43499. #endif
  43500. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43501. /*** Start of inlined file: juce_ComponentPeer.h ***/
  43502. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43503. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  43504. class ComponentBoundsConstrainer;
  43505. /**
  43506. The base class for window objects that wrap a component as a real operating
  43507. system object.
  43508. This is an abstract base class - the platform specific code contains default
  43509. implementations of it that create and manage windows.
  43510. @see Component::createNewPeer
  43511. */
  43512. class JUCE_API ComponentPeer
  43513. {
  43514. public:
  43515. /** A combination of these flags is passed to the ComponentPeer constructor. */
  43516. enum StyleFlags
  43517. {
  43518. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  43519. entry on the taskbar (ignored on MacOSX) */
  43520. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  43521. tooltip, etc. */
  43522. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  43523. through it (may not be possible on some platforms). */
  43524. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  43525. title bar and frame\. if not specified, the window will be
  43526. borderless. */
  43527. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  43528. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  43529. minimise button on it. */
  43530. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  43531. maximise button on it. */
  43532. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  43533. close button on it. */
  43534. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  43535. not be possible on all platforms). */
  43536. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  43537. do its own repainting, but only to repaint when the
  43538. performAnyPendingRepaintsNow() method is called. */
  43539. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  43540. be used for things like plugin windows, to stop them interfering
  43541. with the host's shortcut keys */
  43542. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  43543. };
  43544. /** Creates a peer.
  43545. The component is the one that we intend to represent, and the style flags are
  43546. a combination of the values in the StyleFlags enum
  43547. */
  43548. ComponentPeer (Component* component, int styleFlags);
  43549. /** Destructor. */
  43550. virtual ~ComponentPeer();
  43551. /** Returns the component being represented by this peer. */
  43552. Component* getComponent() const throw() { return component; }
  43553. /** Returns the set of style flags that were set when the window was created.
  43554. @see Component::addToDesktop
  43555. */
  43556. int getStyleFlags() const throw() { return styleFlags; }
  43557. /** Returns the raw handle to whatever kind of window is being used.
  43558. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  43559. but rememeber there's no guarantees what you'll get back.
  43560. */
  43561. virtual void* getNativeHandle() const = 0;
  43562. /** Shows or hides the window. */
  43563. virtual void setVisible (bool shouldBeVisible) = 0;
  43564. /** Changes the title of the window. */
  43565. virtual void setTitle (const String& title) = 0;
  43566. /** Moves the window without changing its size.
  43567. If the native window is contained in another window, then the co-ordinates are
  43568. relative to the parent window's origin, not the screen origin.
  43569. This should result in a callback to handleMovedOrResized().
  43570. */
  43571. virtual void setPosition (int x, int y) = 0;
  43572. /** Resizes the window without changing its position.
  43573. This should result in a callback to handleMovedOrResized().
  43574. */
  43575. virtual void setSize (int w, int h) = 0;
  43576. /** Moves and resizes the window.
  43577. If the native window is contained in another window, then the co-ordinates are
  43578. relative to the parent window's origin, not the screen origin.
  43579. This should result in a callback to handleMovedOrResized().
  43580. */
  43581. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  43582. /** Returns the current position and size of the window.
  43583. If the native window is contained in another window, then the co-ordinates are
  43584. relative to the parent window's origin, not the screen origin.
  43585. */
  43586. virtual const Rectangle<int> getBounds() const = 0;
  43587. /** Returns the x-position of this window, relative to the screen's origin. */
  43588. virtual const Point<int> getScreenPosition() const = 0;
  43589. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  43590. virtual const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) = 0;
  43591. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  43592. virtual const Point<int> globalPositionToRelative (const Point<int>& screenPosition) = 0;
  43593. /** Minimises the window. */
  43594. virtual void setMinimised (bool shouldBeMinimised) = 0;
  43595. /** True if the window is currently minimised. */
  43596. virtual bool isMinimised() const = 0;
  43597. /** Enable/disable fullscreen mode for the window. */
  43598. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  43599. /** True if the window is currently full-screen. */
  43600. virtual bool isFullScreen() const = 0;
  43601. /** Sets the size to restore to if fullscreen mode is turned off. */
  43602. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  43603. /** Returns the size to restore to if fullscreen mode is turned off. */
  43604. const Rectangle<int>& getNonFullScreenBounds() const throw();
  43605. /** Attempts to change the icon associated with this window.
  43606. */
  43607. virtual void setIcon (const Image& newIcon) = 0;
  43608. /** Sets a constrainer to use if the peer can resize itself.
  43609. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  43610. */
  43611. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  43612. /** Returns the current constrainer, if one has been set. */
  43613. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  43614. /** Checks if a point is in the window.
  43615. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  43616. is false, then this returns false if the point is actually inside a child of this
  43617. window.
  43618. */
  43619. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  43620. /** Returns the size of the window frame that's around this window.
  43621. Whether or not the window has a normal window frame depends on the flags
  43622. that were set when the window was created by Component::addToDesktop()
  43623. */
  43624. virtual const BorderSize getFrameSize() const = 0;
  43625. /** This is called when the window's bounds change.
  43626. A peer implementation must call this when the window is moved and resized, so that
  43627. this method can pass the message on to the component.
  43628. */
  43629. void handleMovedOrResized();
  43630. /** This is called if the screen resolution changes.
  43631. A peer implementation must call this if the monitor arrangement changes or the available
  43632. screen size changes.
  43633. */
  43634. void handleScreenSizeChange();
  43635. /** This is called to repaint the component into the given context. */
  43636. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  43637. /** Sets this window to either be always-on-top or normal.
  43638. Some kinds of window might not be able to do this, so should return false.
  43639. */
  43640. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  43641. /** Brings the window to the top, optionally also giving it focus. */
  43642. virtual void toFront (bool makeActive) = 0;
  43643. /** Moves the window to be just behind another one. */
  43644. virtual void toBehind (ComponentPeer* other) = 0;
  43645. /** Called when the window is brought to the front, either by the OS or by a call
  43646. to toFront().
  43647. */
  43648. void handleBroughtToFront();
  43649. /** True if the window has the keyboard focus. */
  43650. virtual bool isFocused() const = 0;
  43651. /** Tries to give the window keyboard focus. */
  43652. virtual void grabFocus() = 0;
  43653. /** Tells the window that text input may be required at the given position.
  43654. This may cause things like a virtual on-screen keyboard to appear, depending
  43655. on the OS.
  43656. */
  43657. virtual void textInputRequired (const Point<int>& position) = 0;
  43658. /** Called when the window gains keyboard focus. */
  43659. void handleFocusGain();
  43660. /** Called when the window loses keyboard focus. */
  43661. void handleFocusLoss();
  43662. Component* getLastFocusedSubcomponent() const throw();
  43663. /** Called when a key is pressed.
  43664. For keycode info, see the KeyPress class.
  43665. Returns true if the keystroke was used.
  43666. */
  43667. bool handleKeyPress (int keyCode,
  43668. juce_wchar textCharacter);
  43669. /** Called whenever a key is pressed or released.
  43670. Returns true if the keystroke was used.
  43671. */
  43672. bool handleKeyUpOrDown (bool isKeyDown);
  43673. /** Called whenever a modifier key is pressed or released. */
  43674. void handleModifierKeysChange();
  43675. /** Returns the currently focused TextInputTarget, or null if none is found. */
  43676. TextInputTarget* findCurrentTextInputTarget();
  43677. /** Invalidates a region of the window to be repainted asynchronously. */
  43678. virtual void repaint (const Rectangle<int>& area) = 0;
  43679. /** This can be called (from the message thread) to cause the immediate redrawing
  43680. of any areas of this window that need repainting.
  43681. You shouldn't ever really need to use this, it's mainly for special purposes
  43682. like supporting audio plugins where the host's event loop is out of our control.
  43683. */
  43684. virtual void performAnyPendingRepaintsNow() = 0;
  43685. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  43686. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  43687. void handleUserClosingWindow();
  43688. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  43689. void handleFileDragExit (const StringArray& files);
  43690. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  43691. /** Resets the masking region.
  43692. The subclass should call this every time it's about to call the handlePaint
  43693. method.
  43694. @see addMaskedRegion
  43695. */
  43696. void clearMaskedRegion();
  43697. /** Adds a rectangle to the set of areas not to paint over.
  43698. A component can call this on its peer during its paint() method, to signal
  43699. that the painting code should ignore a given region. The reason
  43700. for this is to stop embedded windows (such as OpenGL) getting painted over.
  43701. The masked region is cleared each time before a paint happens, so a component
  43702. will have to make sure it calls this every time it's painted.
  43703. */
  43704. void addMaskedRegion (int x, int y, int w, int h);
  43705. /** Returns the number of currently-active peers.
  43706. @see getPeer
  43707. */
  43708. static int getNumPeers() throw();
  43709. /** Returns one of the currently-active peers.
  43710. @see getNumPeers
  43711. */
  43712. static ComponentPeer* getPeer (int index) throw();
  43713. /** Checks if this peer object is valid.
  43714. @see getNumPeers
  43715. */
  43716. static bool isValidPeer (const ComponentPeer* peer) throw();
  43717. static void bringModalComponentToFront();
  43718. virtual const StringArray getAvailableRenderingEngines() throw();
  43719. virtual int getCurrentRenderingEngine() throw();
  43720. virtual void setCurrentRenderingEngine (int index) throw();
  43721. juce_UseDebuggingNewOperator
  43722. protected:
  43723. Component* const component;
  43724. const int styleFlags;
  43725. RectangleList maskedRegion;
  43726. Rectangle<int> lastNonFullscreenBounds;
  43727. uint32 lastPaintTime;
  43728. ComponentBoundsConstrainer* constrainer;
  43729. static void updateCurrentModifiers() throw();
  43730. private:
  43731. Component::SafePointer<Component> lastFocusedComponent, dragAndDropTargetComponent;
  43732. Component* lastDragAndDropCompUnderMouse;
  43733. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  43734. friend class Component;
  43735. static ComponentPeer* getPeerFor (const Component* component) throw();
  43736. void setLastDragDropTarget (Component* comp);
  43737. ComponentPeer (const ComponentPeer&);
  43738. ComponentPeer& operator= (const ComponentPeer&);
  43739. };
  43740. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  43741. /*** End of inlined file: juce_ComponentPeer.h ***/
  43742. #endif
  43743. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43744. /*** Start of inlined file: juce_DialogWindow.h ***/
  43745. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43746. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  43747. /**
  43748. A dialog-box style window.
  43749. This class is a convenient way of creating a DocumentWindow with a close button
  43750. that can be triggered by pressing the escape key.
  43751. Any of the methods available to a DocumentWindow or ResizableWindow are also
  43752. available to this, so it can be made resizable, have a menu bar, etc.
  43753. To add items to the box, see the ResizableWindow::setContentComponent() method.
  43754. Don't add components directly to this class - always put them in a content component!
  43755. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  43756. the user clicking the close button - for more info, see the DocumentWindow
  43757. help.
  43758. @see DocumentWindow, ResizableWindow
  43759. */
  43760. class JUCE_API DialogWindow : public DocumentWindow
  43761. {
  43762. public:
  43763. /** Creates a DialogWindow.
  43764. @param name the name to give the component - this is also
  43765. the title shown at the top of the window. To change
  43766. this later, use setName()
  43767. @param backgroundColour the colour to use for filling the window's background.
  43768. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43769. close button to be triggered
  43770. @param addToDesktop if true, the window will be automatically added to the
  43771. desktop; if false, you can use it as a child component
  43772. */
  43773. DialogWindow (const String& name,
  43774. const Colour& backgroundColour,
  43775. bool escapeKeyTriggersCloseButton,
  43776. bool addToDesktop = true);
  43777. /** Destructor.
  43778. If a content component has been set with setContentComponent(), it
  43779. will be deleted.
  43780. */
  43781. ~DialogWindow();
  43782. /** Easy way of quickly showing a dialog box containing a given component.
  43783. This will open and display a DialogWindow containing a given component, returning
  43784. when the user clicks its close button.
  43785. It returns the value that was returned by the dialog box's runModalLoop() call.
  43786. To close the dialog programatically, you should call exitModalState (returnValue) on
  43787. the DialogWindow that is created. To find a pointer to this window from your
  43788. contentComponent, you can do something like this:
  43789. @code
  43790. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  43791. if (dw != 0)
  43792. dw->exitModalState (1234);
  43793. @endcode
  43794. @param dialogTitle the dialog box's title
  43795. @param contentComponent the content component for the dialog box. Make sure
  43796. that this has been set to the size you want it to
  43797. be before calling this method. The component won't
  43798. be deleted by this call, so you can re-use it or delete
  43799. it afterwards
  43800. @param componentToCentreAround if this is non-zero, it indicates a component that
  43801. you'd like to show this dialog box in front of. See the
  43802. DocumentWindow::centreAroundComponent() method for more
  43803. info on this parameter
  43804. @param backgroundColour a colour to use for the dialog box's background colour
  43805. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43806. close button to be triggered
  43807. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  43808. a corner resizer
  43809. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  43810. to use a border or corner resizer component. See ResizableWindow::setResizable()
  43811. */
  43812. static int showModalDialog (const String& dialogTitle,
  43813. Component* contentComponent,
  43814. Component* componentToCentreAround,
  43815. const Colour& backgroundColour,
  43816. bool escapeKeyTriggersCloseButton,
  43817. bool shouldBeResizable = false,
  43818. bool useBottomRightCornerResizer = false);
  43819. juce_UseDebuggingNewOperator
  43820. protected:
  43821. /** @internal */
  43822. void resized();
  43823. private:
  43824. bool escapeKeyTriggersCloseButton;
  43825. DialogWindow (const DialogWindow&);
  43826. DialogWindow& operator= (const DialogWindow&);
  43827. };
  43828. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  43829. /*** End of inlined file: juce_DialogWindow.h ***/
  43830. #endif
  43831. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43832. #endif
  43833. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43834. #endif
  43835. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43836. /*** Start of inlined file: juce_SplashScreen.h ***/
  43837. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43838. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  43839. /** A component for showing a splash screen while your app starts up.
  43840. This will automatically position itself, and delete itself when the app has
  43841. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  43842. this).
  43843. To use it, just create one of these in your JUCEApplication::initialise() method,
  43844. call its show() method and let the object delete itself later.
  43845. E.g. @code
  43846. void MyApp::initialise (const String& commandLine)
  43847. {
  43848. SplashScreen* splash = new SplashScreen();
  43849. splash->show ("welcome to my app",
  43850. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  43851. 4000, false);
  43852. .. no need to delete the splash screen - it'll do that itself.
  43853. }
  43854. @endcode
  43855. */
  43856. class JUCE_API SplashScreen : public Component,
  43857. public Timer,
  43858. private DeletedAtShutdown
  43859. {
  43860. public:
  43861. /** Creates a SplashScreen object.
  43862. After creating one of these (or your subclass of it), call one of the show()
  43863. methods to display it.
  43864. */
  43865. SplashScreen();
  43866. /** Destructor. */
  43867. ~SplashScreen();
  43868. /** Creates a SplashScreen object that will display an image.
  43869. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43870. screen. This method will also dispatch any pending messages to make sure that when
  43871. it returns, the splash screen has been completely drawn, and your initialisation
  43872. code can carry on.
  43873. @param title the name to give the component
  43874. @param backgroundImage an image to draw on the component. The component's size
  43875. will be set to the size of this image, and if the image is
  43876. semi-transparent, the component will be made semi-transparent
  43877. too. This image will be deleted (or released from the ImageCache
  43878. if that's how it was created) by the splash screen object when
  43879. it is itself deleted.
  43880. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43881. should stay visible for. If the initialisation takes longer than
  43882. this time, the splash screen will wait for it to finish before
  43883. disappearing, but if initialisation is very quick, this lets
  43884. you make sure that people get a good look at your splash.
  43885. @param useDropShadow if true, the window will have a drop shadow
  43886. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43887. the mouse (anywhere)
  43888. */
  43889. void show (const String& title,
  43890. const Image& backgroundImage,
  43891. int minimumTimeToDisplayFor,
  43892. bool useDropShadow,
  43893. bool removeOnMouseClick = true);
  43894. /** Creates a SplashScreen object with a specified size.
  43895. For a custom splash screen, you can use this method to display it at a certain size
  43896. and then override the paint() method yourself to do whatever's necessary.
  43897. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43898. screen. This method will also dispatch any pending messages to make sure that when
  43899. it returns, the splash screen has been completely drawn, and your initialisation
  43900. code can carry on.
  43901. @param title the name to give the component
  43902. @param width the width to use
  43903. @param height the height to use
  43904. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43905. should stay visible for. If the initialisation takes longer than
  43906. this time, the splash screen will wait for it to finish before
  43907. disappearing, but if initialisation is very quick, this lets
  43908. you make sure that people get a good look at your splash.
  43909. @param useDropShadow if true, the window will have a drop shadow
  43910. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43911. the mouse (anywhere)
  43912. */
  43913. void show (const String& title,
  43914. int width,
  43915. int height,
  43916. int minimumTimeToDisplayFor,
  43917. bool useDropShadow,
  43918. bool removeOnMouseClick = true);
  43919. /** @internal */
  43920. void paint (Graphics& g);
  43921. /** @internal */
  43922. void timerCallback();
  43923. juce_UseDebuggingNewOperator
  43924. private:
  43925. Image backgroundImage;
  43926. Time earliestTimeToDelete;
  43927. int originalClickCounter;
  43928. SplashScreen (const SplashScreen&);
  43929. SplashScreen& operator= (const SplashScreen&);
  43930. };
  43931. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  43932. /*** End of inlined file: juce_SplashScreen.h ***/
  43933. #endif
  43934. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43935. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  43936. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43937. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43938. /**
  43939. A thread that automatically pops up a modal dialog box with a progress bar
  43940. and cancel button while it's busy running.
  43941. These are handy for performing some sort of task while giving the user feedback
  43942. about how long there is to go, etc.
  43943. E.g. @code
  43944. class MyTask : public ThreadWithProgressWindow
  43945. {
  43946. public:
  43947. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  43948. {
  43949. }
  43950. ~MyTask()
  43951. {
  43952. }
  43953. void run()
  43954. {
  43955. for (int i = 0; i < thingsToDo; ++i)
  43956. {
  43957. // must check this as often as possible, because this is
  43958. // how we know if the user's pressed 'cancel'
  43959. if (threadShouldExit())
  43960. break;
  43961. // this will update the progress bar on the dialog box
  43962. setProgress (i / (double) thingsToDo);
  43963. // ... do the business here...
  43964. }
  43965. }
  43966. };
  43967. void doTheTask()
  43968. {
  43969. MyTask m;
  43970. if (m.runThread())
  43971. {
  43972. // thread finished normally..
  43973. }
  43974. else
  43975. {
  43976. // user pressed the cancel button..
  43977. }
  43978. }
  43979. @endcode
  43980. @see Thread, AlertWindow
  43981. */
  43982. class JUCE_API ThreadWithProgressWindow : public Thread,
  43983. private Timer
  43984. {
  43985. public:
  43986. /** Creates the thread.
  43987. Initially, the dialog box won't be visible, it'll only appear when the
  43988. runThread() method is called.
  43989. @param windowTitle the title to go at the top of the dialog box
  43990. @param hasProgressBar whether the dialog box should have a progress bar (see
  43991. setProgress() )
  43992. @param hasCancelButton whether the dialog box should have a cancel button
  43993. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  43994. the thread to stop before killing it forcibly (see
  43995. Thread::stopThread() )
  43996. @param cancelButtonText the text that should be shown in the cancel button
  43997. (if it has one)
  43998. */
  43999. ThreadWithProgressWindow (const String& windowTitle,
  44000. bool hasProgressBar,
  44001. bool hasCancelButton,
  44002. int timeOutMsWhenCancelling = 10000,
  44003. const String& cancelButtonText = "Cancel");
  44004. /** Destructor. */
  44005. ~ThreadWithProgressWindow();
  44006. /** Starts the thread and waits for it to finish.
  44007. This will start the thread, make the dialog box appear, and wait until either
  44008. the thread finishes normally, or until the cancel button is pressed.
  44009. Before returning, the dialog box will be hidden.
  44010. @param threadPriority the priority to use when starting the thread - see
  44011. Thread::startThread() for values
  44012. @returns true if the thread finished normally; false if the user pressed cancel
  44013. */
  44014. bool runThread (int threadPriority = 5);
  44015. /** The thread should call this periodically to update the position of the progress bar.
  44016. @param newProgress the progress, from 0.0 to 1.0
  44017. @see setStatusMessage
  44018. */
  44019. void setProgress (double newProgress);
  44020. /** The thread can call this to change the message that's displayed in the dialog box.
  44021. */
  44022. void setStatusMessage (const String& newStatusMessage);
  44023. /** Returns the AlertWindow that is being used.
  44024. */
  44025. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  44026. juce_UseDebuggingNewOperator
  44027. private:
  44028. void timerCallback();
  44029. double progress;
  44030. ScopedPointer <AlertWindow> alertWindow;
  44031. String message;
  44032. CriticalSection messageLock;
  44033. const int timeOutMsWhenCancelling;
  44034. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  44035. ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  44036. };
  44037. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  44038. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  44039. #endif
  44040. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  44041. #endif
  44042. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  44043. #endif
  44044. #ifndef __JUCE_COLOUR_JUCEHEADER__
  44045. #endif
  44046. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  44047. #endif
  44048. #ifndef __JUCE_COLOURS_JUCEHEADER__
  44049. #endif
  44050. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  44051. #endif
  44052. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  44053. /*** Start of inlined file: juce_EdgeTable.h ***/
  44054. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  44055. #define __JUCE_EDGETABLE_JUCEHEADER__
  44056. class Path;
  44057. class Image;
  44058. /**
  44059. A table of horizontal scan-line segments - used for rasterising Paths.
  44060. @see Path, Graphics
  44061. */
  44062. class JUCE_API EdgeTable
  44063. {
  44064. public:
  44065. /** Creates an edge table containing a path.
  44066. A table is created with a fixed vertical range, and only sections of the path
  44067. which lie within this range will be added to the table.
  44068. @param clipLimits only the region of the path that lies within this area will be added
  44069. @param pathToAdd the path to add to the table
  44070. @param transform a transform to apply to the path being added
  44071. */
  44072. EdgeTable (const Rectangle<int>& clipLimits,
  44073. const Path& pathToAdd,
  44074. const AffineTransform& transform);
  44075. /** Creates an edge table containing a rectangle.
  44076. */
  44077. EdgeTable (const Rectangle<int>& rectangleToAdd);
  44078. /** Creates an edge table containing a rectangle list.
  44079. */
  44080. EdgeTable (const RectangleList& rectanglesToAdd);
  44081. /** Creates an edge table containing a rectangle.
  44082. */
  44083. EdgeTable (const Rectangle<float>& rectangleToAdd);
  44084. /** Creates a copy of another edge table. */
  44085. EdgeTable (const EdgeTable& other);
  44086. /** Copies from another edge table. */
  44087. EdgeTable& operator= (const EdgeTable& other);
  44088. /** Destructor. */
  44089. ~EdgeTable();
  44090. void clipToRectangle (const Rectangle<int>& r) throw();
  44091. void excludeRectangle (const Rectangle<int>& r) throw();
  44092. void clipToEdgeTable (const EdgeTable& other);
  44093. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw();
  44094. bool isEmpty() throw();
  44095. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  44096. void translate (float dx, int dy) throw();
  44097. /** Reduces the amount of space the table has allocated.
  44098. This will shrink the table down to use as little memory as possible - useful for
  44099. read-only tables that get stored and re-used for rendering.
  44100. */
  44101. void optimiseTable() throw();
  44102. /** Iterates the lines in the table, for rendering.
  44103. This function will iterate each line in the table, and call a user-defined class
  44104. to render each pixel or continuous line of pixels that the table contains.
  44105. @param iterationCallback this templated class must contain the following methods:
  44106. @code
  44107. inline void setEdgeTableYPos (int y);
  44108. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  44109. inline void handleEdgeTablePixelFull (int x) const;
  44110. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  44111. inline void handleEdgeTableLineFull (int x, int width) const;
  44112. @endcode
  44113. (these don't necessarily have to be 'const', but it might help it go faster)
  44114. */
  44115. template <class EdgeTableIterationCallback>
  44116. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  44117. {
  44118. const int* lineStart = table;
  44119. for (int y = 0; y < bounds.getHeight(); ++y)
  44120. {
  44121. const int* line = lineStart;
  44122. lineStart += lineStrideElements;
  44123. int numPoints = line[0];
  44124. if (--numPoints > 0)
  44125. {
  44126. int x = *++line;
  44127. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  44128. int levelAccumulator = 0;
  44129. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  44130. while (--numPoints >= 0)
  44131. {
  44132. const int level = *++line;
  44133. jassert (((unsigned int) level) < (unsigned int) 256);
  44134. const int endX = *++line;
  44135. jassert (endX >= x);
  44136. const int endOfRun = (endX >> 8);
  44137. if (endOfRun == (x >> 8))
  44138. {
  44139. // small segment within the same pixel, so just save it for the next
  44140. // time round..
  44141. levelAccumulator += (endX - x) * level;
  44142. }
  44143. else
  44144. {
  44145. // plot the fist pixel of this segment, including any accumulated
  44146. // levels from smaller segments that haven't been drawn yet
  44147. levelAccumulator += (0xff - (x & 0xff)) * level;
  44148. levelAccumulator >>= 8;
  44149. x >>= 8;
  44150. if (levelAccumulator > 0)
  44151. {
  44152. if (levelAccumulator >> 8)
  44153. iterationCallback.handleEdgeTablePixelFull (x);
  44154. else
  44155. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  44156. }
  44157. // if there's a run of similar pixels, do it all in one go..
  44158. if (level > 0)
  44159. {
  44160. jassert (endOfRun <= bounds.getRight());
  44161. const int numPix = endOfRun - ++x;
  44162. if (numPix > 0)
  44163. iterationCallback.handleEdgeTableLine (x, numPix, level);
  44164. }
  44165. // save the bit at the end to be drawn next time round the loop.
  44166. levelAccumulator = (endX & 0xff) * level;
  44167. }
  44168. x = endX;
  44169. }
  44170. levelAccumulator >>= 8;
  44171. if (levelAccumulator > 0)
  44172. {
  44173. x >>= 8;
  44174. jassert (x >= bounds.getX() && x < bounds.getRight());
  44175. if (levelAccumulator >> 8)
  44176. iterationCallback.handleEdgeTablePixelFull (x);
  44177. else
  44178. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  44179. }
  44180. }
  44181. }
  44182. }
  44183. juce_UseDebuggingNewOperator
  44184. private:
  44185. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  44186. HeapBlock<int> table;
  44187. Rectangle<int> bounds;
  44188. int maxEdgesPerLine, lineStrideElements;
  44189. bool needToCheckEmptinesss;
  44190. void addEdgePoint (int x, int y, int winding) throw();
  44191. void remapTableForNumEdges (int newNumEdgesPerLine) throw();
  44192. void intersectWithEdgeTableLine (int y, const int* otherLine) throw();
  44193. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  44194. void sanitiseLevels (bool useNonZeroWinding) throw();
  44195. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  44196. };
  44197. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  44198. /*** End of inlined file: juce_EdgeTable.h ***/
  44199. #endif
  44200. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  44201. /*** Start of inlined file: juce_FillType.h ***/
  44202. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  44203. #define __JUCE_FILLTYPE_JUCEHEADER__
  44204. /**
  44205. Represents a colour or fill pattern to use for rendering paths.
  44206. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  44207. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  44208. @see Graphics::setFillType, DrawablePath::setFill
  44209. */
  44210. class JUCE_API FillType
  44211. {
  44212. public:
  44213. /** Creates a default fill type, of solid black. */
  44214. FillType() throw();
  44215. /** Creates a fill type of a solid colour.
  44216. @see setColour
  44217. */
  44218. FillType (const Colour& colour) throw();
  44219. /** Creates a gradient fill type.
  44220. @see setGradient
  44221. */
  44222. FillType (const ColourGradient& gradient);
  44223. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  44224. and rotation of the pattern.
  44225. @see setTiledImage
  44226. */
  44227. FillType (const Image& image, const AffineTransform& transform) throw();
  44228. /** Creates a copy of another FillType. */
  44229. FillType (const FillType& other);
  44230. /** Makes a copy of another FillType. */
  44231. FillType& operator= (const FillType& other);
  44232. /** Destructor. */
  44233. ~FillType() throw();
  44234. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  44235. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  44236. /** Returns true if this is a gradient fill. */
  44237. bool isGradient() const throw() { return gradient != 0; }
  44238. /** Returns true if this is a tiled image pattern fill. */
  44239. bool isTiledImage() const throw() { return image.isValid(); }
  44240. /** Turns this object into a solid colour fill.
  44241. If the object was an image or gradient, those fields will no longer be valid. */
  44242. void setColour (const Colour& newColour) throw();
  44243. /** Turns this object into a gradient fill. */
  44244. void setGradient (const ColourGradient& newGradient);
  44245. /** Turns this object into a tiled image fill type. The transform allows you to set
  44246. the scaling, offset and rotation of the pattern.
  44247. */
  44248. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  44249. /** Changes the opacity that should be used.
  44250. If the fill is a solid colour, this just changes the opacity of that colour. For
  44251. gradients and image tiles, it changes the opacity that will be used for them.
  44252. */
  44253. void setOpacity (float newOpacity) throw();
  44254. /** Returns the current opacity to be applied to the colour, gradient, or image.
  44255. @see setOpacity
  44256. */
  44257. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  44258. /** Returns true if this fill type is completely transparent. */
  44259. bool isInvisible() const throw();
  44260. bool operator== (const FillType& other) const;
  44261. bool operator!= (const FillType& other) const;
  44262. /** The solid colour being used.
  44263. If the fill type is not a solid colour, the alpha channel of this colour indicates
  44264. the opacity that should be used for the fill, and the RGB channels are ignored.
  44265. */
  44266. Colour colour;
  44267. /** Returns the gradient that should be used for filling.
  44268. This will be zero if the object is some other type of fill.
  44269. If a gradient is active, the overall opacity with which it should be applied
  44270. is indicated by the alpha channel of the colour variable.
  44271. */
  44272. ScopedPointer <ColourGradient> gradient;
  44273. /** The image that should be used for tiling.
  44274. If an image fill is active, the overall opacity with which it should be applied
  44275. is indicated by the alpha channel of the colour variable.
  44276. */
  44277. Image image;
  44278. /** The transform that should be applied to the image or gradient that's being drawn.
  44279. */
  44280. AffineTransform transform;
  44281. juce_UseDebuggingNewOperator
  44282. };
  44283. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  44284. /*** End of inlined file: juce_FillType.h ***/
  44285. #endif
  44286. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  44287. #endif
  44288. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  44289. #endif
  44290. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44291. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  44292. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44293. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44294. /**
  44295. Interface class for graphics context objects, used internally by the Graphics class.
  44296. Users are not supposed to create instances of this class directly - do your drawing
  44297. via the Graphics object instead.
  44298. It's a base class for different types of graphics context, that may perform software-based
  44299. or OS-accelerated rendering.
  44300. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  44301. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  44302. context.
  44303. */
  44304. class JUCE_API LowLevelGraphicsContext
  44305. {
  44306. protected:
  44307. LowLevelGraphicsContext();
  44308. public:
  44309. virtual ~LowLevelGraphicsContext();
  44310. /** Returns true if this device is vector-based, e.g. a printer. */
  44311. virtual bool isVectorDevice() const = 0;
  44312. /** Moves the origin to a new position.
  44313. The co-ords are relative to the current origin, and indicate the new position
  44314. of (0, 0).
  44315. */
  44316. virtual void setOrigin (int x, int y) = 0;
  44317. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  44318. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  44319. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  44320. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  44321. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  44322. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  44323. virtual const Rectangle<int> getClipBounds() const = 0;
  44324. virtual bool isClipEmpty() const = 0;
  44325. virtual void saveState() = 0;
  44326. virtual void restoreState() = 0;
  44327. virtual void setFill (const FillType& fillType) = 0;
  44328. virtual void setOpacity (float newOpacity) = 0;
  44329. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  44330. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  44331. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  44332. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  44333. virtual void drawLine (const Line <float>& line) = 0;
  44334. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  44335. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  44336. virtual void setFont (const Font& newFont) = 0;
  44337. virtual const Font getFont() = 0;
  44338. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  44339. };
  44340. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44341. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  44342. #endif
  44343. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44344. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  44345. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44346. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44347. /**
  44348. An implementation of LowLevelGraphicsContext that turns the drawing operations
  44349. into a PostScript document.
  44350. */
  44351. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  44352. {
  44353. public:
  44354. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  44355. const String& documentTitle,
  44356. int totalWidth,
  44357. int totalHeight);
  44358. ~LowLevelGraphicsPostScriptRenderer();
  44359. bool isVectorDevice() const;
  44360. void setOrigin (int x, int y);
  44361. bool clipToRectangle (const Rectangle<int>& r);
  44362. bool clipToRectangleList (const RectangleList& clipRegion);
  44363. void excludeClipRectangle (const Rectangle<int>& r);
  44364. void clipToPath (const Path& path, const AffineTransform& transform);
  44365. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  44366. void saveState();
  44367. void restoreState();
  44368. bool clipRegionIntersects (const Rectangle<int>& r);
  44369. const Rectangle<int> getClipBounds() const;
  44370. bool isClipEmpty() const;
  44371. void setFill (const FillType& fillType);
  44372. void setOpacity (float opacity);
  44373. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44374. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44375. void fillPath (const Path& path, const AffineTransform& transform);
  44376. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  44377. void drawLine (const Line <float>& line);
  44378. void drawVerticalLine (int x, float top, float bottom);
  44379. void drawHorizontalLine (int x, float top, float bottom);
  44380. const Font getFont();
  44381. void setFont (const Font& newFont);
  44382. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44383. juce_UseDebuggingNewOperator
  44384. protected:
  44385. OutputStream& out;
  44386. int totalWidth, totalHeight;
  44387. bool needToClip;
  44388. Colour lastColour;
  44389. struct SavedState
  44390. {
  44391. SavedState();
  44392. ~SavedState();
  44393. RectangleList clip;
  44394. int xOffset, yOffset;
  44395. FillType fillType;
  44396. Font font;
  44397. private:
  44398. SavedState& operator= (const SavedState&);
  44399. };
  44400. OwnedArray <SavedState> stateStack;
  44401. void writeClip();
  44402. void writeColour (const Colour& colour);
  44403. void writePath (const Path& path) const;
  44404. void writeXY (float x, float y) const;
  44405. void writeTransform (const AffineTransform& trans) const;
  44406. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  44407. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  44408. LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  44409. };
  44410. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44411. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  44412. #endif
  44413. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44414. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44415. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44416. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44417. /**
  44418. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  44419. its rendering in memory.
  44420. User code is not supposed to create instances of this class directly - do all your
  44421. rendering via the Graphics class instead.
  44422. */
  44423. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  44424. {
  44425. public:
  44426. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  44427. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  44428. ~LowLevelGraphicsSoftwareRenderer();
  44429. bool isVectorDevice() const;
  44430. void setOrigin (int x, int y);
  44431. bool clipToRectangle (const Rectangle<int>& r);
  44432. bool clipToRectangleList (const RectangleList& clipRegion);
  44433. void excludeClipRectangle (const Rectangle<int>& r);
  44434. void clipToPath (const Path& path, const AffineTransform& transform);
  44435. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  44436. bool clipRegionIntersects (const Rectangle<int>& r);
  44437. const Rectangle<int> getClipBounds() const;
  44438. bool isClipEmpty() const;
  44439. void saveState();
  44440. void restoreState();
  44441. void setFill (const FillType& fillType);
  44442. void setOpacity (float opacity);
  44443. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44444. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44445. void fillPath (const Path& path, const AffineTransform& transform);
  44446. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  44447. void drawLine (const Line <float>& line);
  44448. void drawVerticalLine (int x, float top, float bottom);
  44449. void drawHorizontalLine (int x, float top, float bottom);
  44450. void setFont (const Font& newFont);
  44451. const Font getFont();
  44452. void drawGlyph (int glyphNumber, float x, float y);
  44453. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44454. juce_UseDebuggingNewOperator
  44455. protected:
  44456. Image image;
  44457. class GlyphCache;
  44458. class CachedGlyph;
  44459. class SavedState;
  44460. friend class ScopedPointer <SavedState>;
  44461. friend class OwnedArray <SavedState>;
  44462. friend class OwnedArray <CachedGlyph>;
  44463. ScopedPointer <SavedState> currentState;
  44464. OwnedArray <SavedState> stateStack;
  44465. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  44466. LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  44467. };
  44468. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44469. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44470. #endif
  44471. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  44472. #endif
  44473. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  44474. #endif
  44475. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44476. /*** Start of inlined file: juce_DrawableComposite.h ***/
  44477. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44478. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44479. /**
  44480. A drawable object which acts as a container for a set of other Drawables.
  44481. @see Drawable
  44482. */
  44483. class JUCE_API DrawableComposite : public Drawable,
  44484. public RelativeCoordinate::NamedCoordinateFinder
  44485. {
  44486. public:
  44487. /** Creates a composite Drawable. */
  44488. DrawableComposite();
  44489. /** Creates a copy of a DrawableComposite. */
  44490. DrawableComposite (const DrawableComposite& other);
  44491. /** Destructor. */
  44492. ~DrawableComposite();
  44493. /** Adds a new sub-drawable to this one.
  44494. This passes in a Drawable pointer for this object to look after. To add a copy
  44495. of a drawable, use the form of this method that takes a Drawable reference instead.
  44496. @param drawable the object to add - this will be deleted automatically
  44497. when no longer needed, so the caller mustn't keep any
  44498. pointers to it.
  44499. @param index where to insert it in the list of drawables. 0 is the back,
  44500. -1 is the front, or any value from 0 and getNumDrawables()
  44501. can be used
  44502. @see removeDrawable
  44503. */
  44504. void insertDrawable (Drawable* drawable, int index = -1);
  44505. /** Adds a new sub-drawable to this one.
  44506. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  44507. for this object to look after, use the form of this method that takes a Drawable
  44508. pointer instead.
  44509. @param drawable the object to add - an internal copy will be made of this object
  44510. @param index where to insert it in the list of drawables. 0 is the back,
  44511. -1 is the front, or any value from 0 and getNumDrawables()
  44512. can be used
  44513. @see removeDrawable
  44514. */
  44515. void insertDrawable (const Drawable& drawable, int index = -1);
  44516. /** Deletes one of the Drawable objects.
  44517. @param index the index of the drawable to delete, between 0
  44518. and (getNumDrawables() - 1).
  44519. @param deleteDrawable if this is true, the drawable that is removed will also
  44520. be deleted. If false, it'll just be removed.
  44521. @see insertDrawable, getNumDrawables
  44522. */
  44523. void removeDrawable (int index, bool deleteDrawable = true);
  44524. /** Returns the number of drawables contained inside this one.
  44525. @see getDrawable
  44526. */
  44527. int getNumDrawables() const throw() { return drawables.size(); }
  44528. /** Returns one of the drawables that are contained in this one.
  44529. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  44530. to find it.
  44531. The pointer returned is managed by this object and will be deleted when no longer
  44532. needed, so be careful what you do with it.
  44533. @see getNumDrawables
  44534. */
  44535. Drawable* getDrawable (int index) const throw() { return drawables [index]; }
  44536. /** Looks for a child drawable with the specified name. */
  44537. Drawable* getDrawableWithName (const String& name) const throw();
  44538. /** Brings one of the Drawables to the front.
  44539. @param index the index of the drawable to move, between 0
  44540. and (getNumDrawables() - 1).
  44541. @see insertDrawable, getNumDrawables
  44542. */
  44543. void bringToFront (int index);
  44544. /** Changes the main content area.
  44545. The content area is actually defined by the markers named "left", "right", "top" and
  44546. "bottom", but this method is a shortcut that sets them all at once.
  44547. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44548. */
  44549. const RelativeRectangle getContentArea() const;
  44550. /** Returns the main content rectangle.
  44551. The content area is actually defined by the markers named "left", "right", "top" and
  44552. "bottom", but this method is a shortcut that returns them all at once.
  44553. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44554. */
  44555. void setContentArea (const RelativeRectangle& newArea);
  44556. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44557. @see setContentArea
  44558. */
  44559. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  44560. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44561. @see setBoundingBox
  44562. */
  44563. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44564. /** Changes the bounding box transform to match the content area, so that any sub-items will
  44565. be drawn at their untransformed positions.
  44566. */
  44567. void resetBoundingBoxToContentArea();
  44568. /** Resets the content area and the bounding transform to fit around the area occupied
  44569. by the child components (ignoring any markers).
  44570. */
  44571. void resetContentAreaAndBoundingBoxToFitChildren();
  44572. /** Represents a named marker position.
  44573. @see DrawableComposite::getMarker
  44574. */
  44575. struct Marker
  44576. {
  44577. Marker (const Marker&);
  44578. Marker (const String& name, const RelativeCoordinate& position);
  44579. bool operator!= (const Marker&) const throw();
  44580. String name;
  44581. RelativeCoordinate position;
  44582. };
  44583. int getNumMarkers (bool xAxis) const throw();
  44584. const Marker* getMarker (bool xAxis, int index) const throw();
  44585. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position);
  44586. void removeMarker (bool xAxis, int index);
  44587. /** The name of the marker that defines the left edge of the content area. */
  44588. static const char* const contentLeftMarkerName;
  44589. /** The name of the marker that defines the right edge of the content area. */
  44590. static const char* const contentRightMarkerName;
  44591. /** The name of the marker that defines the top edge of the content area. */
  44592. static const char* const contentTopMarkerName;
  44593. /** The name of the marker that defines the bottom edge of the content area. */
  44594. static const char* const contentBottomMarkerName;
  44595. /** @internal */
  44596. void render (const Drawable::RenderingContext& context) const;
  44597. /** @internal */
  44598. const Rectangle<float> getBounds() const;
  44599. /** @internal */
  44600. bool hitTest (float x, float y) const;
  44601. /** @internal */
  44602. Drawable* createCopy() const;
  44603. /** @internal */
  44604. void invalidatePoints();
  44605. /** @internal */
  44606. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44607. /** @internal */
  44608. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44609. /** @internal */
  44610. static const Identifier valueTreeType;
  44611. /** @internal */
  44612. const Identifier getValueTreeType() const { return valueTreeType; }
  44613. /** @internal */
  44614. const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const;
  44615. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  44616. class ValueTreeWrapper : public ValueTreeWrapperBase
  44617. {
  44618. public:
  44619. ValueTreeWrapper (const ValueTree& state);
  44620. int getNumDrawables() const;
  44621. ValueTree getDrawableState (int index) const;
  44622. ValueTree getDrawableWithId (const String& objectId, bool recursive) const;
  44623. int indexOfDrawable (const ValueTree& item) const;
  44624. void addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager);
  44625. void moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager);
  44626. void removeDrawable (const ValueTree& child, UndoManager* undoManager);
  44627. const RelativeParallelogram getBoundingBox() const;
  44628. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44629. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  44630. const RelativeRectangle getContentArea() const;
  44631. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  44632. int getNumMarkers (bool xAxis) const;
  44633. const ValueTree getMarkerState (bool xAxis, int index) const;
  44634. const ValueTree getMarkerState (bool xAxis, const String& name) const;
  44635. bool containsMarker (bool xAxis, const ValueTree& state) const;
  44636. const Marker getMarker (bool xAxis, const ValueTree& state) const;
  44637. void setMarker (bool xAxis, const Marker& marker, UndoManager* undoManager);
  44638. void removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager);
  44639. static const Identifier nameProperty, posProperty;
  44640. private:
  44641. static const Identifier topLeft, topRight, bottomLeft, childGroupTag, markerGroupTagX,
  44642. markerGroupTagY, markerTag;
  44643. ValueTree getChildList() const;
  44644. ValueTree getChildListCreating (UndoManager* undoManager);
  44645. ValueTree getMarkerList (bool xAxis) const;
  44646. ValueTree getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  44647. };
  44648. juce_UseDebuggingNewOperator
  44649. private:
  44650. OwnedArray <Drawable> drawables;
  44651. RelativeParallelogram bounds;
  44652. OwnedArray <Marker> markersX, markersY;
  44653. const Rectangle<float> getUntransformedBounds (bool includeMarkers) const;
  44654. const AffineTransform calculateTransform() const;
  44655. DrawableComposite& operator= (const DrawableComposite&);
  44656. };
  44657. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44658. /*** End of inlined file: juce_DrawableComposite.h ***/
  44659. #endif
  44660. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44661. /*** Start of inlined file: juce_DrawableImage.h ***/
  44662. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44663. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44664. /**
  44665. A drawable object which is a bitmap image.
  44666. @see Drawable
  44667. */
  44668. class JUCE_API DrawableImage : public Drawable
  44669. {
  44670. public:
  44671. DrawableImage();
  44672. DrawableImage (const DrawableImage& other);
  44673. /** Destructor. */
  44674. ~DrawableImage();
  44675. /** Sets the image that this drawable will render. */
  44676. void setImage (const Image& imageToUse);
  44677. /** Returns the current image. */
  44678. const Image getImage() const { return image; }
  44679. /** Sets the opacity to use when drawing the image. */
  44680. void setOpacity (float newOpacity);
  44681. /** Returns the image's opacity. */
  44682. float getOpacity() const throw() { return opacity; }
  44683. /** Sets a colour to draw over the image's alpha channel.
  44684. By default this is transparent so isn't drawn, but if you set a non-transparent
  44685. colour here, then it will be overlaid on the image, using the image's alpha
  44686. channel as a mask.
  44687. This is handy for doing things like darkening or lightening an image by overlaying
  44688. it with semi-transparent black or white.
  44689. */
  44690. void setOverlayColour (const Colour& newOverlayColour);
  44691. /** Returns the overlay colour. */
  44692. const Colour& getOverlayColour() const throw() { return overlayColour; }
  44693. /** Sets the bounding box within which the image should be displayed. */
  44694. void setBoundingBox (const RelativeParallelogram& newBounds);
  44695. /** Returns the position to which the image's top-left corner should be remapped in the target
  44696. coordinate space when rendering this object.
  44697. @see setTransform
  44698. */
  44699. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44700. /** @internal */
  44701. void render (const Drawable::RenderingContext& context) const;
  44702. /** @internal */
  44703. const Rectangle<float> getBounds() const;
  44704. /** @internal */
  44705. bool hitTest (float x, float y) const;
  44706. /** @internal */
  44707. Drawable* createCopy() const;
  44708. /** @internal */
  44709. void invalidatePoints();
  44710. /** @internal */
  44711. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44712. /** @internal */
  44713. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44714. /** @internal */
  44715. static const Identifier valueTreeType;
  44716. /** @internal */
  44717. const Identifier getValueTreeType() const { return valueTreeType; }
  44718. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  44719. class ValueTreeWrapper : public ValueTreeWrapperBase
  44720. {
  44721. public:
  44722. ValueTreeWrapper (const ValueTree& state);
  44723. const var getImageIdentifier() const;
  44724. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  44725. Value getImageIdentifierValue (UndoManager* undoManager);
  44726. float getOpacity() const;
  44727. void setOpacity (float newOpacity, UndoManager* undoManager);
  44728. Value getOpacityValue (UndoManager* undoManager);
  44729. const Colour getOverlayColour() const;
  44730. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  44731. Value getOverlayColourValue (UndoManager* undoManager);
  44732. const RelativeParallelogram getBoundingBox() const;
  44733. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44734. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  44735. };
  44736. juce_UseDebuggingNewOperator
  44737. private:
  44738. Image image;
  44739. float opacity;
  44740. Colour overlayColour;
  44741. RelativeParallelogram bounds;
  44742. const AffineTransform calculateTransform() const;
  44743. DrawableImage& operator= (const DrawableImage&);
  44744. };
  44745. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44746. /*** End of inlined file: juce_DrawableImage.h ***/
  44747. #endif
  44748. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44749. /*** Start of inlined file: juce_DrawablePath.h ***/
  44750. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44751. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  44752. /**
  44753. A drawable object which renders a filled or outlined shape.
  44754. @see Drawable
  44755. */
  44756. class JUCE_API DrawablePath : public Drawable
  44757. {
  44758. public:
  44759. /** Creates a DrawablePath. */
  44760. DrawablePath();
  44761. DrawablePath (const DrawablePath& other);
  44762. /** Destructor. */
  44763. ~DrawablePath();
  44764. /** Changes the path that will be drawn.
  44765. @see setFillColour, setStrokeType
  44766. */
  44767. void setPath (const Path& newPath);
  44768. /** Sets a fill type for the path.
  44769. This colour is used to fill the path - if you don't want the path to be
  44770. filled (e.g. if you're just drawing an outline), set this to a transparent
  44771. colour.
  44772. @see setPath, setStrokeFill
  44773. */
  44774. void setFill (const FillType& newFill);
  44775. /** Returns the current fill type.
  44776. @see setFill
  44777. */
  44778. const FillType& getFill() const throw() { return mainFill; }
  44779. /** Sets the fill type with which the outline will be drawn.
  44780. @see setFill
  44781. */
  44782. void setStrokeFill (const FillType& newStrokeFill);
  44783. /** Returns the current stroke fill.
  44784. @see setStrokeFill
  44785. */
  44786. const FillType& getStrokeFill() const throw() { return strokeFill; }
  44787. /** Changes the properties of the outline that will be drawn around the path.
  44788. If the stroke has 0 thickness, no stroke will be drawn.
  44789. @see setStrokeThickness, setStrokeColour
  44790. */
  44791. void setStrokeType (const PathStrokeType& newStrokeType);
  44792. /** Changes the stroke thickness.
  44793. This is a shortcut for calling setStrokeType.
  44794. */
  44795. void setStrokeThickness (float newThickness);
  44796. /** Returns the current outline style. */
  44797. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  44798. /** Returns the current path. */
  44799. const Path& getPath() const;
  44800. /** Returns the current path for the outline. */
  44801. const Path& getStrokePath() const;
  44802. /** @internal */
  44803. void render (const Drawable::RenderingContext& context) const;
  44804. /** @internal */
  44805. const Rectangle<float> getBounds() const;
  44806. /** @internal */
  44807. bool hitTest (float x, float y) const;
  44808. /** @internal */
  44809. Drawable* createCopy() const;
  44810. /** @internal */
  44811. void invalidatePoints();
  44812. /** @internal */
  44813. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44814. /** @internal */
  44815. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44816. /** @internal */
  44817. static const Identifier valueTreeType;
  44818. /** @internal */
  44819. const Identifier getValueTreeType() const { return valueTreeType; }
  44820. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  44821. class ValueTreeWrapper : public ValueTreeWrapperBase
  44822. {
  44823. public:
  44824. ValueTreeWrapper (const ValueTree& state);
  44825. const FillType getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44826. ImageProvider* imageProvider) const;
  44827. ValueTree getMainFillState();
  44828. void setMainFill (const FillType& newFill, const RelativePoint* gradientPoint1,
  44829. const RelativePoint* gradientPoint2, const RelativePoint* gradientPoint3,
  44830. ImageProvider* imageProvider, UndoManager* undoManager);
  44831. const FillType getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44832. ImageProvider* imageProvider) const;
  44833. ValueTree getStrokeFillState();
  44834. void setStrokeFill (const FillType& newFill, const RelativePoint* gradientPoint1,
  44835. const RelativePoint* gradientPoint2, const RelativePoint* gradientPoint3,
  44836. ImageProvider* imageProvider, UndoManager* undoManager);
  44837. const PathStrokeType getStrokeType() const;
  44838. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager);
  44839. bool usesNonZeroWinding() const;
  44840. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  44841. class Element
  44842. {
  44843. public:
  44844. explicit Element (const ValueTree& state);
  44845. ~Element();
  44846. const Identifier getType() const throw() { return state.getType(); }
  44847. int getNumControlPoints() const throw();
  44848. const RelativePoint getControlPoint (int index) const;
  44849. Value getControlPointValue (int index, UndoManager* undoManager) const;
  44850. const RelativePoint getStartPoint() const;
  44851. const RelativePoint getEndPoint() const;
  44852. void setControlPoint (int index, const RelativePoint& point, UndoManager* undoManager);
  44853. float getLength (RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  44854. ValueTreeWrapper getParent() const;
  44855. Element getPreviousElement() const;
  44856. const String getModeOfEndPoint() const;
  44857. void setModeOfEndPoint (const String& newMode, UndoManager* undoManager);
  44858. void convertToLine (UndoManager* undoManager);
  44859. void convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager);
  44860. void convertToPathBreak (UndoManager* undoManager);
  44861. ValueTree insertPoint (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager);
  44862. void removePoint (UndoManager* undoManager);
  44863. float findProportionAlongLine (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  44864. static const Identifier mode, startSubPathElement, closeSubPathElement,
  44865. lineToElement, quadraticToElement, cubicToElement;
  44866. static const char* cornerMode;
  44867. static const char* roundedMode;
  44868. static const char* symmetricMode;
  44869. ValueTree state;
  44870. };
  44871. ValueTree getPathState();
  44872. static const Identifier fill, stroke, path, jointStyle, capStyle, strokeWidth,
  44873. nonZeroWinding, point1, point2, point3;
  44874. };
  44875. juce_UseDebuggingNewOperator
  44876. private:
  44877. FillType mainFill, strokeFill;
  44878. PathStrokeType strokeType;
  44879. ScopedPointer<RelativePointPath> relativePath;
  44880. mutable Path path, stroke;
  44881. mutable bool pathNeedsUpdating, strokeNeedsUpdating;
  44882. void updatePath() const;
  44883. void updateStroke() const;
  44884. bool isStrokeVisible() const throw();
  44885. DrawablePath& operator= (const DrawablePath&);
  44886. };
  44887. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  44888. /*** End of inlined file: juce_DrawablePath.h ***/
  44889. #endif
  44890. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44891. /*** Start of inlined file: juce_DrawableText.h ***/
  44892. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44893. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  44894. /**
  44895. A drawable object which renders a line of text.
  44896. @see Drawable
  44897. */
  44898. class JUCE_API DrawableText : public Drawable
  44899. {
  44900. public:
  44901. /** Creates a DrawableText object. */
  44902. DrawableText();
  44903. DrawableText (const DrawableText& other);
  44904. /** Destructor. */
  44905. ~DrawableText();
  44906. /** Sets the text to display.*/
  44907. void setText (const String& newText);
  44908. /** Sets the colour of the text. */
  44909. void setColour (const Colour& newColour);
  44910. /** Returns the current text colour. */
  44911. const Colour& getColour() const throw() { return colour; }
  44912. /** Sets the font to use.
  44913. Note that the font height and horizontal scale are actually based upon the position
  44914. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  44915. the height and scale control point will be moved to match the dimensions of the font supplied;
  44916. if it is false, then the new font's height and scale are ignored.
  44917. */
  44918. void setFont (const Font& newFont, bool applySizeAndScale);
  44919. /** Changes the justification of the text within the bounding box. */
  44920. void setJustification (const Justification& newJustification);
  44921. /** Returns the parallelogram that defines the text bounding box. */
  44922. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44923. /** Sets the bounding box that contains the text. */
  44924. void setBoundingBox (const RelativeParallelogram& newBounds);
  44925. /** Returns the point within the bounds that defines the font's size and scale. */
  44926. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  44927. /** Sets the control point that defines the font's height and horizontal scale.
  44928. This position is a point within the bounding box parallelogram, whose Y position (relative
  44929. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  44930. and its X defines the font's horizontal scale.
  44931. */
  44932. void setFontSizeControlPoint (const RelativePoint& newPoint);
  44933. /** @internal */
  44934. void render (const Drawable::RenderingContext& context) const;
  44935. /** @internal */
  44936. const Rectangle<float> getBounds() const;
  44937. /** @internal */
  44938. bool hitTest (float x, float y) const;
  44939. /** @internal */
  44940. Drawable* createCopy() const;
  44941. /** @internal */
  44942. void invalidatePoints();
  44943. /** @internal */
  44944. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44945. /** @internal */
  44946. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44947. /** @internal */
  44948. static const Identifier valueTreeType;
  44949. /** @internal */
  44950. const Identifier getValueTreeType() const { return valueTreeType; }
  44951. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  44952. class ValueTreeWrapper : public ValueTreeWrapperBase
  44953. {
  44954. public:
  44955. ValueTreeWrapper (const ValueTree& state);
  44956. const String getText() const;
  44957. void setText (const String& newText, UndoManager* undoManager);
  44958. Value getTextValue (UndoManager* undoManager);
  44959. const Colour getColour() const;
  44960. void setColour (const Colour& newColour, UndoManager* undoManager);
  44961. const Justification getJustification() const;
  44962. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  44963. const Font getFont() const;
  44964. void setFont (const Font& newFont, UndoManager* undoManager);
  44965. Value getFontValue (UndoManager* undoManager);
  44966. const RelativeParallelogram getBoundingBox() const;
  44967. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44968. const RelativePoint getFontSizeControlPoint() const;
  44969. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  44970. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  44971. };
  44972. juce_UseDebuggingNewOperator
  44973. private:
  44974. RelativeParallelogram bounds;
  44975. RelativePoint fontSizeControlPoint;
  44976. Font font;
  44977. String text;
  44978. Colour colour;
  44979. Justification justification;
  44980. DrawableText& operator= (const DrawableText&);
  44981. };
  44982. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  44983. /*** End of inlined file: juce_DrawableText.h ***/
  44984. #endif
  44985. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  44986. #endif
  44987. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44988. /*** Start of inlined file: juce_GlowEffect.h ***/
  44989. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44990. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  44991. /**
  44992. A component effect that adds a coloured blur around the component's contents.
  44993. (This will only work on non-opaque components).
  44994. @see Component::setComponentEffect, DropShadowEffect
  44995. */
  44996. class JUCE_API GlowEffect : public ImageEffectFilter
  44997. {
  44998. public:
  44999. /** Creates a default 'glow' effect.
  45000. To customise its appearance, use the setGlowProperties() method.
  45001. */
  45002. GlowEffect();
  45003. /** Destructor. */
  45004. ~GlowEffect();
  45005. /** Sets the glow's radius and colour.
  45006. The radius is how large the blur should be, and the colour is
  45007. used to render it (for a less intense glow, lower the colour's
  45008. opacity).
  45009. */
  45010. void setGlowProperties (float newRadius,
  45011. const Colour& newColour);
  45012. /** @internal */
  45013. void applyEffect (Image& sourceImage, Graphics& destContext);
  45014. juce_UseDebuggingNewOperator
  45015. private:
  45016. float radius;
  45017. Colour colour;
  45018. };
  45019. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  45020. /*** End of inlined file: juce_GlowEffect.h ***/
  45021. #endif
  45022. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  45023. #endif
  45024. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  45025. /*** Start of inlined file: juce_ReduceOpacityEffect.h ***/
  45026. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  45027. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  45028. /**
  45029. An effect filter that reduces the image's opacity.
  45030. This can be used to make a component (and its child components) more
  45031. transparent.
  45032. @see Component::setComponentEffect
  45033. */
  45034. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  45035. {
  45036. public:
  45037. /** Creates the effect object.
  45038. The opacity of the component to which the effect is applied will be
  45039. scaled by the given factor (in the range 0 to 1.0f).
  45040. */
  45041. ReduceOpacityEffect (float opacity = 1.0f);
  45042. /** Destructor. */
  45043. ~ReduceOpacityEffect();
  45044. /** Sets how much to scale the component's opacity.
  45045. @param newOpacity should be between 0 and 1.0f
  45046. */
  45047. void setOpacity (float newOpacity);
  45048. /** @internal */
  45049. void applyEffect (Image& sourceImage, Graphics& destContext);
  45050. juce_UseDebuggingNewOperator
  45051. private:
  45052. float opacity;
  45053. };
  45054. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  45055. /*** End of inlined file: juce_ReduceOpacityEffect.h ***/
  45056. #endif
  45057. #ifndef __JUCE_FONT_JUCEHEADER__
  45058. #endif
  45059. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  45060. #endif
  45061. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  45062. #endif
  45063. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  45064. #endif
  45065. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  45066. #endif
  45067. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  45068. #endif
  45069. #ifndef __JUCE_LINE_JUCEHEADER__
  45070. #endif
  45071. #ifndef __JUCE_PATH_JUCEHEADER__
  45072. #endif
  45073. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  45074. /*** Start of inlined file: juce_PathIterator.h ***/
  45075. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  45076. #define __JUCE_PATHITERATOR_JUCEHEADER__
  45077. /**
  45078. Flattens a Path object into a series of straight-line sections.
  45079. Use one of these to iterate through a Path object, and it will convert
  45080. all the curves into line sections so it's easy to render or perform
  45081. geometric operations on.
  45082. @see Path
  45083. */
  45084. class JUCE_API PathFlatteningIterator
  45085. {
  45086. public:
  45087. /** Creates a PathFlatteningIterator.
  45088. After creation, use the next() method to initialise the fields in the
  45089. object with the first line's position.
  45090. @param path the path to iterate along
  45091. @param transform a transform to apply to each point in the path being iterated
  45092. @param tolerence the amount by which the curves are allowed to deviate from the
  45093. lines into which they are being broken down - a higher tolerence
  45094. is a bit faster, but less smooth.
  45095. */
  45096. PathFlatteningIterator (const Path& path,
  45097. const AffineTransform& transform = AffineTransform::identity,
  45098. float tolerence = 6.0f);
  45099. /** Destructor. */
  45100. ~PathFlatteningIterator();
  45101. /** Fetches the next line segment from the path.
  45102. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  45103. so that they describe the new line segment.
  45104. @returns false when there are no more lines to fetch.
  45105. */
  45106. bool next();
  45107. float x1; /**< The x position of the start of the current line segment. */
  45108. float y1; /**< The y position of the start of the current line segment. */
  45109. float x2; /**< The x position of the end of the current line segment. */
  45110. float y2; /**< The y position of the end of the current line segment. */
  45111. /** Indicates whether the current line segment is closing a sub-path.
  45112. If the current line is the one that connects the end of a sub-path
  45113. back to the start again, this will be true.
  45114. */
  45115. bool closesSubPath;
  45116. /** The index of the current line within the current sub-path.
  45117. E.g. you can use this to see whether the line is the first one in the
  45118. subpath by seeing if it's 0.
  45119. */
  45120. int subPathIndex;
  45121. /** Returns true if the current segment is the last in the current sub-path. */
  45122. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  45123. && (index >= path.numElements || points [index] == Path::moveMarker); }
  45124. juce_UseDebuggingNewOperator
  45125. private:
  45126. const Path& path;
  45127. const AffineTransform transform;
  45128. float* points;
  45129. float tolerence, subPathCloseX, subPathCloseY;
  45130. const bool isIdentityTransform;
  45131. HeapBlock <float> stackBase;
  45132. float* stackPos;
  45133. size_t index, stackSize;
  45134. PathFlatteningIterator (const PathFlatteningIterator&);
  45135. PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  45136. };
  45137. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  45138. /*** End of inlined file: juce_PathIterator.h ***/
  45139. #endif
  45140. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  45141. #endif
  45142. #ifndef __JUCE_POINT_JUCEHEADER__
  45143. #endif
  45144. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45145. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  45146. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45147. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45148. /**
  45149. A rectangle whose co-ordinates can be defined in terms of absolute or
  45150. proportional distances.
  45151. Designed mainly for storing component positions, this gives you a lot of
  45152. control over how each co-ordinate is stored, either as an absolute position,
  45153. or as a proportion of the size of a parent rectangle.
  45154. It also allows you to define the anchor points by which the rectangle is
  45155. positioned, so for example you could specify that the top right of the
  45156. rectangle should be an absolute distance from its parent's bottom-right corner.
  45157. This object can be stored as a string, which takes the form "x y w h", including
  45158. symbols like '%' and letters to indicate the anchor point. See its toString()
  45159. method for more info.
  45160. Example usage:
  45161. @code
  45162. class MyComponent
  45163. {
  45164. void resized()
  45165. {
  45166. // this will set the child component's x to be 20% of our width, its y
  45167. // to be 30, its width to be 150, and its height to be 50% of our
  45168. // height..
  45169. const PositionedRectangle pos1 ("20% 30 150 50%");
  45170. pos1.applyToComponent (*myChildComponent1);
  45171. // this will inset the child component with a gap of 10 pixels
  45172. // around each of its edges..
  45173. const PositionedRectangle pos2 ("10 10 20M 20M");
  45174. pos2.applyToComponent (*myChildComponent2);
  45175. }
  45176. };
  45177. @endcode
  45178. */
  45179. class JUCE_API PositionedRectangle
  45180. {
  45181. public:
  45182. /** Creates an empty rectangle with all co-ordinates set to zero.
  45183. The default anchor point is top-left; the default
  45184. */
  45185. PositionedRectangle() throw();
  45186. /** Initialises a PositionedRectangle from a saved string version.
  45187. The string must be in the format generated by toString().
  45188. */
  45189. PositionedRectangle (const String& stringVersion) throw();
  45190. /** Creates a copy of another PositionedRectangle. */
  45191. PositionedRectangle (const PositionedRectangle& other) throw();
  45192. /** Copies another PositionedRectangle. */
  45193. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  45194. /** Destructor. */
  45195. ~PositionedRectangle() throw();
  45196. /** Returns a string version of this position, from which it can later be
  45197. re-generated.
  45198. The format is four co-ordinates, "x y w h".
  45199. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  45200. - If a co-ordinate is proportional to its parent's width or height, it is stored
  45201. as a percentage, e.g. "80%".
  45202. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  45203. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  45204. the parent's right-hand edge.
  45205. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  45206. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  45207. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  45208. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  45209. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  45210. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  45211. has "c" appended to it. So "-50Rc" would mean that this component's
  45212. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  45213. this component's centre should be placed 40% across the parent's width.
  45214. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  45215. the number has "M" appended to it.
  45216. To reload a stored string, use the constructor that takes a string parameter.
  45217. */
  45218. const String toString() const throw();
  45219. /** Calculates the absolute position, given the size of the space that
  45220. it should go in.
  45221. This will work out any proportional distances and sizes relative to the
  45222. target rectangle, and will return the absolute position.
  45223. @see applyToComponent
  45224. */
  45225. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  45226. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  45227. */
  45228. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  45229. double& x,
  45230. double& y,
  45231. double& width,
  45232. double& height) const throw();
  45233. /** This sets the bounds of the given component to this position.
  45234. This is equivalent to writing:
  45235. @code
  45236. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  45237. @endcode
  45238. @see getRectangle, updateFromComponent
  45239. */
  45240. void applyToComponent (Component& comp) const throw();
  45241. /** Updates this object's co-ordinates to match the given rectangle.
  45242. This will set all co-ordinates based on the given rectangle, re-calculating
  45243. any proportional distances, and using the current anchor points.
  45244. So for example if the x co-ordinate mode is currently proportional, this will
  45245. re-calculate x based on the rectangle's relative position within the target
  45246. rectangle's width.
  45247. If the target rectangle's width or height are zero then it may not be possible
  45248. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  45249. will not be changed.
  45250. */
  45251. void updateFrom (const Rectangle<int>& newPosition,
  45252. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45253. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  45254. */
  45255. void updateFromDouble (double x, double y, double width, double height,
  45256. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45257. /** Updates this object's co-ordinates to match the bounds of this component.
  45258. This is equivalent to calling updateFrom() with the component's bounds and
  45259. it parent size.
  45260. If the component doesn't currently have a parent, then proportional co-ordinates
  45261. might not be updated because it would need to know the parent's size to do the
  45262. maths for this.
  45263. */
  45264. void updateFromComponent (const Component& comp) throw();
  45265. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  45266. enum AnchorPoint
  45267. {
  45268. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  45269. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  45270. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  45271. };
  45272. /** Specifies how an x or y co-ordinate should be interpreted. */
  45273. enum PositionMode
  45274. {
  45275. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  45276. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  45277. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  45278. 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. */
  45279. };
  45280. /** Specifies how the width or height should be interpreted. */
  45281. enum SizeMode
  45282. {
  45283. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  45284. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  45285. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  45286. };
  45287. /** Sets all options for all co-ordinates.
  45288. This requires a reference rectangle to be specified, because if you're changing any
  45289. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  45290. the co-ordinates, and will need to know the parent size so it can calculate this.
  45291. */
  45292. void setModes (const AnchorPoint xAnchorMode,
  45293. const PositionMode xPositionMode,
  45294. const AnchorPoint yAnchorMode,
  45295. const PositionMode yPositionMode,
  45296. const SizeMode widthMode,
  45297. const SizeMode heightMode,
  45298. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45299. /** Returns the anchoring mode for the x co-ordinate.
  45300. To change any of the modes, use setModes().
  45301. */
  45302. AnchorPoint getAnchorPointX() const throw();
  45303. /** Returns the positioning mode for the x co-ordinate.
  45304. To change any of the modes, use setModes().
  45305. */
  45306. PositionMode getPositionModeX() const throw();
  45307. /** Returns the raw x co-ordinate.
  45308. If the x position mode is absolute, then this will be the absolute value. If it's
  45309. proportional, then this will be a fractional proportion, where 1.0 means the full
  45310. width of the parent space.
  45311. */
  45312. double getX() const throw() { return x; }
  45313. /** Sets the raw value of the x co-ordinate.
  45314. See getX() for the meaning of this value.
  45315. */
  45316. void setX (const double newX) throw() { x = newX; }
  45317. /** Returns the anchoring mode for the y co-ordinate.
  45318. To change any of the modes, use setModes().
  45319. */
  45320. AnchorPoint getAnchorPointY() const throw();
  45321. /** Returns the positioning mode for the y co-ordinate.
  45322. To change any of the modes, use setModes().
  45323. */
  45324. PositionMode getPositionModeY() const throw();
  45325. /** Returns the raw y co-ordinate.
  45326. If the y position mode is absolute, then this will be the absolute value. If it's
  45327. proportional, then this will be a fractional proportion, where 1.0 means the full
  45328. height of the parent space.
  45329. */
  45330. double getY() const throw() { return y; }
  45331. /** Sets the raw value of the y co-ordinate.
  45332. See getY() for the meaning of this value.
  45333. */
  45334. void setY (const double newY) throw() { y = newY; }
  45335. /** Returns the mode used to calculate the width.
  45336. To change any of the modes, use setModes().
  45337. */
  45338. SizeMode getWidthMode() const throw();
  45339. /** Returns the raw width value.
  45340. If the width mode is absolute, then this will be the absolute value. If the mode is
  45341. proportional, then this will be a fractional proportion, where 1.0 means the full
  45342. width of the parent space.
  45343. */
  45344. double getWidth() const throw() { return w; }
  45345. /** Sets the raw width value.
  45346. See getWidth() for the details about what this value means.
  45347. */
  45348. void setWidth (const double newWidth) throw() { w = newWidth; }
  45349. /** Returns the mode used to calculate the height.
  45350. To change any of the modes, use setModes().
  45351. */
  45352. SizeMode getHeightMode() const throw();
  45353. /** Returns the raw height value.
  45354. If the height mode is absolute, then this will be the absolute value. If the mode is
  45355. proportional, then this will be a fractional proportion, where 1.0 means the full
  45356. height of the parent space.
  45357. */
  45358. double getHeight() const throw() { return h; }
  45359. /** Sets the raw height value.
  45360. See getHeight() for the details about what this value means.
  45361. */
  45362. void setHeight (const double newHeight) throw() { h = newHeight; }
  45363. /** If the size and position are constance, and wouldn't be affected by changes
  45364. in the parent's size, then this will return true.
  45365. */
  45366. bool isPositionAbsolute() const throw();
  45367. /** Compares two objects. */
  45368. bool operator== (const PositionedRectangle& other) const throw();
  45369. /** Compares two objects. */
  45370. bool operator!= (const PositionedRectangle& other) const throw();
  45371. juce_UseDebuggingNewOperator
  45372. private:
  45373. double x, y, w, h;
  45374. uint8 xMode, yMode, wMode, hMode;
  45375. void addPosDescription (String& result, uint8 mode, double value) const throw();
  45376. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  45377. void decodePosString (const String& s, uint8& mode, double& value) throw();
  45378. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  45379. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  45380. uint8 xMode, uint8 wMode,
  45381. int parentPos, int parentSize) const throw();
  45382. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  45383. uint8 xMode, uint8 wMode,
  45384. int parentPos, int parentSize) const throw();
  45385. };
  45386. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45387. /*** End of inlined file: juce_PositionedRectangle.h ***/
  45388. #endif
  45389. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  45390. #endif
  45391. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  45392. #endif
  45393. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  45394. #endif
  45395. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  45396. /*** Start of inlined file: juce_CameraDevice.h ***/
  45397. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  45398. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  45399. #if JUCE_USE_CAMERA || DOXYGEN
  45400. /**
  45401. Controls any video capture devices that might be available.
  45402. Use getAvailableDevices() to list the devices that are attached to the
  45403. system, then call openDevice to open one for use. Once you have a CameraDevice
  45404. object, you can get a viewer component from it, and use its methods to
  45405. stream to a file or capture still-frames.
  45406. */
  45407. class JUCE_API CameraDevice
  45408. {
  45409. public:
  45410. /** Destructor. */
  45411. virtual ~CameraDevice();
  45412. /** Returns a list of the available cameras on this machine.
  45413. You can open one of these devices by calling openDevice().
  45414. */
  45415. static const StringArray getAvailableDevices();
  45416. /** Opens a camera device.
  45417. The index parameter indicates which of the items returned by getAvailableDevices()
  45418. to open.
  45419. The size constraints allow the method to choose between different resolutions if
  45420. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  45421. then these will be ignored.
  45422. */
  45423. static CameraDevice* openDevice (int deviceIndex,
  45424. int minWidth = 128, int minHeight = 64,
  45425. int maxWidth = 1024, int maxHeight = 768);
  45426. /** Returns the name of this device */
  45427. const String getName() const { return name; }
  45428. /** Creates a component that can be used to display a preview of the
  45429. video from this camera.
  45430. */
  45431. Component* createViewerComponent();
  45432. /** Starts recording video to the specified file.
  45433. You should use getFileExtension() to find out the correct extension to
  45434. use for your filename.
  45435. If the file exists, it will be deleted before the recording starts.
  45436. This method may not start recording instantly, so if you need to know the
  45437. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  45438. after the recording has finished.
  45439. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  45440. or may not be used, depending on the driver.
  45441. */
  45442. void startRecordingToFile (const File& file, int quality = 2);
  45443. /** Stops recording, after a call to startRecordingToFile().
  45444. */
  45445. void stopRecording();
  45446. /** Returns the file extension that should be used for the files
  45447. that you pass to startRecordingToFile().
  45448. This may be platform-specific, e.g. ".mov" or ".avi".
  45449. */
  45450. static const String getFileExtension();
  45451. /** After calling stopRecording(), this method can be called to return the timestamp
  45452. of the first frame that was written to the file.
  45453. */
  45454. const Time getTimeOfFirstRecordedFrame() const;
  45455. /**
  45456. Receives callbacks with images from a CameraDevice.
  45457. @see CameraDevice::addListener
  45458. */
  45459. class JUCE_API Listener
  45460. {
  45461. public:
  45462. Listener() {}
  45463. virtual ~Listener() {}
  45464. /** This method is called when a new image arrives.
  45465. This may be called by any thread, so be careful about thread-safety,
  45466. and make sure that you process the data as quickly as possible to
  45467. avoid glitching!
  45468. */
  45469. virtual void imageReceived (const Image& image) = 0;
  45470. };
  45471. /** Adds a listener to receive images from the camera.
  45472. Be very careful not to delete the listener without first removing it by calling
  45473. removeListener().
  45474. */
  45475. void addListener (Listener* listenerToAdd);
  45476. /** Removes a listener that was previously added with addListener().
  45477. */
  45478. void removeListener (Listener* listenerToRemove);
  45479. juce_UseDebuggingNewOperator
  45480. protected:
  45481. /** @internal */
  45482. CameraDevice (const String& name, int index);
  45483. private:
  45484. void* internal;
  45485. bool isRecording;
  45486. String name;
  45487. CameraDevice (const CameraDevice&);
  45488. CameraDevice& operator= (const CameraDevice&);
  45489. };
  45490. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  45491. typedef CameraDevice::Listener CameraImageListener;
  45492. #endif
  45493. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  45494. /*** End of inlined file: juce_CameraDevice.h ***/
  45495. #endif
  45496. #ifndef __JUCE_IMAGE_JUCEHEADER__
  45497. #endif
  45498. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45499. /*** Start of inlined file: juce_ImageCache.h ***/
  45500. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45501. #define __JUCE_IMAGECACHE_JUCEHEADER__
  45502. /**
  45503. A global cache of images that have been loaded from files or memory.
  45504. If you're loading an image and may need to use the image in more than one
  45505. place, this is used to allow the same image to be shared rather than loading
  45506. multiple copies into memory.
  45507. Another advantage is that after images are released, they will be kept in
  45508. memory for a few seconds before it is actually deleted, so if you're repeatedly
  45509. loading/deleting the same image, it'll reduce the chances of having to reload it
  45510. each time.
  45511. @see Image, ImageFileFormat
  45512. */
  45513. class JUCE_API ImageCache
  45514. {
  45515. public:
  45516. /** Loads an image from a file, (or just returns the image if it's already cached).
  45517. If the cache already contains an image that was loaded from this file,
  45518. that image will be returned. Otherwise, this method will try to load the
  45519. file, add it to the cache, and return it.
  45520. Remember that the image returned is shared, so drawing into it might
  45521. affect other things that are using it! If you want to draw on it, first
  45522. call Image::duplicateIfShared()
  45523. @param file the file to try to load
  45524. @returns the image, or null if it there was an error loading it
  45525. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45526. */
  45527. static const Image getFromFile (const File& file);
  45528. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  45529. If the cache already contains an image that was loaded from this block of memory,
  45530. that image will be returned. Otherwise, this method will try to load the
  45531. file, add it to the cache, and return it.
  45532. Remember that the image returned is shared, so drawing into it might
  45533. affect other things that are using it! If you want to draw on it, first
  45534. call Image::duplicateIfShared()
  45535. @param imageData the block of memory containing the image data
  45536. @param dataSize the data size in bytes
  45537. @returns the image, or an invalid image if it there was an error loading it
  45538. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45539. */
  45540. static const Image getFromMemory (const void* imageData, int dataSize);
  45541. /** Checks the cache for an image with a particular hashcode.
  45542. If there's an image in the cache with this hashcode, it will be returned,
  45543. otherwise it will return an invalid image.
  45544. @param hashCode the hash code that was associated with the image by addImageToCache()
  45545. @see addImageToCache
  45546. */
  45547. static const Image getFromHashCode (int64 hashCode);
  45548. /** Adds an image to the cache with a user-defined hash-code.
  45549. The image passed-in will be referenced (not copied) by the cache, so it's probably
  45550. a good idea not to draw into it after adding it, otherwise this will affect all
  45551. instances of it that may be in use.
  45552. @param image the image to add
  45553. @param hashCode the hash-code to associate with it
  45554. @see getFromHashCode
  45555. */
  45556. static void addImageToCache (const Image& image, int64 hashCode);
  45557. /** Changes the amount of time before an unused image will be removed from the cache.
  45558. By default this is about 5 seconds.
  45559. */
  45560. static void setCacheTimeout (int millisecs);
  45561. juce_UseDebuggingNewOperator
  45562. private:
  45563. class Pimpl;
  45564. ImageCache();
  45565. ImageCache (const ImageCache&);
  45566. ImageCache& operator= (const ImageCache&);
  45567. ~ImageCache();
  45568. };
  45569. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  45570. /*** End of inlined file: juce_ImageCache.h ***/
  45571. #endif
  45572. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45573. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  45574. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45575. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45576. /**
  45577. Represents a filter kernel to use in convoluting an image.
  45578. @see Image::applyConvolution
  45579. */
  45580. class JUCE_API ImageConvolutionKernel
  45581. {
  45582. public:
  45583. /** Creates an empty convulution kernel.
  45584. @param size the length of each dimension of the kernel, so e.g. if the size
  45585. is 5, it will create a 5x5 kernel
  45586. */
  45587. ImageConvolutionKernel (int size);
  45588. /** Destructor. */
  45589. ~ImageConvolutionKernel();
  45590. /** Resets all values in the kernel to zero. */
  45591. void clear();
  45592. /** Returns one of the kernel values. */
  45593. float getKernelValue (int x, int y) const throw();
  45594. /** Sets the value of a specific cell in the kernel.
  45595. The x and y parameters must be in the range 0 < x < getKernelSize().
  45596. @see setOverallSum
  45597. */
  45598. void setKernelValue (int x, int y, float value) throw();
  45599. /** Rescales all values in the kernel to make the total add up to a fixed value.
  45600. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  45601. */
  45602. void setOverallSum (float desiredTotalSum);
  45603. /** Multiplies all values in the kernel by a value. */
  45604. void rescaleAllValues (float multiplier);
  45605. /** Intialises the kernel for a gaussian blur.
  45606. @param blurRadius this may be larger or smaller than the kernel's actual
  45607. size but this will obviously be wasteful or clip at the
  45608. edges. Ideally the kernel should be just larger than
  45609. (blurRadius * 2).
  45610. */
  45611. void createGaussianBlur (float blurRadius);
  45612. /** Returns the size of the kernel.
  45613. E.g. if it's a 3x3 kernel, this returns 3.
  45614. */
  45615. int getKernelSize() const { return size; }
  45616. /** Applies the kernel to an image.
  45617. @param destImage the image that will receive the resultant convoluted pixels.
  45618. @param sourceImage the source image to read from - this can be the same image as
  45619. the destination, but if different, it must be exactly the same
  45620. size and format.
  45621. @param destinationArea the region of the image to apply the filter to
  45622. */
  45623. void applyToImage (Image& destImage,
  45624. const Image& sourceImage,
  45625. const Rectangle<int>& destinationArea) const;
  45626. juce_UseDebuggingNewOperator
  45627. private:
  45628. HeapBlock <float> values;
  45629. const int size;
  45630. // no reason not to implement these one day..
  45631. ImageConvolutionKernel (const ImageConvolutionKernel&);
  45632. ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  45633. };
  45634. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45635. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  45636. #endif
  45637. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45638. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  45639. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45640. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45641. /**
  45642. Base-class for codecs that can read and write image file formats such
  45643. as PNG, JPEG, etc.
  45644. This class also contains static methods to make it easy to load images
  45645. from files, streams or from memory.
  45646. @see Image, ImageCache
  45647. */
  45648. class JUCE_API ImageFileFormat
  45649. {
  45650. protected:
  45651. /** Creates an ImageFormat. */
  45652. ImageFileFormat() {}
  45653. public:
  45654. /** Destructor. */
  45655. virtual ~ImageFileFormat() {}
  45656. /** Returns a description of this file format.
  45657. E.g. "JPEG", "PNG"
  45658. */
  45659. virtual const String getFormatName() = 0;
  45660. /** Returns true if the given stream seems to contain data that this format
  45661. understands.
  45662. The format class should only read the first few bytes of the stream and sniff
  45663. for header bytes that it understands.
  45664. @see decodeImage
  45665. */
  45666. virtual bool canUnderstand (InputStream& input) = 0;
  45667. /** Tries to decode and return an image from the given stream.
  45668. This will be called for an image format after calling its canUnderStand() method
  45669. to see if it can handle the stream.
  45670. @param input the stream to read the data from. The stream will be positioned
  45671. at the start of the image data (but this may not necessarily
  45672. be position 0)
  45673. @returns the image that was decoded, or an invalid image if it fails.
  45674. @see loadFrom
  45675. */
  45676. virtual const Image decodeImage (InputStream& input) = 0;
  45677. /** Attempts to write an image to a stream.
  45678. To specify extra information like encoding quality, there will be appropriate parameters
  45679. in the subclasses of the specific file types.
  45680. @returns true if it nothing went wrong.
  45681. */
  45682. virtual bool writeImageToStream (const Image& sourceImage,
  45683. OutputStream& destStream) = 0;
  45684. /** Tries the built-in decoders to see if it can find one to read this stream.
  45685. There are currently built-in decoders for PNG, JPEG and GIF formats.
  45686. The object that is returned should not be deleted by the caller.
  45687. @see canUnderstand, decodeImage, loadFrom
  45688. */
  45689. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  45690. /** Tries to load an image from a stream.
  45691. This will use the findImageFormatForStream() method to locate a suitable
  45692. codec, and use that to load the image.
  45693. @returns the image that was decoded, or an invalid image if it fails.
  45694. */
  45695. static const Image loadFrom (InputStream& input);
  45696. /** Tries to load an image from a file.
  45697. This will use the findImageFormatForStream() method to locate a suitable
  45698. codec, and use that to load the image.
  45699. @returns the image that was decoded, or an invalid image if it fails.
  45700. */
  45701. static const Image loadFrom (const File& file);
  45702. /** Tries to load an image from a block of raw image data.
  45703. This will use the findImageFormatForStream() method to locate a suitable
  45704. codec, and use that to load the image.
  45705. @returns the image that was decoded, or an invalid image if it fails.
  45706. */
  45707. static const Image loadFrom (const void* rawData,
  45708. const int numBytesOfData);
  45709. };
  45710. /**
  45711. A type of ImageFileFormat for reading and writing PNG files.
  45712. @see ImageFileFormat, JPEGImageFormat
  45713. */
  45714. class JUCE_API PNGImageFormat : public ImageFileFormat
  45715. {
  45716. public:
  45717. PNGImageFormat();
  45718. ~PNGImageFormat();
  45719. const String getFormatName();
  45720. bool canUnderstand (InputStream& input);
  45721. const Image decodeImage (InputStream& input);
  45722. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45723. };
  45724. /**
  45725. A type of ImageFileFormat for reading and writing JPEG files.
  45726. @see ImageFileFormat, PNGImageFormat
  45727. */
  45728. class JUCE_API JPEGImageFormat : public ImageFileFormat
  45729. {
  45730. public:
  45731. JPEGImageFormat();
  45732. ~JPEGImageFormat();
  45733. /** Specifies the quality to be used when writing a JPEG file.
  45734. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  45735. any negative value is "default" quality
  45736. */
  45737. void setQuality (const float newQuality);
  45738. const String getFormatName();
  45739. bool canUnderstand (InputStream& input);
  45740. const Image decodeImage (InputStream& input);
  45741. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45742. private:
  45743. float quality;
  45744. };
  45745. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45746. /*** End of inlined file: juce_ImageFileFormat.h ***/
  45747. #endif
  45748. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  45749. #endif
  45750. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45751. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  45752. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45753. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45754. /**
  45755. A class to take care of the logic involved with the loading/saving of some kind
  45756. of document.
  45757. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  45758. functions you need for documents that get saved to a file, so this class attempts
  45759. to abstract most of the boring stuff.
  45760. Your subclass should just implement all the pure virtual methods, and you can
  45761. then use the higher-level public methods to do the load/save dialogs, to warn the user
  45762. about overwriting files, etc.
  45763. The document object keeps track of whether it has changed since it was last saved or
  45764. loaded, so when you change something, call its changed() method. This will set a
  45765. flag so it knows it needs saving, and will also broadcast a change message using the
  45766. ChangeBroadcaster base class.
  45767. @see ChangeBroadcaster
  45768. */
  45769. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  45770. {
  45771. public:
  45772. /** Creates a FileBasedDocument.
  45773. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  45774. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  45775. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  45776. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  45777. */
  45778. FileBasedDocument (const String& fileExtension,
  45779. const String& fileWildCard,
  45780. const String& openFileDialogTitle,
  45781. const String& saveFileDialogTitle);
  45782. /** Destructor. */
  45783. virtual ~FileBasedDocument();
  45784. /** Returns true if the changed() method has been called since the file was
  45785. last saved or loaded.
  45786. @see resetChangedFlag, changed
  45787. */
  45788. bool hasChangedSinceSaved() const { return changedSinceSave; }
  45789. /** Called to indicate that the document has changed and needs saving.
  45790. This method will also trigger a change message to be sent out using the
  45791. ChangeBroadcaster base class.
  45792. After calling the method, the hasChangedSinceSaved() method will return true, until
  45793. it is reset either by saving to a file or using the resetChangedFlag() method.
  45794. @see hasChangedSinceSaved, resetChangedFlag
  45795. */
  45796. virtual void changed();
  45797. /** Sets the state of the 'changed' flag.
  45798. The 'changed' flag is set to true when the changed() method is called - use this method
  45799. to reset it or to set it without also broadcasting a change message.
  45800. @see changed, hasChangedSinceSaved
  45801. */
  45802. void setChangedFlag (bool hasChanged);
  45803. /** Tries to open a file.
  45804. If the file opens correctly, the document's file (see the getFile() method) is set
  45805. to this new one; if it fails, the document's file is left unchanged, and optionally
  45806. a message box is shown telling the user there was an error.
  45807. @returns true if the new file loaded successfully
  45808. @see loadDocument, loadFromUserSpecifiedFile
  45809. */
  45810. bool loadFrom (const File& fileToLoadFrom,
  45811. bool showMessageOnFailure);
  45812. /** Asks the user for a file and tries to load it.
  45813. This will pop up a dialog box using the title, file extension and
  45814. wildcard specified in the document's constructor, and asks the user
  45815. for a file. If they pick one, the loadFrom() method is used to
  45816. try to load it, optionally showing a message if it fails.
  45817. @returns true if a file was loaded; false if the user cancelled or if they
  45818. picked a file which failed to load correctly
  45819. @see loadFrom
  45820. */
  45821. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  45822. /** A set of possible outcomes of one of the save() methods
  45823. */
  45824. enum SaveResult
  45825. {
  45826. savedOk = 0, /**< indicates that a file was saved successfully. */
  45827. userCancelledSave, /**< indicates that the user aborted the save operation. */
  45828. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  45829. };
  45830. /** Tries to save the document to the last file it was saved or loaded from.
  45831. This will always try to write to the file, even if the document isn't flagged as
  45832. having changed.
  45833. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  45834. true, it will prompt the user to pick a file, as if
  45835. saveAsInteractive() was called.
  45836. @param showMessageOnFailure if true it will show a warning message when if the
  45837. save operation fails
  45838. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  45839. */
  45840. SaveResult save (bool askUserForFileIfNotSpecified,
  45841. bool showMessageOnFailure);
  45842. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  45843. it if they say yes.
  45844. If you've got a document open and want to close it (e.g. to quit the app), this is the
  45845. method to call.
  45846. If the document doesn't need saving it'll return the value savedOk so
  45847. you can go ahead and delete the document.
  45848. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  45849. return savedOk, so again, you can safely delete the document.
  45850. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  45851. close-document operation.
  45852. And if they click "save changes", it'll try to save and either return savedOk, or
  45853. failedToWriteToFile if there was a problem.
  45854. @see save, saveAs, saveAsInteractive
  45855. */
  45856. SaveResult saveIfNeededAndUserAgrees();
  45857. /** Tries to save the document to a specified file.
  45858. If this succeeds, it'll also change the document's internal file (as returned by
  45859. the getFile() method). If it fails, the file will be left unchanged.
  45860. @param newFile the file to try to write to
  45861. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45862. the user first if they want to overwrite it
  45863. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  45864. use the saveAsInteractive() method to ask the user for a
  45865. filename
  45866. @param showMessageOnFailure if true and the write operation fails, it'll show
  45867. a message box to warn the user
  45868. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  45869. */
  45870. SaveResult saveAs (const File& newFile,
  45871. bool warnAboutOverwritingExistingFiles,
  45872. bool askUserForFileIfNotSpecified,
  45873. bool showMessageOnFailure);
  45874. /** Prompts the user for a filename and tries to save to it.
  45875. This will pop up a dialog box using the title, file extension and
  45876. wildcard specified in the document's constructor, and asks the user
  45877. for a file. If they pick one, the saveAs() method is used to try to save
  45878. to this file.
  45879. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45880. the user first if they want to overwrite it
  45881. @see saveIfNeededAndUserAgrees, save, saveAs
  45882. */
  45883. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  45884. /** Returns the file that this document was last successfully saved or loaded from.
  45885. When the document object is created, this will be set to File::nonexistent.
  45886. It is changed when one of the load or save methods is used, or when setFile()
  45887. is used to explicitly set it.
  45888. */
  45889. const File getFile() const { return documentFile; }
  45890. /** Sets the file that this document thinks it was loaded from.
  45891. This won't actually load anything - it just changes the file stored internally.
  45892. @see getFile
  45893. */
  45894. void setFile (const File& newFile);
  45895. protected:
  45896. /** Overload this to return the title of the document.
  45897. This is used in message boxes, filenames and file choosers, so it should be
  45898. something sensible.
  45899. */
  45900. virtual const String getDocumentTitle() = 0;
  45901. /** This method should try to load your document from the given file.
  45902. If it fails, it should return an error message. If it succeeds, it should return
  45903. an empty string.
  45904. */
  45905. virtual const String loadDocument (const File& file) = 0;
  45906. /** This method should try to write your document to the given file.
  45907. If it fails, it should return an error message. If it succeeds, it should return
  45908. an empty string.
  45909. */
  45910. virtual const String saveDocument (const File& file) = 0;
  45911. /** This is used for dialog boxes to make them open at the last folder you
  45912. were using.
  45913. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45914. the last document that was used - you might want to store this value
  45915. in a static variable, or even in your application's properties. It should
  45916. be a global setting rather than a property of this object.
  45917. This method works very well in conjunction with a RecentlyOpenedFilesList
  45918. object to manage your recent-files list.
  45919. As a default value, it's ok to return File::nonexistent, and the document
  45920. object will use a sensible one instead.
  45921. @see RecentlyOpenedFilesList
  45922. */
  45923. virtual const File getLastDocumentOpened() = 0;
  45924. /** This is used for dialog boxes to make them open at the last folder you
  45925. were using.
  45926. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45927. the last document that was used - you might want to store this value
  45928. in a static variable, or even in your application's properties. It should
  45929. be a global setting rather than a property of this object.
  45930. This method works very well in conjunction with a RecentlyOpenedFilesList
  45931. object to manage your recent-files list.
  45932. @see RecentlyOpenedFilesList
  45933. */
  45934. virtual void setLastDocumentOpened (const File& file) = 0;
  45935. public:
  45936. juce_UseDebuggingNewOperator
  45937. private:
  45938. File documentFile;
  45939. bool changedSinceSave;
  45940. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  45941. FileBasedDocument (const FileBasedDocument&);
  45942. FileBasedDocument& operator= (const FileBasedDocument&);
  45943. };
  45944. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45945. /*** End of inlined file: juce_FileBasedDocument.h ***/
  45946. #endif
  45947. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  45948. #endif
  45949. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45950. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45951. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45952. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45953. /**
  45954. Manages a set of files for use as a list of recently-opened documents.
  45955. This is a handy class for holding your list of recently-opened documents, with
  45956. helpful methods for things like purging any non-existent files, automatically
  45957. adding them to a menu, and making persistence easy.
  45958. @see File, FileBasedDocument
  45959. */
  45960. class JUCE_API RecentlyOpenedFilesList
  45961. {
  45962. public:
  45963. /** Creates an empty list.
  45964. */
  45965. RecentlyOpenedFilesList();
  45966. /** Destructor. */
  45967. ~RecentlyOpenedFilesList();
  45968. /** Sets a limit for the number of files that will be stored in the list.
  45969. When addFile() is called, then if there is no more space in the list, the
  45970. least-recently added file will be dropped.
  45971. @see getMaxNumberOfItems
  45972. */
  45973. void setMaxNumberOfItems (int newMaxNumber);
  45974. /** Returns the number of items that this list will store.
  45975. @see setMaxNumberOfItems
  45976. */
  45977. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  45978. /** Returns the number of files in the list.
  45979. The most recently added file is always at index 0.
  45980. */
  45981. int getNumFiles() const;
  45982. /** Returns one of the files in the list.
  45983. The most recently added file is always at index 0.
  45984. */
  45985. const File getFile (int index) const;
  45986. /** Returns an array of all the absolute pathnames in the list.
  45987. */
  45988. const StringArray& getAllFilenames() const throw() { return files; }
  45989. /** Clears all the files from the list. */
  45990. void clear();
  45991. /** Adds a file to the list.
  45992. The file will be added at index 0. If this file is already in the list, it will
  45993. be moved up to index 0, but a file can only appear once in the list.
  45994. If the list already contains the maximum number of items that is permitted, the
  45995. least-recently added file will be dropped from the end.
  45996. */
  45997. void addFile (const File& file);
  45998. /** Checks each of the files in the list, removing any that don't exist.
  45999. You might want to call this after reloading a list of files, or before putting them
  46000. on a menu.
  46001. */
  46002. void removeNonExistentFiles();
  46003. /** Adds entries to a menu, representing each of the files in the list.
  46004. This is handy for creating an "open recent file..." menu in your app. The
  46005. menu items are numbered consecutively starting with the baseItemId value,
  46006. and can either be added as complete pathnames, or just the last part of the
  46007. filename.
  46008. If dontAddNonExistentFiles is true, then each file will be checked and only those
  46009. that exist will be added.
  46010. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  46011. pointers to file objects. Any files that appear in this list will not be added to the
  46012. menu - the reason for this is that you might have a number of files already open, so
  46013. might not want these to be shown in the menu.
  46014. It returns the number of items that were added.
  46015. */
  46016. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  46017. int baseItemId,
  46018. bool showFullPaths,
  46019. bool dontAddNonExistentFiles,
  46020. const File** filesToAvoid = 0);
  46021. /** Returns a string that encapsulates all the files in the list.
  46022. The string that is returned can later be passed into restoreFromString() in
  46023. order to recreate the list. This is handy for persisting your list, e.g. in
  46024. a PropertiesFile object.
  46025. @see restoreFromString
  46026. */
  46027. const String toString() const;
  46028. /** Restores the list from a previously stringified version of the list.
  46029. Pass in a stringified version created with toString() in order to persist/restore
  46030. your list.
  46031. @see toString
  46032. */
  46033. void restoreFromString (const String& stringifiedVersion);
  46034. juce_UseDebuggingNewOperator
  46035. private:
  46036. StringArray files;
  46037. int maxNumberOfItems;
  46038. };
  46039. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  46040. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  46041. #endif
  46042. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46043. #endif
  46044. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  46045. /*** Start of inlined file: juce_SystemClipboard.h ***/
  46046. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  46047. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  46048. /**
  46049. Handles reading/writing to the system's clipboard.
  46050. */
  46051. class JUCE_API SystemClipboard
  46052. {
  46053. public:
  46054. /** Copies a string of text onto the clipboard */
  46055. static void copyTextToClipboard (const String& text);
  46056. /** Gets the current clipboard's contents.
  46057. Obviously this might have come from another app, so could contain
  46058. anything..
  46059. */
  46060. static const String getTextFromClipboard();
  46061. };
  46062. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  46063. /*** End of inlined file: juce_SystemClipboard.h ***/
  46064. #endif
  46065. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  46066. #endif
  46067. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  46068. #endif
  46069. #endif
  46070. /*** End of inlined file: juce_app_includes.h ***/
  46071. #endif
  46072. #if JUCE_MSVC
  46073. #pragma warning (pop)
  46074. #pragma pack (pop)
  46075. #endif
  46076. END_JUCE_NAMESPACE
  46077. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  46078. #ifdef JUCE_NAMESPACE
  46079. // this will obviously save a lot of typing, but can be disabled by
  46080. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  46081. using namespace JUCE_NAMESPACE;
  46082. /* On the Mac, these symbols are defined in the Mac libraries, so
  46083. these macros make it easier to reference them without writing out
  46084. the namespace every time.
  46085. If you run into difficulties where these macros interfere with the contents
  46086. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  46087. the comments in that file for more information.
  46088. */
  46089. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  46090. #define Component JUCE_NAMESPACE::Component
  46091. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  46092. #define Point JUCE_NAMESPACE::Point
  46093. #define Button JUCE_NAMESPACE::Button
  46094. #endif
  46095. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  46096. it easier to use the juce version explicitly.
  46097. If you run into difficulties where this macro interferes with other 3rd party header
  46098. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  46099. file for more information.
  46100. */
  46101. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  46102. #define Rectangle JUCE_NAMESPACE::Rectangle
  46103. #endif
  46104. #endif
  46105. #endif
  46106. /* Easy autolinking to the right JUCE libraries under win32.
  46107. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  46108. including this header file.
  46109. */
  46110. #if JUCE_MSVC
  46111. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  46112. /** If you want your application to link to Juce as a DLL instead of
  46113. a static library (on win32), just define the JUCE_DLL macro before
  46114. including juce.h
  46115. */
  46116. #ifdef JUCE_DLL
  46117. #if JUCE_DEBUG
  46118. #define AUTOLINKEDLIB "JUCE_debug.lib"
  46119. #else
  46120. #define AUTOLINKEDLIB "JUCE.lib"
  46121. #endif
  46122. #else
  46123. #if JUCE_DEBUG
  46124. #ifdef _WIN64
  46125. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  46126. #else
  46127. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  46128. #endif
  46129. #else
  46130. #ifdef _WIN64
  46131. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  46132. #else
  46133. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  46134. #endif
  46135. #endif
  46136. #endif
  46137. #pragma comment(lib, AUTOLINKEDLIB)
  46138. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  46139. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  46140. #endif
  46141. // Auto-link the other win32 libs that are needed by library calls..
  46142. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  46143. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  46144. // Auto-links to various win32 libs that are needed by library calls..
  46145. #pragma comment(lib, "kernel32.lib")
  46146. #pragma comment(lib, "user32.lib")
  46147. #pragma comment(lib, "shell32.lib")
  46148. #pragma comment(lib, "gdi32.lib")
  46149. #pragma comment(lib, "vfw32.lib")
  46150. #pragma comment(lib, "comdlg32.lib")
  46151. #pragma comment(lib, "winmm.lib")
  46152. #pragma comment(lib, "wininet.lib")
  46153. #pragma comment(lib, "ole32.lib")
  46154. #pragma comment(lib, "oleaut32.lib")
  46155. #pragma comment(lib, "advapi32.lib")
  46156. #pragma comment(lib, "ws2_32.lib")
  46157. #pragma comment(lib, "comsupp.lib")
  46158. #pragma comment(lib, "version.lib")
  46159. #if JUCE_OPENGL
  46160. #pragma comment(lib, "OpenGL32.Lib")
  46161. #pragma comment(lib, "GlU32.Lib")
  46162. #endif
  46163. #if JUCE_QUICKTIME
  46164. #pragma comment (lib, "QTMLClient.lib")
  46165. #endif
  46166. #if JUCE_USE_CAMERA
  46167. #pragma comment (lib, "Strmiids.lib")
  46168. #pragma comment (lib, "wmvcore.lib")
  46169. #endif
  46170. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  46171. #endif
  46172. #endif
  46173. #endif
  46174. #endif // __JUCE_JUCEHEADER__
  46175. /*** End of inlined file: juce.h ***/
  46176. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__