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.

53721 lines
1.9MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. ==============================================================================
  25. This header contains the entire Juce source tree, and can be #included in
  26. all your source files.
  27. As well as including this in your files, you should also add juce_inline.cpp
  28. to your project (or juce_inline.mm on the Mac).
  29. ==============================================================================
  30. */
  31. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  32. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  33. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  34. /********* Start of inlined file: juce.h *********/
  35. #ifndef __JUCE_JUCEHEADER__
  36. #define __JUCE_JUCEHEADER__
  37. /*
  38. This is the main JUCE header file that applications need to include.
  39. */
  40. // (this includes things that need defining outside of the JUCE namespace)
  41. /********* Start of inlined file: juce_StandardHeader.h *********/
  42. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  43. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  44. /** Current Juce version number.
  45. See also SystemStats::getJUCEVersion() for a string version.
  46. */
  47. #define JUCE_MAJOR_VERSION 1
  48. #define JUCE_MINOR_VERSION 46
  49. /** Current Juce version number.
  50. Bits 16 to 32 = major version.
  51. Bits 8 to 16 = minor version.
  52. Bits 0 to 8 = point release (not currently used).
  53. See also SystemStats::getJUCEVersion() for a string version.
  54. */
  55. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8))
  56. /********* Start of inlined file: juce_Config.h *********/
  57. #ifndef __JUCE_CONFIG_JUCEHEADER__
  58. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  59. /*
  60. This file contains macros that enable/disable various JUCE features.
  61. */
  62. /** The name of the namespace that all Juce classes and functions will be
  63. put inside. If this is not defined, no namespace will be used.
  64. */
  65. #ifndef JUCE_NAMESPACE
  66. #define JUCE_NAMESPACE juce
  67. #endif
  68. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  69. but if you define this value, you can override this can force it to be true or
  70. false.
  71. */
  72. #ifndef JUCE_FORCE_DEBUG
  73. //#define JUCE_FORCE_DEBUG 1
  74. #endif
  75. /** If this flag is enabled, the the jassert and jassertfalse macros will
  76. always use Logger::writeToLog() to write a message when an assertion happens.
  77. Enabling it will also leave this turned on in release builds. When it's disabled,
  78. however, the jassert and jassertfalse macros will not be compiled in a
  79. release build.
  80. @see jassert, jassertfalse, Logger
  81. */
  82. #ifndef JUCE_LOG_ASSERTIONS
  83. // #define JUCE_LOG_ASSERTIONS 1
  84. #endif
  85. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  86. which the ASIOAudioIODevice class can't be built. See the comments in the
  87. ASIOAudioIODevice class's header file for more info about this.
  88. (This only affects a Win32 build)
  89. */
  90. #ifndef JUCE_ASIO
  91. #define JUCE_ASIO 1
  92. #endif
  93. /** Comment out this macro to disable building of ALSA device support on Linux.
  94. */
  95. #ifndef JUCE_ALSA
  96. #define JUCE_ALSA 1
  97. #endif
  98. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  99. have the SDK installed.
  100. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  101. classes will be unavailable.
  102. On Windows, if you enable this, you'll need to have the QuickTime SDK
  103. installed, and its header files will need to be on your include path.
  104. */
  105. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  106. #define JUCE_QUICKTIME 1
  107. #endif
  108. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  109. have the appropriate headers and libraries available. If it's not enabled, the
  110. OpenGLComponent class will be unavailable.
  111. */
  112. #ifndef JUCE_OPENGL
  113. #define JUCE_OPENGL 1
  114. #endif
  115. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  116. If you're not going to need either of these formats, turn off the flags to
  117. avoid bloating your codebase with them.
  118. */
  119. #ifndef JUCE_USE_FLAC
  120. #define JUCE_USE_FLAC 1
  121. #endif
  122. #ifndef JUCE_USE_OGGVORBIS
  123. #define JUCE_USE_OGGVORBIS 1
  124. #endif
  125. /** This flag lets you enable support for CD-burning. You might want to disable
  126. it to build without the MS SDK under windows.
  127. */
  128. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  129. #define JUCE_USE_CDBURNER 1
  130. #endif
  131. /** Enabling this macro means that all regions that get repainted will have a coloured
  132. line drawn around them.
  133. This is handy if you're trying to optimise drawing, because it lets you easily see
  134. when anything is being repainted unnecessarily.
  135. */
  136. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  137. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  138. #endif
  139. /** Enable this under Linux to use Xinerama for multi-monitor support.
  140. */
  141. #ifndef JUCE_USE_XINERAMA
  142. #define JUCE_USE_XINERAMA 1
  143. #endif
  144. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  145. */
  146. #ifndef JUCE_USE_XSHM
  147. #define JUCE_USE_XSHM 1
  148. #endif
  149. /** Enabling this builds support for VST audio plugins.
  150. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  151. */
  152. #ifndef JUCE_PLUGINHOST_VST
  153. // #define JUCE_PLUGINHOST_VST 1
  154. #endif
  155. /** Enabling this builds support for AudioUnit audio plugins.
  156. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  157. */
  158. #ifndef JUCE_PLUGINHOST_AU
  159. // #define JUCE_PLUGINHOST_AU 1
  160. #endif
  161. /** Enabling this will avoid including any UI code in the build. This is handy for
  162. writing command-line utilities, e.g. on linux boxes which don't have some
  163. of the UI libraries installed.
  164. */
  165. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  166. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  167. #endif
  168. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  169. */
  170. #ifndef JUCE_WEB_BROWSER
  171. #define JUCE_WEB_BROWSER 1
  172. #endif
  173. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  174. codebase - you might need to use this if you're linking to some of these libraries
  175. yourself.
  176. */
  177. #ifndef JUCE_INCLUDE_ZLIB_CODE
  178. #define JUCE_INCLUDE_ZLIB_CODE 1
  179. #endif
  180. #ifndef JUCE_INCLUDE_FLAC_CODE
  181. #define JUCE_INCLUDE_FLAC_CODE 1
  182. #endif
  183. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  184. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  185. #endif
  186. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  187. #define JUCE_INCLUDE_PNGLIB_CODE 1
  188. #endif
  189. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  190. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  191. #endif
  192. /** Enable this to add extra memory-leak info to the new and delete operators.
  193. (Currently, this only affects Windows builds in debug mode).
  194. */
  195. #ifndef JUCE_CHECK_MEMORY_LEAKS
  196. #define JUCE_CHECK_MEMORY_LEAKS 1
  197. #endif
  198. /** Enable this to turn on juce's internal catching of exceptions.
  199. Turning it off will avoid any exception catching. With it on, all exceptions
  200. are passed to the JUCEApplication::unhandledException() callback for logging.
  201. */
  202. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  204. #endif
  205. /** If this macro is set, the Juce String class will use unicode as its
  206. internal representation. If it isn't set, it'll use ANSI.
  207. */
  208. #ifndef JUCE_STRINGS_ARE_UNICODE
  209. #define JUCE_STRINGS_ARE_UNICODE 1
  210. #endif
  211. #endif
  212. /********* End of inlined file: juce_Config.h *********/
  213. #ifdef JUCE_NAMESPACE
  214. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  215. #define END_JUCE_NAMESPACE }
  216. #else
  217. #define BEGIN_JUCE_NAMESPACE
  218. #define END_JUCE_NAMESPACE
  219. #endif
  220. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  221. /********* Start of inlined file: juce_PlatformDefs.h *********/
  222. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  223. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  224. /* This file figures out which platform is being built, and defines some macros
  225. that the rest of the code can use for OS-specific compilation.
  226. Macros that will be set here are:
  227. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  228. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  229. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  230. - Either JUCE_INTEL or JUCE_PPC
  231. - Either JUCE_GCC or JUCE_MSVC
  232. On the Mac, it also defines MACOS_10_2_OR_EARLIER if the build is targeting OSX10.2,
  233. and MACOS_10_3_OR_EARLIER if it is targeting either 10.2 or 10.3
  234. It also includes a set of macros for debug console output and assertions.
  235. */
  236. #if (defined (_WIN32) || defined (_WIN64))
  237. #define JUCE_WIN32 1
  238. #else
  239. #if defined (LINUX) || defined (__linux__)
  240. #define JUCE_LINUX 1
  241. #else
  242. #define JUCE_MAC 1
  243. #endif
  244. #endif
  245. #if JUCE_WIN32
  246. #ifdef _MSC_VER
  247. #ifdef _WIN64
  248. #define JUCE_64BIT 1
  249. #else
  250. #define JUCE_32BIT 1
  251. #endif
  252. #endif
  253. #ifdef _DEBUG
  254. #define JUCE_DEBUG 1
  255. #endif
  256. /** If defined, this indicates that the processor is little-endian. */
  257. #define JUCE_LITTLE_ENDIAN 1
  258. #define JUCE_INTEL 1
  259. #endif
  260. #if JUCE_MAC
  261. #include <CoreFoundation/CoreFoundation.h>
  262. #ifndef NDEBUG
  263. #define JUCE_DEBUG 1
  264. #endif
  265. #ifdef __LITTLE_ENDIAN__
  266. #define JUCE_LITTLE_ENDIAN 1
  267. #else
  268. #define JUCE_BIG_ENDIAN 1
  269. #endif
  270. #if defined (__ppc__) || defined (__ppc64__)
  271. #define JUCE_PPC 1
  272. #else
  273. #define JUCE_INTEL 1
  274. #endif
  275. #ifdef __LP64__
  276. #define JUCE_64BIT 1
  277. #else
  278. #define JUCE_32BIT 1
  279. #endif
  280. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  281. #define MACOS_10_2_OR_EARLIER 1
  282. #endif
  283. #if (! defined (MAC_OS_X_VERSION_10_4)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  284. #define MACOS_10_3_OR_EARLIER 1
  285. #endif
  286. #if (! defined (MAC_OS_X_VERSION_10_5)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  287. #define MACOS_10_4_OR_EARLIER 1
  288. #endif
  289. #endif
  290. #if JUCE_LINUX
  291. #ifdef _DEBUG
  292. #define JUCE_DEBUG 1
  293. #endif
  294. // Allow override for big-endian Linux platforms
  295. #ifndef JUCE_BIG_ENDIAN
  296. #define JUCE_LITTLE_ENDIAN 1
  297. #endif
  298. #if defined (__LP64__) || defined (_LP64)
  299. #define JUCE_64BIT 1
  300. #else
  301. #define JUCE_32BIT 1
  302. #endif
  303. #define JUCE_INTEL 1
  304. #endif
  305. #ifdef JUCE_FORCE_DEBUG
  306. #undef JUCE_DEBUG
  307. #if JUCE_FORCE_DEBUG
  308. #define JUCE_DEBUG 1
  309. #endif
  310. #endif
  311. // Compiler type macros.
  312. #ifdef __GNUC__
  313. #define JUCE_GCC 1
  314. #elif defined (_MSC_VER)
  315. #define JUCE_MSVC 1
  316. #if _MSC_VER >= 1400
  317. #define JUCE_USE_INTRINSICS 1
  318. #endif
  319. #else
  320. #error unknown compiler
  321. #endif
  322. /** This macro defines the C calling convention used as the standard for Juce calls. */
  323. #if JUCE_MSVC
  324. #define JUCE_CALLTYPE __stdcall
  325. #else
  326. #define JUCE_CALLTYPE
  327. #endif
  328. // Debugging and assertion macros
  329. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  330. #if JUCE_LOG_ASSERTIONS
  331. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  332. #elif defined (JUCE_DEBUG)
  333. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  334. #else
  335. #define juce_LogCurrentAssertion
  336. #endif
  337. #ifdef JUCE_DEBUG
  338. // If debugging is enabled..
  339. /** Writes a string to the standard error stream.
  340. This is only compiled in a debug build.
  341. @see Logger::outputDebugString
  342. */
  343. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  344. /** Printf's a string to the standard error stream.
  345. This is only compiled in a debug build.
  346. @see Logger::outputDebugString
  347. */
  348. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  349. // Assertions..
  350. #if JUCE_WIN32 || DOXYGEN
  351. #if JUCE_USE_INTRINSICS
  352. #pragma intrinsic (__debugbreak)
  353. /** This will try to break the debugger if one is currently hosting this app.
  354. @see jassert()
  355. */
  356. #define juce_breakDebugger __debugbreak();
  357. #elif JUCE_GCC
  358. /** This will try to break the debugger if one is currently hosting this app.
  359. @see jassert()
  360. */
  361. #define juce_breakDebugger asm("int $3");
  362. #else
  363. /** This will try to break the debugger if one is currently hosting this app.
  364. @see jassert()
  365. */
  366. #define juce_breakDebugger { __asm int 3 }
  367. #endif
  368. #elif JUCE_MAC
  369. #define juce_breakDebugger Debugger();
  370. #elif JUCE_LINUX
  371. #define juce_breakDebugger kill (0, SIGTRAP);
  372. #endif
  373. /** This will always cause an assertion failure.
  374. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  375. in juce_Config.h).
  376. @see jassert()
  377. */
  378. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  379. /** Platform-independent assertion macro.
  380. This gets optimised out when not being built with debugging turned on.
  381. Be careful not to call any functions within its arguments that are vital to
  382. the behaviour of the program, because these won't get called in the release
  383. build.
  384. @see jassertfalse
  385. */
  386. #define jassert(expression) { if (! (expression)) jassertfalse }
  387. #else
  388. // If debugging is disabled, these dummy debug and assertion macros are used..
  389. #define DBG(dbgtext)
  390. #define DBG_PRINTF(dbgprintf)
  391. #define jassertfalse { juce_LogCurrentAssertion }
  392. #if JUCE_LOG_ASSERTIONS
  393. #define jassert(expression) { if (! (expression)) jassertfalse }
  394. #else
  395. #define jassert(a) { }
  396. #endif
  397. #endif
  398. #ifndef DOXYGEN
  399. template <bool b> struct JuceStaticAssert;
  400. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  401. #endif
  402. /** A compile-time assertion macro.
  403. If the expression parameter is false, the macro will cause a compile error.
  404. */
  405. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  406. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  407. #define JUCE_TRY try
  408. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  409. object so they can be logged by the application if it wants to.
  410. */
  411. #define JUCE_CATCH_EXCEPTION \
  412. catch (const std::exception& e) \
  413. { \
  414. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  415. } \
  416. catch (...) \
  417. { \
  418. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  419. }
  420. #define JUCE_CATCH_ALL catch (...) {}
  421. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  422. #else
  423. #define JUCE_TRY
  424. #define JUCE_CATCH_EXCEPTION
  425. #define JUCE_CATCH_ALL
  426. #define JUCE_CATCH_ALL_ASSERT
  427. #endif
  428. // Macros for inlining.
  429. #if JUCE_MSVC
  430. /** A platform-independent way of forcing an inline function.
  431. Use the syntax: @code
  432. forcedinline void myfunction (int x)
  433. @endcode
  434. */
  435. #ifdef JUCE_DEBUG
  436. #define forcedinline __forceinline
  437. #else
  438. #define forcedinline inline
  439. #endif
  440. /** A platform-independent way of stopping the compiler inlining a function.
  441. Use the syntax: @code
  442. juce_noinline void myfunction (int x)
  443. @endcode
  444. */
  445. #define juce_noinline
  446. #else
  447. /** A platform-independent way of forcing an inline function.
  448. Use the syntax: @code
  449. forcedinline void myfunction (int x)
  450. @endcode
  451. */
  452. #ifndef JUCE_DEBUG
  453. #define forcedinline inline __attribute__((always_inline))
  454. #else
  455. #define forcedinline inline
  456. #endif
  457. /** A platform-independent way of stopping the compiler inlining a function.
  458. Use the syntax: @code
  459. juce_noinline void myfunction (int x)
  460. @endcode
  461. */
  462. #define juce_noinline __attribute__((noinline))
  463. #endif
  464. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  465. /********* End of inlined file: juce_PlatformDefs.h *********/
  466. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  467. #if JUCE_MSVC
  468. #pragma warning (push)
  469. #pragma warning (disable: 4514 4245 4100)
  470. #endif
  471. #include <cstdlib>
  472. #include <cstdarg>
  473. #include <climits>
  474. #include <cmath>
  475. #include <cwchar>
  476. #include <stdexcept>
  477. #include <typeinfo>
  478. #include <cstring>
  479. #include <cstdio>
  480. #if JUCE_MAC || JUCE_LINUX
  481. #include <pthread.h>
  482. #endif
  483. #if JUCE_USE_INTRINSICS
  484. #include <intrin.h>
  485. #endif
  486. #if JUCE_MAC
  487. #if MACOS_10_3_OR_EARLIER
  488. #include <CoreServices/CoreServices.h>
  489. #else
  490. #include <libkern/OSAtomic.h>
  491. #endif
  492. #endif
  493. #if JUCE_LINUX
  494. #include <signal.h>
  495. #endif
  496. #if JUCE_MSVC && JUCE_DEBUG
  497. #include <crtdbg.h>
  498. #endif
  499. #if JUCE_MSVC
  500. #pragma warning (pop)
  501. #endif
  502. // DLL building settings on Win32
  503. #if JUCE_MSVC
  504. #ifdef JUCE_DLL_BUILD
  505. #define JUCE_API __declspec (dllexport)
  506. #pragma warning (disable: 4251)
  507. #elif defined (JUCE_DLL)
  508. #define JUCE_API __declspec (dllimport)
  509. #pragma warning (disable: 4251)
  510. #endif
  511. #endif
  512. #ifndef JUCE_API
  513. /** This macro is added to all juce public class declarations. */
  514. #define JUCE_API
  515. #endif
  516. /** This macro is added to all juce public function declarations. */
  517. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  518. // Now include some basics that are needed by most of the Juce classes...
  519. BEGIN_JUCE_NAMESPACE
  520. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  521. #if JUCE_LOG_ASSERTIONS
  522. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  523. #endif
  524. /********* Start of inlined file: juce_Memory.h *********/
  525. #ifndef __JUCE_MEMORY_JUCEHEADER__
  526. #define __JUCE_MEMORY_JUCEHEADER__
  527. /*
  528. This file defines the various juce_malloc(), juce_free() macros that should be used in
  529. preference to the standard calls.
  530. */
  531. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  532. #ifndef JUCE_DLL
  533. // Win32 debug non-DLL versions..
  534. /** This should be used instead of calling malloc directly. */
  535. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  536. /** This should be used instead of calling calloc directly. */
  537. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  538. /** This should be used instead of calling realloc directly. */
  539. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  540. /** This should be used instead of calling free directly. */
  541. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  542. #else
  543. // Win32 debug DLL versions..
  544. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  545. // way all juce calls in the DLL and in the host API will all use the same allocator.
  546. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  547. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  548. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  549. extern JUCE_API void juce_DebugFree (void* const block);
  550. /** This should be used instead of calling malloc directly. */
  551. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  552. /** This should be used instead of calling calloc directly. */
  553. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  554. /** This should be used instead of calling realloc directly. */
  555. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  556. /** This should be used instead of calling free directly. */
  557. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  558. #endif
  559. #if ! defined (_AFXDLL)
  560. /** This macro can be added to classes to add extra debugging information to the memory
  561. allocated for them, so you can see the type of objects involved when there's a dump
  562. of leaked objects at program shutdown. (Only works on win32 at the moment).
  563. */
  564. #define juce_UseDebuggingNewOperator \
  565. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  566. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  567. static void operator delete (void* p) { juce_free (p); }
  568. #endif
  569. #elif defined (JUCE_DLL)
  570. // Win32 DLL (release) versions..
  571. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  572. // way all juce calls in the DLL and in the host API will all use the same allocator.
  573. extern JUCE_API void* juce_Malloc (const int size);
  574. extern JUCE_API void* juce_Calloc (const int size);
  575. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  576. extern JUCE_API void juce_Free (void* const block);
  577. /** This should be used instead of calling malloc directly. */
  578. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  579. /** This should be used instead of calling calloc directly. */
  580. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  581. /** This should be used instead of calling realloc directly. */
  582. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  583. /** This should be used instead of calling free directly. */
  584. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  585. #define juce_UseDebuggingNewOperator \
  586. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  587. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  588. static void operator delete (void* p) { juce_free (p); }
  589. #else
  590. // Mac, Linux and Win32 (release) versions..
  591. /** This should be used instead of calling malloc directly. */
  592. #define juce_malloc(numBytes) malloc (numBytes)
  593. /** This should be used instead of calling calloc directly. */
  594. #define juce_calloc(numBytes) calloc (1, numBytes)
  595. /** This should be used instead of calling realloc directly. */
  596. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  597. /** This should be used instead of calling free directly. */
  598. #define juce_free(location) free (location)
  599. #endif
  600. /** This macro can be added to classes to add extra debugging information to the memory
  601. allocated for them, so you can see the type of objects involved when there's a dump
  602. of leaked objects at program shutdown. (Only works on win32 at the moment).
  603. Note that if you create a class that inherits from a class that uses this macro,
  604. your class must also use the macro, otherwise you'll probably get compile errors
  605. because of ambiguous new operators.
  606. Most of the JUCE classes use it, so see these for examples of where it should go.
  607. */
  608. #ifndef juce_UseDebuggingNewOperator
  609. #define juce_UseDebuggingNewOperator
  610. #endif
  611. #if JUCE_MSVC
  612. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  613. E.g.
  614. @code
  615. juce_ThreadLocal int myVariable;
  616. @endcode
  617. */
  618. #define juce_ThreadLocal __declspec(thread)
  619. #else
  620. #define juce_ThreadLocal __thread
  621. #endif
  622. /** Clears a block of memory. */
  623. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  624. /** Clears a reference to a local structure. */
  625. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  626. /** A handy macro that calls delete on a pointer if it's non-zero, and
  627. then sets the pointer to null.
  628. */
  629. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  630. #endif // __JUCE_MEMORY_JUCEHEADER__
  631. /********* End of inlined file: juce_Memory.h *********/
  632. /********* Start of inlined file: juce_MathsFunctions.h *********/
  633. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  634. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  635. /*
  636. This file sets up some handy mathematical typdefs and functions.
  637. */
  638. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  639. /** A platform-independent 8-bit signed integer type. */
  640. typedef signed char int8;
  641. /** A platform-independent 8-bit unsigned integer type. */
  642. typedef unsigned char uint8;
  643. /** A platform-independent 16-bit signed integer type. */
  644. typedef signed short int16;
  645. /** A platform-independent 16-bit unsigned integer type. */
  646. typedef unsigned short uint16;
  647. /** A platform-independent 32-bit signed integer type. */
  648. typedef signed int int32;
  649. /** A platform-independent 32-bit unsigned integer type. */
  650. typedef unsigned int uint32;
  651. #if JUCE_MSVC
  652. /** A platform-independent 64-bit integer type. */
  653. typedef __int64 int64;
  654. /** A platform-independent 64-bit unsigned integer type. */
  655. typedef unsigned __int64 uint64;
  656. /** A platform-independent macro for writing 64-bit literals, needed because
  657. different compilers have different syntaxes for this.
  658. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  659. GCC, or 0x1000000000 for MSVC.
  660. */
  661. #define literal64bit(longLiteral) ((__int64) longLiteral)
  662. #else
  663. /** A platform-independent 64-bit integer type. */
  664. typedef long long int64;
  665. /** A platform-independent 64-bit unsigned integer type. */
  666. typedef unsigned long long uint64;
  667. /** A platform-independent macro for writing 64-bit literals, needed because
  668. different compilers have different syntaxes for this.
  669. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  670. GCC, or 0x1000000000 for MSVC.
  671. */
  672. #define literal64bit(longLiteral) (longLiteral##LL)
  673. #endif
  674. #if JUCE_64BIT
  675. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  676. typedef int64 pointer_sized_int;
  677. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  678. typedef uint64 pointer_sized_uint;
  679. #elif _MSC_VER >= 1300
  680. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  681. typedef _W64 int pointer_sized_int;
  682. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  683. typedef _W64 unsigned int pointer_sized_uint;
  684. #else
  685. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  686. typedef int pointer_sized_int;
  687. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  688. typedef unsigned int pointer_sized_uint;
  689. #endif
  690. /** A platform-independent unicode character type. */
  691. typedef wchar_t juce_wchar;
  692. // Some indispensible min/max functions
  693. /** Returns the larger of two values. */
  694. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  695. /** Returns the larger of two values. */
  696. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  697. /** Returns the larger of two values. */
  698. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  699. /** Returns the larger of two values. */
  700. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  701. /** Returns the larger of three values. */
  702. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  703. /** Returns the larger of three values. */
  704. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  705. /** Returns the larger of three values. */
  706. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  707. /** Returns the larger of three values. */
  708. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  709. /** Returns the larger of four values. */
  710. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  711. /** Returns the larger of four values. */
  712. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  713. /** Returns the larger of four values. */
  714. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  715. /** Returns the larger of four values. */
  716. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  717. /** Returns the smaller of two values. */
  718. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  719. /** Returns the smaller of two values. */
  720. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  721. /** Returns the smaller of two values. */
  722. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  723. /** Returns the smaller of two values. */
  724. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  725. /** Returns the smaller of three values. */
  726. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  727. /** Returns the smaller of three values. */
  728. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  729. /** Returns the smaller of three values. */
  730. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  731. /** Returns the smaller of three values. */
  732. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  733. /** Returns the smaller of four values. */
  734. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  735. /** Returns the smaller of four values. */
  736. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  737. /** Returns the smaller of four values. */
  738. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  739. /** Returns the smaller of four values. */
  740. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  741. /** Constrains a value to keep it within a given range.
  742. This will check that the specified value lies between the lower and upper bounds
  743. specified, and if not, will return the nearest value that would be in-range. Effectively,
  744. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  745. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  746. the results will be unpredictable.
  747. @param lowerLimit the minimum value to return
  748. @param upperLimit the maximum value to return
  749. @param valueToConstrain the value to try to return
  750. @returns the closest value to valueToConstrain which lies between lowerLimit
  751. and upperLimit (inclusive)
  752. @see jlimit0To, jmin, jmax
  753. */
  754. template <class Type>
  755. inline Type jlimit (const Type lowerLimit,
  756. const Type upperLimit,
  757. const Type valueToConstrain) throw()
  758. {
  759. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  760. return (valueToConstrain < lowerLimit) ? lowerLimit
  761. : ((valueToConstrain > upperLimit) ? upperLimit
  762. : valueToConstrain);
  763. }
  764. /** Handy function to swap two values over.
  765. */
  766. template <class Type>
  767. inline void swapVariables (Type& variable1, Type& variable2) throw()
  768. {
  769. const Type tempVal = variable1;
  770. variable1 = variable2;
  771. variable2 = tempVal;
  772. }
  773. /** Handy macro for getting the number of elements in a simple const C array.
  774. E.g.
  775. @code
  776. static int myArray[] = { 1, 2, 3 };
  777. int numElements = numElementsInArray (myArray) // returns 3
  778. @endcode
  779. */
  780. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  781. // Some useful maths functions that aren't always present with all compilers and build settings.
  782. #if JUCE_WIN32 || defined (DOXYGEN)
  783. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  784. versions of these functions of various platforms and compilers. */
  785. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  786. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  787. versions of these functions of various platforms and compilers. */
  788. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  789. #elif MACOS_10_2_OR_EARLIER
  790. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  791. versions of these functions of various platforms and compilers. */
  792. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  793. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  794. versions of these functions of various platforms and compilers. */
  795. forcedinline float juce_hypotf (float a, float b) { return (float) hypot (a, b); }
  796. forcedinline float sinf (const float a) { return (float) sin (a); }
  797. forcedinline float cosf (const float a) { return (float) cos (a); }
  798. forcedinline float tanf (const float a) { return (float) tan (a); }
  799. forcedinline float atan2f (const float a, const float b) { return (float) atan2 (a, b); }
  800. forcedinline float sqrtf (const float a) { return (float) sqrt (a); }
  801. forcedinline float logf (const float a) { return (float) log (a); }
  802. forcedinline float powf (const float a, const float b) { return (float) pow (a, b); }
  803. forcedinline float expf (const float a) { return (float) exp (a); }
  804. #else
  805. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  806. versions of these functions of various platforms and compilers. */
  807. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  808. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  809. versions of these functions of various platforms and compilers. */
  810. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  811. #endif
  812. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  813. /** A predefined value for Pi, at double-precision.
  814. @see float_Pi
  815. */
  816. const double double_Pi = 3.1415926535897932384626433832795;
  817. /** A predefined value for Pi, at sngle-precision.
  818. @see double_Pi
  819. */
  820. const float float_Pi = 3.14159265358979323846f;
  821. /** The isfinite() method seems to vary greatly between platforms, so this is a
  822. platform-independent macro for it.
  823. */
  824. #if JUCE_LINUX
  825. #define juce_isfinite(v) std::isfinite(v)
  826. #elif JUCE_MAC
  827. #if MACOS_10_2_OR_EARLIER
  828. #define juce_isfinite(v) __isfinite(v)
  829. #elif MACOS_10_3_OR_EARLIER
  830. #ifdef isfinite
  831. #define juce_isfinite(v) isfinite(v)
  832. #else
  833. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  834. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  835. #endif
  836. #else
  837. #define juce_isfinite(v) std::isfinite(v)
  838. #endif
  839. #elif JUCE_WIN32 && ! defined (isfinite)
  840. #define juce_isfinite(v) _finite(v)
  841. #else
  842. #define juce_isfinite(v) isfinite(v)
  843. #endif
  844. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  845. /********* End of inlined file: juce_MathsFunctions.h *********/
  846. /********* Start of inlined file: juce_DataConversions.h *********/
  847. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  848. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  849. #if JUCE_USE_INTRINSICS
  850. #pragma intrinsic (_byteswap_ulong)
  851. #endif
  852. // Endianness conversions..
  853. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  854. forcedinline uint32 swapByteOrder (uint32 n) throw()
  855. {
  856. #if JUCE_MAC
  857. // Mac version
  858. return CFSwapInt32 (n);
  859. #elif JUCE_GCC
  860. // Inpenetrable GCC version..
  861. asm("bswap %%eax" : "=a"(n) : "a"(n));
  862. return n;
  863. #elif JUCE_USE_INTRINSICS
  864. // Win32 intrinsics version..
  865. return _byteswap_ulong (n);
  866. #else
  867. // Win32 version..
  868. __asm {
  869. mov eax, n
  870. bswap eax
  871. mov n, eax
  872. }
  873. return n;
  874. #endif
  875. }
  876. /** Swaps the byte-order of a 16-bit short. */
  877. inline uint16 swapByteOrder (const uint16 n) throw()
  878. {
  879. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  880. // Win32 intrinsics version..
  881. return (uint16) _byteswap_ushort (n);
  882. #else
  883. return (uint16) ((n << 8) | (n >> 8));
  884. #endif
  885. }
  886. inline uint64 swapByteOrder (const uint64 value) throw()
  887. {
  888. #if JUCE_MAC
  889. return CFSwapInt64 (value);
  890. #elif JUCE_USE_INTRINSICS
  891. return _byteswap_uint64 (value);
  892. #else
  893. return (((int64) swapByteOrder ((uint32) value)) << 32)
  894. | swapByteOrder ((uint32) (value >> 32));
  895. #endif
  896. }
  897. #if JUCE_LITTLE_ENDIAN
  898. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  899. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  900. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  901. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  902. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  903. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  904. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  905. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  906. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  907. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  908. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  909. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  910. /** Turns 4 bytes into a little-endian integer. */
  911. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  912. /** Turns 2 bytes into a little-endian integer. */
  913. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  914. /** Turns 4 bytes into a big-endian integer. */
  915. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  916. /** Turns 2 bytes into a big-endian integer. */
  917. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  918. #else
  919. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  920. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  921. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  922. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  923. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  924. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  925. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  926. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  927. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  928. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  929. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  930. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  931. /** Turns 4 bytes into a little-endian integer. */
  932. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  933. /** Turns 2 bytes into a little-endian integer. */
  934. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  935. /** Turns 4 bytes into a big-endian integer. */
  936. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  937. /** Turns 2 bytes into a big-endian integer. */
  938. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  939. #endif
  940. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  941. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  942. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  943. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  944. /** Copies a 24-bit number to 3 little-endian bytes. */
  945. inline void littleEndian24BitToChars (const int value, char* const destBytes) throw() { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  946. /** Copies a 24-bit number to 3 big-endian bytes. */
  947. inline void bigEndian24BitToChars (const int value, char* const destBytes) throw() { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  948. /** Fast floating-point-to-integer conversion.
  949. This is faster than using the normal c++ cast to convert a double to an int, and
  950. it will round the value to the nearest integer, rather than rounding it down
  951. like the normal cast does.
  952. Note that this routine gets its speed at the expense of some accuracy, and when
  953. rounding values whose floating point component is exactly 0.5, odd numbers and
  954. even numbers will be rounded up or down differently. For a more accurate conversion,
  955. see roundDoubleToIntAccurate().
  956. */
  957. inline int roundDoubleToInt (const double value) throw()
  958. {
  959. union { int asInt[2]; double asDouble; } n;
  960. n.asDouble = value + 6755399441055744.0;
  961. #if JUCE_BIG_ENDIAN
  962. return n.asInt [1];
  963. #else
  964. return n.asInt [0];
  965. #endif
  966. }
  967. /** Fast floating-point-to-integer conversion.
  968. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  969. fine for values above zero, but negative numbers are rounded the wrong way.
  970. */
  971. inline int roundDoubleToIntAccurate (const double value) throw()
  972. {
  973. return roundDoubleToInt (value + 1.5e-8);
  974. }
  975. /** Fast floating-point-to-integer conversion.
  976. This is faster than using the normal c++ cast to convert a float to an int, and
  977. it will round the value to the nearest integer, rather than rounding it down
  978. like the normal cast does.
  979. Note that this routine gets its speed at the expense of some accuracy, and when
  980. rounding values whose floating point component is exactly 0.5, odd numbers and
  981. even numbers will be rounded up or down differently.
  982. */
  983. inline int roundFloatToInt (const float value) throw()
  984. {
  985. union { int asInt[2]; double asDouble; } n;
  986. n.asDouble = value + 6755399441055744.0;
  987. #if JUCE_BIG_ENDIAN
  988. return n.asInt [1];
  989. #else
  990. return n.asInt [0];
  991. #endif
  992. }
  993. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  994. /********* End of inlined file: juce_DataConversions.h *********/
  995. /********* Start of inlined file: juce_Logger.h *********/
  996. #ifndef __JUCE_LOGGER_JUCEHEADER__
  997. #define __JUCE_LOGGER_JUCEHEADER__
  998. /********* Start of inlined file: juce_String.h *********/
  999. #ifndef __JUCE_STRING_JUCEHEADER__
  1000. #define __JUCE_STRING_JUCEHEADER__
  1001. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1002. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1003. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1004. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1005. (in the default system encoding) as its internal representation.
  1006. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1007. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1008. literals in the T("abcd") macro, so that it all works nicely either way round.
  1009. */
  1010. #if JUCE_STRINGS_ARE_UNICODE
  1011. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1012. typedef juce_wchar tchar;
  1013. #define juce_tcharToWideChar(c) (c)
  1014. #else
  1015. #define JUCE_T(stringLiteral) (stringLiteral)
  1016. typedef char tchar;
  1017. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1018. #endif
  1019. #if ! JUCE_DONT_DEFINE_MACROS
  1020. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1021. or unicode.
  1022. If you write your string literals in the form T("xyz"), this will either be compiled
  1023. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1024. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1025. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1026. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1027. the juce/src directory) to avoid defining this macro. See the comments in
  1028. juce_withoutMacros.h for more info.
  1029. */
  1030. #define T(stringLiteral) JUCE_T(stringLiteral)
  1031. #endif
  1032. /**
  1033. A set of methods for manipulating characters and character strings, with
  1034. duplicate methods to handle 8-bit and unicode characters.
  1035. These are defined as wrappers around the basic C string handlers, to provide
  1036. a clean, cross-platform layer, (because various platforms differ in the
  1037. range of C library calls that they provide).
  1038. @see String
  1039. */
  1040. class JUCE_API CharacterFunctions
  1041. {
  1042. public:
  1043. static int length (const char* const s) throw();
  1044. static int length (const juce_wchar* const s) throw();
  1045. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1046. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1047. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1048. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1049. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1050. static void append (char* dest, const char* src) throw();
  1051. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1052. static int compare (const char* const s1, const char* const s2) throw();
  1053. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1054. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1055. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1056. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1057. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1058. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1059. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1060. static const char* find (const char* const haystack, const char* const needle) throw();
  1061. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1062. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1063. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1064. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1065. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1066. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1067. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1068. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1069. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1070. static int getIntValue (const char* const s) throw();
  1071. static int getIntValue (const juce_wchar* s) throw();
  1072. static int64 getInt64Value (const char* s) throw();
  1073. static int64 getInt64Value (const juce_wchar* s) throw();
  1074. static double getDoubleValue (const char* const s) throw();
  1075. static double getDoubleValue (const juce_wchar* const s) throw();
  1076. static char toUpperCase (const char character) throw();
  1077. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1078. static void toUpperCase (char* s) throw();
  1079. static void toUpperCase (juce_wchar* s) throw();
  1080. static bool isUpperCase (const char character) throw();
  1081. static bool isUpperCase (const juce_wchar character) throw();
  1082. static char toLowerCase (const char character) throw();
  1083. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1084. static void toLowerCase (char* s) throw();
  1085. static void toLowerCase (juce_wchar* s) throw();
  1086. static bool isLowerCase (const char character) throw();
  1087. static bool isLowerCase (const juce_wchar character) throw();
  1088. static bool isWhitespace (const char character) throw();
  1089. static bool isWhitespace (const juce_wchar character) throw();
  1090. static bool isDigit (const char character) throw();
  1091. static bool isDigit (const juce_wchar character) throw();
  1092. static bool isLetter (const char character) throw();
  1093. static bool isLetter (const juce_wchar character) throw();
  1094. static bool isLetterOrDigit (const char character) throw();
  1095. static bool isLetterOrDigit (const juce_wchar character) throw();
  1096. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1097. hex digit.
  1098. */
  1099. static int getHexDigitValue (const tchar digit) throw();
  1100. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1101. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1102. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1103. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1104. };
  1105. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1106. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1107. /**
  1108. The JUCE String class!
  1109. Using a reference-counted internal representation, these strings are fast
  1110. and efficient, and there are methods to do just about any operation you'll ever
  1111. dream of.
  1112. @see StringArray, StringPairArray
  1113. */
  1114. class JUCE_API String
  1115. {
  1116. public:
  1117. /** Creates an empty string.
  1118. @see empty
  1119. */
  1120. String() throw();
  1121. /** Creates a copy of another string. */
  1122. String (const String& other) throw();
  1123. /** Creates a string from a zero-terminated text string.
  1124. The string is assumed to be stored in the default system encoding.
  1125. */
  1126. String (const char* const text) throw();
  1127. /** Creates a string from an string of characters.
  1128. This will use up the the first maxChars characters of the string (or
  1129. less if the string is actually shorter)
  1130. */
  1131. String (const char* const text,
  1132. const int maxChars) throw();
  1133. /** Creates a string from a zero-terminated unicode text string. */
  1134. String (const juce_wchar* const unicodeText) throw();
  1135. /** Creates a string from a unicode text string.
  1136. This will use up the the first maxChars characters of the string (or
  1137. less if the string is actually shorter)
  1138. */
  1139. String (const juce_wchar* const unicodeText,
  1140. const int maxChars) throw();
  1141. /** Creates a string from a single character. */
  1142. static const String charToString (const tchar character) throw();
  1143. /** Destructor. */
  1144. ~String() throw();
  1145. /** This is an empty string that can be used whenever one is needed.
  1146. It's better to use this than String() because it explains what's going on
  1147. and is more efficient.
  1148. */
  1149. static const String empty;
  1150. /** Generates a probably-unique 32-bit hashcode from this string. */
  1151. int hashCode() const throw();
  1152. /** Generates a probably-unique 64-bit hashcode from this string. */
  1153. int64 hashCode64() const throw();
  1154. /** Returns the number of characters in the string. */
  1155. int length() const throw();
  1156. // Assignment and concatenation operators..
  1157. /** Replaces this string's contents with another string. */
  1158. const String& operator= (const tchar* const other) throw();
  1159. /** Replaces this string's contents with another string. */
  1160. const String& operator= (const String& other) throw();
  1161. /** Appends another string at the end of this one. */
  1162. const String& operator+= (const tchar* const textToAppend) throw();
  1163. /** Appends another string at the end of this one. */
  1164. const String& operator+= (const String& stringToAppend) throw();
  1165. /** Appends a character at the end of this string. */
  1166. const String& operator+= (const char characterToAppend) throw();
  1167. /** Appends a character at the end of this string. */
  1168. const String& operator+= (const juce_wchar characterToAppend) throw();
  1169. /** Appends a string at the end of this one.
  1170. @param textToAppend the string to add
  1171. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1172. */
  1173. void append (const tchar* const textToAppend,
  1174. const int maxCharsToTake) throw();
  1175. /** Appends a string at the end of this one.
  1176. @returns the concatenated string
  1177. */
  1178. const String operator+ (const String& stringToAppend) const throw();
  1179. /** Appends a string at the end of this one.
  1180. @returns the concatenated string
  1181. */
  1182. const String operator+ (const tchar* const textToAppend) const throw();
  1183. /** Appends a character at the end of this one.
  1184. @returns the concatenated string
  1185. */
  1186. const String operator+ (const tchar characterToAppend) const throw();
  1187. /** Appends a character at the end of this string. */
  1188. String& operator<< (const char n) throw();
  1189. /** Appends a character at the end of this string. */
  1190. String& operator<< (const juce_wchar n) throw();
  1191. /** Appends another string at the end of this one. */
  1192. String& operator<< (const char* const text) throw();
  1193. /** Appends another string at the end of this one. */
  1194. String& operator<< (const juce_wchar* const text) throw();
  1195. /** Appends another string at the end of this one. */
  1196. String& operator<< (const String& text) throw();
  1197. /** Appends a decimal number at the end of this string. */
  1198. String& operator<< (const short number) throw();
  1199. /** Appends a decimal number at the end of this string. */
  1200. String& operator<< (const int number) throw();
  1201. /** Appends a decimal number at the end of this string. */
  1202. String& operator<< (const unsigned int number) throw();
  1203. /** Appends a decimal number at the end of this string. */
  1204. String& operator<< (const float number) throw();
  1205. /** Appends a decimal number at the end of this string. */
  1206. String& operator<< (const double number) throw();
  1207. // Comparison methods..
  1208. /** Returns true if the string contains no characters.
  1209. Note that there's also an isNotEmpty() method to help write readable code.
  1210. */
  1211. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1212. /** Returns true if the string contains at least one character.
  1213. Note that there's also an isEmpty() method to help write readable code.
  1214. */
  1215. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1216. /** Case-sensitive comparison with another string. */
  1217. bool operator== (const String& other) const throw();
  1218. /** Case-sensitive comparison with another string. */
  1219. bool operator== (const tchar* const other) const throw();
  1220. /** Case-sensitive comparison with another string. */
  1221. bool operator!= (const String& other) const throw();
  1222. /** Case-sensitive comparison with another string. */
  1223. bool operator!= (const tchar* const other) const throw();
  1224. /** Case-insensitive comparison with another string. */
  1225. bool equalsIgnoreCase (const String& other) const throw();
  1226. /** Case-insensitive comparison with another string. */
  1227. bool equalsIgnoreCase (const tchar* const other) const throw();
  1228. /** Case-sensitive comparison with another string. */
  1229. bool operator> (const String& other) const throw();
  1230. /** Case-sensitive comparison with another string. */
  1231. bool operator< (const tchar* const other) const throw();
  1232. /** Case-sensitive comparison with another string. */
  1233. bool operator>= (const String& other) const throw();
  1234. /** Case-sensitive comparison with another string. */
  1235. bool operator<= (const tchar* const other) const throw();
  1236. /** Case-sensitive comparison with another string.
  1237. @returns 0 if the two strings are identical; negative if this string
  1238. comes before the other one alphabetically, or positive if it
  1239. comes after it.
  1240. */
  1241. int compare (const tchar* const other) const throw();
  1242. /** Case-insensitive comparison with another string.
  1243. @returns 0 if the two strings are identical; negative if this string
  1244. comes before the other one alphabetically, or positive if it
  1245. comes after it.
  1246. */
  1247. int compareIgnoreCase (const tchar* const other) const throw();
  1248. /** Lexicographic comparison with another string.
  1249. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1250. characters, making it good for sorting human-readable strings.
  1251. @returns 0 if the two strings are identical; negative if this string
  1252. comes before the other one alphabetically, or positive if it
  1253. comes after it.
  1254. */
  1255. int compareLexicographically (const tchar* const other) const throw();
  1256. /** Tests whether the string begins with another string.
  1257. Uses a case-sensitive comparison.
  1258. */
  1259. bool startsWith (const tchar* const text) const throw();
  1260. /** Tests whether the string begins with a particular character.
  1261. Uses a case-sensitive comparison.
  1262. */
  1263. bool startsWithChar (const tchar character) const throw();
  1264. /** Tests whether the string begins with another string.
  1265. Uses a case-insensitive comparison.
  1266. */
  1267. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1268. /** Tests whether the string ends with another string.
  1269. Uses a case-sensitive comparison.
  1270. */
  1271. bool endsWith (const tchar* const text) const throw();
  1272. /** Tests whether the string ends with a particular character.
  1273. Uses a case-sensitive comparison.
  1274. */
  1275. bool endsWithChar (const tchar character) const throw();
  1276. /** Tests whether the string ends with another string.
  1277. Uses a case-insensitive comparison.
  1278. */
  1279. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1280. /** Tests whether the string contains another substring.
  1281. Uses a case-sensitive comparison.
  1282. */
  1283. bool contains (const tchar* const text) const throw();
  1284. /** Tests whether the string contains a particular character.
  1285. Uses a case-sensitive comparison.
  1286. */
  1287. bool containsChar (const tchar character) const throw();
  1288. /** Tests whether the string contains another substring.
  1289. Uses a case-insensitive comparison.
  1290. */
  1291. bool containsIgnoreCase (const tchar* const text) const throw();
  1292. /** Tests whether the string contains another substring as a distict word.
  1293. @returns true if the string contains this word, surrounded by
  1294. non-alphanumeric characters
  1295. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1296. */
  1297. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1298. /** Tests whether the string contains another substring as a distict word.
  1299. @returns true if the string contains this word, surrounded by
  1300. non-alphanumeric characters
  1301. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1302. */
  1303. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1304. /** Finds an instance of another substring if it exists as a distict word.
  1305. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1306. then this will return the index of the start of the substring. If it isn't
  1307. found, then it will return -1
  1308. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1309. */
  1310. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1311. /** Finds an instance of another substring if it exists as a distict word.
  1312. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1313. then this will return the index of the start of the substring. If it isn't
  1314. found, then it will return -1
  1315. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1316. */
  1317. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1318. /** Looks for any of a set of characters in the string.
  1319. Uses a case-sensitive comparison.
  1320. @returns true if the string contains any of the characters from
  1321. the string that is passed in.
  1322. */
  1323. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1324. /** Looks for a set of characters in the string.
  1325. Uses a case-sensitive comparison.
  1326. @returns true if the all the characters in the string are also found in the
  1327. string that is passed in.
  1328. */
  1329. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1330. /** Returns true if the string matches this simple wildcard expression.
  1331. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1332. This isn't a full-blown regex though! The only wildcard characters supported
  1333. are "*" and "?". It's mainly intended for filename pattern matching.
  1334. */
  1335. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1336. // Substring location methods..
  1337. /** Searches for a character inside this string.
  1338. Uses a case-sensitive comparison.
  1339. @returns the index of the first occurrence of the character in this
  1340. string, or -1 if it's not found.
  1341. */
  1342. int indexOfChar (const tchar characterToLookFor) const throw();
  1343. /** Searches for a character inside this string.
  1344. Uses a case-sensitive comparison.
  1345. @param startIndex the index from which the search should proceed
  1346. @param characterToLookFor the character to look for
  1347. @returns the index of the first occurrence of the character in this
  1348. string, or -1 if it's not found.
  1349. */
  1350. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1351. /** Returns the index of the first character that matches one of the characters
  1352. passed-in to this method.
  1353. This scans the string, beginning from the startIndex supplied, and if it finds
  1354. a character that appears in the string charactersToLookFor, it returns its index.
  1355. If none of these characters are found, it returns -1.
  1356. If ignoreCase is true, the comparison will be case-insensitive.
  1357. @see indexOfChar, lastIndexOfAnyOf
  1358. */
  1359. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1360. const int startIndex = 0,
  1361. const bool ignoreCase = false) const throw();
  1362. /** Searches for a substring within this string.
  1363. Uses a case-sensitive comparison.
  1364. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1365. */
  1366. int indexOf (const tchar* const text) const throw();
  1367. /** Searches for a substring within this string.
  1368. Uses a case-sensitive comparison.
  1369. @param startIndex the index from which the search should proceed
  1370. @param textToLookFor the string to search for
  1371. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1372. */
  1373. int indexOf (const int startIndex,
  1374. const tchar* const textToLookFor) const throw();
  1375. /** Searches for a substring within this string.
  1376. Uses a case-insensitive comparison.
  1377. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1378. */
  1379. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1380. /** Searches for a substring within this string.
  1381. Uses a case-insensitive comparison.
  1382. @param startIndex the index from which the search should proceed
  1383. @param textToLookFor the string to search for
  1384. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1385. */
  1386. int indexOfIgnoreCase (const int startIndex,
  1387. const tchar* const textToLookFor) const throw();
  1388. /** Searches for a character inside this string (working backwards from the end of the string).
  1389. Uses a case-sensitive comparison.
  1390. @returns the index of the last occurrence of the character in this
  1391. string, or -1 if it's not found.
  1392. */
  1393. int lastIndexOfChar (const tchar character) const throw();
  1394. /** Searches for a substring inside this string (working backwards from the end of the string).
  1395. Uses a case-sensitive comparison.
  1396. @returns the index of the start of the last occurrence of the
  1397. substring within this string, or -1 if it's not found.
  1398. */
  1399. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1400. /** Searches for a substring inside this string (working backwards from the end of the string).
  1401. Uses a case-insensitive comparison.
  1402. @returns the index of the start of the last occurrence of the
  1403. substring within this string, or -1 if it's not found.
  1404. */
  1405. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1406. /** Returns the index of the last character in this string that matches one of the
  1407. characters passed-in to this method.
  1408. This scans the string backwards, starting from its end, and if it finds
  1409. a character that appears in the string charactersToLookFor, it returns its index.
  1410. If none of these characters are found, it returns -1.
  1411. If ignoreCase is true, the comparison will be case-insensitive.
  1412. @see lastIndexOf, indexOfAnyOf
  1413. */
  1414. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1415. const bool ignoreCase = false) const throw();
  1416. // Substring extraction and manipulation methods..
  1417. /** Returns the character at this index in the string.
  1418. No checks are made to see if the index is within a valid range, so be careful!
  1419. */
  1420. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1421. /** Returns a character from the string such that it can also be altered.
  1422. This can be used as a way of easily changing characters in the string.
  1423. Note that the index passed-in is not checked to see whether it's in-range, so
  1424. be careful when using this.
  1425. */
  1426. tchar& operator[] (const int index) throw();
  1427. /** Returns the final character of the string.
  1428. If the string is empty this will return 0.
  1429. */
  1430. tchar getLastCharacter() const throw();
  1431. /** Returns a subsection of the string.
  1432. If the range specified is beyond the limits of the string, as much as
  1433. possible is returned.
  1434. @param startIndex the index of the start of the substring needed
  1435. @param endIndex all characters from startIndex up to (but not including)
  1436. this index are returned
  1437. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1438. */
  1439. const String substring (int startIndex,
  1440. int endIndex) const throw();
  1441. /** Returns a section of the string, starting from a given position.
  1442. @param startIndex the first character to include. If this is beyond the end
  1443. of the string, an empty string is returned. If it is zero or
  1444. less, the whole string is returned.
  1445. @returns the substring from startIndex up to the end of the string
  1446. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1447. */
  1448. const String substring (const int startIndex) const throw();
  1449. /** Returns a version of this string with a number of characters removed
  1450. from the end.
  1451. @param numberToDrop the number of characters to drop from the end of the
  1452. string. If this is greater than the length of the string,
  1453. an empty string will be returned. If zero or less, the
  1454. original string will be returned.
  1455. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1456. */
  1457. const String dropLastCharacters (const int numberToDrop) const throw();
  1458. /** Returns a section of the string starting from a given substring.
  1459. This will search for the first occurrence of the given substring, and
  1460. return the section of the string starting from the point where this is
  1461. found (optionally not including the substring itself).
  1462. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1463. fromFirstOccurrenceOf ("34", false) would return "56".
  1464. If the substring isn't found, the method will return an empty string.
  1465. If ignoreCase is true, the comparison will be case-insensitive.
  1466. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1467. */
  1468. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1469. const bool includeSubStringInResult,
  1470. const bool ignoreCase) const throw();
  1471. /** Returns a section of the string starting from the last occurrence of a given substring.
  1472. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1473. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1474. return the whole of the original string.
  1475. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1476. */
  1477. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1478. const bool includeSubStringInResult,
  1479. const bool ignoreCase) const throw();
  1480. /** Returns the start of this string, up to the first occurrence of a substring.
  1481. This will search for the first occurrence of a given substring, and then
  1482. return a copy of the string, up to the position of this substring,
  1483. optionally including or excluding the substring itself in the result.
  1484. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1485. upTo ("34", true) would return "1234".
  1486. If the substring isn't found, this will return the whole of the original string.
  1487. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1488. */
  1489. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1490. const bool includeSubStringInResult,
  1491. const bool ignoreCase) const throw();
  1492. /** Returns the start of this string, up to the last occurrence of a substring.
  1493. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1494. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1495. */
  1496. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1497. const bool includeSubStringInResult,
  1498. const bool ignoreCase) const throw();
  1499. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1500. const String trim() const throw();
  1501. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1502. const String trimStart() const throw();
  1503. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1504. const String trimEnd() const throw();
  1505. /** Returns an upper-case version of this string. */
  1506. const String toUpperCase() const throw();
  1507. /** Returns an lower-case version of this string. */
  1508. const String toLowerCase() const throw();
  1509. /** Replaces a sub-section of the string with another string.
  1510. This will return a copy of this string, with a set of characters
  1511. from startIndex to startIndex + numCharsToReplace removed, and with
  1512. a new string inserted in their place.
  1513. Note that this is a const method, and won't alter the string itself.
  1514. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1515. it will be constrained to a valid range.
  1516. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1517. characters will be taken out.
  1518. @param stringToInsert the new string to insert at startIndex after the characters have been
  1519. removed.
  1520. */
  1521. const String replaceSection (int startIndex,
  1522. int numCharactersToReplace,
  1523. const tchar* const stringToInsert) const throw();
  1524. /** Replaces all occurrences of a substring with another string.
  1525. Returns a copy of this string, with any occurrences of stringToReplace
  1526. swapped for stringToInsertInstead.
  1527. Note that this is a const method, and won't alter the string itself.
  1528. */
  1529. const String replace (const tchar* const stringToReplace,
  1530. const tchar* const stringToInsertInstead,
  1531. const bool ignoreCase = false) const throw();
  1532. /** Returns a string with all occurrences of a character replaced with a different one. */
  1533. const String replaceCharacter (const tchar characterToReplace,
  1534. const tchar characterToInsertInstead) const throw();
  1535. /** Replaces a set of characters with another set.
  1536. Returns a string in which each character from charactersToReplace has been replaced
  1537. by the character at the equivalent position in newCharacters (so the two strings
  1538. passed in must be the same length).
  1539. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1540. Note that this is a const method, and won't affect the string itself.
  1541. */
  1542. const String replaceCharacters (const String& charactersToReplace,
  1543. const tchar* const charactersToInsertInstead) const throw();
  1544. /** Returns a version of this string that only retains a fixed set of characters.
  1545. This will return a copy of this string, omitting any characters which are not
  1546. found in the string passed-in.
  1547. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1548. Note that this is a const method, and won't alter the string itself.
  1549. */
  1550. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1551. /** Returns a version of this string with a set of characters removed.
  1552. This will return a copy of this string, omitting any characters which are
  1553. found in the string passed-in.
  1554. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1555. Note that this is a const method, and won't alter the string itself.
  1556. */
  1557. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1558. /** Returns a section from the start of the string that only contains a certain set of characters.
  1559. This returns the leftmost section of the string, up to (and not including) the
  1560. first character that doesn't appear in the string passed in.
  1561. */
  1562. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1563. /** Returns a section from the start of the string that only contains a certain set of characters.
  1564. This returns the leftmost section of the string, up to (and not including) the
  1565. first character that occurs in the string passed in.
  1566. */
  1567. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1568. /** Checks whether the string might be in quotation marks.
  1569. @returns true if the string begins with a quote character (either a double or single quote).
  1570. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1571. @see unquoted, quoted
  1572. */
  1573. bool isQuotedString() const throw();
  1574. /** Removes quotation marks from around the string, (if there are any).
  1575. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1576. at the ends of the string are not affected. If there aren't any quotes, the original string
  1577. is returned.
  1578. Note that this is a const method, and won't alter the string itself.
  1579. @see isQuotedString, quoted
  1580. */
  1581. const String unquoted() const throw();
  1582. /** Adds quotation marks around a string.
  1583. This will return a copy of the string with a quote at the start and end, (but won't
  1584. add the quote if there's already one there, so it's safe to call this on strings that
  1585. may already have quotes around them).
  1586. Note that this is a const method, and won't alter the string itself.
  1587. @param quoteCharacter the character to add at the start and end
  1588. @see isQuotedString, unquoted
  1589. */
  1590. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1591. /** Writes text into this string, using printf style-arguments.
  1592. This will replace the contents of the string with the output of this
  1593. formatted printf.
  1594. Note that using the %s token with a juce string is probably a bad idea, as
  1595. this may expect differect encodings on different platforms.
  1596. @see formatted
  1597. */
  1598. void printf (const tchar* const format, ...) throw();
  1599. /** Returns a string, created using arguments in the style of printf.
  1600. This will return a string which is the result of a sprintf using the
  1601. arguments passed-in.
  1602. Note that using the %s token with a juce string is probably a bad idea, as
  1603. this may expect differect encodings on different platforms.
  1604. @see printf, vprintf
  1605. */
  1606. static const String formatted (const tchar* const format, ...) throw();
  1607. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1608. This will replace the contents of the string with the output of this
  1609. formatted printf. Used by other methods, this is public in case it's
  1610. useful for other purposes where you want to pass a va_list through directly.
  1611. Note that using the %s token with a juce string is probably a bad idea, as
  1612. this may expect differect encodings on different platforms.
  1613. @see printf, formatted
  1614. */
  1615. void vprintf (const tchar* const format, va_list& args) throw();
  1616. /** Creates a string which is a version of a string repeated and joined together.
  1617. @param stringToRepeat the string to repeat
  1618. @param numberOfTimesToRepeat how many times to repeat it
  1619. */
  1620. static const String repeatedString (const tchar* const stringToRepeat,
  1621. int numberOfTimesToRepeat) throw();
  1622. /** Creates a string from data in an unknown format.
  1623. This looks at some binary data and tries to guess whether it's Unicode
  1624. or 8-bit characters, then returns a string that represents it correctly.
  1625. Should be able to handle Unicode endianness correctly, by looking at
  1626. the first two bytes.
  1627. */
  1628. static const String createStringFromData (const void* const data,
  1629. const int size) throw();
  1630. // Numeric conversions..
  1631. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1632. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1633. */
  1634. explicit String (const int decimalInteger) throw();
  1635. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1636. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1637. */
  1638. explicit String (const unsigned int decimalInteger) throw();
  1639. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1640. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1641. */
  1642. explicit String (const short decimalInteger) throw();
  1643. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1644. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1645. */
  1646. explicit String (const unsigned short decimalInteger) throw();
  1647. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1648. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1649. */
  1650. explicit String (const int64 largeIntegerValue) throw();
  1651. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1652. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1653. */
  1654. explicit String (const uint64 largeIntegerValue) throw();
  1655. /** Creates a string representing this floating-point number.
  1656. @param floatValue the value to convert to a string
  1657. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1658. decimal places, and will not use exponent notation. If 0 or
  1659. less, it will use exponent notation if necessary.
  1660. @see getDoubleValue, getIntValue
  1661. */
  1662. explicit String (const float floatValue,
  1663. const int numberOfDecimalPlaces = 0) throw();
  1664. /** Creates a string representing this floating-point number.
  1665. @param doubleValue the value to convert to a string
  1666. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1667. decimal places, and will not use exponent notation. If 0 or
  1668. less, it will use exponent notation if necessary.
  1669. @see getFloatValue, getIntValue
  1670. */
  1671. explicit String (const double doubleValue,
  1672. const int numberOfDecimalPlaces = 0) throw();
  1673. /** Parses this string to find its numerical value (up to 32 bits in size).
  1674. @returns the value of the string as a 32 bit signed base-10 integer.
  1675. @see getTrailingIntValue, getHexValue32, getHexValue64
  1676. */
  1677. int getIntValue() const throw();
  1678. /** Parses this string to find its numerical value (up to 64 bits in size).
  1679. @returns the value of the string as a 64 bit signed base-10 integer.
  1680. */
  1681. int64 getLargeIntValue() const throw();
  1682. /** Parses a decimal number from the end of the string.
  1683. This will look for a value at the end of the string.
  1684. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1685. Negative numbers are not handled, so "xyz-5" returns 5.
  1686. @see getIntValue
  1687. */
  1688. int getTrailingIntValue() const throw();
  1689. /** Parses this string as a floating point number.
  1690. @returns the value of the string as a 32-bit floating point value.
  1691. @see getDoubleValue
  1692. */
  1693. float getFloatValue() const throw();
  1694. /** Parses this string as a floating point number.
  1695. @returns the value of the string as a 64-bit floating point value.
  1696. @see getFloatValue
  1697. */
  1698. double getDoubleValue() const throw();
  1699. /** Parses the string as a hexadecimal number.
  1700. Non-hexadecimal characters in the string are ignored.
  1701. If the string contains too many characters, then the lowest significant
  1702. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1703. @returns a 32-bit number which is the value of the string in hex.
  1704. */
  1705. int getHexValue32() const throw();
  1706. /** Parses the string as a hexadecimal number.
  1707. Non-hexadecimal characters in the string are ignored.
  1708. If the string contains too many characters, then the lowest significant
  1709. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1710. @returns a 64-bit number which is the value of the string in hex.
  1711. */
  1712. int64 getHexValue64() const throw();
  1713. /** Creates a string representing this 32-bit value in hexadecimal. */
  1714. static const String toHexString (const int number) throw();
  1715. /** Creates a string representing this 64-bit value in hexadecimal. */
  1716. static const String toHexString (const int64 number) throw();
  1717. /** Creates a string representing this 16-bit value in hexadecimal. */
  1718. static const String toHexString (const short number) throw();
  1719. /** Creates a string containing a hex dump of a block of binary data.
  1720. @param data the binary data to use as input
  1721. @param size how many bytes of data to use
  1722. @param groupSize how many bytes are grouped together before inserting a
  1723. space into the output. e.g. group size 0 has no spaces,
  1724. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1725. like "bea1 c2ff".
  1726. */
  1727. static const String toHexString (const unsigned char* data,
  1728. const int size,
  1729. const int groupSize = 1) throw();
  1730. // Casting to character arrays..
  1731. #if JUCE_STRINGS_ARE_UNICODE
  1732. /** Returns a version of this string using the default 8-bit system encoding.
  1733. Because it returns a reference to the string's internal data, the pointer
  1734. that is returned must not be stored anywhere, as it can be deleted whenever the
  1735. string changes.
  1736. */
  1737. operator const char*() const throw();
  1738. /** Returns a unicode version of this string.
  1739. Because it returns a reference to the string's internal data, the pointer
  1740. that is returned must not be stored anywhere, as it can be deleted whenever the
  1741. string changes.
  1742. */
  1743. inline operator const juce_wchar*() const throw() { return text->text; }
  1744. #else
  1745. /** Returns a version of this string using the default 8-bit system encoding.
  1746. Because it returns a reference to the string's internal data, the pointer
  1747. that is returned must not be stored anywhere, as it can be deleted whenever the
  1748. string changes.
  1749. */
  1750. inline operator const char*() const throw() { return text->text; }
  1751. /** Returns a unicode version of this string.
  1752. Because it returns a reference to the string's internal data, the pointer
  1753. that is returned must not be stored anywhere, as it can be deleted whenever the
  1754. string changes.
  1755. */
  1756. operator const juce_wchar*() const throw();
  1757. #endif
  1758. /** Copies the string to a buffer.
  1759. @param destBuffer the place to copy it to
  1760. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1761. not including the tailing zero, so this shouldn't be
  1762. larger than the size of your destination buffer - 1
  1763. */
  1764. void copyToBuffer (char* const destBuffer,
  1765. const int maxCharsToCopy) const throw();
  1766. /** Copies the string to a unicode buffer.
  1767. @param destBuffer the place to copy it to
  1768. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1769. not including the tailing zero, so this shouldn't be
  1770. larger than the size of your destination buffer - 1
  1771. */
  1772. void copyToBuffer (juce_wchar* const destBuffer,
  1773. const int maxCharsToCopy) const throw();
  1774. /** Copies the string to a buffer as UTF-8 characters.
  1775. Returns the number of bytes copied to the buffer, including the terminating null
  1776. character.
  1777. @param destBuffer the place to copy it to; if this is a null pointer,
  1778. the method just returns the number of bytes required
  1779. (including the terminating null character).
  1780. */
  1781. int copyToUTF8 (uint8* const destBuffer) const throw();
  1782. /** Returns a pointer to a UTF-8 version of this string.
  1783. Because it returns a reference to the string's internal data, the pointer
  1784. that is returned must not be stored anywhere, as it can be deleted whenever the
  1785. string changes.
  1786. */
  1787. const char* toUTF8() const throw();
  1788. /** Creates a String from a UTF-8 encoded buffer.
  1789. If the size is < 0, it'll keep reading until it hits a zero.
  1790. */
  1791. static const String fromUTF8 (const uint8* const utf8buffer,
  1792. int bufferSizeBytes = -1) throw();
  1793. /** Increases the string's internally allocated storage.
  1794. Although the string's contents won't be affected by this call, it will
  1795. increase the amount of memory allocated internally for the string to grow into.
  1796. If you're about to make a large number of calls to methods such
  1797. as += or <<, it's more efficient to preallocate enough extra space
  1798. beforehand, so that these methods won't have to keep resizing the string
  1799. to append the extra characters.
  1800. @param numCharsNeeded the number of characters to allocate storage for. If this
  1801. value is less than the currently allocated size, it will
  1802. have no effect.
  1803. */
  1804. void preallocateStorage (const int numCharsNeeded) throw();
  1805. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1806. private:
  1807. struct InternalRefCountedStringHolder
  1808. {
  1809. int refCount;
  1810. int allocatedNumChars;
  1811. #if JUCE_STRINGS_ARE_UNICODE
  1812. wchar_t text[1];
  1813. #else
  1814. char text[1];
  1815. #endif
  1816. };
  1817. InternalRefCountedStringHolder* text;
  1818. static InternalRefCountedStringHolder emptyString;
  1819. // internal constructor that preallocates a certain amount of memory
  1820. String (const int numChars, const int dummyVariable) throw();
  1821. void deleteInternal() throw();
  1822. void createInternal (const int numChars) throw();
  1823. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1824. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1825. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1826. void dupeInternalIfMultiplyReferenced() throw();
  1827. };
  1828. /** Global operator to allow a String to be appended to a string literal.
  1829. This allows the use of expressions such as "abc" + String (x)
  1830. @see String
  1831. */
  1832. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1833. const String& string2) throw();
  1834. /** Global operator to allow a String to be appended to a string literal.
  1835. This allows the use of expressions such as "abc" + String (x)
  1836. @see String
  1837. */
  1838. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1839. const String& string2) throw();
  1840. #endif // __JUCE_STRING_JUCEHEADER__
  1841. /********* End of inlined file: juce_String.h *********/
  1842. /**
  1843. Acts as an application-wide logging class.
  1844. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1845. method and this will then be used by all calls to writeToLog.
  1846. The logger class also contains methods for writing messages to the debugger's
  1847. output stream.
  1848. @see FileLogger
  1849. */
  1850. class JUCE_API Logger
  1851. {
  1852. public:
  1853. /** Destructor. */
  1854. virtual ~Logger();
  1855. /** Sets the current logging class to use.
  1856. Note that the object passed in won't be deleted when no longer needed.
  1857. A null pointer can be passed-in to disable any logging.
  1858. If deleteOldLogger is set to true, the existing logger will be
  1859. deleted (if there is one).
  1860. */
  1861. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1862. const bool deleteOldLogger = false);
  1863. /** Writes a string to the current logger.
  1864. This will pass the string to the logger's logMessage() method if a logger
  1865. has been set.
  1866. @see logMessage
  1867. */
  1868. static void JUCE_CALLTYPE writeToLog (const String& message);
  1869. /** Writes a message to the standard error stream.
  1870. This can be called directly, or by using the DBG() macro in
  1871. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1872. */
  1873. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1874. /** Writes a message to the standard error stream.
  1875. This can be called directly, or by using the DBG_PRINTF() macro in
  1876. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1877. */
  1878. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1879. protected:
  1880. Logger();
  1881. /** This is overloaded by subclasses to implement custom logging behaviour.
  1882. @see setCurrentLogger
  1883. */
  1884. virtual void logMessage (const String& message) = 0;
  1885. };
  1886. #endif // __JUCE_LOGGER_JUCEHEADER__
  1887. /********* End of inlined file: juce_Logger.h *********/
  1888. END_JUCE_NAMESPACE
  1889. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1890. /********* End of inlined file: juce_StandardHeader.h *********/
  1891. BEGIN_JUCE_NAMESPACE
  1892. #if JUCE_MSVC
  1893. // this is set explicitly in case the app is using a different packing size.
  1894. #pragma pack (push, 8)
  1895. #pragma warning (push)
  1896. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1897. #endif
  1898. #if JUCE_MAC
  1899. #pragma align=natural
  1900. #endif
  1901. #define JUCE_PUBLIC_INCLUDES
  1902. // this is where all the class header files get brought in..
  1903. /********* Start of inlined file: juce_core_includes.h *********/
  1904. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1905. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1906. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1907. /********* Start of inlined file: juce_Atomic.h *********/
  1908. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1909. #define __JUCE_ATOMIC_JUCEHEADER__
  1910. // Atomic increment/decrement operations..
  1911. #if JUCE_MAC && ! DOXYGEN
  1912. #if ! MACOS_10_3_OR_EARLIER
  1913. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1914. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1915. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1916. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1917. #else
  1918. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  1919. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  1920. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1921. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1922. #endif
  1923. #elif JUCE_GCC
  1924. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1925. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1926. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1927. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1928. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1929. #else
  1930. /** Increments an integer in a thread-safe way. */
  1931. forcedinline void atomicIncrement (int& variable) throw()
  1932. {
  1933. __asm__ __volatile__ (
  1934. #if JUCE_64BIT
  1935. "lock incl (%%rax)"
  1936. :
  1937. : "a" (&variable)
  1938. : "cc", "memory");
  1939. #else
  1940. "lock incl %0"
  1941. : "=m" (variable)
  1942. : "m" (variable));
  1943. #endif
  1944. }
  1945. /** Increments an integer in a thread-safe way and returns the incremented value. */
  1946. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  1947. {
  1948. int result;
  1949. __asm__ __volatile__ (
  1950. #if JUCE_64BIT
  1951. "lock xaddl %%ebx, (%%rax) \n\
  1952. incl %%ebx"
  1953. : "=b" (result)
  1954. : "a" (&variable), "b" (1)
  1955. : "cc", "memory");
  1956. #else
  1957. "lock xaddl %%eax, (%%ecx) \n\
  1958. incl %%eax"
  1959. : "=a" (result)
  1960. : "c" (&variable), "a" (1)
  1961. : "memory");
  1962. #endif
  1963. return result;
  1964. }
  1965. /** Decrememts an integer in a thread-safe way. */
  1966. forcedinline void atomicDecrement (int& variable) throw()
  1967. {
  1968. __asm__ __volatile__ (
  1969. #if JUCE_64BIT
  1970. "lock decl (%%rax)"
  1971. :
  1972. : "a" (&variable)
  1973. : "cc", "memory");
  1974. #else
  1975. "lock decl %0"
  1976. : "=m" (variable)
  1977. : "m" (variable));
  1978. #endif
  1979. }
  1980. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  1981. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  1982. {
  1983. int result;
  1984. __asm__ __volatile__ (
  1985. #if JUCE_64BIT
  1986. "lock xaddl %%ebx, (%%rax) \n\
  1987. decl %%ebx"
  1988. : "=b" (result)
  1989. : "a" (&variable), "b" (-1)
  1990. : "cc", "memory");
  1991. #else
  1992. "lock xaddl %%eax, (%%ecx) \n\
  1993. decl %%eax"
  1994. : "=a" (result)
  1995. : "c" (&variable), "a" (-1)
  1996. : "memory");
  1997. #endif
  1998. return result;
  1999. }
  2000. #endif
  2001. #elif JUCE_USE_INTRINSICS
  2002. #pragma intrinsic (_InterlockedIncrement)
  2003. #pragma intrinsic (_InterlockedDecrement)
  2004. /** Increments an integer in a thread-safe way. */
  2005. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2006. {
  2007. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2008. }
  2009. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2010. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2011. {
  2012. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2013. }
  2014. /** Decrememts an integer in a thread-safe way. */
  2015. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2016. {
  2017. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2018. }
  2019. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2020. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2021. {
  2022. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2023. }
  2024. #else
  2025. /** Increments an integer in a thread-safe way. */
  2026. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2027. {
  2028. __asm {
  2029. mov ecx, dword ptr [variable]
  2030. lock inc dword ptr [ecx]
  2031. }
  2032. }
  2033. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2034. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2035. {
  2036. int result;
  2037. __asm {
  2038. mov ecx, dword ptr [variable]
  2039. mov eax, 1
  2040. lock xadd dword ptr [ecx], eax
  2041. inc eax
  2042. mov result, eax
  2043. }
  2044. return result;
  2045. }
  2046. /** Decrememts an integer in a thread-safe way. */
  2047. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2048. {
  2049. __asm {
  2050. mov ecx, dword ptr [variable]
  2051. lock dec dword ptr [ecx]
  2052. }
  2053. }
  2054. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2055. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2056. {
  2057. int result;
  2058. __asm {
  2059. mov ecx, dword ptr [variable]
  2060. mov eax, -1
  2061. lock xadd dword ptr [ecx], eax
  2062. dec eax
  2063. mov result, eax
  2064. }
  2065. return result;
  2066. }
  2067. #endif
  2068. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2069. /********* End of inlined file: juce_Atomic.h *********/
  2070. #endif
  2071. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2072. #endif
  2073. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2074. /********* Start of inlined file: juce_FileLogger.h *********/
  2075. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2076. #define __JUCE_FILELOGGER_JUCEHEADER__
  2077. /********* Start of inlined file: juce_File.h *********/
  2078. #ifndef __JUCE_FILE_JUCEHEADER__
  2079. #define __JUCE_FILE_JUCEHEADER__
  2080. /********* Start of inlined file: juce_OwnedArray.h *********/
  2081. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2082. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2083. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2084. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2085. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2086. /** The default size of chunk in which arrays increase their storage.
  2087. Used by ArrayAllocationBase and its subclasses.
  2088. */
  2089. const int juceDefaultArrayGranularity = 8;
  2090. /**
  2091. Implements some basic array storage allocation functions.
  2092. This class isn't really for public use - it's used by the other
  2093. array classes, but might come in handy for some purposes.
  2094. @see Array, OwnedArray, ReferenceCountedArray
  2095. */
  2096. template <class ElementType>
  2097. class ArrayAllocationBase
  2098. {
  2099. protected:
  2100. /** Creates an empty array.
  2101. @param granularity_ this is the size of increment by which the internal storage
  2102. will be increased.
  2103. */
  2104. ArrayAllocationBase (const int granularity_) throw()
  2105. : elements (0),
  2106. numAllocated (0),
  2107. granularity (granularity_)
  2108. {
  2109. }
  2110. /** Destructor. */
  2111. ~ArrayAllocationBase() throw()
  2112. {
  2113. delete[] elements;
  2114. }
  2115. /** Changes the amount of storage allocated.
  2116. This will retain any data currently held in the array, and either add or
  2117. remove extra space at the end.
  2118. @param numElements the number of elements that are needed
  2119. */
  2120. void setAllocatedSize (const int numElements) throw()
  2121. {
  2122. if (numAllocated != numElements)
  2123. {
  2124. if (numElements > 0)
  2125. {
  2126. ElementType* const newElements = new ElementType [numElements];
  2127. const int itemsToRetain = jmin (numElements, numAllocated);
  2128. for (int i = 0; i < itemsToRetain; ++i)
  2129. newElements[i] = elements[i];
  2130. delete[] elements;
  2131. elements = newElements;
  2132. }
  2133. else if (elements != 0)
  2134. {
  2135. delete[] elements;
  2136. elements = 0;
  2137. }
  2138. numAllocated = numElements;
  2139. }
  2140. }
  2141. /** Increases the amount of storage allocated if it is less than a given amount.
  2142. This will retain any data currently held in the array, but will add
  2143. extra space at the end to make sure there it's at least as big as the size
  2144. passed in. If it's already bigger, no action is taken.
  2145. @param minNumElements the minimum number of elements that are needed
  2146. */
  2147. void ensureAllocatedSize (int minNumElements) throw()
  2148. {
  2149. if (minNumElements > numAllocated)
  2150. {
  2151. // for arrays with small granularity that get big, start
  2152. // increasing the size in bigger jumps
  2153. if (minNumElements > (granularity << 6))
  2154. {
  2155. minNumElements += (minNumElements / granularity);
  2156. if (minNumElements > (granularity << 8))
  2157. minNumElements += granularity << 6;
  2158. else
  2159. minNumElements += granularity << 5;
  2160. }
  2161. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2162. }
  2163. }
  2164. ElementType* elements;
  2165. int numAllocated, granularity;
  2166. private:
  2167. ArrayAllocationBase (const ArrayAllocationBase&);
  2168. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2169. };
  2170. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2171. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2172. /********* Start of inlined file: juce_ElementComparator.h *********/
  2173. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2174. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2175. /**
  2176. Sorts a range of elements in an array.
  2177. The comparator object that is passed-in must define a public method with the following
  2178. signature:
  2179. @code
  2180. int compareElements (ElementType first, ElementType second);
  2181. @endcode
  2182. ..and this method must return:
  2183. - a value of < 0 if the first comes before the second
  2184. - a value of 0 if the two objects are equivalent
  2185. - a value of > 0 if the second comes before the first
  2186. To improve performance, the compareElements() method can be declared as static or const.
  2187. @param comparator an object which defines a compareElements() method
  2188. @param array the array to sort
  2189. @param firstElement the index of the first element of the range to be sorted
  2190. @param lastElement the index of the last element in the range that needs
  2191. sorting (this is inclusive)
  2192. @param retainOrderOfEquivalentItems if true, the order of items that the
  2193. comparator deems the same will be maintained - this will be
  2194. a slower algorithm than if they are allowed to be moved around.
  2195. @see sortArrayRetainingOrder
  2196. */
  2197. template <class ElementType, class ElementComparator>
  2198. static void sortArray (ElementComparator& comparator,
  2199. ElementType* const array,
  2200. int firstElement,
  2201. int lastElement,
  2202. const bool retainOrderOfEquivalentItems)
  2203. {
  2204. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2205. // avoids getting warning messages about the parameter being unused
  2206. if (lastElement > firstElement)
  2207. {
  2208. if (retainOrderOfEquivalentItems)
  2209. {
  2210. for (int i = firstElement; i < lastElement; ++i)
  2211. {
  2212. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2213. {
  2214. const ElementType temp = array [i];
  2215. array [i] = array[i + 1];
  2216. array [i + 1] = temp;
  2217. if (i > firstElement)
  2218. i -= 2;
  2219. }
  2220. }
  2221. }
  2222. else
  2223. {
  2224. int fromStack[30], toStack[30];
  2225. int stackIndex = 0;
  2226. for (;;)
  2227. {
  2228. const int size = (lastElement - firstElement) + 1;
  2229. if (size <= 8)
  2230. {
  2231. int j = lastElement;
  2232. int maxIndex;
  2233. while (j > firstElement)
  2234. {
  2235. maxIndex = firstElement;
  2236. for (int k = firstElement + 1; k <= j; ++k)
  2237. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2238. maxIndex = k;
  2239. const ElementType temp = array [maxIndex];
  2240. array [maxIndex] = array[j];
  2241. array [j] = temp;
  2242. --j;
  2243. }
  2244. }
  2245. else
  2246. {
  2247. const int mid = firstElement + (size >> 1);
  2248. ElementType temp = array [mid];
  2249. array [mid] = array [firstElement];
  2250. array [firstElement] = temp;
  2251. int i = firstElement;
  2252. int j = lastElement + 1;
  2253. for (;;)
  2254. {
  2255. while (++i <= lastElement
  2256. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2257. {}
  2258. while (--j > firstElement
  2259. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2260. {}
  2261. if (j < i)
  2262. break;
  2263. temp = array[i];
  2264. array[i] = array[j];
  2265. array[j] = temp;
  2266. }
  2267. temp = array [firstElement];
  2268. array [firstElement] = array[j];
  2269. array [j] = temp;
  2270. if (j - 1 - firstElement >= lastElement - i)
  2271. {
  2272. if (firstElement + 1 < j)
  2273. {
  2274. fromStack [stackIndex] = firstElement;
  2275. toStack [stackIndex] = j - 1;
  2276. ++stackIndex;
  2277. }
  2278. if (i < lastElement)
  2279. {
  2280. firstElement = i;
  2281. continue;
  2282. }
  2283. }
  2284. else
  2285. {
  2286. if (i < lastElement)
  2287. {
  2288. fromStack [stackIndex] = i;
  2289. toStack [stackIndex] = lastElement;
  2290. ++stackIndex;
  2291. }
  2292. if (firstElement + 1 < j)
  2293. {
  2294. lastElement = j - 1;
  2295. continue;
  2296. }
  2297. }
  2298. }
  2299. if (--stackIndex < 0)
  2300. break;
  2301. jassert (stackIndex < numElementsInArray (fromStack));
  2302. firstElement = fromStack [stackIndex];
  2303. lastElement = toStack [stackIndex];
  2304. }
  2305. }
  2306. }
  2307. }
  2308. /**
  2309. Searches a sorted array of elements, looking for the index at which a specified value
  2310. should be inserted for it to be in the correct order.
  2311. The comparator object that is passed-in must define a public method with the following
  2312. signature:
  2313. @code
  2314. int compareElements (ElementType first, ElementType second);
  2315. @endcode
  2316. ..and this method must return:
  2317. - a value of < 0 if the first comes before the second
  2318. - a value of 0 if the two objects are equivalent
  2319. - a value of > 0 if the second comes before the first
  2320. To improve performance, the compareElements() method can be declared as static or const.
  2321. @param comparator an object which defines a compareElements() method
  2322. @param array the array to search
  2323. @param newElement the value that is going to be inserted
  2324. @param firstElement the index of the first element to search
  2325. @param lastElement the index of the last element in the range (this is non-inclusive)
  2326. */
  2327. template <class ElementType, class ElementComparator>
  2328. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2329. ElementType* const array,
  2330. const ElementType newElement,
  2331. int firstElement,
  2332. int lastElement)
  2333. {
  2334. jassert (firstElement <= lastElement);
  2335. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2336. // avoids getting warning messages about the parameter being unused
  2337. while (firstElement < lastElement)
  2338. {
  2339. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2340. {
  2341. ++firstElement;
  2342. break;
  2343. }
  2344. else
  2345. {
  2346. const int halfway = (firstElement + lastElement) >> 1;
  2347. if (halfway == firstElement)
  2348. {
  2349. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2350. ++firstElement;
  2351. break;
  2352. }
  2353. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2354. {
  2355. firstElement = halfway;
  2356. }
  2357. else
  2358. {
  2359. lastElement = halfway;
  2360. }
  2361. }
  2362. }
  2363. return firstElement;
  2364. }
  2365. /**
  2366. A simple ElementComparator class that can be used to sort an array of
  2367. integer primitive objects.
  2368. Example: @code
  2369. Array <int> myArray;
  2370. IntegerElementComparator<int> sorter;
  2371. myArray.sort (sorter);
  2372. @endcode
  2373. For floating point values, see the FloatElementComparator class instead.
  2374. @see FloatElementComparator, ElementComparator
  2375. */
  2376. template <class ElementType>
  2377. class IntegerElementComparator
  2378. {
  2379. public:
  2380. static int compareElements (const ElementType first,
  2381. const ElementType second) throw()
  2382. {
  2383. return first - second;
  2384. }
  2385. };
  2386. /**
  2387. A simple ElementComparator class that can be used to sort an array of numeric
  2388. double or floating point primitive objects.
  2389. Example: @code
  2390. Array <double> myArray;
  2391. FloatElementComparator<double> sorter;
  2392. myArray.sort (sorter);
  2393. @endcode
  2394. For integer values, see the IntegerElementComparator class instead.
  2395. @see IntegerElementComparator, ElementComparator
  2396. */
  2397. template <class ElementType>
  2398. class FloatElementComparator
  2399. {
  2400. public:
  2401. static int compareElements (const ElementType first,
  2402. const ElementType second) throw()
  2403. {
  2404. return (first < second) ? -1
  2405. : ((first == second) ? 0
  2406. : 1);
  2407. }
  2408. };
  2409. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2410. /********* End of inlined file: juce_ElementComparator.h *********/
  2411. /********* Start of inlined file: juce_CriticalSection.h *********/
  2412. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2413. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2414. /**
  2415. Prevents multiple threads from accessing shared objects at the same time.
  2416. @see ScopedLock, Thread, InterProcessLock
  2417. */
  2418. class JUCE_API CriticalSection
  2419. {
  2420. public:
  2421. /**
  2422. Creates a CriticalSection object
  2423. */
  2424. CriticalSection() throw();
  2425. /** Destroys a CriticalSection object.
  2426. If the critical section is deleted whilst locked, its subsequent behaviour
  2427. is unpredictable.
  2428. */
  2429. ~CriticalSection() throw();
  2430. /** Locks this critical section.
  2431. If the lock is currently held by another thread, this will wait until it
  2432. becomes free.
  2433. If the lock is already held by the caller thread, the method returns immediately.
  2434. @see exit, ScopedLock
  2435. */
  2436. void enter() const throw();
  2437. /** Attempts to lock this critical section without blocking.
  2438. This method behaves identically to CriticalSection::enter, except that the caller thread
  2439. does not wait if the lock is currently held by another thread but returns false immediately.
  2440. @returns false if the lock is currently held by another thread, true otherwise.
  2441. @see enter
  2442. */
  2443. bool tryEnter() const throw();
  2444. /** Releases the lock.
  2445. If the caller thread hasn't got the lock, this can have unpredictable results.
  2446. If the enter() method has been called multiple times by the thread, each
  2447. call must be matched by a call to exit() before other threads will be allowed
  2448. to take over the lock.
  2449. @see enter, ScopedLock
  2450. */
  2451. void exit() const throw();
  2452. juce_UseDebuggingNewOperator
  2453. private:
  2454. #if JUCE_WIN32
  2455. #if JUCE_64BIT
  2456. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2457. // block of memory here that's big enough to be used internally as a windows critical
  2458. // section object.
  2459. uint8 internal [44];
  2460. #else
  2461. uint8 internal [24];
  2462. #endif
  2463. #else
  2464. mutable pthread_mutex_t internal;
  2465. #endif
  2466. CriticalSection (const CriticalSection&);
  2467. const CriticalSection& operator= (const CriticalSection&);
  2468. };
  2469. /**
  2470. A class that can be used in place of a real CriticalSection object.
  2471. This is currently used by some templated array classes, and should get
  2472. optimised out by the compiler.
  2473. @see Array, OwnedArray, ReferenceCountedArray
  2474. */
  2475. class JUCE_API DummyCriticalSection
  2476. {
  2477. public:
  2478. forcedinline DummyCriticalSection() throw() {}
  2479. forcedinline ~DummyCriticalSection() throw() {}
  2480. forcedinline void enter() const throw() {}
  2481. forcedinline void exit() const throw() {}
  2482. };
  2483. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2484. /********* End of inlined file: juce_CriticalSection.h *********/
  2485. /** An array designed for holding objects.
  2486. This holds a list of pointers to objects, and will automatically
  2487. delete the objects when they are removed from the array, or when the
  2488. array is itself deleted.
  2489. Declare it in the form: OwnedArray<MyObjectClass>
  2490. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2491. After adding objects, they are 'owned' by the array and will be deleted when
  2492. removed or replaced.
  2493. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2494. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2495. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2496. */
  2497. template <class ObjectClass,
  2498. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2499. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2500. {
  2501. public:
  2502. /** Creates an empty array.
  2503. @param granularity this is the size of increment by which the internal storage
  2504. used by the array will grow. Only change it from the default if you know the
  2505. array is going to be very big and needs to be able to grow efficiently.
  2506. @see ArrayAllocationBase
  2507. */
  2508. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2509. : ArrayAllocationBase <ObjectClass*> (granularity),
  2510. numUsed (0)
  2511. {
  2512. }
  2513. /** Deletes the array and also deletes any objects inside it.
  2514. To get rid of the array without deleting its objects, use its
  2515. clear (false) method before deleting it.
  2516. */
  2517. ~OwnedArray()
  2518. {
  2519. clear (true);
  2520. }
  2521. /** Clears the array, optionally deleting the objects inside it first. */
  2522. void clear (const bool deleteObjects = true)
  2523. {
  2524. lock.enter();
  2525. if (deleteObjects)
  2526. {
  2527. while (numUsed > 0)
  2528. delete this->elements [--numUsed];
  2529. }
  2530. this->setAllocatedSize (0);
  2531. numUsed = 0;
  2532. lock.exit();
  2533. }
  2534. /** Returns the number of items currently in the array.
  2535. @see operator[]
  2536. */
  2537. inline int size() const throw()
  2538. {
  2539. return numUsed;
  2540. }
  2541. /** Returns a pointer to the object at this index in the array.
  2542. If the index is out-of-range, this will return a null pointer, (and
  2543. it could be null anyway, because it's ok for the array to hold null
  2544. pointers as well as objects).
  2545. @see getUnchecked
  2546. */
  2547. inline ObjectClass* operator[] (const int index) const throw()
  2548. {
  2549. lock.enter();
  2550. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2551. ? this->elements [index]
  2552. : (ObjectClass*) 0;
  2553. lock.exit();
  2554. return result;
  2555. }
  2556. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2557. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2558. it can be used when you're sure the index if always going to be legal.
  2559. */
  2560. inline ObjectClass* getUnchecked (const int index) const throw()
  2561. {
  2562. lock.enter();
  2563. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2564. ObjectClass* const result = this->elements [index];
  2565. lock.exit();
  2566. return result;
  2567. }
  2568. /** Returns a pointer to the first object in the array.
  2569. This will return a null pointer if the array's empty.
  2570. @see getLast
  2571. */
  2572. inline ObjectClass* getFirst() const throw()
  2573. {
  2574. lock.enter();
  2575. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2576. : (ObjectClass*) 0;
  2577. lock.exit();
  2578. return result;
  2579. }
  2580. /** Returns a pointer to the last object in the array.
  2581. This will return a null pointer if the array's empty.
  2582. @see getFirst
  2583. */
  2584. inline ObjectClass* getLast() const throw()
  2585. {
  2586. lock.enter();
  2587. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2588. : (ObjectClass*) 0;
  2589. lock.exit();
  2590. return result;
  2591. }
  2592. /** Finds the index of an object which might be in the array.
  2593. @param objectToLookFor the object to look for
  2594. @returns the index at which the object was found, or -1 if it's not found
  2595. */
  2596. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2597. {
  2598. int result = -1;
  2599. lock.enter();
  2600. ObjectClass* const* e = this->elements;
  2601. for (int i = numUsed; --i >= 0;)
  2602. {
  2603. if (objectToLookFor == *e)
  2604. {
  2605. result = (int) (e - this->elements);
  2606. break;
  2607. }
  2608. ++e;
  2609. }
  2610. lock.exit();
  2611. return result;
  2612. }
  2613. /** Returns true if the array contains a specified object.
  2614. @param objectToLookFor the object to look for
  2615. @returns true if the object is in the array
  2616. */
  2617. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2618. {
  2619. lock.enter();
  2620. ObjectClass* const* e = this->elements;
  2621. int i = numUsed;
  2622. while (i >= 4)
  2623. {
  2624. if (objectToLookFor == *e
  2625. || objectToLookFor == *++e
  2626. || objectToLookFor == *++e
  2627. || objectToLookFor == *++e)
  2628. {
  2629. lock.exit();
  2630. return true;
  2631. }
  2632. i -= 4;
  2633. ++e;
  2634. }
  2635. while (i > 0)
  2636. {
  2637. if (objectToLookFor == *e)
  2638. {
  2639. lock.exit();
  2640. return true;
  2641. }
  2642. --i;
  2643. ++e;
  2644. }
  2645. lock.exit();
  2646. return false;
  2647. }
  2648. /** Appends a new object to the end of the array.
  2649. Note that the this object will be deleted by the OwnedArray when it
  2650. is removed, so be careful not to delete it somewhere else.
  2651. Also be careful not to add the same object to the array more than once,
  2652. as this will obviously cause deletion of dangling pointers.
  2653. @param newObject the new object to add to the array
  2654. @see set, insert, addIfNotAlreadyThere, addSorted
  2655. */
  2656. void add (const ObjectClass* const newObject) throw()
  2657. {
  2658. lock.enter();
  2659. this->ensureAllocatedSize (numUsed + 1);
  2660. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2661. lock.exit();
  2662. }
  2663. /** Inserts a new object into the array at the given index.
  2664. Note that the this object will be deleted by the OwnedArray when it
  2665. is removed, so be careful not to delete it somewhere else.
  2666. If the index is less than 0 or greater than the size of the array, the
  2667. element will be added to the end of the array.
  2668. Otherwise, it will be inserted into the array, moving all the later elements
  2669. along to make room.
  2670. Be careful not to add the same object to the array more than once,
  2671. as this will obviously cause deletion of dangling pointers.
  2672. @param indexToInsertAt the index at which the new element should be inserted
  2673. @param newObject the new object to add to the array
  2674. @see add, addSorted, addIfNotAlreadyThere, set
  2675. */
  2676. void insert (int indexToInsertAt,
  2677. const ObjectClass* const newObject) throw()
  2678. {
  2679. if (indexToInsertAt >= 0)
  2680. {
  2681. lock.enter();
  2682. if (indexToInsertAt > numUsed)
  2683. indexToInsertAt = numUsed;
  2684. this->ensureAllocatedSize (numUsed + 1);
  2685. ObjectClass** const e = this->elements + indexToInsertAt;
  2686. const int numToMove = numUsed - indexToInsertAt;
  2687. if (numToMove > 0)
  2688. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2689. *e = const_cast <ObjectClass*> (newObject);
  2690. ++numUsed;
  2691. lock.exit();
  2692. }
  2693. else
  2694. {
  2695. add (newObject);
  2696. }
  2697. }
  2698. /** Appends a new object at the end of the array as long as the array doesn't
  2699. already contain it.
  2700. If the array already contains a matching object, nothing will be done.
  2701. @param newObject the new object to add to the array
  2702. */
  2703. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2704. {
  2705. lock.enter();
  2706. if (! contains (newObject))
  2707. add (newObject);
  2708. lock.exit();
  2709. }
  2710. /** Replaces an object in the array with a different one.
  2711. If the index is less than zero, this method does nothing.
  2712. If the index is beyond the end of the array, the new object is added to the end of the array.
  2713. Be careful not to add the same object to the array more than once,
  2714. as this will obviously cause deletion of dangling pointers.
  2715. @param indexToChange the index whose value you want to change
  2716. @param newObject the new value to set for this index.
  2717. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2718. @see add, insert, remove
  2719. */
  2720. void set (const int indexToChange,
  2721. const ObjectClass* const newObject,
  2722. const bool deleteOldElement = true)
  2723. {
  2724. if (indexToChange >= 0)
  2725. {
  2726. ObjectClass* toDelete = 0;
  2727. lock.enter();
  2728. if (indexToChange < numUsed)
  2729. {
  2730. if (deleteOldElement)
  2731. toDelete = this->elements [indexToChange];
  2732. if (toDelete == newObject)
  2733. toDelete = 0;
  2734. else
  2735. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2736. }
  2737. else
  2738. {
  2739. this->ensureAllocatedSize (numUsed + 1);
  2740. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2741. }
  2742. lock.exit();
  2743. delete toDelete;
  2744. }
  2745. }
  2746. /** Inserts a new object into the array assuming that the array is sorted.
  2747. This will use a comparator to find the position at which the new object
  2748. should go. If the array isn't sorted, the behaviour of this
  2749. method will be unpredictable.
  2750. @param comparator the comparator to use to compare the elements - see the sort method
  2751. for details about this object's structure
  2752. @param newObject the new object to insert to the array
  2753. @see add, sort, indexOfSorted
  2754. */
  2755. template <class ElementComparator>
  2756. void addSorted (ElementComparator& comparator,
  2757. ObjectClass* const newObject) throw()
  2758. {
  2759. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2760. // avoids getting warning messages about the parameter being unused
  2761. lock.enter();
  2762. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2763. lock.exit();
  2764. }
  2765. /** Finds the index of an object in the array, assuming that the array is sorted.
  2766. This will use a comparator to do a binary-chop to find the index of the given
  2767. element, if it exists. If the array isn't sorted, the behaviour of this
  2768. method will be unpredictable.
  2769. @param comparator the comparator to use to compare the elements - see the sort()
  2770. method for details about the form this object should take
  2771. @param objectToLookFor the object to search for
  2772. @returns the index of the element, or -1 if it's not found
  2773. @see addSorted, sort
  2774. */
  2775. template <class ElementComparator>
  2776. int indexOfSorted (ElementComparator& comparator,
  2777. const ObjectClass* const objectToLookFor) const throw()
  2778. {
  2779. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2780. // avoids getting warning messages about the parameter being unused
  2781. lock.enter();
  2782. int start = 0;
  2783. int end = numUsed;
  2784. for (;;)
  2785. {
  2786. if (start >= end)
  2787. {
  2788. lock.exit();
  2789. return -1;
  2790. }
  2791. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2792. {
  2793. lock.exit();
  2794. return start;
  2795. }
  2796. else
  2797. {
  2798. const int halfway = (start + end) >> 1;
  2799. if (halfway == start)
  2800. {
  2801. lock.exit();
  2802. return -1;
  2803. }
  2804. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2805. start = halfway;
  2806. else
  2807. end = halfway;
  2808. }
  2809. }
  2810. }
  2811. /** Removes an object from the array.
  2812. This will remove the object at a given index (optionally also
  2813. deleting it) and move back all the subsequent objects to close the gap.
  2814. If the index passed in is out-of-range, nothing will happen.
  2815. @param indexToRemove the index of the element to remove
  2816. @param deleteObject whether to delete the object that is removed
  2817. @see removeObject, removeRange
  2818. */
  2819. void remove (const int indexToRemove,
  2820. const bool deleteObject = true)
  2821. {
  2822. lock.enter();
  2823. ObjectClass* toDelete = 0;
  2824. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2825. {
  2826. ObjectClass** const e = this->elements + indexToRemove;
  2827. if (deleteObject)
  2828. toDelete = *e;
  2829. --numUsed;
  2830. const int numToShift = numUsed - indexToRemove;
  2831. if (numToShift > 0)
  2832. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2833. if ((numUsed << 1) < this->numAllocated)
  2834. minimiseStorageOverheads();
  2835. }
  2836. lock.exit();
  2837. delete toDelete;
  2838. }
  2839. /** Removes a specified object from the array.
  2840. If the item isn't found, no action is taken.
  2841. @param objectToRemove the object to try to remove
  2842. @param deleteObject whether to delete the object (if it's found)
  2843. @see remove, removeRange
  2844. */
  2845. void removeObject (const ObjectClass* const objectToRemove,
  2846. const bool deleteObject = true)
  2847. {
  2848. lock.enter();
  2849. ObjectClass** e = this->elements;
  2850. for (int i = numUsed; --i >= 0;)
  2851. {
  2852. if (objectToRemove == *e)
  2853. {
  2854. remove ((int) (e - this->elements), deleteObject);
  2855. break;
  2856. }
  2857. ++e;
  2858. }
  2859. lock.exit();
  2860. }
  2861. /** Removes a range of objects from the array.
  2862. This will remove a set of objects, starting from the given index,
  2863. and move any subsequent elements down to close the gap.
  2864. If the range extends beyond the bounds of the array, it will
  2865. be safely clipped to the size of the array.
  2866. @param startIndex the index of the first object to remove
  2867. @param numberToRemove how many objects should be removed
  2868. @param deleteObjects whether to delete the objects that get removed
  2869. @see remove, removeObject
  2870. */
  2871. void removeRange (int startIndex,
  2872. const int numberToRemove,
  2873. const bool deleteObjects = true)
  2874. {
  2875. lock.enter();
  2876. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2877. startIndex = jlimit (0, numUsed, startIndex);
  2878. if (endIndex > startIndex)
  2879. {
  2880. if (deleteObjects)
  2881. {
  2882. for (int i = startIndex; i < endIndex; ++i)
  2883. {
  2884. delete this->elements [i];
  2885. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2886. }
  2887. }
  2888. const int rangeSize = endIndex - startIndex;
  2889. ObjectClass** e = this->elements + startIndex;
  2890. int numToShift = numUsed - endIndex;
  2891. numUsed -= rangeSize;
  2892. while (--numToShift >= 0)
  2893. {
  2894. *e = e [rangeSize];
  2895. ++e;
  2896. }
  2897. if ((numUsed << 1) < this->numAllocated)
  2898. minimiseStorageOverheads();
  2899. }
  2900. lock.exit();
  2901. }
  2902. /** Removes the last n objects from the array.
  2903. @param howManyToRemove how many objects to remove from the end of the array
  2904. @param deleteObjects whether to also delete the objects that are removed
  2905. @see remove, removeObject, removeRange
  2906. */
  2907. void removeLast (int howManyToRemove = 1,
  2908. const bool deleteObjects = true)
  2909. {
  2910. lock.enter();
  2911. if (howManyToRemove >= numUsed)
  2912. {
  2913. clear (deleteObjects);
  2914. }
  2915. else
  2916. {
  2917. while (--howManyToRemove >= 0)
  2918. remove (numUsed - 1, deleteObjects);
  2919. }
  2920. lock.exit();
  2921. }
  2922. /** Swaps a pair of objects in the array.
  2923. If either of the indexes passed in is out-of-range, nothing will happen,
  2924. otherwise the two objects at these positions will be exchanged.
  2925. */
  2926. void swap (const int index1,
  2927. const int index2) throw()
  2928. {
  2929. lock.enter();
  2930. if (((unsigned int) index1) < (unsigned int) numUsed
  2931. && ((unsigned int) index2) < (unsigned int) numUsed)
  2932. {
  2933. swapVariables (this->elements [index1],
  2934. this->elements [index2]);
  2935. }
  2936. lock.exit();
  2937. }
  2938. /** Moves one of the objects to a different position.
  2939. This will move the object to a specified index, shuffling along
  2940. any intervening elements as required.
  2941. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  2942. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  2943. @param currentIndex the index of the object to be moved. If this isn't a
  2944. valid index, then nothing will be done
  2945. @param newIndex the index at which you'd like this object to end up. If this
  2946. is less than zero, it will be moved to the end of the array
  2947. */
  2948. void move (const int currentIndex,
  2949. int newIndex) throw()
  2950. {
  2951. if (currentIndex != newIndex)
  2952. {
  2953. lock.enter();
  2954. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  2955. {
  2956. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  2957. newIndex = numUsed - 1;
  2958. ObjectClass* const value = this->elements [currentIndex];
  2959. if (newIndex > currentIndex)
  2960. {
  2961. memmove (this->elements + currentIndex,
  2962. this->elements + currentIndex + 1,
  2963. (newIndex - currentIndex) * sizeof (ObjectClass*));
  2964. }
  2965. else
  2966. {
  2967. memmove (this->elements + newIndex + 1,
  2968. this->elements + newIndex,
  2969. (currentIndex - newIndex) * sizeof (ObjectClass*));
  2970. }
  2971. this->elements [newIndex] = value;
  2972. }
  2973. lock.exit();
  2974. }
  2975. }
  2976. /** This swaps the contents of this array with those of another array.
  2977. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2978. because it just swaps their internal pointers.
  2979. */
  2980. template <class OtherArrayType>
  2981. void swapWithArray (OtherArrayType& otherArray) throw()
  2982. {
  2983. lock.enter();
  2984. otherArray.lock.enter();
  2985. swapVariables <int> (this->numUsed, otherArray.numUsed);
  2986. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  2987. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  2988. otherArray.lock.exit();
  2989. lock.exit();
  2990. }
  2991. /** Reduces the amount of storage being used by the array.
  2992. Arrays typically allocate slightly more storage than they need, and after
  2993. removing elements, they may have quite a lot of unused space allocated.
  2994. This method will reduce the amount of allocated storage to a minimum.
  2995. */
  2996. void minimiseStorageOverheads() throw()
  2997. {
  2998. lock.enter();
  2999. if (numUsed == 0)
  3000. {
  3001. this->setAllocatedSize (0);
  3002. }
  3003. else
  3004. {
  3005. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3006. if (newAllocation < this->numAllocated)
  3007. this->setAllocatedSize (newAllocation);
  3008. }
  3009. lock.exit();
  3010. }
  3011. /** Increases the array's internal storage to hold a minimum number of elements.
  3012. Calling this before adding a large known number of elements means that
  3013. the array won't have to keep dynamically resizing itself as the elements
  3014. are added, and it'll therefore be more efficient.
  3015. */
  3016. void ensureStorageAllocated (const int minNumElements) throw()
  3017. {
  3018. this->ensureAllocatedSize (minNumElements);
  3019. }
  3020. /** Sorts the elements in the array.
  3021. This will use a comparator object to sort the elements into order. The object
  3022. passed must have a method of the form:
  3023. @code
  3024. int compareElements (ElementType first, ElementType second);
  3025. @endcode
  3026. ..and this method must return:
  3027. - a value of < 0 if the first comes before the second
  3028. - a value of 0 if the two objects are equivalent
  3029. - a value of > 0 if the second comes before the first
  3030. To improve performance, the compareElements() method can be declared as static or const.
  3031. @param comparator the comparator to use for comparing elements.
  3032. @param retainOrderOfEquivalentItems if this is true, then items
  3033. which the comparator says are equivalent will be
  3034. kept in the order in which they currently appear
  3035. in the array. This is slower to perform, but may
  3036. be important in some cases. If it's false, a faster
  3037. algorithm is used, but equivalent elements may be
  3038. rearranged.
  3039. @see sortArray, indexOfSorted
  3040. */
  3041. template <class ElementComparator>
  3042. void sort (ElementComparator& comparator,
  3043. const bool retainOrderOfEquivalentItems = false) const throw()
  3044. {
  3045. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3046. // avoids getting warning messages about the parameter being unused
  3047. lock.enter();
  3048. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3049. lock.exit();
  3050. }
  3051. /** Locks the array's CriticalSection.
  3052. Of course if the type of section used is a DummyCriticalSection, this won't
  3053. have any effect.
  3054. @see unlockArray
  3055. */
  3056. void lockArray() const throw()
  3057. {
  3058. lock.enter();
  3059. }
  3060. /** Unlocks the array's CriticalSection.
  3061. Of course if the type of section used is a DummyCriticalSection, this won't
  3062. have any effect.
  3063. @see lockArray
  3064. */
  3065. void unlockArray() const throw()
  3066. {
  3067. lock.exit();
  3068. }
  3069. juce_UseDebuggingNewOperator
  3070. private:
  3071. int numUsed;
  3072. TypeOfCriticalSectionToUse lock;
  3073. // disallow copy constructor and assignment
  3074. OwnedArray (const OwnedArray&);
  3075. const OwnedArray& operator= (const OwnedArray&);
  3076. };
  3077. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3078. /********* End of inlined file: juce_OwnedArray.h *********/
  3079. /********* Start of inlined file: juce_Time.h *********/
  3080. #ifndef __JUCE_TIME_JUCEHEADER__
  3081. #define __JUCE_TIME_JUCEHEADER__
  3082. /********* Start of inlined file: juce_RelativeTime.h *********/
  3083. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3084. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3085. /** A relative measure of time.
  3086. The time is stored as a number of seconds, at double-precision floating
  3087. point accuracy, and may be positive or negative.
  3088. If you need an absolute time, (i.e. a date + time), see the Time class.
  3089. */
  3090. class JUCE_API RelativeTime
  3091. {
  3092. public:
  3093. /** Creates a RelativeTime.
  3094. @param seconds the number of seconds, which may be +ve or -ve.
  3095. @see milliseconds, minutes, hours, days, weeks
  3096. */
  3097. explicit RelativeTime (const double seconds = 0.0) throw();
  3098. /** Copies another relative time. */
  3099. RelativeTime (const RelativeTime& other) throw();
  3100. /** Copies another relative time. */
  3101. const RelativeTime& operator= (const RelativeTime& other) throw();
  3102. /** Destructor. */
  3103. ~RelativeTime() throw();
  3104. /** Creates a new RelativeTime object representing a number of milliseconds.
  3105. @see minutes, hours, days, weeks
  3106. */
  3107. static const RelativeTime milliseconds (const int milliseconds) throw();
  3108. /** Creates a new RelativeTime object representing a number of milliseconds.
  3109. @see minutes, hours, days, weeks
  3110. */
  3111. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3112. /** Creates a new RelativeTime object representing a number of minutes.
  3113. @see milliseconds, hours, days, weeks
  3114. */
  3115. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3116. /** Creates a new RelativeTime object representing a number of hours.
  3117. @see milliseconds, minutes, days, weeks
  3118. */
  3119. static const RelativeTime hours (const double numberOfHours) throw();
  3120. /** Creates a new RelativeTime object representing a number of days.
  3121. @see milliseconds, minutes, hours, weeks
  3122. */
  3123. static const RelativeTime days (const double numberOfDays) throw();
  3124. /** Creates a new RelativeTime object representing a number of weeks.
  3125. @see milliseconds, minutes, hours, days
  3126. */
  3127. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3128. /** Returns the number of milliseconds this time represents.
  3129. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3130. */
  3131. int64 inMilliseconds() const throw();
  3132. /** Returns the number of seconds this time represents.
  3133. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3134. */
  3135. double inSeconds() const throw() { return seconds; }
  3136. /** Returns the number of minutes this time represents.
  3137. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3138. */
  3139. double inMinutes() const throw();
  3140. /** Returns the number of hours this time represents.
  3141. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3142. */
  3143. double inHours() const throw();
  3144. /** Returns the number of days this time represents.
  3145. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3146. */
  3147. double inDays() const throw();
  3148. /** Returns the number of weeks this time represents.
  3149. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3150. */
  3151. double inWeeks() const throw();
  3152. /** Returns a readable textual description of the time.
  3153. The exact format of the string returned will depend on
  3154. the magnitude of the time - e.g.
  3155. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3156. so that only the two most significant units are printed.
  3157. The returnValueForZeroTime value is the result that is returned if the
  3158. length is zero. Depending on your application you might want to use this
  3159. to return something more relevant like "empty" or "0 secs", etc.
  3160. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3161. */
  3162. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3163. /** Compares two RelativeTimes. */
  3164. bool operator== (const RelativeTime& other) const throw();
  3165. /** Compares two RelativeTimes. */
  3166. bool operator!= (const RelativeTime& other) const throw();
  3167. /** Compares two RelativeTimes. */
  3168. bool operator> (const RelativeTime& other) const throw();
  3169. /** Compares two RelativeTimes. */
  3170. bool operator< (const RelativeTime& other) const throw();
  3171. /** Compares two RelativeTimes. */
  3172. bool operator>= (const RelativeTime& other) const throw();
  3173. /** Compares two RelativeTimes. */
  3174. bool operator<= (const RelativeTime& other) const throw();
  3175. /** Adds another RelativeTime to this one and returns the result. */
  3176. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3177. /** Subtracts another RelativeTime from this one and returns the result. */
  3178. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3179. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3180. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3181. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3182. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3183. /** Adds another RelativeTime to this one. */
  3184. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3185. /** Subtracts another RelativeTime from this one. */
  3186. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3187. /** Adds a number of seconds to this time. */
  3188. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3189. /** Subtracts a number of seconds from this time. */
  3190. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3191. juce_UseDebuggingNewOperator
  3192. private:
  3193. double seconds;
  3194. };
  3195. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3196. /********* End of inlined file: juce_RelativeTime.h *********/
  3197. /**
  3198. Holds an absolute date and time.
  3199. Internally, the time is stored at millisecond precision.
  3200. @see RelativeTime
  3201. */
  3202. class JUCE_API Time
  3203. {
  3204. public:
  3205. /** Creates a Time object.
  3206. This default constructor creates a time of 1st January 1970, (which is
  3207. represented internally as 0ms).
  3208. To create a time object representing the current time, use getCurrentTime().
  3209. @see getCurrentTime
  3210. */
  3211. Time() throw();
  3212. /** Creates a copy of another Time object. */
  3213. Time (const Time& other) throw();
  3214. /** Creates a time based on a number of milliseconds.
  3215. The internal millisecond count is set to 0 (1st January 1970). To create a
  3216. time object set to the current time, use getCurrentTime().
  3217. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3218. 'epoch' (midnight Jan 1st 1970).
  3219. @see getCurrentTime, currentTimeMillis
  3220. */
  3221. Time (const int64 millisecondsSinceEpoch) throw();
  3222. /** Creates a time from a set of date components.
  3223. The timezone is assumed to be whatever the system is using as its locale.
  3224. @param year the year, in 4-digit format, e.g. 2004
  3225. @param month the month, in the range 0 to 11
  3226. @param day the day of the month, in the range 1 to 31
  3227. @param hours hours in 24-hour clock format, 0 to 23
  3228. @param minutes minutes 0 to 59
  3229. @param seconds seconds 0 to 59
  3230. @param milliseconds milliseconds 0 to 999
  3231. @param useLocalTime if true, encode using the current machine's local time; if
  3232. false, it will always work in GMT.
  3233. */
  3234. Time (const int year,
  3235. const int month,
  3236. const int day,
  3237. const int hours,
  3238. const int minutes,
  3239. const int seconds = 0,
  3240. const int milliseconds = 0,
  3241. const bool useLocalTime = true) throw();
  3242. /** Destructor. */
  3243. ~Time() throw();
  3244. /** Copies this time from another one. */
  3245. const Time& operator= (const Time& other) throw();
  3246. /** Returns a Time object that is set to the current system time.
  3247. @see currentTimeMillis
  3248. */
  3249. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3250. /** Returns the time as a number of milliseconds.
  3251. @returns the number of milliseconds this Time object represents, since
  3252. midnight jan 1st 1970.
  3253. @see getMilliseconds
  3254. */
  3255. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3256. /** Returns the year.
  3257. A 4-digit format is used, e.g. 2004.
  3258. */
  3259. int getYear() const throw();
  3260. /** Returns the number of the month.
  3261. The value returned is in the range 0 to 11.
  3262. @see getMonthName
  3263. */
  3264. int getMonth() const throw();
  3265. /** Returns the name of the month.
  3266. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3267. it'll return the long form, e.g. "January"
  3268. @see getMonth
  3269. */
  3270. const String getMonthName (const bool threeLetterVersion) const throw();
  3271. /** Returns the day of the month.
  3272. The value returned is in the range 1 to 31.
  3273. */
  3274. int getDayOfMonth() const throw();
  3275. /** Returns the number of the day of the week.
  3276. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3277. */
  3278. int getDayOfWeek() const throw();
  3279. /** Returns the name of the weekday.
  3280. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3281. false, it'll return the full version, e.g. "Tuesday".
  3282. */
  3283. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3284. /** Returns the number of hours since midnight.
  3285. This is in 24-hour clock format, in the range 0 to 23.
  3286. @see getHoursInAmPmFormat, isAfternoon
  3287. */
  3288. int getHours() const throw();
  3289. /** Returns true if the time is in the afternoon.
  3290. So it returns true for "PM", false for "AM".
  3291. @see getHoursInAmPmFormat, getHours
  3292. */
  3293. bool isAfternoon() const throw();
  3294. /** Returns the hours in 12-hour clock format.
  3295. This will return a value 1 to 12 - use isAfternoon() to find out
  3296. whether this is in the afternoon or morning.
  3297. @see getHours, isAfternoon
  3298. */
  3299. int getHoursInAmPmFormat() const throw();
  3300. /** Returns the number of minutes, 0 to 59. */
  3301. int getMinutes() const throw();
  3302. /** Returns the number of seconds, 0 to 59. */
  3303. int getSeconds() const throw();
  3304. /** Returns the number of milliseconds, 0 to 999.
  3305. Unlike toMilliseconds(), this just returns the position within the
  3306. current second rather than the total number since the epoch.
  3307. @see toMilliseconds
  3308. */
  3309. int getMilliseconds() const throw();
  3310. /** Returns true if the local timezone uses a daylight saving correction. */
  3311. bool isDaylightSavingTime() const throw();
  3312. /** Returns a 3-character string to indicate the local timezone. */
  3313. const String getTimeZone() const throw();
  3314. /** Quick way of getting a string version of a date and time.
  3315. For a more powerful way of formatting the date and time, see the formatted() method.
  3316. @param includeDate whether to include the date in the string
  3317. @param includeTime whether to include the time in the string
  3318. @param includeSeconds if the time is being included, this provides an option not to include
  3319. the seconds in it
  3320. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3321. hour notation.
  3322. @see formatted
  3323. */
  3324. const String toString (const bool includeDate,
  3325. const bool includeTime,
  3326. const bool includeSeconds = true,
  3327. const bool use24HourClock = false) const throw();
  3328. /** Converts this date/time to a string with a user-defined format.
  3329. This uses the C strftime() function to format this time as a string. To save you
  3330. looking it up, these are the escape codes that strftime uses (other codes might
  3331. work on some platforms and not others, but these are the common ones):
  3332. %a is replaced by the locale's abbreviated weekday name.
  3333. %A is replaced by the locale's full weekday name.
  3334. %b is replaced by the locale's abbreviated month name.
  3335. %B is replaced by the locale's full month name.
  3336. %c is replaced by the locale's appropriate date and time representation.
  3337. %d is replaced by the day of the month as a decimal number [01,31].
  3338. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3339. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3340. %j is replaced by the day of the year as a decimal number [001,366].
  3341. %m is replaced by the month as a decimal number [01,12].
  3342. %M is replaced by the minute as a decimal number [00,59].
  3343. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3344. %S is replaced by the second as a decimal number [00,61].
  3345. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3346. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3347. %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.
  3348. %x is replaced by the locale's appropriate date representation.
  3349. %X is replaced by the locale's appropriate time representation.
  3350. %y is replaced by the year without century as a decimal number [00,99].
  3351. %Y is replaced by the year with century as a decimal number.
  3352. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3353. %% is replaced by %.
  3354. @see toString
  3355. */
  3356. const String formatted (const tchar* const format) const throw();
  3357. /** Adds a RelativeTime to this time and returns the result. */
  3358. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3359. /** Subtracts a RelativeTime from this time and returns the result. */
  3360. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3361. /** Returns the relative time difference between this time and another one. */
  3362. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3363. /** Compares two Time objects. */
  3364. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3365. /** Compares two Time objects. */
  3366. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3367. /** Compares two Time objects. */
  3368. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3369. /** Compares two Time objects. */
  3370. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3371. /** Compares two Time objects. */
  3372. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3373. /** Compares two Time objects. */
  3374. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3375. /** Tries to set the computer's clock.
  3376. @returns true if this succeeds, although depending on the system, the
  3377. application might not have sufficient privileges to do this.
  3378. */
  3379. bool setSystemTimeToThisTime() const throw();
  3380. /** Returns the name of a day of the week.
  3381. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3382. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3383. false, it'll return the full version, e.g. "Tuesday".
  3384. */
  3385. static const String getWeekdayName (int dayNumber,
  3386. const bool threeLetterVersion) throw();
  3387. /** Returns the name of one of the months.
  3388. @param monthNumber the month, 0 to 11
  3389. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3390. it'll return the long form, e.g. "January"
  3391. */
  3392. static const String getMonthName (int monthNumber,
  3393. const bool threeLetterVersion) throw();
  3394. // Static methods for getting system timers directly..
  3395. /** Returns the current system time.
  3396. Returns the number of milliseconds since midnight jan 1st 1970.
  3397. Should be accurate to within a few millisecs, depending on platform,
  3398. hardware, etc.
  3399. */
  3400. static int64 currentTimeMillis() throw();
  3401. /** Returns the number of millisecs since system startup.
  3402. Should be accurate to within a few millisecs, depending on platform,
  3403. hardware, etc.
  3404. @see getApproximateMillisecondCounter
  3405. */
  3406. static uint32 getMillisecondCounter() throw();
  3407. /** Returns the number of millisecs since system startup.
  3408. Same as getMillisecondCounter(), but returns a more accurate value, using
  3409. the high-res timer.
  3410. @see getMillisecondCounter
  3411. */
  3412. static double getMillisecondCounterHiRes() throw();
  3413. /** Waits until the getMillisecondCounter() reaches a given value.
  3414. This will make the thread sleep as efficiently as it can while it's waiting.
  3415. */
  3416. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3417. /** Less-accurate but faster version of getMillisecondCounter().
  3418. This will return the last value that getMillisecondCounter() returned, so doesn't
  3419. need to make a system call, but is less accurate - it shouldn't be more than
  3420. 100ms away from the correct time, though, so is still accurate enough for a
  3421. lot of purposes.
  3422. @see getMillisecondCounter
  3423. */
  3424. static uint32 getApproximateMillisecondCounter() throw();
  3425. // High-resolution timers..
  3426. /** Returns the current high-resolution counter's tick-count.
  3427. This is a similar idea to getMillisecondCounter(), but with a higher
  3428. resolution.
  3429. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3430. secondsToHighResolutionTicks
  3431. */
  3432. static int64 getHighResolutionTicks() throw();
  3433. /** Returns the resolution of the high-resolution counter in ticks per second.
  3434. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3435. secondsToHighResolutionTicks
  3436. */
  3437. static int64 getHighResolutionTicksPerSecond() throw();
  3438. /** Converts a number of high-resolution ticks into seconds.
  3439. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3440. secondsToHighResolutionTicks
  3441. */
  3442. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3443. /** Converts a number seconds into high-resolution ticks.
  3444. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3445. highResolutionTicksToSeconds
  3446. */
  3447. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3448. private:
  3449. int64 millisSinceEpoch;
  3450. };
  3451. #endif // __JUCE_TIME_JUCEHEADER__
  3452. /********* End of inlined file: juce_Time.h *********/
  3453. /********* Start of inlined file: juce_StringArray.h *********/
  3454. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3455. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3456. /********* Start of inlined file: juce_VoidArray.h *********/
  3457. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3458. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3459. /********* Start of inlined file: juce_Array.h *********/
  3460. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3461. #define __JUCE_ARRAY_JUCEHEADER__
  3462. /**
  3463. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3464. Examples of arrays are: Array<int> or Array<MyClass*>
  3465. Note that when holding pointers to objects, the array doesn't take any ownership
  3466. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3467. If you're using a class or struct as the element type, it must be
  3468. capable of being copied or moved with a straightforward memcpy, rather than
  3469. needing construction and destruction code.
  3470. For holding lists of strings, use the specialised class StringArray.
  3471. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3472. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3473. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3474. */
  3475. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3476. class Array : private ArrayAllocationBase <ElementType>
  3477. {
  3478. public:
  3479. /** Creates an empty array.
  3480. @param granularity this is the size of increment by which the internal storage
  3481. used by the array will grow. Only change it from the default if you know the
  3482. array is going to be very big and needs to be able to grow efficiently.
  3483. @see ArrayAllocationBase
  3484. */
  3485. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3486. : ArrayAllocationBase <ElementType> (granularity),
  3487. numUsed (0)
  3488. {
  3489. }
  3490. /** Creates a copy of another array.
  3491. @param other the array to copy
  3492. */
  3493. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3494. : ArrayAllocationBase <ElementType> (other.granularity)
  3495. {
  3496. other.lockArray();
  3497. numUsed = other.numUsed;
  3498. this->setAllocatedSize (other.numUsed);
  3499. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3500. other.unlockArray();
  3501. }
  3502. /** Initalises from a null-terminated C array of values.
  3503. @param values the array to copy from
  3504. */
  3505. Array (const ElementType* values) throw()
  3506. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3507. numUsed (0)
  3508. {
  3509. while (*values != 0)
  3510. add (*values++);
  3511. }
  3512. /** Initalises from a C array of values.
  3513. @param values the array to copy from
  3514. @param numValues the number of values in the array
  3515. */
  3516. Array (const ElementType* values, int numValues) throw()
  3517. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3518. numUsed (numValues)
  3519. {
  3520. this->setAllocatedSize (numValues);
  3521. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3522. }
  3523. /** Destructor. */
  3524. ~Array() throw()
  3525. {
  3526. }
  3527. /** Copies another array.
  3528. @param other the array to copy
  3529. */
  3530. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3531. {
  3532. if (this != &other)
  3533. {
  3534. other.lockArray();
  3535. lock.enter();
  3536. this->granularity = other.granularity;
  3537. this->ensureAllocatedSize (other.size());
  3538. numUsed = other.numUsed;
  3539. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3540. minimiseStorageOverheads();
  3541. lock.exit();
  3542. other.unlockArray();
  3543. }
  3544. return *this;
  3545. }
  3546. /** Compares this array to another one.
  3547. Two arrays are considered equal if they both contain the same set of
  3548. elements, in the same order.
  3549. @param other the other array to compare with
  3550. */
  3551. template <class OtherArrayType>
  3552. bool operator== (const OtherArrayType& other) const throw()
  3553. {
  3554. lock.enter();
  3555. if (this->numUsed != other.numUsed)
  3556. {
  3557. lock.exit();
  3558. return false;
  3559. }
  3560. for (int i = numUsed; --i >= 0;)
  3561. {
  3562. if (this->elements [i] != other.elements [i])
  3563. {
  3564. lock.exit();
  3565. return false;
  3566. }
  3567. }
  3568. lock.exit();
  3569. return true;
  3570. }
  3571. /** Compares this array to another one.
  3572. Two arrays are considered equal if they both contain the same set of
  3573. elements, in the same order.
  3574. @param other the other array to compare with
  3575. */
  3576. template <class OtherArrayType>
  3577. bool operator!= (const OtherArrayType& other) const throw()
  3578. {
  3579. return ! operator== (other);
  3580. }
  3581. /** Removes all elements from the array.
  3582. This will remove all the elements, and free any storage that the array is
  3583. using. To clear the array without freeing the storage, use the clearQuick()
  3584. method instead.
  3585. @see clearQuick
  3586. */
  3587. void clear() throw()
  3588. {
  3589. lock.enter();
  3590. this->setAllocatedSize (0);
  3591. numUsed = 0;
  3592. lock.exit();
  3593. }
  3594. /** Removes all elements from the array without freeing the array's allocated storage.
  3595. @see clear
  3596. */
  3597. void clearQuick() throw()
  3598. {
  3599. lock.enter();
  3600. numUsed = 0;
  3601. lock.exit();
  3602. }
  3603. /** Returns the current number of elements in the array.
  3604. */
  3605. inline int size() const throw()
  3606. {
  3607. return numUsed;
  3608. }
  3609. /** Returns one of the elements in the array.
  3610. If the index passed in is beyond the range of valid elements, this
  3611. will return zero.
  3612. If you're certain that the index will always be a valid element, you
  3613. can call getUnchecked() instead, which is faster.
  3614. @param index the index of the element being requested (0 is the first element in the array)
  3615. @see getUnchecked, getFirst, getLast
  3616. */
  3617. inline ElementType operator[] (const int index) const throw()
  3618. {
  3619. lock.enter();
  3620. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3621. ? this->elements [index]
  3622. : ElementType();
  3623. lock.exit();
  3624. return result;
  3625. }
  3626. /** Returns one of the elements in the array, without checking the index passed in.
  3627. Unlike the operator[] method, this will try to return an element without
  3628. checking that the index is within the bounds of the array, so should only
  3629. be used when you're confident that it will always be a valid index.
  3630. @param index the index of the element being requested (0 is the first element in the array)
  3631. @see operator[], getFirst, getLast
  3632. */
  3633. inline ElementType getUnchecked (const int index) const throw()
  3634. {
  3635. lock.enter();
  3636. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3637. const ElementType result = this->elements [index];
  3638. lock.exit();
  3639. return result;
  3640. }
  3641. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3642. This is like getUnchecked, but returns a direct reference to the element, so that
  3643. you can alter it directly. Obviously this can be dangerous, so only use it when
  3644. absolutely necessary.
  3645. @param index the index of the element being requested (0 is the first element in the array)
  3646. @see operator[], getFirst, getLast
  3647. */
  3648. inline ElementType& getReference (const int index) const throw()
  3649. {
  3650. lock.enter();
  3651. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3652. ElementType& result = this->elements [index];
  3653. lock.exit();
  3654. return result;
  3655. }
  3656. /** Returns the first element in the array, or 0 if the array is empty.
  3657. @see operator[], getUnchecked, getLast
  3658. */
  3659. inline ElementType getFirst() const throw()
  3660. {
  3661. lock.enter();
  3662. const ElementType result = (numUsed > 0) ? this->elements [0]
  3663. : ElementType();
  3664. lock.exit();
  3665. return result;
  3666. }
  3667. /** Returns the last element in the array, or 0 if the array is empty.
  3668. @see operator[], getUnchecked, getFirst
  3669. */
  3670. inline ElementType getLast() const throw()
  3671. {
  3672. lock.enter();
  3673. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3674. : ElementType();
  3675. lock.exit();
  3676. return result;
  3677. }
  3678. /** Finds the index of the first element which matches the value passed in.
  3679. This will search the array for the given object, and return the index
  3680. of its first occurrence. If the object isn't found, the method will return -1.
  3681. @param elementToLookFor the value or object to look for
  3682. @returns the index of the object, or -1 if it's not found
  3683. */
  3684. int indexOf (const ElementType elementToLookFor) const throw()
  3685. {
  3686. int result = -1;
  3687. lock.enter();
  3688. const ElementType* e = this->elements;
  3689. for (int i = numUsed; --i >= 0;)
  3690. {
  3691. if (elementToLookFor == *e)
  3692. {
  3693. result = (int) (e - this->elements);
  3694. break;
  3695. }
  3696. ++e;
  3697. }
  3698. lock.exit();
  3699. return result;
  3700. }
  3701. /** Returns true if the array contains at least one occurrence of an object.
  3702. @param elementToLookFor the value or object to look for
  3703. @returns true if the item is found
  3704. */
  3705. bool contains (const ElementType elementToLookFor) const throw()
  3706. {
  3707. lock.enter();
  3708. const ElementType* e = this->elements;
  3709. int num = numUsed;
  3710. while (num >= 4)
  3711. {
  3712. if (*e == elementToLookFor
  3713. || *++e == elementToLookFor
  3714. || *++e == elementToLookFor
  3715. || *++e == elementToLookFor)
  3716. {
  3717. lock.exit();
  3718. return true;
  3719. }
  3720. num -= 4;
  3721. ++e;
  3722. }
  3723. while (num > 0)
  3724. {
  3725. if (elementToLookFor == *e)
  3726. {
  3727. lock.exit();
  3728. return true;
  3729. }
  3730. --num;
  3731. ++e;
  3732. }
  3733. lock.exit();
  3734. return false;
  3735. }
  3736. /** Appends a new element at the end of the array.
  3737. @param newElement the new object to add to the array
  3738. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3739. */
  3740. void add (const ElementType newElement) throw()
  3741. {
  3742. lock.enter();
  3743. this->ensureAllocatedSize (numUsed + 1);
  3744. this->elements [numUsed++] = newElement;
  3745. lock.exit();
  3746. }
  3747. /** Inserts a new element into the array at a given position.
  3748. If the index is less than 0 or greater than the size of the array, the
  3749. element will be added to the end of the array.
  3750. Otherwise, it will be inserted into the array, moving all the later elements
  3751. along to make room.
  3752. @param indexToInsertAt the index at which the new element should be
  3753. inserted (pass in -1 to add it to the end)
  3754. @param newElement the new object to add to the array
  3755. @see add, addSorted, set
  3756. */
  3757. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3758. {
  3759. lock.enter();
  3760. this->ensureAllocatedSize (numUsed + 1);
  3761. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3762. {
  3763. ElementType* const insertPos = this->elements + indexToInsertAt;
  3764. const int numberToMove = numUsed - indexToInsertAt;
  3765. if (numberToMove > 0)
  3766. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3767. *insertPos = newElement;
  3768. ++numUsed;
  3769. }
  3770. else
  3771. {
  3772. this->elements [numUsed++] = newElement;
  3773. }
  3774. lock.exit();
  3775. }
  3776. /** Inserts multiple copies of an element into the array at a given position.
  3777. If the index is less than 0 or greater than the size of the array, the
  3778. element will be added to the end of the array.
  3779. Otherwise, it will be inserted into the array, moving all the later elements
  3780. along to make room.
  3781. @param indexToInsertAt the index at which the new element should be inserted
  3782. @param newElement the new object to add to the array
  3783. @param numberOfTimesToInsertIt how many copies of the value to insert
  3784. @see insert, add, addSorted, set
  3785. */
  3786. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3787. int numberOfTimesToInsertIt) throw()
  3788. {
  3789. if (numberOfTimesToInsertIt > 0)
  3790. {
  3791. lock.enter();
  3792. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3793. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3794. {
  3795. ElementType* insertPos = this->elements + indexToInsertAt;
  3796. const int numberToMove = numUsed - indexToInsertAt;
  3797. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3798. numUsed += numberOfTimesToInsertIt;
  3799. while (--numberOfTimesToInsertIt >= 0)
  3800. *insertPos++ = newElement;
  3801. }
  3802. else
  3803. {
  3804. while (--numberOfTimesToInsertIt >= 0)
  3805. this->elements [numUsed++] = newElement;
  3806. }
  3807. lock.exit();
  3808. }
  3809. }
  3810. /** Inserts an array of values into this array at a given position.
  3811. If the index is less than 0 or greater than the size of the array, the
  3812. new elements will be added to the end of the array.
  3813. Otherwise, they will be inserted into the array, moving all the later elements
  3814. along to make room.
  3815. @param indexToInsertAt the index at which the first new element should be inserted
  3816. @param newElements the new values to add to the array
  3817. @param numberOfElements how many items are in the array
  3818. @see insert, add, addSorted, set
  3819. */
  3820. void insertArray (int indexToInsertAt,
  3821. const ElementType* newElements,
  3822. int numberOfElements) throw()
  3823. {
  3824. if (numberOfElements > 0)
  3825. {
  3826. lock.enter();
  3827. this->ensureAllocatedSize (numUsed + numberOfElements);
  3828. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3829. {
  3830. ElementType* insertPos = this->elements + indexToInsertAt;
  3831. const int numberToMove = numUsed - indexToInsertAt;
  3832. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3833. numUsed += numberOfElements;
  3834. while (--numberOfElements >= 0)
  3835. *insertPos++ = *newElements++;
  3836. }
  3837. else
  3838. {
  3839. while (--numberOfElements >= 0)
  3840. this->elements [numUsed++] = *newElements++;
  3841. }
  3842. lock.exit();
  3843. }
  3844. }
  3845. /** Appends a new element at the end of the array as long as the array doesn't
  3846. already contain it.
  3847. If the array already contains an element that matches the one passed in, nothing
  3848. will be done.
  3849. @param newElement the new object to add to the array
  3850. */
  3851. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3852. {
  3853. lock.enter();
  3854. if (! contains (newElement))
  3855. add (newElement);
  3856. lock.exit();
  3857. }
  3858. /** Replaces an element with a new value.
  3859. If the index is less than zero, this method does nothing.
  3860. If the index is beyond the end of the array, the item is added to the end of the array.
  3861. @param indexToChange the index whose value you want to change
  3862. @param newValue the new value to set for this index.
  3863. @see add, insert
  3864. */
  3865. void set (const int indexToChange,
  3866. const ElementType newValue) throw()
  3867. {
  3868. jassert (indexToChange >= 0);
  3869. if (indexToChange >= 0)
  3870. {
  3871. lock.enter();
  3872. if (indexToChange < numUsed)
  3873. {
  3874. this->elements [indexToChange] = newValue;
  3875. }
  3876. else
  3877. {
  3878. this->ensureAllocatedSize (numUsed + 1);
  3879. this->elements [numUsed++] = newValue;
  3880. }
  3881. lock.exit();
  3882. }
  3883. }
  3884. /** Replaces an element with a new value without doing any bounds-checking.
  3885. This just sets a value directly in the array's internal storage, so you'd
  3886. better make sure it's in range!
  3887. @param indexToChange the index whose value you want to change
  3888. @param newValue the new value to set for this index.
  3889. @see set, getUnchecked
  3890. */
  3891. void setUnchecked (const int indexToChange,
  3892. const ElementType newValue) throw()
  3893. {
  3894. lock.enter();
  3895. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3896. this->elements [indexToChange] = newValue;
  3897. lock.exit();
  3898. }
  3899. /** Adds elements from an array to the end of this array.
  3900. @param elementsToAdd the array of elements to add
  3901. @param numElementsToAdd how many elements are in this other array
  3902. @see add
  3903. */
  3904. void addArray (const ElementType* elementsToAdd,
  3905. int numElementsToAdd) throw()
  3906. {
  3907. lock.enter();
  3908. if (numElementsToAdd > 0)
  3909. {
  3910. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3911. while (--numElementsToAdd >= 0)
  3912. this->elements [numUsed++] = *elementsToAdd++;
  3913. }
  3914. lock.exit();
  3915. }
  3916. /** This swaps the contents of this array with those of another array.
  3917. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3918. because it just swaps their internal pointers.
  3919. */
  3920. template <class OtherArrayType>
  3921. void swapWithArray (OtherArrayType& otherArray) throw()
  3922. {
  3923. lock.enter();
  3924. otherArray.lock.enter();
  3925. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3926. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3927. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3928. otherArray.lock.exit();
  3929. lock.exit();
  3930. }
  3931. /** Adds elements from another array to the end of this array.
  3932. @param arrayToAddFrom the array from which to copy the elements
  3933. @param startIndex the first element of the other array to start copying from
  3934. @param numElementsToAdd how many elements to add from the other array. If this
  3935. value is negative or greater than the number of available elements,
  3936. all available elements will be copied.
  3937. @see add
  3938. */
  3939. template <class OtherArrayType>
  3940. void addArray (const OtherArrayType& arrayToAddFrom,
  3941. int startIndex = 0,
  3942. int numElementsToAdd = -1) throw()
  3943. {
  3944. arrayToAddFrom.lockArray();
  3945. lock.enter();
  3946. jassert (this != &arrayToAddFrom);
  3947. if (startIndex < 0)
  3948. {
  3949. jassertfalse
  3950. startIndex = 0;
  3951. }
  3952. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3953. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3954. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  3955. lock.exit();
  3956. arrayToAddFrom.unlockArray();
  3957. }
  3958. /** Inserts a new element into the array, assuming that the array is sorted.
  3959. This will use a comparator to find the position at which the new element
  3960. should go. If the array isn't sorted, the behaviour of this
  3961. method will be unpredictable.
  3962. @param comparator the comparator to use to compare the elements - see the sort()
  3963. method for details about the form this object should take
  3964. @param newElement the new element to insert to the array
  3965. @see add, sort
  3966. */
  3967. template <class ElementComparator>
  3968. void addSorted (ElementComparator& comparator,
  3969. const ElementType newElement) throw()
  3970. {
  3971. lock.enter();
  3972. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  3973. lock.exit();
  3974. }
  3975. /** Finds the index of an element in the array, assuming that the array is sorted.
  3976. This will use a comparator to do a binary-chop to find the index of the given
  3977. element, if it exists. If the array isn't sorted, the behaviour of this
  3978. method will be unpredictable.
  3979. @param comparator the comparator to use to compare the elements - see the sort()
  3980. method for details about the form this object should take
  3981. @param elementToLookFor the element to search for
  3982. @returns the index of the element, or -1 if it's not found
  3983. @see addSorted, sort
  3984. */
  3985. template <class ElementComparator>
  3986. int indexOfSorted (ElementComparator& comparator,
  3987. const ElementType elementToLookFor) const throw()
  3988. {
  3989. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3990. // avoids getting warning messages about the parameter being unused
  3991. lock.enter();
  3992. int start = 0;
  3993. int end = numUsed;
  3994. for (;;)
  3995. {
  3996. if (start >= end)
  3997. {
  3998. lock.exit();
  3999. return -1;
  4000. }
  4001. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4002. {
  4003. lock.exit();
  4004. return start;
  4005. }
  4006. else
  4007. {
  4008. const int halfway = (start + end) >> 1;
  4009. if (halfway == start)
  4010. {
  4011. lock.exit();
  4012. return -1;
  4013. }
  4014. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4015. start = halfway;
  4016. else
  4017. end = halfway;
  4018. }
  4019. }
  4020. }
  4021. /** Removes an element from the array.
  4022. This will remove the element at a given index, and move back
  4023. all the subsequent elements to close the gap.
  4024. If the index passed in is out-of-range, nothing will happen.
  4025. @param indexToRemove the index of the element to remove
  4026. @returns the element that has been removed
  4027. @see removeValue, removeRange
  4028. */
  4029. ElementType remove (const int indexToRemove) throw()
  4030. {
  4031. lock.enter();
  4032. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4033. {
  4034. --numUsed;
  4035. ElementType* const e = this->elements + indexToRemove;
  4036. ElementType const removed = *e;
  4037. const int numberToShift = numUsed - indexToRemove;
  4038. if (numberToShift > 0)
  4039. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4040. if ((numUsed << 1) < this->numAllocated)
  4041. minimiseStorageOverheads();
  4042. lock.exit();
  4043. return removed;
  4044. }
  4045. else
  4046. {
  4047. lock.exit();
  4048. return ElementType();
  4049. }
  4050. }
  4051. /** Removes an item from the array.
  4052. This will remove the first occurrence of the given element from the array.
  4053. If the item isn't found, no action is taken.
  4054. @param valueToRemove the object to try to remove
  4055. @see remove, removeRange
  4056. */
  4057. void removeValue (const ElementType valueToRemove) throw()
  4058. {
  4059. lock.enter();
  4060. ElementType* e = this->elements;
  4061. for (int i = numUsed; --i >= 0;)
  4062. {
  4063. if (valueToRemove == *e)
  4064. {
  4065. remove ((int) (e - this->elements));
  4066. break;
  4067. }
  4068. ++e;
  4069. }
  4070. lock.exit();
  4071. }
  4072. /** Removes a range of elements from the array.
  4073. This will remove a set of elements, starting from the given index,
  4074. and move subsequent elements down to close the gap.
  4075. If the range extends beyond the bounds of the array, it will
  4076. be safely clipped to the size of the array.
  4077. @param startIndex the index of the first element to remove
  4078. @param numberToRemove how many elements should be removed
  4079. @see remove, removeValue
  4080. */
  4081. void removeRange (int startIndex,
  4082. const int numberToRemove) throw()
  4083. {
  4084. lock.enter();
  4085. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4086. startIndex = jlimit (0, numUsed, startIndex);
  4087. if (endIndex > startIndex)
  4088. {
  4089. const int rangeSize = endIndex - startIndex;
  4090. ElementType* e = this->elements + startIndex;
  4091. int numToShift = numUsed - endIndex;
  4092. numUsed -= rangeSize;
  4093. while (--numToShift >= 0)
  4094. {
  4095. *e = e [rangeSize];
  4096. ++e;
  4097. }
  4098. if ((numUsed << 1) < this->numAllocated)
  4099. minimiseStorageOverheads();
  4100. }
  4101. lock.exit();
  4102. }
  4103. /** Removes the last n elements from the array.
  4104. @param howManyToRemove how many elements to remove from the end of the array
  4105. @see remove, removeValue, removeRange
  4106. */
  4107. void removeLast (const int howManyToRemove = 1) throw()
  4108. {
  4109. lock.enter();
  4110. numUsed = jmax (0, numUsed - howManyToRemove);
  4111. if ((numUsed << 1) < this->numAllocated)
  4112. minimiseStorageOverheads();
  4113. lock.exit();
  4114. }
  4115. /** Removes any elements which are also in another array.
  4116. @param otherArray the other array in which to look for elements to remove
  4117. @see removeValuesNotIn, remove, removeValue, removeRange
  4118. */
  4119. template <class OtherArrayType>
  4120. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4121. {
  4122. otherArray.lockArray();
  4123. lock.enter();
  4124. if (this == &otherArray)
  4125. {
  4126. clear();
  4127. }
  4128. else
  4129. {
  4130. if (otherArray.size() > 0)
  4131. {
  4132. for (int i = numUsed; --i >= 0;)
  4133. if (otherArray.contains (this->elements [i]))
  4134. remove (i);
  4135. }
  4136. }
  4137. lock.exit();
  4138. otherArray.unlockArray();
  4139. }
  4140. /** Removes any elements which are not found in another array.
  4141. Only elements which occur in this other array will be retained.
  4142. @param otherArray the array in which to look for elements NOT to remove
  4143. @see removeValuesIn, remove, removeValue, removeRange
  4144. */
  4145. template <class OtherArrayType>
  4146. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4147. {
  4148. otherArray.lockArray();
  4149. lock.enter();
  4150. if (this != &otherArray)
  4151. {
  4152. if (otherArray.size() <= 0)
  4153. {
  4154. clear();
  4155. }
  4156. else
  4157. {
  4158. for (int i = numUsed; --i >= 0;)
  4159. if (! otherArray.contains (this->elements [i]))
  4160. remove (i);
  4161. }
  4162. }
  4163. lock.exit();
  4164. otherArray.unlockArray();
  4165. }
  4166. /** Swaps over two elements in the array.
  4167. This swaps over the elements found at the two indexes passed in.
  4168. If either index is out-of-range, this method will do nothing.
  4169. @param index1 index of one of the elements to swap
  4170. @param index2 index of the other element to swap
  4171. */
  4172. void swap (const int index1,
  4173. const int index2) throw()
  4174. {
  4175. lock.enter();
  4176. if (((unsigned int) index1) < (unsigned int) numUsed
  4177. && ((unsigned int) index2) < (unsigned int) numUsed)
  4178. {
  4179. swapVariables (this->elements [index1],
  4180. this->elements [index2]);
  4181. }
  4182. lock.exit();
  4183. }
  4184. /** Moves one of the values to a different position.
  4185. This will move the value to a specified index, shuffling along
  4186. any intervening elements as required.
  4187. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4188. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4189. @param currentIndex the index of the value to be moved. If this isn't a
  4190. valid index, then nothing will be done
  4191. @param newIndex the index at which you'd like this value to end up. If this
  4192. is less than zero, the value will be moved to the end
  4193. of the array
  4194. */
  4195. void move (const int currentIndex,
  4196. int newIndex) throw()
  4197. {
  4198. if (currentIndex != newIndex)
  4199. {
  4200. lock.enter();
  4201. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4202. {
  4203. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4204. newIndex = numUsed - 1;
  4205. const ElementType value = this->elements [currentIndex];
  4206. if (newIndex > currentIndex)
  4207. {
  4208. memmove (this->elements + currentIndex,
  4209. this->elements + currentIndex + 1,
  4210. (newIndex - currentIndex) * sizeof (ElementType));
  4211. }
  4212. else
  4213. {
  4214. memmove (this->elements + newIndex + 1,
  4215. this->elements + newIndex,
  4216. (currentIndex - newIndex) * sizeof (ElementType));
  4217. }
  4218. this->elements [newIndex] = value;
  4219. }
  4220. lock.exit();
  4221. }
  4222. }
  4223. /** Reduces the amount of storage being used by the array.
  4224. Arrays typically allocate slightly more storage than they need, and after
  4225. removing elements, they may have quite a lot of unused space allocated.
  4226. This method will reduce the amount of allocated storage to a minimum.
  4227. */
  4228. void minimiseStorageOverheads() throw()
  4229. {
  4230. lock.enter();
  4231. if (numUsed == 0)
  4232. {
  4233. this->setAllocatedSize (0);
  4234. }
  4235. else
  4236. {
  4237. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4238. if (newAllocation < this->numAllocated)
  4239. this->setAllocatedSize (newAllocation);
  4240. }
  4241. lock.exit();
  4242. }
  4243. /** Increases the array's internal storage to hold a minimum number of elements.
  4244. Calling this before adding a large known number of elements means that
  4245. the array won't have to keep dynamically resizing itself as the elements
  4246. are added, and it'll therefore be more efficient.
  4247. */
  4248. void ensureStorageAllocated (const int minNumElements) throw()
  4249. {
  4250. this->ensureAllocatedSize (minNumElements);
  4251. }
  4252. /** Sorts the elements in the array.
  4253. This will use a comparator object to sort the elements into order. The object
  4254. passed must have a method of the form:
  4255. @code
  4256. int compareElements (ElementType first, ElementType second);
  4257. @endcode
  4258. ..and this method must return:
  4259. - a value of < 0 if the first comes before the second
  4260. - a value of 0 if the two objects are equivalent
  4261. - a value of > 0 if the second comes before the first
  4262. To improve performance, the compareElements() method can be declared as static or const.
  4263. @param comparator the comparator to use for comparing elements.
  4264. @param retainOrderOfEquivalentItems if this is true, then items
  4265. which the comparator says are equivalent will be
  4266. kept in the order in which they currently appear
  4267. in the array. This is slower to perform, but may
  4268. be important in some cases. If it's false, a faster
  4269. algorithm is used, but equivalent elements may be
  4270. rearranged.
  4271. @see addSorted, indexOfSorted, sortArray
  4272. */
  4273. template <class ElementComparator>
  4274. void sort (ElementComparator& comparator,
  4275. const bool retainOrderOfEquivalentItems = false) const throw()
  4276. {
  4277. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4278. // avoids getting warning messages about the parameter being unused
  4279. lock.enter();
  4280. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4281. lock.exit();
  4282. }
  4283. /** Locks the array's CriticalSection.
  4284. Of course if the type of section used is a DummyCriticalSection, this won't
  4285. have any effect.
  4286. @see unlockArray
  4287. */
  4288. void lockArray() const throw()
  4289. {
  4290. lock.enter();
  4291. }
  4292. /** Unlocks the array's CriticalSection.
  4293. Of course if the type of section used is a DummyCriticalSection, this won't
  4294. have any effect.
  4295. @see lockArray
  4296. */
  4297. void unlockArray() const throw()
  4298. {
  4299. lock.exit();
  4300. }
  4301. juce_UseDebuggingNewOperator
  4302. private:
  4303. int numUsed;
  4304. TypeOfCriticalSectionToUse lock;
  4305. };
  4306. #endif // __JUCE_ARRAY_JUCEHEADER__
  4307. /********* End of inlined file: juce_Array.h *********/
  4308. /**
  4309. A typedef for an Array of void*'s.
  4310. VoidArrays are used in various places throughout the library instead of
  4311. more strongly-typed arrays, to keep code-size low.
  4312. */
  4313. typedef Array <void*> VoidArray;
  4314. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4315. /********* End of inlined file: juce_VoidArray.h *********/
  4316. #ifndef DOXYGEN
  4317. // (used in StringArray::appendNumbersToDuplicates)
  4318. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4319. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4320. #endif
  4321. /**
  4322. A special array for holding a list of strings.
  4323. @see String, StringPairArray
  4324. */
  4325. class JUCE_API StringArray
  4326. {
  4327. public:
  4328. /** Creates an empty string array */
  4329. StringArray() throw();
  4330. /** Creates a copy of another string array */
  4331. StringArray (const StringArray& other) throw();
  4332. /** Creates a copy of an array of string literals.
  4333. @param strings an array of strings to add. Null pointers in the array will be
  4334. treated as empty strings
  4335. @param numberOfStrings how many items there are in the array
  4336. */
  4337. StringArray (const juce_wchar** const strings,
  4338. const int numberOfStrings) throw();
  4339. /** Creates a copy of an array of string literals.
  4340. @param strings an array of strings to add. Null pointers in the array will be
  4341. treated as empty strings
  4342. @param numberOfStrings how many items there are in the array
  4343. */
  4344. StringArray (const char** const strings,
  4345. const int numberOfStrings) throw();
  4346. /** Creates a copy of a null-terminated array of string literals.
  4347. Each item from the array passed-in is added, until it encounters a null pointer,
  4348. at which point it stops.
  4349. */
  4350. StringArray (const juce_wchar** const strings) throw();
  4351. /** Creates a copy of a null-terminated array of string literals.
  4352. Each item from the array passed-in is added, until it encounters a null pointer,
  4353. at which point it stops.
  4354. */
  4355. StringArray (const char** const strings) throw();
  4356. /** Destructor. */
  4357. virtual ~StringArray() throw();
  4358. /** Copies the contents of another string array into this one */
  4359. const StringArray& operator= (const StringArray& other) throw();
  4360. /** Compares two arrays.
  4361. Comparisons are case-sensitive.
  4362. @returns true only if the other array contains exactly the same strings in the same order
  4363. */
  4364. bool operator== (const StringArray& other) const throw();
  4365. /** Compares two arrays.
  4366. Comparisons are case-sensitive.
  4367. @returns false if the other array contains exactly the same strings in the same order
  4368. */
  4369. bool operator!= (const StringArray& other) const throw();
  4370. /** Returns the number of strings in the array */
  4371. inline int size() const throw() { return strings.size(); };
  4372. /** Returns one of the strings from the array.
  4373. If the index is out-of-range, an empty string is returned.
  4374. Obviously the reference returned shouldn't be stored for later use, as the
  4375. string it refers to may disappear when the array changes.
  4376. */
  4377. const String& operator[] (const int index) const throw();
  4378. /** Searches for a string in the array.
  4379. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4380. @returns true if the string is found inside the array
  4381. */
  4382. bool contains (const String& stringToLookFor,
  4383. const bool ignoreCase = false) const throw();
  4384. /** Searches for a string in the array.
  4385. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4386. @param stringToLookFor the string to try to find
  4387. @param ignoreCase whether the comparison should be case-insensitive
  4388. @param startIndex the first index to start searching from
  4389. @returns the index of the first occurrence of the string in this array,
  4390. or -1 if it isn't found.
  4391. */
  4392. int indexOf (const String& stringToLookFor,
  4393. const bool ignoreCase = false,
  4394. int startIndex = 0) const throw();
  4395. /** Appends a string at the end of the array. */
  4396. void add (const String& stringToAdd) throw();
  4397. /** Inserts a string into the array.
  4398. This will insert a string into the array at the given index, moving
  4399. up the other elements to make room for it.
  4400. If the index is less than zero or greater than the size of the array,
  4401. the new string will be added to the end of the array.
  4402. */
  4403. void insert (const int index,
  4404. const String& stringToAdd) throw();
  4405. /** Adds a string to the array as long as it's not already in there.
  4406. The search can optionally be case-insensitive.
  4407. */
  4408. void addIfNotAlreadyThere (const String& stringToAdd,
  4409. const bool ignoreCase = false) throw();
  4410. /** Replaces one of the strings in the array with another one.
  4411. If the index is higher than the array's size, the new string will be
  4412. added to the end of the array; if it's less than zero nothing happens.
  4413. */
  4414. void set (const int index,
  4415. const String& newString) throw();
  4416. /** Appends some strings from another array to the end of this one.
  4417. @param other the array to add
  4418. @param startIndex the first element of the other array to add
  4419. @param numElementsToAdd the maximum number of elements to add (if this is
  4420. less than zero, they are all added)
  4421. */
  4422. void addArray (const StringArray& other,
  4423. int startIndex = 0,
  4424. int numElementsToAdd = -1) throw();
  4425. /** Breaks up a string into tokens and adds them to this array.
  4426. This will tokenise the given string using whitespace characters as the
  4427. token delimiters, and will add these tokens to the end of the array.
  4428. @returns the number of tokens added
  4429. */
  4430. int addTokens (const tchar* const stringToTokenise,
  4431. const bool preserveQuotedStrings) throw();
  4432. /** Breaks up a string into tokens and adds them to this array.
  4433. This will tokenise the given string (using the string passed in to define the
  4434. token delimiters), and will add these tokens to the end of the array.
  4435. @param stringToTokenise the string to tokenise
  4436. @param breakCharacters a string of characters, any of which will be considered
  4437. to be a token delimiter.
  4438. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4439. which are treated as quotes. Any text occurring
  4440. between quotes is not broken up into tokens.
  4441. @returns the number of tokens added
  4442. */
  4443. int addTokens (const tchar* const stringToTokenise,
  4444. const tchar* breakCharacters,
  4445. const tchar* quoteCharacters) throw();
  4446. /** Breaks up a string into lines and adds them to this array.
  4447. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4448. to the array. Line-break characters are omitted from the strings that are added to
  4449. the array.
  4450. */
  4451. int addLines (const tchar* stringToBreakUp) throw();
  4452. /** Removes all elements from the array. */
  4453. void clear() throw();
  4454. /** Removes a string from the array.
  4455. If the index is out-of-range, no action will be taken.
  4456. */
  4457. void remove (const int index) throw();
  4458. /** Finds a string in the array and removes it.
  4459. This will remove the first occurrence of the given string from the array. The
  4460. comparison may be case-insensitive depending on the ignoreCase parameter.
  4461. */
  4462. void removeString (const String& stringToRemove,
  4463. const bool ignoreCase = false) throw();
  4464. /** Removes any duplicated elements from the array.
  4465. If any string appears in the array more than once, only the first occurrence of
  4466. it will be retained.
  4467. @param ignoreCase whether to use a case-insensitive comparison
  4468. */
  4469. void removeDuplicates (const bool ignoreCase) throw();
  4470. /** Removes empty strings from the array.
  4471. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4472. characters will also be removed
  4473. */
  4474. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4475. /** Moves one of the strings to a different position.
  4476. This will move the string to a specified index, shuffling along
  4477. any intervening elements as required.
  4478. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4479. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4480. @param currentIndex the index of the value to be moved. If this isn't a
  4481. valid index, then nothing will be done
  4482. @param newIndex the index at which you'd like this value to end up. If this
  4483. is less than zero, the value will be moved to the end
  4484. of the array
  4485. */
  4486. void move (const int currentIndex, int newIndex) throw();
  4487. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4488. void trim() throw();
  4489. /** Adds numbers to the strings in the array, to make each string unique.
  4490. This will add numbers to the ends of groups of similar strings.
  4491. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4492. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4493. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4494. also has a number appended to it.
  4495. @param preNumberString when adding a number, this string is added before the number
  4496. @param postNumberString this string is appended after any numbers that are added
  4497. */
  4498. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4499. const bool appendNumberToFirstInstance,
  4500. const tchar* const preNumberString = defaultPreNumberString,
  4501. const tchar* const postNumberString = defaultPostNumberString) throw();
  4502. /** Joins the strings in the array together into one string.
  4503. This will join a range of elements from the array into a string, separating
  4504. them with a given string.
  4505. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4506. @param separatorString the string to insert between all the strings
  4507. @param startIndex the first element to join
  4508. @param numberOfElements how many elements to join together. If this is less
  4509. than zero, all available elements will be used.
  4510. */
  4511. const String joinIntoString (const String& separatorString,
  4512. int startIndex = 0,
  4513. int numberOfElements = -1) const throw();
  4514. /** Sorts the array into alphabetical order.
  4515. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4516. */
  4517. void sort (const bool ignoreCase) throw();
  4518. /** Reduces the amount of storage being used by the array.
  4519. Arrays typically allocate slightly more storage than they need, and after
  4520. removing elements, they may have quite a lot of unused space allocated.
  4521. This method will reduce the amount of allocated storage to a minimum.
  4522. */
  4523. void minimiseStorageOverheads() throw();
  4524. juce_UseDebuggingNewOperator
  4525. private:
  4526. VoidArray strings;
  4527. };
  4528. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4529. /********* End of inlined file: juce_StringArray.h *********/
  4530. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4531. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4532. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4533. /**
  4534. A class to hold a resizable block of raw data.
  4535. */
  4536. class JUCE_API MemoryBlock
  4537. {
  4538. public:
  4539. /** Create an uninitialised block with 0 size. */
  4540. MemoryBlock() throw();
  4541. /** Creates a memory block with a given initial size.
  4542. @param initialSize the size of block to create
  4543. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4544. */
  4545. MemoryBlock (const int initialSize,
  4546. const bool initialiseToZero = false) throw();
  4547. /** Creates a copy of another memory block. */
  4548. MemoryBlock (const MemoryBlock& other) throw();
  4549. /** Creates a memory block using a copy of a block of data.
  4550. @param dataToInitialiseFrom some data to copy into this block
  4551. @param sizeInBytes how much space to use
  4552. */
  4553. MemoryBlock (const void* const dataToInitialiseFrom,
  4554. const int sizeInBytes) throw();
  4555. /** Destructor. */
  4556. ~MemoryBlock() throw();
  4557. /** Copies another memory block onto this one.
  4558. This block will be resized and copied to exactly match the other one.
  4559. */
  4560. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4561. /** Compares two memory blocks.
  4562. @returns true only if the two blocks are the same size and have identical contents.
  4563. */
  4564. bool operator== (const MemoryBlock& other) const throw();
  4565. /** Compares two memory blocks.
  4566. @returns true if the two blocks are different sizes or have different contents.
  4567. */
  4568. bool operator!= (const MemoryBlock& other) const throw();
  4569. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4570. Note that the pointer returned will probably become invalid when the
  4571. block is resized.
  4572. */
  4573. template <class DataType>
  4574. operator DataType*() const throw() { return (DataType*) data; }
  4575. /** Returns a void pointer to the data.
  4576. Note that the pointer returned will probably become invalid when the
  4577. block is resized.
  4578. */
  4579. void* getData() const throw() { return data; }
  4580. /** Returns a byte from the memory block.
  4581. This returns a reference, so you can also use it to set a byte.
  4582. */
  4583. char& operator[] (const int offset) const throw() { return data [offset]; }
  4584. /** Returns the block's current allocated size, in bytes. */
  4585. int getSize() const throw() { return size; }
  4586. /** Resizes the memory block.
  4587. This will try to keep as much of the block's current content as it can,
  4588. and can optionally be made to clear any new space that gets allocated at
  4589. the end of the block.
  4590. @param newSize the new desired size for the block
  4591. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4592. whether to clear the new section or just leave it
  4593. uninitialised
  4594. @see ensureSize
  4595. */
  4596. void setSize (const int newSize,
  4597. const bool initialiseNewSpaceToZero = false) throw();
  4598. /** Increases the block's size only if it's smaller than a given size.
  4599. @param minimumSize if the block is already bigger than this size, no action
  4600. will be taken; otherwise it will be increased to this size
  4601. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4602. whether to clear the new section or just leave it
  4603. uninitialised
  4604. @see setSize
  4605. */
  4606. void ensureSize (const int minimumSize,
  4607. const bool initialiseNewSpaceToZero = false) throw();
  4608. /** Fills the entire memory block with a repeated byte value.
  4609. This is handy for clearing a block of memory to zero.
  4610. */
  4611. void fillWith (const uint8 valueToUse) throw();
  4612. /** Adds another block of data to the end of this one.
  4613. This block's size will be increased accordingly.
  4614. */
  4615. void append (const void* const data,
  4616. const int numBytes) throw();
  4617. /** Copies data into this MemoryBlock from a memory address.
  4618. @param srcData the memory location of the data to copy into this block
  4619. @param destinationOffset the offset in this block at which the data being copied should begin
  4620. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4621. it will be clipped so not to do anything nasty)
  4622. */
  4623. void copyFrom (const void* srcData,
  4624. int destinationOffset,
  4625. int numBytes) throw();
  4626. /** Copies data from this MemoryBlock to a memory address.
  4627. @param destData the memory location to write to
  4628. @param sourceOffset the offset within this block from which the copied data will be read
  4629. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4630. zeros will be used for that portion of the data)
  4631. */
  4632. void copyTo (void* destData,
  4633. int sourceOffset,
  4634. int numBytes) const throw();
  4635. /** Chops out a section of the block.
  4636. This will remove a section of the memory block and close the gap around it,
  4637. shifting any subsequent data downwards and reducing the size of the block.
  4638. If the range specified goes beyond the size of the block, it will be clipped.
  4639. */
  4640. void removeSection (int startByte, int numBytesToRemove) throw();
  4641. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4642. characters in the system's default encoding. */
  4643. const String toString() const throw();
  4644. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4645. The block will be resized to the number of valid bytes read from the string.
  4646. Non-hex characters in the string will be ignored.
  4647. @see String::toHexString()
  4648. */
  4649. void loadFromHexString (const String& sourceHexString) throw();
  4650. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4651. void setBitRange (int bitRangeStart,
  4652. int numBits,
  4653. int binaryNumberToApply) throw();
  4654. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4655. int getBitRange (int bitRangeStart,
  4656. int numBitsToRead) const throw();
  4657. /** Returns a string of characters that represent the binary contents of this block.
  4658. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4659. of simple non-extended characters, e.g. for storage in XML.
  4660. @see fromBase64Encoding
  4661. */
  4662. const String toBase64Encoding() const throw();
  4663. /** Takes a string of encoded characters and turns it into binary data.
  4664. The string passed in must have been created by to64BitEncoding(), and this
  4665. block will be resized to recreate the original data block.
  4666. @see toBase64Encoding
  4667. */
  4668. bool fromBase64Encoding (const String& encodedString) throw();
  4669. juce_UseDebuggingNewOperator
  4670. private:
  4671. char* data;
  4672. int size;
  4673. };
  4674. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4675. /********* End of inlined file: juce_MemoryBlock.h *********/
  4676. class FileInputStream;
  4677. class FileOutputStream;
  4678. /**
  4679. Represents a local file or directory.
  4680. This class encapsulates the absolute pathname of a file or directory, and
  4681. has methods for finding out about the file and changing its properties.
  4682. To read or write to the file, there are methods for returning an input or
  4683. output stream.
  4684. @see FileInputStream, FileOutputStream
  4685. */
  4686. class JUCE_API File
  4687. {
  4688. public:
  4689. /** Creates an (invalid) file object.
  4690. The file is initially set to an empty path, so getFullPath() will return
  4691. an empty string, and comparing the file to File::nonexistent will return
  4692. true.
  4693. You can use its operator= method to point it at a proper file.
  4694. */
  4695. File() throw() {}
  4696. /** Creates a file from an absolute path.
  4697. If the path supplied is a relative path, it is taken to be relative
  4698. to the current working directory (see File::getCurrentWorkingDirectory()),
  4699. but this isn't a recommended way of creating a file, because you
  4700. never know what the CWD is going to be.
  4701. On the Mac/Linux, the path can include "~" notation for referring to
  4702. user home directories.
  4703. */
  4704. File (const String& path) throw();
  4705. /** Creates a copy of another file object. */
  4706. File (const File& other) throw();
  4707. /** Destructor. */
  4708. ~File() throw() {}
  4709. /** Sets the file based on an absolute pathname.
  4710. If the path supplied is a relative path, it is taken to be relative
  4711. to the current working directory (see File::getCurrentWorkingDirectory()),
  4712. but this isn't a recommended way of creating a file, because you
  4713. never know what the CWD is going to be.
  4714. On the Mac/Linux, the path can include "~" notation for referring to
  4715. user home directories.
  4716. */
  4717. const File& operator= (const String& newFilePath) throw();
  4718. /** Copies from another file object. */
  4719. const File& operator= (const File& otherFile) throw();
  4720. /** This static constant is used for referring to an 'invalid' file. */
  4721. static const File nonexistent;
  4722. /** Checks whether the file actually exists.
  4723. @returns true if the file exists, either as a file or a directory.
  4724. @see existsAsFile, isDirectory
  4725. */
  4726. bool exists() const throw();
  4727. /** Checks whether the file exists and is a file rather than a directory.
  4728. @returns true only if this is a real file, false if it's a directory
  4729. or doesn't exist
  4730. @see exists, isDirectory
  4731. */
  4732. bool existsAsFile() const throw();
  4733. /** Checks whether the file is a directory that exists.
  4734. @returns true only if the file is a directory which actually exists, so
  4735. false if it's a file or doesn't exist at all
  4736. @see exists, existsAsFile
  4737. */
  4738. bool isDirectory() const throw();
  4739. /** Returns the size of the file in bytes.
  4740. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4741. */
  4742. int64 getSize() const throw();
  4743. /** Utility function to convert a file size in bytes to a neat string description.
  4744. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4745. 2000000 would produce "2 MB", etc.
  4746. */
  4747. static const String descriptionOfSizeInBytes (const int64 bytes);
  4748. /** Returns the complete, absolute path of this file.
  4749. This includes the filename and all its parent folders. On Windows it'll
  4750. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4751. path starting from the root folder.
  4752. If you just want the file's name, you should use getFileName() or
  4753. getFileNameWithoutExtension().
  4754. @see getFileName, getRelativePathFrom
  4755. */
  4756. const String& getFullPathName() const throw() { return fullPath; }
  4757. /** Returns the last section of the pathname.
  4758. Returns just the final part of the path - e.g. if the whole path
  4759. is "/moose/fish/foo.txt" this will return "foo.txt".
  4760. For a directory, it returns the final part of the path - e.g. for the
  4761. directory "/moose/fish" it'll return "fish".
  4762. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4763. "/moose/.fish", it'll return ".fish"
  4764. @see getFullPathName, getFileNameWithoutExtension
  4765. */
  4766. const String getFileName() const throw();
  4767. /** Creates a relative path that refers to a file relatively to a given directory.
  4768. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4769. would return "../../foo.txt".
  4770. If it's not possible to navigate from one file to the other, an absolute
  4771. path is returned. If the paths are invalid, an empty string may also be
  4772. returned.
  4773. @param directoryToBeRelativeTo the directory which the resultant string will
  4774. be relative to. If this is actually a file rather than
  4775. a directory, its parent directory will be used instead.
  4776. If it doesn't exist, it's assumed to be a directory.
  4777. @see getChildFile, isAbsolutePath
  4778. */
  4779. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4780. /** Returns the file's extension.
  4781. Returns the file extension of this file, also including the dot.
  4782. e.g. "/moose/fish/foo.txt" would return ".txt"
  4783. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4784. */
  4785. const String getFileExtension() const throw();
  4786. /** Checks whether the file has a given extension.
  4787. @param extensionToTest the extension to look for - it doesn't matter whether or
  4788. not this string has a dot at the start, so ".wav" and "wav"
  4789. will have the same effect. The comparison used is
  4790. case-insensitve.
  4791. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4792. */
  4793. bool hasFileExtension (const String& extensionToTest) const throw();
  4794. /** Returns a version of this file with a different file extension.
  4795. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4796. @param newExtension the new extension, either with or without a dot at the start (this
  4797. doesn't make any difference). To get remove a file's extension altogether,
  4798. pass an empty string into this function.
  4799. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4800. */
  4801. const File withFileExtension (const String& newExtension) const throw();
  4802. /** Returns the last part of the filename, without its file extension.
  4803. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4804. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4805. */
  4806. const String getFileNameWithoutExtension() const throw();
  4807. /** Returns a 32-bit hash-code that identifies this file.
  4808. This is based on the filename. Obviously it's possible, although unlikely, that
  4809. two files will have the same hash-code.
  4810. */
  4811. int hashCode() const throw();
  4812. /** Returns a 64-bit hash-code that identifies this file.
  4813. This is based on the filename. Obviously it's possible, although unlikely, that
  4814. two files will have the same hash-code.
  4815. */
  4816. int64 hashCode64() const throw();
  4817. /** Returns a file based on a relative path.
  4818. This will find a child file or directory of the current object.
  4819. e.g.
  4820. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4821. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4822. If the string is actually an absolute path, it will be treated as such, e.g.
  4823. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4824. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4825. */
  4826. const File getChildFile (String relativePath) const throw();
  4827. /** Returns a file which is in the same directory as this one.
  4828. This is equivalent to getParentDirectory().getChildFile (name).
  4829. @see getChildFile, getParentDirectory
  4830. */
  4831. const File getSiblingFile (const String& siblingFileName) const throw();
  4832. /** Returns the directory that contains this file or directory.
  4833. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4834. */
  4835. const File getParentDirectory() const throw();
  4836. /** Checks whether a file is somewhere inside a directory.
  4837. Returns true if this file is somewhere inside a subdirectory of the directory
  4838. that is passed in. Neither file actually has to exist, because the function
  4839. just checks the paths for similarities.
  4840. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4841. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4842. */
  4843. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4844. /** Chooses a filename relative to this one that doesn't already exist.
  4845. If this file is a directory, this will return a child file of this
  4846. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4847. it finds one that isn't already there.
  4848. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4849. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4850. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4851. @param prefix the string to use for the filename before the number
  4852. @param suffix the string to add to the filename after the number
  4853. @param putNumbersInBrackets if true, this will create filenames in the
  4854. format "prefix(number)suffix", if false, it will leave the
  4855. brackets out.
  4856. */
  4857. const File getNonexistentChildFile (const String& prefix,
  4858. const String& suffix,
  4859. bool putNumbersInBrackets = true) const throw();
  4860. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4861. If this file doesn't exist, this will just return itself, otherwise it
  4862. will return an appropriate sibling that doesn't exist, e.g. if a file
  4863. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4864. @param putNumbersInBrackets whether to add brackets around the numbers that
  4865. get appended to the new filename.
  4866. */
  4867. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4868. /** Compares the pathnames for two files. */
  4869. bool operator== (const File& otherFile) const throw();
  4870. /** Compares the pathnames for two files. */
  4871. bool operator!= (const File& otherFile) const throw();
  4872. /** Checks whether a file can be created or written to.
  4873. @returns true if it's possible to create and write to this file. If the file
  4874. doesn't already exist, this will check its parent directory to
  4875. see if writing is allowed.
  4876. @see setReadOnly
  4877. */
  4878. bool hasWriteAccess() const throw();
  4879. /** Changes the write-permission of a file or directory.
  4880. @param shouldBeReadOnly whether to add or remove write-permission
  4881. @param applyRecursively if the file is a directory and this is true, it will
  4882. recurse through all the subfolders changing the permissions
  4883. of all files
  4884. @returns true if it manages to change the file's permissions.
  4885. @see hasWriteAccess
  4886. */
  4887. bool setReadOnly (const bool shouldBeReadOnly,
  4888. const bool applyRecursively = false) const throw();
  4889. /** Returns true if this file is a hidden or system file.
  4890. The criteria for deciding whether a file is hidden are platform-dependent.
  4891. */
  4892. bool isHidden() const throw();
  4893. /** Returns the last modification time of this file.
  4894. @returns the time, or an invalid time if the file doesn't exist.
  4895. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4896. */
  4897. const Time getLastModificationTime() const throw();
  4898. /** Returns the last time this file was accessed.
  4899. @returns the time, or an invalid time if the file doesn't exist.
  4900. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4901. */
  4902. const Time getLastAccessTime() const throw();
  4903. /** Returns the time that this file was created.
  4904. @returns the time, or an invalid time if the file doesn't exist.
  4905. @see getLastModificationTime, getLastAccessTime
  4906. */
  4907. const Time getCreationTime() const throw();
  4908. /** Changes the modification time for this file.
  4909. @param newTime the time to apply to the file
  4910. @returns true if it manages to change the file's time.
  4911. @see getLastModificationTime, setLastAccessTime, setCreationTime
  4912. */
  4913. bool setLastModificationTime (const Time& newTime) const throw();
  4914. /** Changes the last-access time for this file.
  4915. @param newTime the time to apply to the file
  4916. @returns true if it manages to change the file's time.
  4917. @see getLastAccessTime, setLastModificationTime, setCreationTime
  4918. */
  4919. bool setLastAccessTime (const Time& newTime) const throw();
  4920. /** Changes the creation date for this file.
  4921. @param newTime the time to apply to the file
  4922. @returns true if it manages to change the file's time.
  4923. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4924. */
  4925. bool setCreationTime (const Time& newTime) const throw();
  4926. /** Creates an empty file if it doesn't already exist.
  4927. If the file that this object refers to doesn't exist, this will create a file
  4928. of zero size.
  4929. If it already exists or is a directory, this method will do nothing.
  4930. @returns true if the file has been created (or if it already existed).
  4931. @see createDirectory
  4932. */
  4933. bool create() const throw();
  4934. /** Creates a new directory for this filename.
  4935. This will try to create the file as a directory, and fill also create
  4936. any parent directories it needs in order to complete the operation.
  4937. @returns true if the directory has been created successfully, (or if it
  4938. already existed beforehand).
  4939. @see create
  4940. */
  4941. bool createDirectory() const throw();
  4942. /** Deletes a file.
  4943. If this file is actually a directory, it may not be deleted correctly if it
  4944. contains files. See deleteRecursively() as a better way of deleting directories.
  4945. @returns true if the file has been successfully deleted (or if it didn't exist to
  4946. begin with).
  4947. @see deleteRecursively
  4948. */
  4949. bool deleteFile() const throw();
  4950. /** Deletes a file or directory and all its subdirectories.
  4951. If this file is a directory, this will try to delete it and all its subfolders. If
  4952. it's just a file, it will just try to delete the file.
  4953. @returns true if the file and all its subfolders have been successfully deleted
  4954. (or if it didn't exist to begin with).
  4955. @see deleteFile
  4956. */
  4957. bool deleteRecursively() const throw();
  4958. /** Moves or renames a file.
  4959. Tries to move a file to a different location.
  4960. If the target file already exists, this will attempt to delete it first, and
  4961. will fail if this can't be done.
  4962. Note that the destination file isn't the directory to put it in, it's the actual
  4963. filename that you want the new file to have.
  4964. @returns true if the operation succeeds
  4965. */
  4966. bool moveFileTo (const File& targetLocation) const throw();
  4967. /** Copies a file.
  4968. Tries to copy a file to a different location.
  4969. If the target file already exists, this will attempt to delete it first, and
  4970. will fail if this can't be done.
  4971. @returns true if the operation succeeds
  4972. */
  4973. bool copyFileTo (const File& targetLocation) const throw();
  4974. /** Copies a directory.
  4975. Tries to copy an entire directory, recursively.
  4976. If this file isn't a directory or if any target files can't be created, this
  4977. will return false.
  4978. @param newDirectory the directory that this one should be copied to. Note that this
  4979. is the name of the actual directory to create, not the directory
  4980. into which the new one should be placed, so there must be enough
  4981. write privileges to create it if it doesn't exist. Any files inside
  4982. it will be overwritten by similarly named ones that are copied.
  4983. */
  4984. bool copyDirectoryTo (const File& newDirectory) const throw();
  4985. /** Used in file searching, to specify whether to return files, directories, or both.
  4986. */
  4987. enum TypesOfFileToFind
  4988. {
  4989. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  4990. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  4991. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  4992. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  4993. };
  4994. /** Searches inside a directory for files matching a wildcard pattern.
  4995. Assuming that this file is a directory, this method will search it
  4996. for either files or subdirectories whose names match a filename pattern.
  4997. @param results an array to which File objects will be added for the
  4998. files that the search comes up with
  4999. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5000. return files, directories, or both. If the ignoreHiddenFiles flag
  5001. is also added to this value, hidden files won't be returned
  5002. @param searchRecursively if true, all subdirectories will be recursed into to do
  5003. an exhaustive search
  5004. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5005. @returns the number of results that have been found
  5006. @see getNumberOfChildFiles, DirectoryIterator
  5007. */
  5008. int findChildFiles (OwnedArray<File>& results,
  5009. const int whatToLookFor,
  5010. const bool searchRecursively,
  5011. const String& wildCardPattern = JUCE_T("*")) const throw();
  5012. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5013. Assuming that this file is a directory, this method will search it
  5014. for either files or subdirectories whose names match a filename pattern,
  5015. and will return the number of matches found.
  5016. This isn't a recursive call, and will only search this directory, not
  5017. its children.
  5018. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5019. count files, directories, or both. If the ignoreHiddenFiles flag
  5020. is also added to this value, hidden files won't be counted
  5021. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5022. @returns the number of matches found
  5023. @see findChildFiles, DirectoryIterator
  5024. */
  5025. int getNumberOfChildFiles (const int whatToLookFor,
  5026. const String& wildCardPattern = JUCE_T("*")) const throw();
  5027. /** Creates a stream to read from this file.
  5028. @returns a stream that will read from this file (initially positioned at the
  5029. start of the file), or 0 if the file can't be opened for some reason
  5030. @see createOutputStream, loadFileAsData
  5031. */
  5032. FileInputStream* createInputStream() const throw();
  5033. /** Creates a stream to write to this file.
  5034. If the file exists, the stream that is returned will be positioned ready for
  5035. writing at the end of the file, so you might want to use deleteFile() first
  5036. to write to an empty file.
  5037. @returns a stream that will write to this file (initially positioned at the
  5038. end of the file), or 0 if the file can't be opened for some reason
  5039. @see createInputStream, printf, appendData, appendText
  5040. */
  5041. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5042. /** Loads a file's contents into memory as a block of binary data.
  5043. Of course, trying to load a very large file into memory will blow up, so
  5044. it's better to check first.
  5045. @param result the data block to which the file's contents should be appended - note
  5046. that if the memory block might already contain some data, you
  5047. might want to clear it first
  5048. @returns true if the file could all be read into memory
  5049. */
  5050. bool loadFileAsData (MemoryBlock& result) const throw();
  5051. /** Reads a file into memory as a string.
  5052. Attempts to load the entire file as a zero-terminated string.
  5053. This makes use of InputStream::readEntireStreamAsString, which should
  5054. automatically cope with unicode/acsii file formats.
  5055. */
  5056. const String loadFileAsString() const throw();
  5057. /** Writes text to the end of the file.
  5058. This will try to do a printf to the file.
  5059. @returns false if it can't write to the file for some reason
  5060. */
  5061. bool printf (const tchar* format, ...) const throw();
  5062. /** Appends a block of binary data to the end of the file.
  5063. This will try to write the given buffer to the end of the file.
  5064. @returns false if it can't write to the file for some reason
  5065. */
  5066. bool appendData (const void* const dataToAppend,
  5067. const int numberOfBytes) const throw();
  5068. /** Replaces this file's contents with a given block of data.
  5069. This will delete the file and replace it with the given data.
  5070. A nice feature of this method is that it's safe - instead of deleting
  5071. the file first and then re-writing it, it creates a new temporary file,
  5072. writes the data to that, and then moves the new file to replace the existing
  5073. file. This means that if the power gets pulled out or something crashes,
  5074. you're a lot less likely to end up with an empty file..
  5075. Returns true if the operation succeeds, or false if it fails.
  5076. @see appendText
  5077. */
  5078. bool replaceWithData (const void* const dataToWrite,
  5079. const int numberOfBytes) const throw();
  5080. /** Appends a string to the end of the file.
  5081. This will try to append a text string to the file, as either 16-bit unicode
  5082. or 8-bit characters in the default system encoding.
  5083. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5084. the endianness of the file.
  5085. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5086. @see replaceWithText
  5087. */
  5088. bool appendText (const String& textToAppend,
  5089. const bool asUnicode = false,
  5090. const bool writeUnicodeHeaderBytes = false) const throw();
  5091. /** Replaces this file's contents with a given text string.
  5092. This will delete the file and replace it with the given text.
  5093. A nice feature of this method is that it's safe - instead of deleting
  5094. the file first and then re-writing it, it creates a new temporary file,
  5095. writes the text to that, and then moves the new file to replace the existing
  5096. file. This means that if the power gets pulled out or something crashes,
  5097. you're a lot less likely to end up with an empty file..
  5098. For an explanation of the parameters here, see the appendText() method.
  5099. Returns true if the operation succeeds, or false if it fails.
  5100. @see appendText
  5101. */
  5102. bool replaceWithText (const String& textToWrite,
  5103. const bool asUnicode = false,
  5104. const bool writeUnicodeHeaderBytes = false) const throw();
  5105. /** Creates a set of files to represent each file root.
  5106. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5107. to which ones are available. On the Mac/Linux, this will probably
  5108. just add a single entry for "/".
  5109. */
  5110. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5111. /** Finds the name of the drive on which this file lives.
  5112. @returns the volume label of the drive, or an empty string if this isn't possible
  5113. */
  5114. const String getVolumeLabel() const throw();
  5115. /** Returns the serial number of the volume on which this file lives.
  5116. @returns the serial number, or zero if there's a problem doing this
  5117. */
  5118. int getVolumeSerialNumber() const throw();
  5119. /** Returns the number of bytes free on the drive that this file lives on.
  5120. @returns the number of bytes free, or 0 if there's a problem finding this out
  5121. */
  5122. int64 getBytesFreeOnVolume() const throw();
  5123. /** Returns true if this file is on a CD or DVD drive. */
  5124. bool isOnCDRomDrive() const throw();
  5125. /** Returns true if this file is on a hard disk.
  5126. This will fail if it's a network drive, but will still be true for
  5127. removable hard-disks.
  5128. */
  5129. bool isOnHardDisk() const throw();
  5130. /** Returns true if this file is on a removable disk drive.
  5131. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5132. */
  5133. bool isOnRemovableDrive() const throw();
  5134. /** Launches the file as a process.
  5135. - if the file is executable, this will run it.
  5136. - if it's a document of some kind, it will launch the document with its
  5137. default viewer application.
  5138. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5139. */
  5140. bool startAsProcess (const String& parameters = String::empty) const throw();
  5141. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5142. */
  5143. enum SpecialLocationType
  5144. {
  5145. /** The user's home folder. This is the same as using File ("~"). */
  5146. userHomeDirectory,
  5147. /** The user's default documents folder. On Windows, this might be the user's
  5148. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5149. doesn't tend to have one of these, so it might just return their home folder.
  5150. */
  5151. userDocumentsDirectory,
  5152. /** The folder that contains the user's desktop objects. */
  5153. userDesktopDirectory,
  5154. /** The folder in which applications store their persistent user-specific settings.
  5155. On Windows, this might be "\Documents and Settings\username\Application Data".
  5156. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5157. always create your own sub-folder to put them in, to avoid making a mess.
  5158. */
  5159. userApplicationDataDirectory,
  5160. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5161. of the computer, rather than just the current user.
  5162. On the Mac it'll be "/Library", on Windows, it could be something like
  5163. "\Documents and Settings\All Users\Application Data".
  5164. Depending on the setup, this folder may be read-only.
  5165. */
  5166. commonApplicationDataDirectory,
  5167. /** The folder that should be used for temporary files.
  5168. Always delete them when you're finished, to keep the user's computer tidy!
  5169. */
  5170. tempDirectory,
  5171. /** Returns this application's executable file.
  5172. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5173. host app.
  5174. On the mac this will return the unix binary, not the package folder - see
  5175. currentApplicationFile for that.
  5176. */
  5177. currentExecutableFile,
  5178. /** Returns this application's location.
  5179. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5180. host app.
  5181. On the mac this will return the package folder (if it's in one), not the unix binary
  5182. that's inside it - compare with currentExecutableFile.
  5183. */
  5184. currentApplicationFile,
  5185. /** The directory in which applications normally get installed.
  5186. So on windows, this would be something like "c:\program files", on the
  5187. Mac "/Applications", or "/usr" on linux.
  5188. */
  5189. globalApplicationsDirectory,
  5190. /** The most likely place where a user might store their music files.
  5191. */
  5192. userMusicDirectory,
  5193. /** The most likely place where a user might store their movie files.
  5194. */
  5195. userMoviesDirectory,
  5196. };
  5197. /** Finds the location of a special type of file or directory, such as a home folder or
  5198. documents folder.
  5199. @see SpecialLocationType
  5200. */
  5201. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5202. /** Returns a temporary file in the system's temp directory.
  5203. This will try to return the name of a non-existent temp file.
  5204. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5205. */
  5206. static const File createTempFile (const String& fileNameEnding) throw();
  5207. /** Returns the current working directory.
  5208. @see setAsCurrentWorkingDirectory
  5209. */
  5210. static const File getCurrentWorkingDirectory() throw();
  5211. /** Sets the current working directory to be this file.
  5212. For this to work the file must point to a valid directory.
  5213. @returns true if the current directory has been changed.
  5214. @see getCurrentWorkingDirectory
  5215. */
  5216. bool setAsCurrentWorkingDirectory() const throw();
  5217. /** The system-specific file separator character.
  5218. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5219. */
  5220. static const tchar separator;
  5221. /** The system-specific file separator character, as a string.
  5222. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5223. */
  5224. static const tchar* separatorString;
  5225. /** Removes illegal characters from a filename.
  5226. This will return a copy of the given string after removing characters
  5227. that are not allowed in a legal filename, and possibly shortening the
  5228. string if it's too long.
  5229. Because this will remove slashes, don't use it on an absolute pathname.
  5230. @see createLegalPathName
  5231. */
  5232. static const String createLegalFileName (const String& fileNameToFix) throw();
  5233. /** Removes illegal characters from a pathname.
  5234. Similar to createLegalFileName(), but this won't remove slashes, so can
  5235. be used on a complete pathname.
  5236. @see createLegalFileName
  5237. */
  5238. static const String createLegalPathName (const String& pathNameToFix) throw();
  5239. /** Indicates whether filenames are case-sensitive on the current operating system.
  5240. */
  5241. static bool areFileNamesCaseSensitive();
  5242. /** Returns true if the string seems to be a fully-specified absolute path.
  5243. */
  5244. static bool isAbsolutePath (const String& path) throw();
  5245. juce_UseDebuggingNewOperator
  5246. private:
  5247. String fullPath;
  5248. // internal way of contructing a file without checking the path
  5249. friend class DirectoryIterator;
  5250. File (const String&, int) throw();
  5251. const String getPathUpToLastSlash() const throw();
  5252. };
  5253. #endif // __JUCE_FILE_JUCEHEADER__
  5254. /********* End of inlined file: juce_File.h *********/
  5255. /**
  5256. A simple implemenation of a Logger that writes to a file.
  5257. @see Logger
  5258. */
  5259. class JUCE_API FileLogger : public Logger
  5260. {
  5261. public:
  5262. /** Creates a FileLogger for a given file.
  5263. @param fileToWriteTo the file that to use - new messages will be appended
  5264. to the file. If the file doesn't exist, it will be created,
  5265. along with any parent directories that are needed.
  5266. @param welcomeMessage when opened, the logger will write a header to the log, along
  5267. with the current date and time, and this welcome message
  5268. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5269. but is larger than this number of bytes, then the start of the
  5270. file will be truncated to keep the size down. This prevents a log
  5271. file getting ridiculously large over time. The file will be truncated
  5272. at a new-line boundary. If this value is less than zero, no size limit
  5273. will be imposed; if it's zero, the file will always be deleted. Note that
  5274. the size is only checked once when this object is created - any logging
  5275. that is done later will be appended without any checking
  5276. */
  5277. FileLogger (const File& fileToWriteTo,
  5278. const String& welcomeMessage,
  5279. const int maxInitialFileSizeBytes = 128 * 1024);
  5280. /** Destructor. */
  5281. ~FileLogger();
  5282. void logMessage (const String& message);
  5283. /** Helper function to create a log file in the correct place for this platform.
  5284. On Windows this will return a logger with a path such as:
  5285. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5286. On the Mac it'll create something like:
  5287. ~/Library/Logs/[logFileName]
  5288. The method might return 0 if the file can't be created for some reason.
  5289. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5290. it's best to use the something like the name of your application here.
  5291. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5292. call it "log.txt" because if it goes in a directory with logs
  5293. from other applications (as it will do on the Mac) then no-one
  5294. will know which one is yours!
  5295. @param welcomeMessage a message that will be written to the log when it's opened.
  5296. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5297. */
  5298. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5299. const String& logFileName,
  5300. const String& welcomeMessage,
  5301. const int maxInitialFileSizeBytes = 128 * 1024);
  5302. juce_UseDebuggingNewOperator
  5303. private:
  5304. File logFile;
  5305. CriticalSection logLock;
  5306. FileOutputStream* logStream;
  5307. void trimFileSize (int maxFileSizeBytes) const;
  5308. FileLogger (const FileLogger&);
  5309. const FileLogger& operator= (const FileLogger&);
  5310. };
  5311. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5312. /********* End of inlined file: juce_FileLogger.h *********/
  5313. #endif
  5314. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5315. /********* Start of inlined file: juce_Initialisation.h *********/
  5316. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5317. #define __JUCE_INITIALISATION_JUCEHEADER__
  5318. /** Initialises Juce's GUI classes.
  5319. If you're embedding Juce into an application that uses its own event-loop rather
  5320. than using the START_JUCE_APPLICATION macro, call this function before making any
  5321. Juce calls, to make sure things are initialised correctly.
  5322. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5323. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5324. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5325. */
  5326. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5327. /** Clears up any static data being used by Juce's GUI classes.
  5328. If you're embedding Juce into an application that uses its own event-loop rather
  5329. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5330. code to clean up any juce objects that might be lying around.
  5331. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5332. */
  5333. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5334. /** Initialises the core parts of Juce.
  5335. If you're embedding Juce into either a command-line program, call this function
  5336. at the start of your main() function to make sure that Juce is initialised correctly.
  5337. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5338. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5339. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5340. */
  5341. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5342. /** Clears up any static data being used by Juce's non-gui core classes.
  5343. If you're embedding Juce into either a command-line program, call this function
  5344. at the end of your main() function if you want to make sure any Juce objects are
  5345. cleaned up correctly.
  5346. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5347. */
  5348. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5349. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5350. /********* End of inlined file: juce_Initialisation.h *********/
  5351. #endif
  5352. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5353. #endif
  5354. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  5355. #endif
  5356. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5357. #endif
  5358. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5359. #endif
  5360. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5361. /********* Start of inlined file: juce_Random.h *********/
  5362. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5363. #define __JUCE_RANDOM_JUCEHEADER__
  5364. /********* Start of inlined file: juce_BitArray.h *********/
  5365. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5366. #define __JUCE_BITARRAY_JUCEHEADER__
  5367. class MemoryBlock;
  5368. /**
  5369. An array of on/off bits, also usable to store large binary integers.
  5370. A BitArray acts like an arbitrarily large integer whose bits can be set or
  5371. cleared, and some basic mathematical operations can be done on the number as
  5372. a whole.
  5373. */
  5374. class JUCE_API BitArray
  5375. {
  5376. public:
  5377. /** Creates an empty BitArray */
  5378. BitArray() throw();
  5379. /** Creates a BitArray containing an integer value in its low bits.
  5380. The low 32 bits of the array are initialised with this value.
  5381. */
  5382. BitArray (const unsigned int value) throw();
  5383. /** Creates a BitArray containing an integer value in its low bits.
  5384. The low 32 bits of the array are initialised with the absolute value
  5385. passed in, and its sign is set to reflect the sign of the number.
  5386. */
  5387. BitArray (const int value) throw();
  5388. /** Creates a BitArray containing an integer value in its low bits.
  5389. The low 64 bits of the array are initialised with the absolute value
  5390. passed in, and its sign is set to reflect the sign of the number.
  5391. */
  5392. BitArray (int64 value) throw();
  5393. /** Creates a copy of another BitArray. */
  5394. BitArray (const BitArray& other) throw();
  5395. /** Destructor. */
  5396. ~BitArray() throw();
  5397. /** Copies another BitArray onto this one. */
  5398. const BitArray& operator= (const BitArray& other) throw();
  5399. /** Two arrays are the same if the same bits are set. */
  5400. bool operator== (const BitArray& other) const throw();
  5401. /** Two arrays are the same if the same bits are set. */
  5402. bool operator!= (const BitArray& other) const throw();
  5403. /** Clears all bits in the BitArray to 0. */
  5404. void clear() throw();
  5405. /** Clears a particular bit in the array. */
  5406. void clearBit (const int bitNumber) throw();
  5407. /** Sets a specified bit to 1.
  5408. If the bit number is high, this will grow the array to accomodate it.
  5409. */
  5410. void setBit (const int bitNumber) throw();
  5411. /** Sets or clears a specified bit. */
  5412. void setBit (const int bitNumber,
  5413. const bool shouldBeSet) throw();
  5414. /** Sets a range of bits to be either on or off.
  5415. @param startBit the first bit to change
  5416. @param numBits the number of bits to change
  5417. @param shouldBeSet whether to turn these bits on or off
  5418. */
  5419. void setRange (int startBit,
  5420. int numBits,
  5421. const bool shouldBeSet) throw();
  5422. /** Inserts a bit an a given position, shifting up any bits above it. */
  5423. void insertBit (const int bitNumber,
  5424. const bool shouldBeSet) throw();
  5425. /** Returns the value of a specified bit in the array.
  5426. If the index is out-of-range, the result will be false.
  5427. */
  5428. bool operator[] (const int bit) const throw();
  5429. /** Returns true if no bits are set. */
  5430. bool isEmpty() const throw();
  5431. /** Returns a range of bits in the array as an integer value.
  5432. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  5433. Asking for more than 32 bits isn't allowed (obviously).
  5434. */
  5435. int getBitRangeAsInt (int startBit, int numBits) const throw();
  5436. /** Sets a range of bits in the array based on an integer value.
  5437. Copies the given integer into the array, starting at startBit,
  5438. and only using up to numBits of the available bits.
  5439. */
  5440. void setBitRangeAsInt (int startBit, int numBits,
  5441. unsigned int valueToSet) throw();
  5442. /** Performs a bitwise OR with another BitArray.
  5443. The result ends up in this array.
  5444. */
  5445. void orWith (const BitArray& other) throw();
  5446. /** Performs a bitwise AND with another BitArray.
  5447. The result ends up in this array.
  5448. */
  5449. void andWith (const BitArray& other) throw();
  5450. /** Performs a bitwise XOR with another BitArray.
  5451. The result ends up in this array.
  5452. */
  5453. void xorWith (const BitArray& other) throw();
  5454. /** Adds another BitArray's value to this one.
  5455. Treating the two arrays as large positive integers, this
  5456. adds them up and puts the result in this array.
  5457. */
  5458. void add (const BitArray& other) throw();
  5459. /** Subtracts another BitArray's value from this one.
  5460. Treating the two arrays as large positive integers, this
  5461. subtracts them and puts the result in this array.
  5462. Note that if the result should be negative, this won't be
  5463. handled correctly.
  5464. */
  5465. void subtract (const BitArray& other) throw();
  5466. /** Multiplies another BitArray's value with this one.
  5467. Treating the two arrays as large positive integers, this
  5468. multiplies them and puts the result in this array.
  5469. */
  5470. void multiplyBy (const BitArray& other) throw();
  5471. /** Divides another BitArray's value into this one and also produces a remainder.
  5472. Treating the two arrays as large positive integers, this
  5473. divides this value by the other, leaving the quotient in this
  5474. array, and the remainder is copied into the other BitArray passed in.
  5475. */
  5476. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  5477. /** Returns the largest value that will divide both this value and the one
  5478. passed-in.
  5479. */
  5480. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  5481. /** Performs a modulo operation on this value.
  5482. The result is stored in this value.
  5483. */
  5484. void modulo (const BitArray& divisor) throw();
  5485. /** Performs a combined exponent and modulo operation.
  5486. This BitArray's value becomes (this ^ exponent) % modulus.
  5487. */
  5488. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  5489. /** Performs an inverse modulo on the value.
  5490. i.e. the result is (this ^ -1) mod (modulus).
  5491. */
  5492. void inverseModulo (const BitArray& modulus) throw();
  5493. /** Shifts a section of bits left or right.
  5494. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  5495. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  5496. */
  5497. void shiftBits (int howManyBitsLeft,
  5498. int startBit = 0) throw();
  5499. /** Does a signed comparison of two BitArrays.
  5500. Return values are:
  5501. - 0 if the numbers are the same
  5502. - < 0 if this number is smaller than the other
  5503. - > 0 if this number is bigger than the other
  5504. */
  5505. int compare (const BitArray& other) const throw();
  5506. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  5507. Return values are:
  5508. - 0 if the numbers are the same
  5509. - < 0 if this number is smaller than the other
  5510. - > 0 if this number is bigger than the other
  5511. */
  5512. int compareAbsolute (const BitArray& other) const throw();
  5513. /** Returns true if the value is less than zero.
  5514. @see setNegative, negate
  5515. */
  5516. bool isNegative() const throw();
  5517. /** Changes the sign of the number to be positive or negative.
  5518. @see isNegative, negate
  5519. */
  5520. void setNegative (const bool shouldBeNegative) throw();
  5521. /** Inverts the sign of the number.
  5522. @see isNegative, setNegative
  5523. */
  5524. void negate() throw();
  5525. /** Counts the total number of set bits in the array. */
  5526. int countNumberOfSetBits() const throw();
  5527. /** Looks for the index of the next set bit after a given starting point.
  5528. searches from startIndex (inclusive) upwards for the first set bit,
  5529. and returns its index.
  5530. If no set bits are found, it returns -1.
  5531. */
  5532. int findNextSetBit (int startIndex = 0) const throw();
  5533. /** Looks for the index of the next clear bit after a given starting point.
  5534. searches from startIndex (inclusive) upwards for the first clear bit,
  5535. and returns its index.
  5536. */
  5537. int findNextClearBit (int startIndex = 0) const throw();
  5538. /** Returns the index of the highest set bit in the array.
  5539. If the array is empty, this will return -1.
  5540. */
  5541. int getHighestBit() const throw();
  5542. /** Converts the array to a number string.
  5543. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5544. */
  5545. const String toString (const int base) const throw();
  5546. /** Converts a number string to an array.
  5547. Any non-valid characters will be ignored.
  5548. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5549. */
  5550. void parseString (const String& text,
  5551. const int base) throw();
  5552. /** Turns the array into a block of binary data.
  5553. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5554. of the array, and so on.
  5555. @see loadFromMemoryBlock
  5556. */
  5557. const MemoryBlock toMemoryBlock() const throw();
  5558. /** Copies a block of raw data onto this array.
  5559. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5560. of the array, and so on.
  5561. @see toMemoryBlock
  5562. */
  5563. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  5564. juce_UseDebuggingNewOperator
  5565. private:
  5566. void ensureSize (const int numVals) throw();
  5567. unsigned int* values;
  5568. int numValues, highestBit;
  5569. bool negative;
  5570. };
  5571. #endif // __JUCE_BITARRAY_JUCEHEADER__
  5572. /********* End of inlined file: juce_BitArray.h *********/
  5573. /**
  5574. A simple pseudo-random number generator.
  5575. */
  5576. class JUCE_API Random
  5577. {
  5578. public:
  5579. /** Creates a Random object based on a seed value.
  5580. For a given seed value, the subsequent numbers generated by this object
  5581. will be predictable, so a good idea is to set this value based
  5582. on the time, e.g.
  5583. new Random (Time::currentTimeMillis())
  5584. */
  5585. Random (const int64 seedValue) throw();
  5586. /** Destructor. */
  5587. ~Random() throw();
  5588. /** Returns the next random 32 bit integer.
  5589. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5590. */
  5591. int nextInt() throw();
  5592. /** Returns the next random number, limited to a given range.
  5593. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5594. */
  5595. int nextInt (const int maxValue) throw();
  5596. /** Returns the next 64-bit random number.
  5597. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5598. */
  5599. int64 nextInt64() throw();
  5600. /** Returns the next random floating-point number.
  5601. @returns a random value in the range 0 to 1.0
  5602. */
  5603. float nextFloat() throw();
  5604. /** Returns the next random floating-point number.
  5605. @returns a random value in the range 0 to 1.0
  5606. */
  5607. double nextDouble() throw();
  5608. /** Returns the next random boolean value.
  5609. */
  5610. bool nextBool() throw();
  5611. /** Returns a BitArray containing a random number.
  5612. @returns a random value in the range 0 to (maximumValue - 1).
  5613. */
  5614. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  5615. /** Sets a range of bits in a BitArray to random values. */
  5616. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  5617. /** To avoid the overhead of having to create a new Random object whenever
  5618. you need a number, this is a shared application-wide object that
  5619. can be used.
  5620. It's not thread-safe though, so threads should use their own Random object.
  5621. */
  5622. static Random& getSystemRandom() throw();
  5623. /** Resets this Random object to a given seed value. */
  5624. void setSeed (const int64 newSeed) throw();
  5625. /** Reseeds this generator using a value generated from various semi-random system
  5626. properties like the current time, etc.
  5627. Because this function convolves the time with the last seed value, calling
  5628. it repeatedly will increase the randomness of the final result.
  5629. */
  5630. void setSeedRandomly();
  5631. juce_UseDebuggingNewOperator
  5632. private:
  5633. int64 seed;
  5634. };
  5635. #endif // __JUCE_RANDOM_JUCEHEADER__
  5636. /********* End of inlined file: juce_Random.h *********/
  5637. #endif
  5638. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5639. #endif
  5640. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5641. /********* Start of inlined file: juce_Singleton.h *********/
  5642. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5643. #define __JUCE_SINGLETON_JUCEHEADER__
  5644. /********* Start of inlined file: juce_ScopedLock.h *********/
  5645. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5646. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5647. /**
  5648. Automatically locks and unlocks a CriticalSection object.
  5649. Use one of these as a local variable to control access to a CriticalSection.
  5650. e.g. @code
  5651. CriticalSection myCriticalSection;
  5652. for (;;)
  5653. {
  5654. const ScopedLock myScopedLock (myCriticalSection);
  5655. // myCriticalSection is now locked
  5656. ...do some stuff...
  5657. // myCriticalSection gets unlocked here.
  5658. }
  5659. @endcode
  5660. @see CriticalSection, ScopedUnlock
  5661. */
  5662. class JUCE_API ScopedLock
  5663. {
  5664. public:
  5665. /** Creates a ScopedLock.
  5666. As soon as it is created, this will lock the CriticalSection, and
  5667. when the ScopedLock object is deleted, the CriticalSection will
  5668. be unlocked.
  5669. Make sure this object is created and deleted by the same thread,
  5670. otherwise there are no guarantees what will happen! Best just to use it
  5671. as a local stack object, rather than creating one with the new() operator.
  5672. */
  5673. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5674. /** Destructor.
  5675. The CriticalSection will be unlocked when the destructor is called.
  5676. Make sure this object is created and deleted by the same thread,
  5677. otherwise there are no guarantees what will happen!
  5678. */
  5679. inline ~ScopedLock() throw() { lock_.exit(); }
  5680. private:
  5681. const CriticalSection& lock_;
  5682. ScopedLock (const ScopedLock&);
  5683. const ScopedLock& operator= (const ScopedLock&);
  5684. };
  5685. /**
  5686. Automatically unlocks and re-locks a CriticalSection object.
  5687. This is the reverse of a ScopedLock object - instead of locking the critical
  5688. section for the lifetime of this object, it unlocks it.
  5689. Make sure you don't try to unlock critical sections that aren't actually locked!
  5690. e.g. @code
  5691. CriticalSection myCriticalSection;
  5692. for (;;)
  5693. {
  5694. const ScopedLock myScopedLock (myCriticalSection);
  5695. // myCriticalSection is now locked
  5696. ... do some stuff with it locked ..
  5697. while (xyz)
  5698. {
  5699. ... do some stuff with it locked ..
  5700. const ScopedUnlock unlocker (myCriticalSection);
  5701. // myCriticalSection is now unlocked for the remainder of this block,
  5702. // and re-locked at the end.
  5703. ...do some stuff with it unlocked ...
  5704. }
  5705. // myCriticalSection gets unlocked here.
  5706. }
  5707. @endcode
  5708. @see CriticalSection, ScopedLock
  5709. */
  5710. class ScopedUnlock
  5711. {
  5712. public:
  5713. /** Creates a ScopedUnlock.
  5714. As soon as it is created, this will unlock the CriticalSection, and
  5715. when the ScopedLock object is deleted, the CriticalSection will
  5716. be re-locked.
  5717. Make sure this object is created and deleted by the same thread,
  5718. otherwise there are no guarantees what will happen! Best just to use it
  5719. as a local stack object, rather than creating one with the new() operator.
  5720. */
  5721. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5722. /** Destructor.
  5723. The CriticalSection will be unlocked when the destructor is called.
  5724. Make sure this object is created and deleted by the same thread,
  5725. otherwise there are no guarantees what will happen!
  5726. */
  5727. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5728. private:
  5729. const CriticalSection& lock_;
  5730. ScopedUnlock (const ScopedLock&);
  5731. const ScopedUnlock& operator= (const ScopedUnlock&);
  5732. };
  5733. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5734. /********* End of inlined file: juce_ScopedLock.h *********/
  5735. /**
  5736. Macro to declare member variables and methods for a singleton class.
  5737. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  5738. to the class's definition.
  5739. If allowOnlyOneInstance == true, it won't allow the object to be created
  5740. more than once in the process's lifetime.
  5741. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5742. implementation code.
  5743. Clients can then call the static MyClass::getInstance() to get a pointer to the
  5744. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  5745. is currently extant
  5746. it's a very good idea to also add the call clearSingletonInstance() to the
  5747. destructor of the class, in case it is deleted by other means than deleteInstance()
  5748. e.g. @code
  5749. class MySingleton
  5750. {
  5751. public:
  5752. MySingleton()
  5753. {
  5754. }
  5755. ~MySingleton()
  5756. {
  5757. // this ensures that no dangling pointers are left when the
  5758. // singleton is deleted.
  5759. clearSingletonInstance();
  5760. }
  5761. juce_DeclareSingleton (MySingleton, false)
  5762. };
  5763. juce_ImplementSingleton (MySingleton)
  5764. // example of usage:
  5765. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5766. ...
  5767. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5768. @endcode
  5769. If you know that your object will only be created and deleted by a single thread, you
  5770. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5771. of this one.
  5772. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5773. */
  5774. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  5775. \
  5776. static classname* _singletonInstance; \
  5777. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5778. \
  5779. static classname* getInstance() \
  5780. { \
  5781. if (_singletonInstance == 0) \
  5782. {\
  5783. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5784. \
  5785. if (_singletonInstance == 0) \
  5786. { \
  5787. static bool alreadyInside = false; \
  5788. static bool createdOnceAlready = false; \
  5789. \
  5790. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5791. jassert (! problem); \
  5792. if (! problem) \
  5793. { \
  5794. createdOnceAlready = true; \
  5795. alreadyInside = true; \
  5796. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5797. alreadyInside = false; \
  5798. \
  5799. _singletonInstance = newObject; \
  5800. } \
  5801. } \
  5802. } \
  5803. \
  5804. return _singletonInstance; \
  5805. } \
  5806. \
  5807. static inline classname* getInstanceWithoutCreating() throw() \
  5808. { \
  5809. return _singletonInstance; \
  5810. } \
  5811. \
  5812. static void deleteInstance() \
  5813. { \
  5814. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5815. if (_singletonInstance != 0) \
  5816. { \
  5817. classname* const old = _singletonInstance; \
  5818. _singletonInstance = 0; \
  5819. delete old; \
  5820. } \
  5821. } \
  5822. \
  5823. void clearSingletonInstance() throw() \
  5824. { \
  5825. if (_singletonInstance == this) \
  5826. _singletonInstance = 0; \
  5827. }
  5828. /** This is a counterpart to the juce_DeclareSingleton macro.
  5829. After adding the juce_DeclareSingleton to the class definition, this macro has
  5830. to be used in the cpp file.
  5831. */
  5832. #define juce_ImplementSingleton(classname) \
  5833. \
  5834. classname* classname::_singletonInstance = 0; \
  5835. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5836. /**
  5837. Macro to declare member variables and methods for a singleton class.
  5838. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5839. section to make access to it thread-safe. If you know that your object will
  5840. only ever be created or deleted by a single thread, then this is a
  5841. more efficient version to use.
  5842. See the documentation for juce_DeclareSingleton for more information about
  5843. how to use it, the only difference being that you have to use
  5844. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5845. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5846. */
  5847. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  5848. \
  5849. static classname* _singletonInstance; \
  5850. \
  5851. static classname* getInstance() \
  5852. { \
  5853. if (_singletonInstance == 0) \
  5854. { \
  5855. static bool alreadyInside = false; \
  5856. static bool createdOnceAlready = false; \
  5857. \
  5858. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5859. jassert (! problem); \
  5860. if (! problem) \
  5861. { \
  5862. createdOnceAlready = true; \
  5863. alreadyInside = true; \
  5864. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5865. alreadyInside = false; \
  5866. \
  5867. _singletonInstance = newObject; \
  5868. } \
  5869. } \
  5870. \
  5871. return _singletonInstance; \
  5872. } \
  5873. \
  5874. static inline classname* getInstanceWithoutCreating() throw() \
  5875. { \
  5876. return _singletonInstance; \
  5877. } \
  5878. \
  5879. static void deleteInstance() \
  5880. { \
  5881. if (_singletonInstance != 0) \
  5882. { \
  5883. classname* const old = _singletonInstance; \
  5884. _singletonInstance = 0; \
  5885. delete old; \
  5886. } \
  5887. } \
  5888. \
  5889. void clearSingletonInstance() throw() \
  5890. { \
  5891. if (_singletonInstance == this) \
  5892. _singletonInstance = 0; \
  5893. }
  5894. /**
  5895. Macro to declare member variables and methods for a singleton class.
  5896. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5897. for recursion or repeated instantiation. It's intended for use as a lightweight
  5898. version of a singleton, where you're using it in very straightforward
  5899. circumstances and don't need the extra checking.
  5900. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  5901. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  5902. See the documentation for juce_DeclareSingleton for more information about
  5903. how to use it, the only difference being that you have to use
  5904. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5905. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  5906. */
  5907. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  5908. \
  5909. static classname* _singletonInstance; \
  5910. \
  5911. static classname* getInstance() \
  5912. { \
  5913. if (_singletonInstance == 0) \
  5914. _singletonInstance = new classname(); \
  5915. \
  5916. return _singletonInstance; \
  5917. } \
  5918. \
  5919. static inline classname* getInstanceWithoutCreating() throw() \
  5920. { \
  5921. return _singletonInstance; \
  5922. } \
  5923. \
  5924. static void deleteInstance() \
  5925. { \
  5926. if (_singletonInstance != 0) \
  5927. { \
  5928. classname* const old = _singletonInstance; \
  5929. _singletonInstance = 0; \
  5930. delete old; \
  5931. } \
  5932. } \
  5933. \
  5934. void clearSingletonInstance() throw() \
  5935. { \
  5936. if (_singletonInstance == this) \
  5937. _singletonInstance = 0; \
  5938. }
  5939. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  5940. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  5941. to the class definition, this macro has to be used somewhere in the cpp file.
  5942. */
  5943. #define juce_ImplementSingleton_SingleThreaded(classname) \
  5944. \
  5945. classname* classname::_singletonInstance = 0;
  5946. #endif // __JUCE_SINGLETON_JUCEHEADER__
  5947. /********* End of inlined file: juce_Singleton.h *********/
  5948. #endif
  5949. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  5950. #endif
  5951. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5952. /********* Start of inlined file: juce_SystemStats.h *********/
  5953. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5954. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  5955. /**
  5956. Contains methods for finding out about the current hardware and OS configuration.
  5957. */
  5958. class JUCE_API SystemStats
  5959. {
  5960. public:
  5961. /** Returns the current version of JUCE,
  5962. (just in case you didn't already know at compile-time.)
  5963. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  5964. */
  5965. static const String getJUCEVersion() throw();
  5966. /** The set of possible results of the getOperatingSystemType() method.
  5967. */
  5968. enum OperatingSystemType
  5969. {
  5970. UnknownOS = 0,
  5971. MacOSX = 0x1000,
  5972. Linux = 0x2000,
  5973. Win95 = 0x4001,
  5974. Win98 = 0x4002,
  5975. WinNT351 = 0x4103,
  5976. WinNT40 = 0x4104,
  5977. Win2000 = 0x4105,
  5978. WinXP = 0x4106,
  5979. WinVista = 0x4107,
  5980. Windows = 0x4000, /**< To test whether any version of Windows is running,
  5981. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  5982. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  5983. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  5984. };
  5985. /** Returns the type of operating system we're running on.
  5986. @returns one of the values from the OperatingSystemType enum.
  5987. @see getOperatingSystemName
  5988. */
  5989. static OperatingSystemType getOperatingSystemType() throw();
  5990. /** Returns the name of the type of operating system we're running on.
  5991. @returns a string describing the OS type.
  5992. @see getOperatingSystemType
  5993. */
  5994. static const String getOperatingSystemName() throw();
  5995. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  5996. */
  5997. static bool isOperatingSystem64Bit() throw();
  5998. // CPU and memory information..
  5999. /** Returns the approximate CPU speed.
  6000. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6001. what year you're reading this...)
  6002. */
  6003. static int getCpuSpeedInMegaherz() throw();
  6004. /** Returns a string to indicate the CPU vendor.
  6005. Might not be known on some systems.
  6006. */
  6007. static const String getCpuVendor() throw();
  6008. /** Checks whether Intel MMX instructions are available. */
  6009. static bool hasMMX() throw();
  6010. /** Checks whether Intel SSE instructions are available. */
  6011. static bool hasSSE() throw();
  6012. /** Checks whether Intel SSE2 instructions are available. */
  6013. static bool hasSSE2() throw();
  6014. /** Checks whether AMD 3DNOW instructions are available. */
  6015. static bool has3DNow() throw();
  6016. /** Returns the number of CPUs.
  6017. */
  6018. static int getNumCpus() throw();
  6019. /** Returns a clock-cycle tick counter, if available.
  6020. If the machine can do it, this will return a tick-count
  6021. where each tick is one cpu clock cycle - used for profiling
  6022. code.
  6023. @returns the tick count, or zero if not available.
  6024. */
  6025. static int64 getClockCycleCounter() throw();
  6026. /** Finds out how much RAM is in the machine.
  6027. @returns the approximate number of megabytes of memory, or zero if
  6028. something goes wrong when finding out.
  6029. */
  6030. static int getMemorySizeInMegabytes() throw();
  6031. /** Returns the system page-size.
  6032. This is only used by programmers with beards.
  6033. */
  6034. static int getPageSize() throw();
  6035. /** Returns a list of MAC addresses found on this machine.
  6036. @param addresses an array into which the MAC addresses should be copied
  6037. @param maxNum the number of elements in this array
  6038. @param littleEndian the endianness of the numbers to return. Note that
  6039. the default values of this parameter are different on
  6040. Mac/PC to avoid breaking old software that was written
  6041. before this parameter was added (when the two systems
  6042. defaulted to using different endiannesses). In newer
  6043. software you probably want to specify an explicit value
  6044. for this.
  6045. @returns the number of MAC addresses that were found
  6046. */
  6047. static int getMACAddresses (int64* addresses, int maxNum,
  6048. #if JUCE_MAC
  6049. const bool littleEndian = true) throw();
  6050. #else
  6051. const bool littleEndian = false) throw();
  6052. #endif
  6053. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6054. static void initialiseStats() throw();
  6055. };
  6056. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6057. /********* End of inlined file: juce_SystemStats.h *********/
  6058. #endif
  6059. #ifndef __JUCE_TIME_JUCEHEADER__
  6060. #endif
  6061. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6062. #endif
  6063. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6064. #endif
  6065. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6066. #endif
  6067. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6068. #endif
  6069. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6070. #endif
  6071. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6072. #endif
  6073. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6074. /********* Start of inlined file: juce_PropertySet.h *********/
  6075. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6076. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6077. /********* Start of inlined file: juce_StringPairArray.h *********/
  6078. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6079. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6080. /**
  6081. A container for holding a set of strings which are keyed by another string.
  6082. @see StringArray
  6083. */
  6084. class JUCE_API StringPairArray
  6085. {
  6086. public:
  6087. /** Creates an empty array */
  6088. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6089. /** Creates a copy of another array */
  6090. StringPairArray (const StringPairArray& other) throw();
  6091. /** Destructor. */
  6092. ~StringPairArray() throw();
  6093. /** Copies the contents of another string array into this one */
  6094. const StringPairArray& operator= (const StringPairArray& other) throw();
  6095. /** Compares two arrays.
  6096. Comparisons are case-sensitive.
  6097. @returns true only if the other array contains exactly the same strings with the same keys
  6098. */
  6099. bool operator== (const StringPairArray& other) const throw();
  6100. /** Compares two arrays.
  6101. Comparisons are case-sensitive.
  6102. @returns false if the other array contains exactly the same strings with the same keys
  6103. */
  6104. bool operator!= (const StringPairArray& other) const throw();
  6105. /** Finds the value corresponding to a key string.
  6106. If no such key is found, this will just return an empty string. To check whether
  6107. a given key actually exists (because it might actually be paired with an empty string), use
  6108. the getAllKeys() method to obtain a list.
  6109. Obviously the reference returned shouldn't be stored for later use, as the
  6110. string it refers to may disappear when the array changes.
  6111. @see getValue
  6112. */
  6113. const String& operator[] (const String& key) const throw();
  6114. /** Finds the value corresponding to a key string.
  6115. If no such key is found, this will just return the value provided as a default.
  6116. @see operator[]
  6117. */
  6118. const String getValue (const String& key, const String& defaultReturnValue) const;
  6119. /** Returns a list of all keys in the array. */
  6120. const StringArray& getAllKeys() const throw() { return keys; }
  6121. /** Returns a list of all values in the array. */
  6122. const StringArray& getAllValues() const throw() { return values; }
  6123. /** Returns the number of strings in the array */
  6124. inline int size() const throw() { return keys.size(); };
  6125. /** Adds or amends a key/value pair.
  6126. If a value already exists with this key, its value will be overwritten,
  6127. otherwise the key/value pair will be added to the array.
  6128. */
  6129. void set (const String& key,
  6130. const String& value) throw();
  6131. /** Adds the items from another array to this one.
  6132. This is equivalent to using set() to add each of the pairs from the other array.
  6133. */
  6134. void addArray (const StringPairArray& other);
  6135. /** Removes all elements from the array. */
  6136. void clear() throw();
  6137. /** Removes a string from the array based on its key.
  6138. If the key isn't found, nothing will happen.
  6139. */
  6140. void remove (const String& key) throw();
  6141. /** Removes a string from the array based on its index.
  6142. If the index is out-of-range, no action will be taken.
  6143. */
  6144. void remove (const int index) throw();
  6145. /** Reduces the amount of storage being used by the array.
  6146. Arrays typically allocate slightly more storage than they need, and after
  6147. removing elements, they may have quite a lot of unused space allocated.
  6148. This method will reduce the amount of allocated storage to a minimum.
  6149. */
  6150. void minimiseStorageOverheads() throw();
  6151. juce_UseDebuggingNewOperator
  6152. private:
  6153. StringArray keys, values;
  6154. bool ignoreCase;
  6155. };
  6156. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6157. /********* End of inlined file: juce_StringPairArray.h *********/
  6158. /********* Start of inlined file: juce_XmlElement.h *********/
  6159. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6160. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6161. /********* Start of inlined file: juce_OutputStream.h *********/
  6162. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6163. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6164. /********* Start of inlined file: juce_InputStream.h *********/
  6165. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6166. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6167. /** The base class for streams that read data.
  6168. Input and output streams are used throughout the library - subclasses can override
  6169. some or all of the virtual functions to implement their behaviour.
  6170. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6171. */
  6172. class JUCE_API InputStream
  6173. {
  6174. public:
  6175. /** Destructor. */
  6176. virtual ~InputStream() {}
  6177. /** Returns the total number of bytes available for reading in this stream.
  6178. Note that this is the number of bytes available from the start of the
  6179. stream, not from the current position.
  6180. If the size of the stream isn't actually known, this may return -1.
  6181. */
  6182. virtual int64 getTotalLength() = 0;
  6183. /** Returns true if the stream has no more data to read. */
  6184. virtual bool isExhausted() = 0;
  6185. /** Reads a set of bytes from the stream into a memory buffer.
  6186. This is the only read method that subclasses actually need to implement, as the
  6187. InputStream base class implements the other read methods in terms of this one (although
  6188. it's often more efficient for subclasses to implement them directly).
  6189. @param destBuffer the destination buffer for the data
  6190. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6191. memory block passed in is big enough to contain this
  6192. many bytes.
  6193. @returns the actual number of bytes that were read, which may be less than
  6194. maxBytesToRead if the stream is exhausted before it gets that far
  6195. */
  6196. virtual int read (void* destBuffer,
  6197. int maxBytesToRead) = 0;
  6198. /** Reads a byte from the stream.
  6199. If the stream is exhausted, this will return zero.
  6200. @see OutputStream::writeByte
  6201. */
  6202. virtual char readByte();
  6203. /** Reads a boolean from the stream.
  6204. The bool is encoded as a single byte - 1 for true, 0 for false.
  6205. If the stream is exhausted, this will return false.
  6206. @see OutputStream::writeBool
  6207. */
  6208. virtual bool readBool();
  6209. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6210. If the next two bytes read are byte1 and byte2, this returns
  6211. (byte1 | (byte2 << 8)).
  6212. If the stream is exhausted partway through reading the bytes, this will return zero.
  6213. @see OutputStream::writeShort, readShortBigEndian
  6214. */
  6215. virtual short readShort();
  6216. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6217. If the next two bytes read are byte1 and byte2, this returns
  6218. (byte2 | (byte1 << 8)).
  6219. If the stream is exhausted partway through reading the bytes, this will return zero.
  6220. @see OutputStream::writeShortBigEndian, readShort
  6221. */
  6222. virtual short readShortBigEndian();
  6223. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6224. If the next four bytes are byte1 to byte4, this returns
  6225. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6226. If the stream is exhausted partway through reading the bytes, this will return zero.
  6227. @see OutputStream::writeInt, readIntBigEndian
  6228. */
  6229. virtual int readInt();
  6230. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6231. If the next four bytes are byte1 to byte4, this returns
  6232. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6233. If the stream is exhausted partway through reading the bytes, this will return zero.
  6234. @see OutputStream::writeIntBigEndian, readInt
  6235. */
  6236. virtual int readIntBigEndian();
  6237. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6238. If the next eight bytes are byte1 to byte8, this returns
  6239. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6240. If the stream is exhausted partway through reading the bytes, this will return zero.
  6241. @see OutputStream::writeInt64, readInt64BigEndian
  6242. */
  6243. virtual int64 readInt64();
  6244. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6245. If the next eight bytes are byte1 to byte8, this returns
  6246. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6247. If the stream is exhausted partway through reading the bytes, this will return zero.
  6248. @see OutputStream::writeInt64BigEndian, readInt64
  6249. */
  6250. virtual int64 readInt64BigEndian();
  6251. /** Reads four bytes as a 32-bit floating point value.
  6252. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6253. If the stream is exhausted partway through reading the bytes, this will return zero.
  6254. @see OutputStream::writeFloat, readDouble
  6255. */
  6256. virtual float readFloat();
  6257. /** Reads four bytes as a 32-bit floating point value.
  6258. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6259. If the stream is exhausted partway through reading the bytes, this will return zero.
  6260. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6261. */
  6262. virtual float readFloatBigEndian();
  6263. /** Reads eight bytes as a 64-bit floating point value.
  6264. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6265. If the stream is exhausted partway through reading the bytes, this will return zero.
  6266. @see OutputStream::writeDouble, readFloat
  6267. */
  6268. virtual double readDouble();
  6269. /** Reads eight bytes as a 64-bit floating point value.
  6270. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6271. If the stream is exhausted partway through reading the bytes, this will return zero.
  6272. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6273. */
  6274. virtual double readDoubleBigEndian();
  6275. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6276. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6277. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6278. @see OutputStream::writeCompressedInt()
  6279. */
  6280. virtual int readCompressedInt();
  6281. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6282. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6283. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6284. After this call, the stream's position will be left pointing to the character
  6285. following the line-feed, but the linefeeds aren't included in the string that
  6286. is returned.
  6287. */
  6288. virtual const String readNextLine();
  6289. /** Reads a zero-terminated string from the stream.
  6290. This will read characters from the stream until it hits a zero character or
  6291. end-of-stream.
  6292. @see OutputStream::writeString, readEntireStreamAsString
  6293. */
  6294. virtual const String readString();
  6295. /** Tries to read the whole stream and turn it into a string.
  6296. This will read from the stream's current position until the end-of-stream, and
  6297. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6298. */
  6299. virtual const String readEntireStreamAsString();
  6300. /** Reads from the stream and appends the data to a MemoryBlock.
  6301. @param destBlock the block to append the data onto
  6302. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6303. of bytes that will be read - if it's negative, data
  6304. will be read until the stream is exhausted.
  6305. @returns the number of bytes that were added to the memory block
  6306. */
  6307. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6308. int maxNumBytesToRead = -1);
  6309. /** Returns the offset of the next byte that will be read from the stream.
  6310. @see setPosition
  6311. */
  6312. virtual int64 getPosition() = 0;
  6313. /** Tries to move the current read position of the stream.
  6314. The position is an absolute number of bytes from the stream's start.
  6315. Some streams might not be able to do this, in which case they should do
  6316. nothing and return false. Others might be able to manage it by resetting
  6317. themselves and skipping to the correct position, although this is
  6318. obviously a bit slow.
  6319. @returns true if the stream manages to reposition itself correctly
  6320. @see getPosition
  6321. */
  6322. virtual bool setPosition (int64 newPosition) = 0;
  6323. /** Reads and discards a number of bytes from the stream.
  6324. Some input streams might implement this efficiently, but the base
  6325. class will just keep reading data until the requisite number of bytes
  6326. have been done.
  6327. */
  6328. virtual void skipNextBytes (int64 numBytesToSkip);
  6329. juce_UseDebuggingNewOperator
  6330. protected:
  6331. InputStream() throw() {}
  6332. };
  6333. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6334. /********* End of inlined file: juce_InputStream.h *********/
  6335. /**
  6336. The base class for streams that write data to some kind of destination.
  6337. Input and output streams are used throughout the library - subclasses can override
  6338. some or all of the virtual functions to implement their behaviour.
  6339. @see InputStream, MemoryOutputStream, FileOutputStream
  6340. */
  6341. class JUCE_API OutputStream
  6342. {
  6343. public:
  6344. /** Destructor.
  6345. Some subclasses might want to do things like call flush() during their
  6346. destructors.
  6347. */
  6348. virtual ~OutputStream();
  6349. /** If the stream is using a buffer, this will ensure it gets written
  6350. out to the destination. */
  6351. virtual void flush() = 0;
  6352. /** Tries to move the stream's output position.
  6353. Not all streams will be able to seek to a new position - this will return
  6354. false if it fails to work.
  6355. @see getPosition
  6356. */
  6357. virtual bool setPosition (int64 newPosition) = 0;
  6358. /** Returns the stream's current position.
  6359. @see setPosition
  6360. */
  6361. virtual int64 getPosition() = 0;
  6362. /** Writes a block of data to the stream.
  6363. When creating a subclass of OutputStream, this is the only write method
  6364. that needs to be overloaded - the base class has methods for writing other
  6365. types of data which use this to do the work.
  6366. @returns false if the write operation fails for some reason
  6367. */
  6368. virtual bool write (const void* dataToWrite,
  6369. int howManyBytes) = 0;
  6370. /** Writes a single byte to the stream.
  6371. @see InputStream::readByte
  6372. */
  6373. virtual void writeByte (char byte);
  6374. /** Writes a boolean to the stream.
  6375. This is encoded as a byte - either 1 or 0.
  6376. @see InputStream::readBool
  6377. */
  6378. virtual void writeBool (bool boolValue);
  6379. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6380. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6381. @see InputStream::readShort
  6382. */
  6383. virtual void writeShort (short value);
  6384. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6385. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6386. @see InputStream::readShortBigEndian
  6387. */
  6388. virtual void writeShortBigEndian (short value);
  6389. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6390. @see InputStream::readInt
  6391. */
  6392. virtual void writeInt (int value);
  6393. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6394. @see InputStream::readIntBigEndian
  6395. */
  6396. virtual void writeIntBigEndian (int value);
  6397. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6398. @see InputStream::readInt64
  6399. */
  6400. virtual void writeInt64 (int64 value);
  6401. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6402. @see InputStream::readInt64BigEndian
  6403. */
  6404. virtual void writeInt64BigEndian (int64 value);
  6405. /** Writes a 32-bit floating point value to the stream.
  6406. The binary 32-bit encoding of the float is written as a little-endian int.
  6407. @see InputStream::readFloat
  6408. */
  6409. virtual void writeFloat (float value);
  6410. /** Writes a 32-bit floating point value to the stream.
  6411. The binary 32-bit encoding of the float is written as a big-endian int.
  6412. @see InputStream::readFloatBigEndian
  6413. */
  6414. virtual void writeFloatBigEndian (float value);
  6415. /** Writes a 64-bit floating point value to the stream.
  6416. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6417. @see InputStream::readDouble
  6418. */
  6419. virtual void writeDouble (double value);
  6420. /** Writes a 64-bit floating point value to the stream.
  6421. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6422. @see InputStream::readDoubleBigEndian
  6423. */
  6424. virtual void writeDoubleBigEndian (double value);
  6425. /** Writes a condensed encoding of a 32-bit integer.
  6426. If you're storing a lot of integers which are unlikely to have very large values,
  6427. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6428. under 0xffff only 3 bytes, etc.
  6429. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6430. @see InputStream::readCompressedInt
  6431. */
  6432. virtual void writeCompressedInt (int value);
  6433. /** Stores a string in the stream.
  6434. This isn't the method to use if you're trying to append text to the end of a
  6435. text-file! It's intended for storing a string for later retrieval
  6436. by InputStream::readString.
  6437. For appending text to a file, instead use writeText, printf, or operator<<
  6438. @see InputStream::readString, writeText, printf, operator<<
  6439. */
  6440. virtual void writeString (const String& text);
  6441. /** Writes a string of text to the stream.
  6442. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6443. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6444. should only be done at the start of a file).
  6445. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6446. */
  6447. virtual void writeText (const String& text,
  6448. const bool asUnicode,
  6449. const bool writeUnicodeHeaderBytes);
  6450. /** Writes a string of text to the stream.
  6451. @see writeText
  6452. */
  6453. virtual void printf (const char* format, ...);
  6454. /** Reads data from an input stream and writes it to this stream.
  6455. @param source the stream to read from
  6456. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6457. less than zero, it will keep reading until the input
  6458. is exhausted)
  6459. */
  6460. virtual int writeFromInputStream (InputStream& source,
  6461. int maxNumBytesToWrite);
  6462. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6463. virtual OutputStream& operator<< (const int number);
  6464. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6465. virtual OutputStream& operator<< (const double number);
  6466. /** Writes a character to the stream. */
  6467. virtual OutputStream& operator<< (const char character);
  6468. /** Writes a null-terminated string to the stream. */
  6469. virtual OutputStream& operator<< (const char* const text);
  6470. /** Writes a null-terminated unicode text string to the stream, converting it
  6471. to 8-bit characters in the default system encoding. */
  6472. virtual OutputStream& operator<< (const juce_wchar* const text);
  6473. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6474. virtual OutputStream& operator<< (const String& text);
  6475. juce_UseDebuggingNewOperator
  6476. protected:
  6477. OutputStream() throw();
  6478. };
  6479. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6480. /********* End of inlined file: juce_OutputStream.h *********/
  6481. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6482. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6483. will be the name of a pointer to each child element.
  6484. E.g. @code
  6485. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6486. forEachXmlChildElement (*myParentXml, child)
  6487. {
  6488. if (child->hasTagName ("FOO"))
  6489. doSomethingWithXmlElement (child);
  6490. }
  6491. @endcode
  6492. @see forEachXmlChildElementWithTagName
  6493. */
  6494. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6495. \
  6496. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6497. childElementVariableName != 0; \
  6498. childElementVariableName = childElementVariableName->getNextElement())
  6499. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6500. which have a specified tag.
  6501. This does the same job as the forEachXmlChildElement macro, but only for those
  6502. elements that have a particular tag name.
  6503. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6504. will be the name of a pointer to each child element. The requiredTagName is the
  6505. tag name to match.
  6506. E.g. @code
  6507. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6508. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6509. {
  6510. // the child object is now guaranteed to be a <MYTAG> element..
  6511. doSomethingWithMYTAGElement (child);
  6512. }
  6513. @endcode
  6514. @see forEachXmlChildElement
  6515. */
  6516. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6517. \
  6518. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6519. childElementVariableName != 0; \
  6520. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6521. /** Used to build a tree of elements representing an XML document.
  6522. An XML document can be parsed into a tree of XmlElements, each of which
  6523. represents an XML tag structure, and which may itself contain other
  6524. nested elements.
  6525. An XmlElement can also be converted back into a text document, and has
  6526. lots of useful methods for manipulating its attributes and sub-elements,
  6527. so XmlElements can actually be used as a handy general-purpose data
  6528. structure.
  6529. Here's an example of parsing some elements: @code
  6530. // check we're looking at the right kind of document..
  6531. if (myElement->hasTagName ("ANIMALS"))
  6532. {
  6533. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6534. forEachXmlChildElement (*myElement, e)
  6535. {
  6536. if (e->hasTagName ("GIRAFFE"))
  6537. {
  6538. // found a giraffe, so use some of its attributes..
  6539. String giraffeName = e->getStringAttribute ("name");
  6540. int giraffeAge = e->getIntAttribute ("age");
  6541. bool isFriendly = e->getBoolAttribute ("friendly");
  6542. }
  6543. }
  6544. }
  6545. @endcode
  6546. And here's an example of how to create an XML document from scratch: @code
  6547. // create an outer node called "ANIMALS"
  6548. XmlElement animalsList ("ANIMALS");
  6549. for (int i = 0; i < numAnimals; ++i)
  6550. {
  6551. // create an inner element..
  6552. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6553. giraffe->setAttribute ("name", "nigel");
  6554. giraffe->setAttribute ("age", 10);
  6555. giraffe->setAttribute ("friendly", true);
  6556. // ..and add our new element to the parent node
  6557. animalsList.addChildElement (giraffe);
  6558. }
  6559. // now we can turn the whole thing into a text document..
  6560. String myXmlDoc = animalsList.createDocument (String::empty);
  6561. @endcode
  6562. @see XmlDocument
  6563. */
  6564. class JUCE_API XmlElement
  6565. {
  6566. public:
  6567. /** Creates an XmlElement with this tag name. */
  6568. XmlElement (const String& tagName) throw();
  6569. /** Creates a (deep) copy of another element. */
  6570. XmlElement (const XmlElement& other) throw();
  6571. /** Creates a (deep) copy of another element. */
  6572. const XmlElement& operator= (const XmlElement& other) throw();
  6573. /** Deleting an XmlElement will also delete all its child elements. */
  6574. ~XmlElement() throw();
  6575. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6576. The elements are only considered equivalent if they contain the same attiributes
  6577. with the same values, and have the same sub-nodes.
  6578. @param other the other element to compare to
  6579. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6580. same attributes in a different order will be
  6581. considered the same; if false, the attributes must
  6582. be in the same order as well
  6583. */
  6584. bool isEquivalentTo (const XmlElement* const other,
  6585. const bool ignoreOrderOfAttributes) const throw();
  6586. /** Returns an XML text document that represents this element.
  6587. The string returned can be parsed to recreate the same XmlElement that
  6588. was used to create it.
  6589. @param dtdToUse the DTD to add to the document
  6590. @param allOnOneLine if true, this means that the document will not contain any
  6591. linefeeds, so it'll be smaller but not very easy to read.
  6592. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6593. document
  6594. @param encodingType the character encoding format string to put into the xml
  6595. header
  6596. @param lineWrapLength the line length that will be used before items get placed on
  6597. a new line. This isn't an absolute maximum length, it just
  6598. determines how lists of attributes get broken up
  6599. @see writeToFile
  6600. */
  6601. const String createDocument (const String& dtdToUse,
  6602. const bool allOnOneLine = false,
  6603. const bool includeXmlHeader = true,
  6604. const tchar* const encodingType = JUCE_T("UTF-8"),
  6605. const int lineWrapLength = 60) const throw();
  6606. /** Writes the element to a file as an XML document.
  6607. To improve safety in case something goes wrong while writing the file, this
  6608. will actually write the document to a new temporary file in the same
  6609. directory as the destination file, and if this succeeds, it will rename this
  6610. new file as the destination file (overwriting any existing file that was there).
  6611. @param destinationFile the file to write to. If this already exists, it will be
  6612. overwritten.
  6613. @param dtdToUse the DTD to add to the document
  6614. @param encodingType the character encoding format string to put into the xml
  6615. header
  6616. @param lineWrapLength the line length that will be used before items get placed on
  6617. a new line. This isn't an absolute maximum length, it just
  6618. determines how lists of attributes get broken up
  6619. @returns true if the file is written successfully; false if something goes wrong
  6620. in the process
  6621. @see createDocument
  6622. */
  6623. bool writeToFile (const File& destinationFile,
  6624. const String& dtdToUse,
  6625. const tchar* const encodingType = JUCE_T("UTF-8"),
  6626. const int lineWrapLength = 60) const throw();
  6627. /** Returns this element's tag type name.
  6628. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6629. "MOOSE".
  6630. @see hasTagName
  6631. */
  6632. inline const String& getTagName() const throw() { return tagName; }
  6633. /** Tests whether this element has a particular tag name.
  6634. @param possibleTagName the tag name you're comparing it with
  6635. @see getTagName
  6636. */
  6637. bool hasTagName (const tchar* const possibleTagName) const throw();
  6638. /** Returns the number of XML attributes this element contains.
  6639. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6640. return 2.
  6641. */
  6642. int getNumAttributes() const throw();
  6643. /** Returns the name of one of the elements attributes.
  6644. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6645. getAttributeName(1) would return "antlers".
  6646. @see getAttributeValue, getStringAttribute
  6647. */
  6648. const String& getAttributeName (const int attributeIndex) const throw();
  6649. /** Returns the value of one of the elements attributes.
  6650. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6651. getAttributeName(1) would return "2".
  6652. @see getAttributeName, getStringAttribute
  6653. */
  6654. const String& getAttributeValue (const int attributeIndex) const throw();
  6655. // Attribute-handling methods..
  6656. /** Checks whether the element contains an attribute with a certain name. */
  6657. bool hasAttribute (const tchar* const attributeName) const throw();
  6658. /** Returns the value of a named attribute.
  6659. @param attributeName the name of the attribute to look up
  6660. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6661. with this name
  6662. */
  6663. const String getStringAttribute (const tchar* const attributeName,
  6664. const tchar* const defaultReturnValue = 0) const throw();
  6665. /** Compares the value of a named attribute with a value passed-in.
  6666. @param attributeName the name of the attribute to look up
  6667. @param stringToCompareAgainst the value to compare it with
  6668. @param ignoreCase whether the comparison should be case-insensitive
  6669. @returns true if the value of the attribute is the same as the string passed-in;
  6670. false if it's different (or if no such attribute exists)
  6671. */
  6672. bool compareAttribute (const tchar* const attributeName,
  6673. const tchar* const stringToCompareAgainst,
  6674. const bool ignoreCase = false) const throw();
  6675. /** Returns the value of a named attribute as an integer.
  6676. This will try to find the attribute and convert it to an integer (using
  6677. the String::getIntValue() method).
  6678. @param attributeName the name of the attribute to look up
  6679. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6680. with this name
  6681. @see setAttribute (const tchar* const, int)
  6682. */
  6683. int getIntAttribute (const tchar* const attributeName,
  6684. const int defaultReturnValue = 0) const throw();
  6685. /** Returns the value of a named attribute as floating-point.
  6686. This will try to find the attribute and convert it to an integer (using
  6687. the String::getDoubleValue() method).
  6688. @param attributeName the name of the attribute to look up
  6689. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6690. with this name
  6691. @see setAttribute (const tchar* const, double)
  6692. */
  6693. double getDoubleAttribute (const tchar* const attributeName,
  6694. const double defaultReturnValue = 0.0) const throw();
  6695. /** Returns the value of a named attribute as a boolean.
  6696. This will try to find the attribute and interpret it as a boolean. To do this,
  6697. it'll return true if the value is "1", "true", "y", etc, or false for other
  6698. values.
  6699. @param attributeName the name of the attribute to look up
  6700. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6701. with this name
  6702. */
  6703. bool getBoolAttribute (const tchar* const attributeName,
  6704. const bool defaultReturnValue = false) const throw();
  6705. /** Adds a named attribute to the element.
  6706. If the element already contains an attribute with this name, it's value will
  6707. be updated to the new value. If there's no such attribute yet, a new one will
  6708. be added.
  6709. Note that there are other setAttribute() methods that take integers,
  6710. doubles, etc. to make it easy to store numbers.
  6711. @param attributeName the name of the attribute to set
  6712. @param newValue the value to set it to
  6713. @see removeAttribute
  6714. */
  6715. void setAttribute (const tchar* const attributeName,
  6716. const String& newValue) throw();
  6717. /** Adds a named attribute to the element.
  6718. If the element already contains an attribute with this name, it's value will
  6719. be updated to the new value. If there's no such attribute yet, a new one will
  6720. be added.
  6721. Note that there are other setAttribute() methods that take integers,
  6722. doubles, etc. to make it easy to store numbers.
  6723. @param attributeName the name of the attribute to set
  6724. @param newValue the value to set it to
  6725. */
  6726. void setAttribute (const tchar* const attributeName,
  6727. const tchar* const newValue) throw();
  6728. /** Adds a named attribute to the element, setting it to an integer value.
  6729. If the element already contains an attribute with this name, it's value will
  6730. be updated to the new value. If there's no such attribute yet, a new one will
  6731. be added.
  6732. Note that there are other setAttribute() methods that take integers,
  6733. doubles, etc. to make it easy to store numbers.
  6734. @param attributeName the name of the attribute to set
  6735. @param newValue the value to set it to
  6736. */
  6737. void setAttribute (const tchar* const attributeName,
  6738. const int newValue) throw();
  6739. /** Adds a named attribute to the element, setting it to a floating-point value.
  6740. If the element already contains an attribute with this name, it's value will
  6741. be updated to the new value. If there's no such attribute yet, a new one will
  6742. be added.
  6743. Note that there are other setAttribute() methods that take integers,
  6744. doubles, etc. to make it easy to store numbers.
  6745. @param attributeName the name of the attribute to set
  6746. @param newValue the value to set it to
  6747. */
  6748. void setAttribute (const tchar* const attributeName,
  6749. const double newValue) throw();
  6750. /** Removes a named attribute from the element.
  6751. @param attributeName the name of the attribute to remove
  6752. @see removeAllAttributes
  6753. */
  6754. void removeAttribute (const tchar* const attributeName) throw();
  6755. /** Removes all attributes from this element.
  6756. */
  6757. void removeAllAttributes() throw();
  6758. // Child element methods..
  6759. /** Returns the first of this element's sub-elements.
  6760. see getNextElement() for an example of how to iterate the sub-elements.
  6761. @see forEachXmlChildElement
  6762. */
  6763. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6764. /** Returns the next of this element's siblings.
  6765. This can be used for iterating an element's sub-elements, e.g.
  6766. @code
  6767. XmlElement* child = myXmlDocument->getFirstChildElement();
  6768. while (child != 0)
  6769. {
  6770. ...do stuff with this child..
  6771. child = child->getNextElement();
  6772. }
  6773. @endcode
  6774. Note that when iterating the child elements, some of them might be
  6775. text elements as well as XML tags - use isTextElement() to work this
  6776. out.
  6777. Also, it's much easier and neater to use this method indirectly via the
  6778. forEachXmlChildElement macro.
  6779. @returns the sibling element that follows this one, or zero if this is the last
  6780. element in its parent
  6781. @see getNextElement, isTextElement, forEachXmlChildElement
  6782. */
  6783. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6784. /** Returns the next of this element's siblings which has the specified tag
  6785. name.
  6786. This is like getNextElement(), but will scan through the list until it
  6787. finds an element with the given tag name.
  6788. @see getNextElement, forEachXmlChildElementWithTagName
  6789. */
  6790. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6791. /** Returns the number of sub-elements in this element.
  6792. @see getChildElement
  6793. */
  6794. int getNumChildElements() const throw();
  6795. /** Returns the sub-element at a certain index.
  6796. It's not very efficient to iterate the sub-elements by index - see
  6797. getNextElement() for an example of how best to iterate.
  6798. @returns the n'th child of this element, or 0 if the index is out-of-range
  6799. @see getNextElement, isTextElement, getChildByName
  6800. */
  6801. XmlElement* getChildElement (const int index) const throw();
  6802. /** Returns the first sub-element with a given tag-name.
  6803. @param tagNameToLookFor the tag name of the element you want to find
  6804. @returns the first element with this tag name, or 0 if none is found
  6805. @see getNextElement, isTextElement, getChildElement
  6806. */
  6807. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6808. /** Appends an element to this element's list of children.
  6809. Child elements are deleted automatically when their parent is deleted, so
  6810. make sure the object that you pass in will not be deleted by anything else,
  6811. and make sure it's not already the child of another element.
  6812. @see getFirstChildElement, getNextElement, getNumChildElements,
  6813. getChildElement, removeChildElement
  6814. */
  6815. void addChildElement (XmlElement* const newChildElement) throw();
  6816. /** Inserts an element into this element's list of children.
  6817. Child elements are deleted automatically when their parent is deleted, so
  6818. make sure the object that you pass in will not be deleted by anything else,
  6819. and make sure it's not already the child of another element.
  6820. @param newChildNode the element to add
  6821. @param indexToInsertAt the index at which to insert the new element - if this is
  6822. below zero, it will be added to the end of the list
  6823. @see addChildElement, insertChildElement
  6824. */
  6825. void insertChildElement (XmlElement* const newChildNode,
  6826. int indexToInsertAt) throw();
  6827. /** Replaces one of this element's children with another node.
  6828. If the current element passed-in isn't actually a child of this element,
  6829. this will return false and the new one won't be added. Otherwise, the
  6830. existing element will be deleted, replaced with the new one, and it
  6831. will return true.
  6832. */
  6833. bool replaceChildElement (XmlElement* const currentChildElement,
  6834. XmlElement* const newChildNode) throw();
  6835. /** Removes a child element.
  6836. @param childToRemove the child to look for and remove
  6837. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6838. just remove it
  6839. */
  6840. void removeChildElement (XmlElement* const childToRemove,
  6841. const bool shouldDeleteTheChild) throw();
  6842. /** Deletes all the child elements in the element.
  6843. @see removeChildElement, deleteAllChildElementsWithTagName
  6844. */
  6845. void deleteAllChildElements() throw();
  6846. /** Deletes all the child elements with a given tag name.
  6847. @see removeChildElement
  6848. */
  6849. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6850. /** Returns true if the given element is a child of this one. */
  6851. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6852. /** Recursively searches all sub-elements to find one that contains the specified
  6853. child element.
  6854. */
  6855. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6856. /** Sorts the child elements using a comparator.
  6857. This will use a comparator object to sort the elements into order. The object
  6858. passed must have a method of the form:
  6859. @code
  6860. int compareElements (const XmlElement* first, const XmlElement* second);
  6861. @endcode
  6862. ..and this method must return:
  6863. - a value of < 0 if the first comes before the second
  6864. - a value of 0 if the two objects are equivalent
  6865. - a value of > 0 if the second comes before the first
  6866. To improve performance, the compareElements() method can be declared as static or const.
  6867. @param comparator the comparator to use for comparing elements.
  6868. @param retainOrderOfEquivalentItems if this is true, then items
  6869. which the comparator says are equivalent will be
  6870. kept in the order in which they currently appear
  6871. in the array. This is slower to perform, but may
  6872. be important in some cases. If it's false, a faster
  6873. algorithm is used, but equivalent elements may be
  6874. rearranged.
  6875. */
  6876. template <class ElementComparator>
  6877. void sortChildElements (ElementComparator& comparator,
  6878. const bool retainOrderOfEquivalentItems = false) throw()
  6879. {
  6880. const int num = getNumChildElements();
  6881. if (num > 1)
  6882. {
  6883. XmlElement** const elems = getChildElementsAsArray (num);
  6884. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  6885. reorderChildElements (elems, num);
  6886. delete[] elems;
  6887. }
  6888. }
  6889. /** Returns true if this element is a section of text.
  6890. Elements can either be an XML tag element or a secton of text, so this
  6891. is used to find out what kind of element this one is.
  6892. @see getAllText, addTextElement, deleteAllTextElements
  6893. */
  6894. bool isTextElement() const throw();
  6895. /** Returns the text for a text element.
  6896. Note that if you have an element like this:
  6897. @code<xyz>hello</xyz>@endcode
  6898. then calling getText on the "xyz" element won't return "hello", because that is
  6899. actually stored in a special text sub-element inside the xyz element. To get the
  6900. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6901. use getAllSubText() to do this automatically.
  6902. @see isTextElement, getAllSubText, getChildElementAllSubText
  6903. */
  6904. const String getText() const throw();
  6905. /** Sets the text in a text element.
  6906. Note that this is only a valid call if this element is a text element. If it's
  6907. not, then no action will be performed.
  6908. */
  6909. void setText (const String& newText) throw();
  6910. /** Returns all the text from this element's child nodes.
  6911. This iterates all the child elements and when it finds text elements,
  6912. it concatenates their text into a big string which it returns.
  6913. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6914. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6915. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6916. */
  6917. const String getAllSubText() const throw();
  6918. /** Returns all the sub-text of a named child element.
  6919. If there is a child element with the given tag name, this will return
  6920. all of its sub-text (by calling getAllSubText() on it). If there is
  6921. no such child element, this will return the default string passed-in.
  6922. @see getAllSubText
  6923. */
  6924. const String getChildElementAllSubText (const tchar* const childTagName,
  6925. const String& defaultReturnValue) const throw();
  6926. /** Appends a section of text to this element.
  6927. @see isTextElement, getText, getAllSubText
  6928. */
  6929. void addTextElement (const String& text) throw();
  6930. /** Removes all the text elements from this element.
  6931. @see isTextElement, getText, getAllSubText, addTextElement
  6932. */
  6933. void deleteAllTextElements() throw();
  6934. /** Creates a text element that can be added to a parent element.
  6935. */
  6936. static XmlElement* createTextElement (const String& text) throw();
  6937. juce_UseDebuggingNewOperator
  6938. private:
  6939. friend class XmlDocument;
  6940. String tagName;
  6941. XmlElement* firstChildElement;
  6942. XmlElement* nextElement;
  6943. struct XmlAttributeNode
  6944. {
  6945. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6946. XmlAttributeNode (const String& name, const String& value) throw();
  6947. String name, value;
  6948. XmlAttributeNode* next;
  6949. };
  6950. XmlAttributeNode* attributes;
  6951. XmlElement (int) throw(); // for internal use
  6952. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6953. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6954. void writeElementAsText (OutputStream& out,
  6955. const int indentationLevel,
  6956. const int lineWrapLength) const throw();
  6957. XmlElement** getChildElementsAsArray (const int) const throw();
  6958. void reorderChildElements (XmlElement** const, const int) throw();
  6959. };
  6960. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6961. /********* End of inlined file: juce_XmlElement.h *********/
  6962. /**
  6963. A set of named property values, which can be strings, integers, floating point, etc.
  6964. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6965. to load and save types other than strings.
  6966. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6967. messages and saves/loads the list from a file.
  6968. */
  6969. class JUCE_API PropertySet
  6970. {
  6971. public:
  6972. /** Creates an empty PropertySet.
  6973. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6974. case-insensitive way
  6975. */
  6976. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6977. /** Creates a copy of another PropertySet.
  6978. */
  6979. PropertySet (const PropertySet& other) throw();
  6980. /** Copies another PropertySet over this one.
  6981. */
  6982. const PropertySet& operator= (const PropertySet& other) throw();
  6983. /** Destructor. */
  6984. virtual ~PropertySet();
  6985. /** Returns one of the properties as a string.
  6986. If the value isn't found in this set, then this will look for it in a fallback
  6987. property set (if you've specified one with the setFallbackPropertySet() method),
  6988. and if it can't find one there, it'll return the default value passed-in.
  6989. @param keyName the name of the property to retrieve
  6990. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6991. */
  6992. const String getValue (const String& keyName,
  6993. const String& defaultReturnValue = String::empty) const throw();
  6994. /** Returns one of the properties as an integer.
  6995. If the value isn't found in this set, then this will look for it in a fallback
  6996. property set (if you've specified one with the setFallbackPropertySet() method),
  6997. and if it can't find one there, it'll return the default value passed-in.
  6998. @param keyName the name of the property to retrieve
  6999. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7000. */
  7001. int getIntValue (const String& keyName,
  7002. const int defaultReturnValue = 0) const throw();
  7003. /** Returns one of the properties as an double.
  7004. If the value isn't found in this set, then this will look for it in a fallback
  7005. property set (if you've specified one with the setFallbackPropertySet() method),
  7006. and if it can't find one there, it'll return the default value passed-in.
  7007. @param keyName the name of the property to retrieve
  7008. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7009. */
  7010. double getDoubleValue (const String& keyName,
  7011. const double defaultReturnValue = 0.0) const throw();
  7012. /** Returns one of the properties as an boolean.
  7013. The result will be true if the string found for this key name can be parsed as a non-zero
  7014. integer.
  7015. If the value isn't found in this set, then this will look for it in a fallback
  7016. property set (if you've specified one with the setFallbackPropertySet() method),
  7017. and if it can't find one there, it'll return the default value passed-in.
  7018. @param keyName the name of the property to retrieve
  7019. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7020. */
  7021. bool getBoolValue (const String& keyName,
  7022. const bool defaultReturnValue = false) const throw();
  7023. /** Returns one of the properties as an XML element.
  7024. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7025. key isn't found, or if the entry contains an string that isn't valid XML.
  7026. If the value isn't found in this set, then this will look for it in a fallback
  7027. property set (if you've specified one with the setFallbackPropertySet() method),
  7028. and if it can't find one there, it'll return the default value passed-in.
  7029. @param keyName the name of the property to retrieve
  7030. */
  7031. XmlElement* getXmlValue (const String& keyName) const;
  7032. /** Sets a named property as a string.
  7033. @param keyName the name of the property to set. (This mustn't be an empty string)
  7034. @param value the new value to set it to
  7035. */
  7036. void setValue (const String& keyName, const String& value) throw();
  7037. /** Sets a named property as a string.
  7038. @param keyName the name of the property to set. (This mustn't be an empty string)
  7039. @param value the new value to set it to
  7040. */
  7041. void setValue (const String& keyName, const tchar* const value) throw();
  7042. /** Sets a named property to an integer.
  7043. @param keyName the name of the property to set. (This mustn't be an empty string)
  7044. @param value the new value to set it to
  7045. */
  7046. void setValue (const String& keyName, const int value) throw();
  7047. /** Sets a named property to a double.
  7048. @param keyName the name of the property to set. (This mustn't be an empty string)
  7049. @param value the new value to set it to
  7050. */
  7051. void setValue (const String& keyName, const double value) throw();
  7052. /** Sets a named property to a boolean.
  7053. @param keyName the name of the property to set. (This mustn't be an empty string)
  7054. @param value the new value to set it to
  7055. */
  7056. void setValue (const String& keyName, const bool value) throw();
  7057. /** Sets a named property to an XML element.
  7058. @param keyName the name of the property to set. (This mustn't be an empty string)
  7059. @param xml the new element to set it to. If this is zero, the value will be set to
  7060. an empty string
  7061. @see getXmlValue
  7062. */
  7063. void setValue (const String& keyName, const XmlElement* const xml);
  7064. /** Deletes a property.
  7065. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7066. */
  7067. void removeValue (const String& keyName) throw();
  7068. /** Returns true if the properies include the given key. */
  7069. bool containsKey (const String& keyName) const throw();
  7070. /** Removes all values. */
  7071. void clear();
  7072. /** Returns the keys/value pair array containing all the properties. */
  7073. StringPairArray& getAllProperties() throw() { return properties; }
  7074. /** Returns the lock used when reading or writing to this set */
  7075. const CriticalSection& getLock() const throw() { return lock; }
  7076. /** Returns an XML element which encapsulates all the items in this property set.
  7077. The string parameter is the tag name that should be used for the node.
  7078. @see restoreFromXml
  7079. */
  7080. XmlElement* createXml (const String& nodeName) const throw();
  7081. /** Reloads a set of properties that were previously stored as XML.
  7082. The node passed in must have been created by the createXml() method.
  7083. @see createXml
  7084. */
  7085. void restoreFromXml (const XmlElement& xml) throw();
  7086. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7087. set in this one.
  7088. If you set this up to be a pointer to a second property set, then whenever one
  7089. of the getValue() methods fails to find an entry in this set, it will look up that
  7090. value in the fallback set, and if it finds it, it will return that.
  7091. Make sure that you don't delete the fallback set while it's still being used by
  7092. another set! To remove the fallback set, just call this method with a null pointer.
  7093. @see getFallbackPropertySet
  7094. */
  7095. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7096. /** Returns the fallback property set.
  7097. @see setFallbackPropertySet
  7098. */
  7099. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7100. juce_UseDebuggingNewOperator
  7101. protected:
  7102. /** Subclasses can override this to be told when one of the properies has been changed.
  7103. */
  7104. virtual void propertyChanged();
  7105. private:
  7106. StringPairArray properties;
  7107. PropertySet* fallbackProperties;
  7108. CriticalSection lock;
  7109. bool ignoreCaseOfKeys;
  7110. };
  7111. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7112. /********* End of inlined file: juce_PropertySet.h *********/
  7113. #endif
  7114. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7115. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7116. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7117. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7118. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7119. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7120. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7121. /**
  7122. Adds reference-counting to an object.
  7123. To add reference-counting to a class, derive it from this class, and
  7124. use the ReferenceCountedObjectPtr class to point to it.
  7125. e.g. @code
  7126. class MyClass : public ReferenceCountedObject
  7127. {
  7128. void foo();
  7129. // This is a neat way of declaring a typedef for a pointer class,
  7130. // rather than typing out the full templated name each time..
  7131. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7132. };
  7133. MyClass::Ptr p = new MyClass();
  7134. MyClass::Ptr p2 = p;
  7135. p = 0;
  7136. p2->foo();
  7137. @endcode
  7138. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7139. careful not to delete the object manually.
  7140. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7141. */
  7142. class JUCE_API ReferenceCountedObject
  7143. {
  7144. public:
  7145. /** Increments the object's reference count.
  7146. This is done automatically by the smart pointer, but is public just
  7147. in case it's needed for nefarious purposes.
  7148. */
  7149. inline void incReferenceCount() throw()
  7150. {
  7151. atomicIncrement (refCounts);
  7152. jassert (refCounts > 0);
  7153. }
  7154. /** Decreases the object's reference count.
  7155. If the count gets to zero, the object will be deleted.
  7156. */
  7157. inline void decReferenceCount() throw()
  7158. {
  7159. jassert (refCounts > 0);
  7160. if (atomicDecrementAndReturn (refCounts) == 0)
  7161. delete this;
  7162. }
  7163. /** Returns the object's current reference count. */
  7164. inline int getReferenceCount() const throw()
  7165. {
  7166. return refCounts;
  7167. }
  7168. protected:
  7169. /** Creates the reference-counted object (with an initial ref count of zero). */
  7170. ReferenceCountedObject()
  7171. : refCounts (0)
  7172. {
  7173. }
  7174. /** Destructor. */
  7175. virtual ~ReferenceCountedObject()
  7176. {
  7177. // it's dangerous to delete an object that's still referenced by something else!
  7178. jassert (refCounts == 0);
  7179. }
  7180. private:
  7181. int refCounts;
  7182. };
  7183. /**
  7184. Used to point to an object of type ReferenceCountedObject.
  7185. It's wise to use a typedef instead of typing out the templated name
  7186. each time - e.g.
  7187. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7188. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7189. */
  7190. template <class ReferenceCountedObjectClass>
  7191. class ReferenceCountedObjectPtr
  7192. {
  7193. public:
  7194. /** Creates a pointer to a null object. */
  7195. inline ReferenceCountedObjectPtr() throw()
  7196. : referencedObject (0)
  7197. {
  7198. }
  7199. /** Creates a pointer to an object.
  7200. This will increment the object's reference-count if it is non-null.
  7201. */
  7202. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7203. : referencedObject (refCountedObject)
  7204. {
  7205. if (refCountedObject != 0)
  7206. refCountedObject->incReferenceCount();
  7207. }
  7208. /** Copies another pointer.
  7209. This will increment the object's reference-count (if it is non-null).
  7210. */
  7211. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7212. : referencedObject (other.referencedObject)
  7213. {
  7214. if (referencedObject != 0)
  7215. referencedObject->incReferenceCount();
  7216. }
  7217. /** Changes this pointer to point at a different object.
  7218. The reference count of the old object is decremented, and it might be
  7219. deleted if it hits zero. The new object's count is incremented.
  7220. */
  7221. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7222. {
  7223. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7224. if (newObject != referencedObject)
  7225. {
  7226. if (newObject != 0)
  7227. newObject->incReferenceCount();
  7228. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7229. referencedObject = newObject;
  7230. if (oldObject != 0)
  7231. oldObject->decReferenceCount();
  7232. }
  7233. return *this;
  7234. }
  7235. /** Changes this pointer to point at a different object.
  7236. The reference count of the old object is decremented, and it might be
  7237. deleted if it hits zero. The new object's count is incremented.
  7238. */
  7239. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7240. {
  7241. if (referencedObject != newObject)
  7242. {
  7243. if (newObject != 0)
  7244. newObject->incReferenceCount();
  7245. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7246. referencedObject = newObject;
  7247. if (oldObject != 0)
  7248. oldObject->decReferenceCount();
  7249. }
  7250. return *this;
  7251. }
  7252. /** Destructor.
  7253. This will decrement the object's reference-count, and may delete it if it
  7254. gets to zero.
  7255. */
  7256. inline ~ReferenceCountedObjectPtr()
  7257. {
  7258. if (referencedObject != 0)
  7259. referencedObject->decReferenceCount();
  7260. }
  7261. /** Returns the object that this pointer references.
  7262. The pointer returned may be zero, of course.
  7263. */
  7264. inline operator ReferenceCountedObjectClass*() const throw()
  7265. {
  7266. return referencedObject;
  7267. }
  7268. /** Returns true if this pointer refers to the given object. */
  7269. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7270. {
  7271. return referencedObject == object;
  7272. }
  7273. /** Returns true if this pointer doesn't refer to the given object. */
  7274. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7275. {
  7276. return referencedObject != object;
  7277. }
  7278. // the -> operator is called on the referenced object
  7279. inline ReferenceCountedObjectClass* operator->() const throw()
  7280. {
  7281. return referencedObject;
  7282. }
  7283. private:
  7284. ReferenceCountedObjectClass* referencedObject;
  7285. };
  7286. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7287. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7288. /**
  7289. Holds a list of objects derived from ReferenceCountedObject.
  7290. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7291. and takes care of incrementing and decrementing their ref counts when they
  7292. are added and removed from the array.
  7293. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7294. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7295. @see Array, OwnedArray, StringArray
  7296. */
  7297. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7298. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7299. {
  7300. public:
  7301. /** Creates an empty array.
  7302. @param granularity this is the size of increment by which the internal storage
  7303. used by the array will grow. Only change it from the default if you know the
  7304. array is going to be very big and needs to be able to grow efficiently.
  7305. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7306. */
  7307. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7308. : ArrayAllocationBase <ObjectClass*> (granularity),
  7309. numUsed (0)
  7310. {
  7311. }
  7312. /** Creates a copy of another array */
  7313. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7314. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  7315. numUsed (other.numUsed)
  7316. {
  7317. other.lockArray();
  7318. this->setAllocatedSize (numUsed);
  7319. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7320. for (int i = numUsed; --i >= 0;)
  7321. if (this->elements[i] != 0)
  7322. this->elements[i]->incReferenceCount();
  7323. other.unlockArray();
  7324. }
  7325. /** Copies another array into this one.
  7326. Any existing objects in this array will first be released.
  7327. */
  7328. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7329. {
  7330. if (this != &other)
  7331. {
  7332. other.lockArray();
  7333. lock.enter();
  7334. clear();
  7335. this->granularity = other.granularity;
  7336. this->ensureAllocatedSize (other.numUsed);
  7337. numUsed = other.numUsed;
  7338. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7339. minimiseStorageOverheads();
  7340. for (int i = numUsed; --i >= 0;)
  7341. if (this->elements[i] != 0)
  7342. this->elements[i]->incReferenceCount();
  7343. lock.exit();
  7344. other.unlockArray();
  7345. }
  7346. return *this;
  7347. }
  7348. /** Destructor.
  7349. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7350. */
  7351. ~ReferenceCountedArray()
  7352. {
  7353. clear();
  7354. }
  7355. /** Removes all objects from the array.
  7356. Any objects in the array that are not referenced from elsewhere will be deleted.
  7357. */
  7358. void clear()
  7359. {
  7360. lock.enter();
  7361. while (numUsed > 0)
  7362. if (this->elements [--numUsed] != 0)
  7363. this->elements [numUsed]->decReferenceCount();
  7364. jassert (numUsed == 0);
  7365. this->setAllocatedSize (0);
  7366. lock.exit();
  7367. }
  7368. /** Returns the current number of objects in the array. */
  7369. inline int size() const throw()
  7370. {
  7371. return numUsed;
  7372. }
  7373. /** Returns a pointer to the object at this index in the array.
  7374. If the index is out-of-range, this will return a null pointer, (and
  7375. it could be null anyway, because it's ok for the array to hold null
  7376. pointers as well as objects).
  7377. @see getUnchecked
  7378. */
  7379. inline ObjectClass* operator[] (const int index) const throw()
  7380. {
  7381. lock.enter();
  7382. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  7383. ? this->elements [index]
  7384. : (ObjectClass*) 0;
  7385. lock.exit();
  7386. return result;
  7387. }
  7388. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7389. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7390. it can be used when you're sure the index if always going to be legal.
  7391. */
  7392. inline ObjectClass* getUnchecked (const int index) const throw()
  7393. {
  7394. lock.enter();
  7395. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7396. ObjectClass* const result = this->elements [index];
  7397. lock.exit();
  7398. return result;
  7399. }
  7400. /** Returns a pointer to the first object in the array.
  7401. This will return a null pointer if the array's empty.
  7402. @see getLast
  7403. */
  7404. inline ObjectClass* getFirst() const throw()
  7405. {
  7406. lock.enter();
  7407. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  7408. : (ObjectClass*) 0;
  7409. lock.exit();
  7410. return result;
  7411. }
  7412. /** Returns a pointer to the last object in the array.
  7413. This will return a null pointer if the array's empty.
  7414. @see getFirst
  7415. */
  7416. inline ObjectClass* getLast() const throw()
  7417. {
  7418. lock.enter();
  7419. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  7420. : (ObjectClass*) 0;
  7421. lock.exit();
  7422. return result;
  7423. }
  7424. /** Finds the index of the first occurrence of an object in the array.
  7425. @param objectToLookFor the object to look for
  7426. @returns the index at which the object was found, or -1 if it's not found
  7427. */
  7428. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7429. {
  7430. int result = -1;
  7431. lock.enter();
  7432. ObjectClass** e = this->elements;
  7433. for (int i = numUsed; --i >= 0;)
  7434. {
  7435. if (objectToLookFor == *e)
  7436. {
  7437. result = (int) (e - this->elements);
  7438. break;
  7439. }
  7440. ++e;
  7441. }
  7442. lock.exit();
  7443. return result;
  7444. }
  7445. /** Returns true if the array contains a specified object.
  7446. @param objectToLookFor the object to look for
  7447. @returns true if the object is in the array
  7448. */
  7449. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7450. {
  7451. lock.enter();
  7452. ObjectClass** e = this->elements;
  7453. for (int i = numUsed; --i >= 0;)
  7454. {
  7455. if (objectToLookFor == *e)
  7456. {
  7457. lock.exit();
  7458. return true;
  7459. }
  7460. ++e;
  7461. }
  7462. lock.exit();
  7463. return false;
  7464. }
  7465. /** Appends a new object to the end of the array.
  7466. This will increase the new object's reference count.
  7467. @param newObject the new object to add to the array
  7468. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7469. */
  7470. void add (ObjectClass* const newObject) throw()
  7471. {
  7472. lock.enter();
  7473. this->ensureAllocatedSize (numUsed + 1);
  7474. this->elements [numUsed++] = newObject;
  7475. if (newObject != 0)
  7476. newObject->incReferenceCount();
  7477. lock.exit();
  7478. }
  7479. /** Inserts a new object into the array at the given index.
  7480. If the index is less than 0 or greater than the size of the array, the
  7481. element will be added to the end of the array.
  7482. Otherwise, it will be inserted into the array, moving all the later elements
  7483. along to make room.
  7484. This will increase the new object's reference count.
  7485. @param indexToInsertAt the index at which the new element should be inserted
  7486. @param newObject the new object to add to the array
  7487. @see add, addSorted, addIfNotAlreadyThere, set
  7488. */
  7489. void insert (int indexToInsertAt,
  7490. ObjectClass* const newObject) throw()
  7491. {
  7492. if (indexToInsertAt >= 0)
  7493. {
  7494. lock.enter();
  7495. if (indexToInsertAt > numUsed)
  7496. indexToInsertAt = numUsed;
  7497. this->ensureAllocatedSize (numUsed + 1);
  7498. ObjectClass** const e = this->elements + indexToInsertAt;
  7499. const int numToMove = numUsed - indexToInsertAt;
  7500. if (numToMove > 0)
  7501. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7502. *e = newObject;
  7503. if (newObject != 0)
  7504. newObject->incReferenceCount();
  7505. ++numUsed;
  7506. lock.exit();
  7507. }
  7508. else
  7509. {
  7510. add (newObject);
  7511. }
  7512. }
  7513. /** Appends a new object at the end of the array as long as the array doesn't
  7514. already contain it.
  7515. If the array already contains a matching object, nothing will be done.
  7516. @param newObject the new object to add to the array
  7517. */
  7518. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7519. {
  7520. lock.enter();
  7521. if (! contains (newObject))
  7522. add (newObject);
  7523. lock.exit();
  7524. }
  7525. /** Replaces an object in the array with a different one.
  7526. If the index is less than zero, this method does nothing.
  7527. If the index is beyond the end of the array, the new object is added to the end of the array.
  7528. The object being added has its reference count increased, and if it's replacing
  7529. another object, then that one has its reference count decreased, and may be deleted.
  7530. @param indexToChange the index whose value you want to change
  7531. @param newObject the new value to set for this index.
  7532. @see add, insert, remove
  7533. */
  7534. void set (const int indexToChange,
  7535. ObjectClass* const newObject)
  7536. {
  7537. if (indexToChange >= 0)
  7538. {
  7539. lock.enter();
  7540. if (newObject != 0)
  7541. newObject->incReferenceCount();
  7542. if (indexToChange < numUsed)
  7543. {
  7544. if (this->elements [indexToChange] != 0)
  7545. this->elements [indexToChange]->decReferenceCount();
  7546. this->elements [indexToChange] = newObject;
  7547. }
  7548. else
  7549. {
  7550. this->ensureAllocatedSize (numUsed + 1);
  7551. this->elements [numUsed++] = newObject;
  7552. }
  7553. lock.exit();
  7554. }
  7555. }
  7556. /** Adds elements from another array to the end of this array.
  7557. @param arrayToAddFrom the array from which to copy the elements
  7558. @param startIndex the first element of the other array to start copying from
  7559. @param numElementsToAdd how many elements to add from the other array. If this
  7560. value is negative or greater than the number of available elements,
  7561. all available elements will be copied.
  7562. @see add
  7563. */
  7564. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7565. int startIndex = 0,
  7566. int numElementsToAdd = -1) throw()
  7567. {
  7568. arrayToAddFrom.lockArray();
  7569. lock.enter();
  7570. if (startIndex < 0)
  7571. {
  7572. jassertfalse
  7573. startIndex = 0;
  7574. }
  7575. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7576. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7577. if (numElementsToAdd > 0)
  7578. {
  7579. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  7580. while (--numElementsToAdd >= 0)
  7581. add (arrayToAddFrom.getUnchecked (startIndex++));
  7582. }
  7583. lock.exit();
  7584. arrayToAddFrom.unlockArray();
  7585. }
  7586. /** Inserts a new object into the array assuming that the array is sorted.
  7587. This will use a comparator to find the position at which the new object
  7588. should go. If the array isn't sorted, the behaviour of this
  7589. method will be unpredictable.
  7590. @param comparator the comparator object to use to compare the elements - see the
  7591. sort() method for details about this object's form
  7592. @param newObject the new object to insert to the array
  7593. @see add, sort
  7594. */
  7595. template <class ElementComparator>
  7596. void addSorted (ElementComparator& comparator,
  7597. ObjectClass* newObject) throw()
  7598. {
  7599. lock.enter();
  7600. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  7601. lock.exit();
  7602. }
  7603. /** Removes an object from the array.
  7604. This will remove the object at a given index and move back all the
  7605. subsequent objects to close the gap.
  7606. If the index passed in is out-of-range, nothing will happen.
  7607. The object that is removed will have its reference count decreased,
  7608. and may be deleted if not referenced from elsewhere.
  7609. @param indexToRemove the index of the element to remove
  7610. @see removeObject, removeRange
  7611. */
  7612. void remove (const int indexToRemove)
  7613. {
  7614. lock.enter();
  7615. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7616. {
  7617. ObjectClass** const e = this->elements + indexToRemove;
  7618. if (*e != 0)
  7619. (*e)->decReferenceCount();
  7620. --numUsed;
  7621. const int numberToShift = numUsed - indexToRemove;
  7622. if (numberToShift > 0)
  7623. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7624. if ((numUsed << 1) < this->numAllocated)
  7625. minimiseStorageOverheads();
  7626. }
  7627. lock.exit();
  7628. }
  7629. /** Removes the first occurrence of a specified object from the array.
  7630. If the item isn't found, no action is taken. If it is found, it is
  7631. removed and has its reference count decreased.
  7632. @param objectToRemove the object to try to remove
  7633. @see remove, removeRange
  7634. */
  7635. void removeObject (ObjectClass* const objectToRemove)
  7636. {
  7637. lock.enter();
  7638. remove (indexOf (objectToRemove));
  7639. lock.exit();
  7640. }
  7641. /** Removes a range of objects from the array.
  7642. This will remove a set of objects, starting from the given index,
  7643. and move any subsequent elements down to close the gap.
  7644. If the range extends beyond the bounds of the array, it will
  7645. be safely clipped to the size of the array.
  7646. The objects that are removed will have their reference counts decreased,
  7647. and may be deleted if not referenced from elsewhere.
  7648. @param startIndex the index of the first object to remove
  7649. @param numberToRemove how many objects should be removed
  7650. @see remove, removeObject
  7651. */
  7652. void removeRange (const int startIndex,
  7653. const int numberToRemove)
  7654. {
  7655. lock.enter();
  7656. const int start = jlimit (0, numUsed, startIndex);
  7657. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7658. if (end > start)
  7659. {
  7660. int i;
  7661. for (i = start; i < end; ++i)
  7662. {
  7663. if (this->elements[i] != 0)
  7664. {
  7665. this->elements[i]->decReferenceCount();
  7666. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7667. }
  7668. }
  7669. const int rangeSize = end - start;
  7670. ObjectClass** e = this->elements + start;
  7671. i = numUsed - end;
  7672. numUsed -= rangeSize;
  7673. while (--i >= 0)
  7674. {
  7675. *e = e [rangeSize];
  7676. ++e;
  7677. }
  7678. if ((numUsed << 1) < this->numAllocated)
  7679. minimiseStorageOverheads();
  7680. }
  7681. lock.exit();
  7682. }
  7683. /** Removes the last n objects from the array.
  7684. The objects that are removed will have their reference counts decreased,
  7685. and may be deleted if not referenced from elsewhere.
  7686. @param howManyToRemove how many objects to remove from the end of the array
  7687. @see remove, removeObject, removeRange
  7688. */
  7689. void removeLast (int howManyToRemove = 1)
  7690. {
  7691. lock.enter();
  7692. if (howManyToRemove > numUsed)
  7693. howManyToRemove = numUsed;
  7694. while (--howManyToRemove >= 0)
  7695. remove (numUsed - 1);
  7696. lock.exit();
  7697. }
  7698. /** Swaps a pair of objects in the array.
  7699. If either of the indexes passed in is out-of-range, nothing will happen,
  7700. otherwise the two objects at these positions will be exchanged.
  7701. */
  7702. void swap (const int index1,
  7703. const int index2) throw()
  7704. {
  7705. lock.enter();
  7706. if (((unsigned int) index1) < (unsigned int) numUsed
  7707. && ((unsigned int) index2) < (unsigned int) numUsed)
  7708. {
  7709. swapVariables (this->elements [index1],
  7710. this->elements [index2]);
  7711. }
  7712. lock.exit();
  7713. }
  7714. /** Moves one of the objects to a different position.
  7715. This will move the object to a specified index, shuffling along
  7716. any intervening elements as required.
  7717. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7718. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7719. @param currentIndex the index of the object to be moved. If this isn't a
  7720. valid index, then nothing will be done
  7721. @param newIndex the index at which you'd like this object to end up. If this
  7722. is less than zero, it will be moved to the end of the array
  7723. */
  7724. void move (const int currentIndex,
  7725. int newIndex) throw()
  7726. {
  7727. if (currentIndex != newIndex)
  7728. {
  7729. lock.enter();
  7730. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7731. {
  7732. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7733. newIndex = numUsed - 1;
  7734. ObjectClass* const value = this->elements [currentIndex];
  7735. if (newIndex > currentIndex)
  7736. {
  7737. memmove (this->elements + currentIndex,
  7738. this->elements + currentIndex + 1,
  7739. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7740. }
  7741. else
  7742. {
  7743. memmove (this->elements + newIndex + 1,
  7744. this->elements + newIndex,
  7745. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7746. }
  7747. this->elements [newIndex] = value;
  7748. }
  7749. lock.exit();
  7750. }
  7751. }
  7752. /** Compares this array to another one.
  7753. @returns true only if the other array contains the same objects in the same order
  7754. */
  7755. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7756. {
  7757. other.lockArray();
  7758. lock.enter();
  7759. bool result = numUsed == other.numUsed;
  7760. if (result)
  7761. {
  7762. for (int i = numUsed; --i >= 0;)
  7763. {
  7764. if (this->elements [i] != other.elements [i])
  7765. {
  7766. result = false;
  7767. break;
  7768. }
  7769. }
  7770. }
  7771. lock.exit();
  7772. other.unlockArray();
  7773. return result;
  7774. }
  7775. /** Compares this array to another one.
  7776. @see operator==
  7777. */
  7778. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7779. {
  7780. return ! operator== (other);
  7781. }
  7782. /** Sorts the elements in the array.
  7783. This will use a comparator object to sort the elements into order. The object
  7784. passed must have a method of the form:
  7785. @code
  7786. int compareElements (ElementType first, ElementType second);
  7787. @endcode
  7788. ..and this method must return:
  7789. - a value of < 0 if the first comes before the second
  7790. - a value of 0 if the two objects are equivalent
  7791. - a value of > 0 if the second comes before the first
  7792. To improve performance, the compareElements() method can be declared as static or const.
  7793. @param comparator the comparator to use for comparing elements.
  7794. @param retainOrderOfEquivalentItems if this is true, then items
  7795. which the comparator says are equivalent will be
  7796. kept in the order in which they currently appear
  7797. in the array. This is slower to perform, but may
  7798. be important in some cases. If it's false, a faster
  7799. algorithm is used, but equivalent elements may be
  7800. rearranged.
  7801. @see sortArray
  7802. */
  7803. template <class ElementComparator>
  7804. void sort (ElementComparator& comparator,
  7805. const bool retainOrderOfEquivalentItems = false) const throw()
  7806. {
  7807. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7808. // avoids getting warning messages about the parameter being unused
  7809. lock.enter();
  7810. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7811. lock.exit();
  7812. }
  7813. /** Reduces the amount of storage being used by the array.
  7814. Arrays typically allocate slightly more storage than they need, and after
  7815. removing elements, they may have quite a lot of unused space allocated.
  7816. This method will reduce the amount of allocated storage to a minimum.
  7817. */
  7818. void minimiseStorageOverheads() throw()
  7819. {
  7820. lock.enter();
  7821. if (numUsed == 0)
  7822. {
  7823. this->setAllocatedSize (0);
  7824. }
  7825. else
  7826. {
  7827. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  7828. if (newAllocation < this->numAllocated)
  7829. this->setAllocatedSize (newAllocation);
  7830. }
  7831. lock.exit();
  7832. }
  7833. /** Locks the array's CriticalSection.
  7834. Of course if the type of section used is a DummyCriticalSection, this won't
  7835. have any effect.
  7836. @see unlockArray
  7837. */
  7838. void lockArray() const throw()
  7839. {
  7840. lock.enter();
  7841. }
  7842. /** Unlocks the array's CriticalSection.
  7843. Of course if the type of section used is a DummyCriticalSection, this won't
  7844. have any effect.
  7845. @see lockArray
  7846. */
  7847. void unlockArray() const throw()
  7848. {
  7849. lock.exit();
  7850. }
  7851. juce_UseDebuggingNewOperator
  7852. private:
  7853. int numUsed;
  7854. TypeOfCriticalSectionToUse lock;
  7855. };
  7856. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7857. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7858. #endif
  7859. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7860. #endif
  7861. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7862. /********* Start of inlined file: juce_SortedSet.h *********/
  7863. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7864. #define __JUCE_SORTEDSET_JUCEHEADER__
  7865. #if JUCE_MSVC
  7866. #pragma warning (push)
  7867. #pragma warning (disable: 4512)
  7868. #endif
  7869. /**
  7870. Holds a set of unique primitive objects, such as ints or doubles.
  7871. A set can only hold one item with a given value, so if for example it's a
  7872. set of integers, attempting to add the same integer twice will do nothing
  7873. the second time.
  7874. Internally, the list of items is kept sorted (which means that whatever
  7875. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7876. to determine the order), and searching the set for known values is very fast
  7877. because it uses a binary-chop method.
  7878. Note that if you're using a class or struct as the element type, it must be
  7879. capable of being copied or moved with a straightforward memcpy, rather than
  7880. needing construction and destruction code.
  7881. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7882. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7883. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7884. */
  7885. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7886. class SortedSet : private ArrayAllocationBase <ElementType>
  7887. {
  7888. public:
  7889. /** Creates an empty set.
  7890. @param granularity this is the size of increment by which the internal storage
  7891. used by the array will grow. Only change it from the default if you know the
  7892. array is going to be very big and needs to be able to grow efficiently.
  7893. @see ArrayAllocationBase
  7894. */
  7895. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7896. : ArrayAllocationBase <ElementType> (granularity),
  7897. numUsed (0)
  7898. {
  7899. }
  7900. /** Creates a copy of another set.
  7901. @param other the set to copy
  7902. */
  7903. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7904. : ArrayAllocationBase <ElementType> (other.granularity)
  7905. {
  7906. other.lockSet();
  7907. numUsed = other.numUsed;
  7908. setAllocatedSize (other.numUsed);
  7909. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7910. other.unlockSet();
  7911. }
  7912. /** Destructor. */
  7913. ~SortedSet() throw()
  7914. {
  7915. }
  7916. /** Copies another set over this one.
  7917. @param other the set to copy
  7918. */
  7919. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7920. {
  7921. if (this != &other)
  7922. {
  7923. other.lockSet();
  7924. lock.enter();
  7925. this->granularity = other.granularity;
  7926. ensureAllocatedSize (other.size());
  7927. numUsed = other.numUsed;
  7928. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7929. minimiseStorageOverheads();
  7930. lock.exit();
  7931. other.unlockSet();
  7932. }
  7933. return *this;
  7934. }
  7935. /** Compares this set to another one.
  7936. Two sets are considered equal if they both contain the same set of
  7937. elements.
  7938. @param other the other set to compare with
  7939. */
  7940. bool operator== (const SortedSet<ElementType>& other) const throw()
  7941. {
  7942. lock.enter();
  7943. if (numUsed != other.numUsed)
  7944. {
  7945. lock.exit();
  7946. return false;
  7947. }
  7948. for (int i = numUsed; --i >= 0;)
  7949. {
  7950. if (this->elements [i] != other.elements [i])
  7951. {
  7952. lock.exit();
  7953. return false;
  7954. }
  7955. }
  7956. lock.exit();
  7957. return true;
  7958. }
  7959. /** Compares this set to another one.
  7960. Two sets are considered equal if they both contain the same set of
  7961. elements.
  7962. @param other the other set to compare with
  7963. */
  7964. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7965. {
  7966. return ! operator== (other);
  7967. }
  7968. /** Removes all elements from the set.
  7969. This will remove all the elements, and free any storage that the set is
  7970. using. To clear it without freeing the storage, use the clearQuick()
  7971. method instead.
  7972. @see clearQuick
  7973. */
  7974. void clear() throw()
  7975. {
  7976. lock.enter();
  7977. this->setAllocatedSize (0);
  7978. numUsed = 0;
  7979. lock.exit();
  7980. }
  7981. /** Removes all elements from the set without freeing the array's allocated storage.
  7982. @see clear
  7983. */
  7984. void clearQuick() throw()
  7985. {
  7986. lock.enter();
  7987. numUsed = 0;
  7988. lock.exit();
  7989. }
  7990. /** Returns the current number of elements in the set.
  7991. */
  7992. inline int size() const throw()
  7993. {
  7994. return numUsed;
  7995. }
  7996. /** Returns one of the elements in the set.
  7997. If the index passed in is beyond the range of valid elements, this
  7998. will return zero.
  7999. If you're certain that the index will always be a valid element, you
  8000. can call getUnchecked() instead, which is faster.
  8001. @param index the index of the element being requested (0 is the first element in the set)
  8002. @see getUnchecked, getFirst, getLast
  8003. */
  8004. inline ElementType operator[] (const int index) const throw()
  8005. {
  8006. lock.enter();
  8007. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8008. ? this->elements [index]
  8009. : (ElementType) 0;
  8010. lock.exit();
  8011. return result;
  8012. }
  8013. /** Returns one of the elements in the set, without checking the index passed in.
  8014. Unlike the operator[] method, this will try to return an element without
  8015. checking that the index is within the bounds of the set, so should only
  8016. be used when you're confident that it will always be a valid index.
  8017. @param index the index of the element being requested (0 is the first element in the set)
  8018. @see operator[], getFirst, getLast
  8019. */
  8020. inline ElementType getUnchecked (const int index) const throw()
  8021. {
  8022. lock.enter();
  8023. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8024. const ElementType result = this->elements [index];
  8025. lock.exit();
  8026. return result;
  8027. }
  8028. /** Returns the first element in the set, or 0 if the set is empty.
  8029. @see operator[], getUnchecked, getLast
  8030. */
  8031. inline ElementType getFirst() const throw()
  8032. {
  8033. lock.enter();
  8034. const ElementType result = (numUsed > 0) ? this->elements [0]
  8035. : (ElementType) 0;
  8036. lock.exit();
  8037. return result;
  8038. }
  8039. /** Returns the last element in the set, or 0 if the set is empty.
  8040. @see operator[], getUnchecked, getFirst
  8041. */
  8042. inline ElementType getLast() const throw()
  8043. {
  8044. lock.enter();
  8045. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8046. : (ElementType) 0;
  8047. lock.exit();
  8048. return result;
  8049. }
  8050. /** Finds the index of the first element which matches the value passed in.
  8051. This will search the set for the given object, and return the index
  8052. of its first occurrence. If the object isn't found, the method will return -1.
  8053. @param elementToLookFor the value or object to look for
  8054. @returns the index of the object, or -1 if it's not found
  8055. */
  8056. int indexOf (const ElementType elementToLookFor) const throw()
  8057. {
  8058. lock.enter();
  8059. int start = 0;
  8060. int end = numUsed;
  8061. for (;;)
  8062. {
  8063. if (start >= end)
  8064. {
  8065. lock.exit();
  8066. return -1;
  8067. }
  8068. else if (elementToLookFor == this->elements [start])
  8069. {
  8070. lock.exit();
  8071. return start;
  8072. }
  8073. else
  8074. {
  8075. const int halfway = (start + end) >> 1;
  8076. if (halfway == start)
  8077. {
  8078. lock.exit();
  8079. return -1;
  8080. }
  8081. else if (elementToLookFor >= this->elements [halfway])
  8082. start = halfway;
  8083. else
  8084. end = halfway;
  8085. }
  8086. }
  8087. }
  8088. /** Returns true if the set contains at least one occurrence of an object.
  8089. @param elementToLookFor the value or object to look for
  8090. @returns true if the item is found
  8091. */
  8092. bool contains (const ElementType elementToLookFor) const throw()
  8093. {
  8094. lock.enter();
  8095. int start = 0;
  8096. int end = numUsed;
  8097. for (;;)
  8098. {
  8099. if (start >= end)
  8100. {
  8101. lock.exit();
  8102. return false;
  8103. }
  8104. else if (elementToLookFor == this->elements [start])
  8105. {
  8106. lock.exit();
  8107. return true;
  8108. }
  8109. else
  8110. {
  8111. const int halfway = (start + end) >> 1;
  8112. if (halfway == start)
  8113. {
  8114. lock.exit();
  8115. return false;
  8116. }
  8117. else if (elementToLookFor >= this->elements [halfway])
  8118. start = halfway;
  8119. else
  8120. end = halfway;
  8121. }
  8122. }
  8123. }
  8124. /** Adds a new element to the set, (as long as it's not already in there).
  8125. @param newElement the new object to add to the set
  8126. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8127. */
  8128. void add (const ElementType newElement) throw()
  8129. {
  8130. lock.enter();
  8131. int start = 0;
  8132. int end = numUsed;
  8133. for (;;)
  8134. {
  8135. if (start >= end)
  8136. {
  8137. jassert (start <= end);
  8138. insertInternal (start, newElement);
  8139. break;
  8140. }
  8141. else if (newElement == this->elements [start])
  8142. {
  8143. break;
  8144. }
  8145. else
  8146. {
  8147. const int halfway = (start + end) >> 1;
  8148. if (halfway == start)
  8149. {
  8150. if (newElement >= this->elements [halfway])
  8151. insertInternal (start + 1, newElement);
  8152. else
  8153. insertInternal (start, newElement);
  8154. break;
  8155. }
  8156. else if (newElement >= this->elements [halfway])
  8157. start = halfway;
  8158. else
  8159. end = halfway;
  8160. }
  8161. }
  8162. lock.exit();
  8163. }
  8164. /** Adds elements from an array to this set.
  8165. @param elementsToAdd the array of elements to add
  8166. @param numElementsToAdd how many elements are in this other array
  8167. @see add
  8168. */
  8169. void addArray (const ElementType* elementsToAdd,
  8170. int numElementsToAdd) throw()
  8171. {
  8172. lock.enter();
  8173. while (--numElementsToAdd >= 0)
  8174. add (*elementsToAdd++);
  8175. lock.exit();
  8176. }
  8177. /** Adds elements from another set to this one.
  8178. @param setToAddFrom the set from which to copy the elements
  8179. @param startIndex the first element of the other set to start copying from
  8180. @param numElementsToAdd how many elements to add from the other set. If this
  8181. value is negative or greater than the number of available elements,
  8182. all available elements will be copied.
  8183. @see add
  8184. */
  8185. template <class OtherSetType>
  8186. void addSet (const OtherSetType& setToAddFrom,
  8187. int startIndex = 0,
  8188. int numElementsToAdd = -1) throw()
  8189. {
  8190. setToAddFrom.lockSet();
  8191. lock.enter();
  8192. jassert (this != &setToAddFrom);
  8193. if (this != &setToAddFrom)
  8194. {
  8195. if (startIndex < 0)
  8196. {
  8197. jassertfalse
  8198. startIndex = 0;
  8199. }
  8200. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8201. numElementsToAdd = setToAddFrom.size() - startIndex;
  8202. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8203. }
  8204. lock.exit();
  8205. setToAddFrom.unlockSet();
  8206. }
  8207. /** Removes an element from the set.
  8208. This will remove the element at a given index.
  8209. If the index passed in is out-of-range, nothing will happen.
  8210. @param indexToRemove the index of the element to remove
  8211. @returns the element that has been removed
  8212. @see removeValue, removeRange
  8213. */
  8214. ElementType remove (const int indexToRemove) throw()
  8215. {
  8216. lock.enter();
  8217. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8218. {
  8219. --numUsed;
  8220. ElementType* const e = this->elements + indexToRemove;
  8221. ElementType const removed = *e;
  8222. const int numberToShift = numUsed - indexToRemove;
  8223. if (numberToShift > 0)
  8224. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8225. if ((numUsed << 1) < this->numAllocated)
  8226. minimiseStorageOverheads();
  8227. lock.exit();
  8228. return removed;
  8229. }
  8230. else
  8231. {
  8232. lock.exit();
  8233. return 0;
  8234. }
  8235. }
  8236. /** Removes an item from the set.
  8237. This will remove the given element from the set, if it's there.
  8238. @param valueToRemove the object to try to remove
  8239. @see remove, removeRange
  8240. */
  8241. void removeValue (const ElementType valueToRemove) throw()
  8242. {
  8243. lock.enter();
  8244. remove (indexOf (valueToRemove));
  8245. lock.exit();
  8246. }
  8247. /** Removes any elements which are also in another set.
  8248. @param otherSet the other set in which to look for elements to remove
  8249. @see removeValuesNotIn, remove, removeValue, removeRange
  8250. */
  8251. template <class OtherSetType>
  8252. void removeValuesIn (const OtherSetType& otherSet) throw()
  8253. {
  8254. otherSet.lockSet();
  8255. lock.enter();
  8256. if (this == &otherSet)
  8257. {
  8258. clear();
  8259. }
  8260. else
  8261. {
  8262. if (otherSet.size() > 0)
  8263. {
  8264. for (int i = numUsed; --i >= 0;)
  8265. if (otherSet.contains (this->elements [i]))
  8266. remove (i);
  8267. }
  8268. }
  8269. lock.exit();
  8270. otherSet.unlockSet();
  8271. }
  8272. /** Removes any elements which are not found in another set.
  8273. Only elements which occur in this other set will be retained.
  8274. @param otherSet the set in which to look for elements NOT to remove
  8275. @see removeValuesIn, remove, removeValue, removeRange
  8276. */
  8277. template <class OtherSetType>
  8278. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8279. {
  8280. otherSet.lockSet();
  8281. lock.enter();
  8282. if (this != &otherSet)
  8283. {
  8284. if (otherSet.size() <= 0)
  8285. {
  8286. clear();
  8287. }
  8288. else
  8289. {
  8290. for (int i = numUsed; --i >= 0;)
  8291. if (! otherSet.contains (this->elements [i]))
  8292. remove (i);
  8293. }
  8294. }
  8295. lock.exit();
  8296. otherSet.lockSet();
  8297. }
  8298. /** Reduces the amount of storage being used by the set.
  8299. Sets typically allocate slightly more storage than they need, and after
  8300. removing elements, they may have quite a lot of unused space allocated.
  8301. This method will reduce the amount of allocated storage to a minimum.
  8302. */
  8303. void minimiseStorageOverheads() throw()
  8304. {
  8305. lock.enter();
  8306. if (numUsed == 0)
  8307. {
  8308. this->setAllocatedSize (0);
  8309. }
  8310. else
  8311. {
  8312. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8313. if (newAllocation < this->numAllocated)
  8314. this->setAllocatedSize (newAllocation);
  8315. }
  8316. lock.exit();
  8317. }
  8318. /** Locks the set's CriticalSection.
  8319. Of course if the type of section used is a DummyCriticalSection, this won't
  8320. have any effect.
  8321. @see unlockSet
  8322. */
  8323. void lockSet() const throw()
  8324. {
  8325. lock.enter();
  8326. }
  8327. /** Unlocks the set's CriticalSection.
  8328. Of course if the type of section used is a DummyCriticalSection, this won't
  8329. have any effect.
  8330. @see lockSet
  8331. */
  8332. void unlockSet() const throw()
  8333. {
  8334. lock.exit();
  8335. }
  8336. juce_UseDebuggingNewOperator
  8337. private:
  8338. int numUsed;
  8339. TypeOfCriticalSectionToUse lock;
  8340. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8341. {
  8342. this->ensureAllocatedSize (numUsed + 1);
  8343. ElementType* const insertPos = this->elements + indexToInsertAt;
  8344. const int numberToMove = numUsed - indexToInsertAt;
  8345. if (numberToMove > 0)
  8346. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8347. *insertPos = newElement;
  8348. ++numUsed;
  8349. }
  8350. };
  8351. #if JUCE_MSVC
  8352. #pragma warning (pop)
  8353. #endif
  8354. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8355. /********* End of inlined file: juce_SortedSet.h *********/
  8356. #endif
  8357. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8358. /********* Start of inlined file: juce_SparseSet.h *********/
  8359. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8360. #define __JUCE_SPARSESET_JUCEHEADER__
  8361. /**
  8362. Holds a set of primitive values, storing them as a set of ranges.
  8363. This container acts like a simple BitArray, but can efficiently hold large
  8364. continguous ranges of values. It's quite a specialised class, mostly useful
  8365. for things like keeping the set of selected rows in a listbox.
  8366. The type used as a template paramter must be an integer type, such as int, short,
  8367. int64, etc.
  8368. */
  8369. template <class Type>
  8370. class SparseSet
  8371. {
  8372. public:
  8373. /** Creates a new empty set. */
  8374. SparseSet() throw()
  8375. {
  8376. }
  8377. /** Creates a copy of another SparseSet. */
  8378. SparseSet (const SparseSet<Type>& other) throw()
  8379. : values (other.values)
  8380. {
  8381. }
  8382. /** Destructor. */
  8383. ~SparseSet() throw()
  8384. {
  8385. }
  8386. /** Clears the set. */
  8387. void clear() throw()
  8388. {
  8389. values.clear();
  8390. }
  8391. /** Checks whether the set is empty.
  8392. This is much quicker than using (size() == 0).
  8393. */
  8394. bool isEmpty() const throw()
  8395. {
  8396. return values.size() == 0;
  8397. }
  8398. /** Returns the number of values in the set.
  8399. Because of the way the data is stored, this method can take longer if there
  8400. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8401. are any items.
  8402. */
  8403. Type size() const throw()
  8404. {
  8405. Type num = 0;
  8406. for (int i = 0; i < values.size(); i += 2)
  8407. num += values[i + 1] - values[i];
  8408. return num;
  8409. }
  8410. /** Returns one of the values in the set.
  8411. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8412. @returns the value at this index, or 0 if it's out-of-range
  8413. */
  8414. Type operator[] (int index) const throw()
  8415. {
  8416. for (int i = 0; i < values.size(); i += 2)
  8417. {
  8418. const Type s = values.getUnchecked(i);
  8419. const Type e = values.getUnchecked(i + 1);
  8420. if (index < e - s)
  8421. return s + index;
  8422. index -= e - s;
  8423. }
  8424. return (Type) 0;
  8425. }
  8426. /** Checks whether a particular value is in the set. */
  8427. bool contains (const Type valueToLookFor) const throw()
  8428. {
  8429. bool on = false;
  8430. for (int i = 0; i < values.size(); ++i)
  8431. {
  8432. if (values.getUnchecked(i) > valueToLookFor)
  8433. return on;
  8434. on = ! on;
  8435. }
  8436. return false;
  8437. }
  8438. /** Returns the number of contiguous blocks of values.
  8439. @see getRange
  8440. */
  8441. int getNumRanges() const throw()
  8442. {
  8443. return values.size() >> 1;
  8444. }
  8445. /** Returns one of the contiguous ranges of values stored.
  8446. @param rangeIndex the index of the range to look up, between 0
  8447. and (getNumRanges() - 1)
  8448. @param startValue on return, the value at the start of the range
  8449. @param numValues on return, the number of values in the range
  8450. @see getTotalRange
  8451. */
  8452. bool getRange (const int rangeIndex,
  8453. Type& startValue,
  8454. Type& numValues) const throw()
  8455. {
  8456. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8457. {
  8458. startValue = values [rangeIndex << 1];
  8459. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8460. return true;
  8461. }
  8462. return false;
  8463. }
  8464. /** Returns the lowest and highest values in the set.
  8465. @see getRange
  8466. */
  8467. bool getTotalRange (Type& lowestValue,
  8468. Type& highestValue) const throw()
  8469. {
  8470. if (values.size() > 0)
  8471. {
  8472. lowestValue = values.getUnchecked (0);
  8473. highestValue = values.getUnchecked (values.size() - 1);
  8474. return true;
  8475. }
  8476. return false;
  8477. }
  8478. /** Adds a range of contiguous values to the set.
  8479. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8480. @param firstValue the start of the range of values to add
  8481. @param numValuesToAdd how many values to add
  8482. */
  8483. void addRange (const Type firstValue,
  8484. const Type numValuesToAdd) throw()
  8485. {
  8486. jassert (numValuesToAdd >= 0);
  8487. if (numValuesToAdd > 0)
  8488. {
  8489. removeRange (firstValue, numValuesToAdd);
  8490. IntegerElementComparator<Type> sorter;
  8491. values.addSorted (sorter, firstValue);
  8492. values.addSorted (sorter, firstValue + numValuesToAdd);
  8493. simplify();
  8494. }
  8495. }
  8496. /** Removes a range of values from the set.
  8497. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8498. @param firstValue the start of the range of values to remove
  8499. @param numValuesToRemove how many values to remove
  8500. */
  8501. void removeRange (const Type firstValue,
  8502. const Type numValuesToRemove) throw()
  8503. {
  8504. jassert (numValuesToRemove >= 0);
  8505. if (numValuesToRemove > 0
  8506. && firstValue < values.getLast())
  8507. {
  8508. const bool onAtStart = contains (firstValue - 1);
  8509. Type lastValue = firstValue + numValuesToRemove;
  8510. if (lastValue < firstValue) // possible if the signed arithmetic wraps around
  8511. lastValue = values.getLast();
  8512. const bool onAtEnd = contains (lastValue);
  8513. for (int i = values.size(); --i >= 0;)
  8514. {
  8515. if (values.getUnchecked(i) >= firstValue
  8516. && values.getUnchecked(i) <= lastValue)
  8517. {
  8518. values.remove (i);
  8519. }
  8520. }
  8521. IntegerElementComparator<Type> sorter;
  8522. if (onAtStart)
  8523. values.addSorted (sorter, firstValue);
  8524. if (onAtEnd)
  8525. values.addSorted (sorter, lastValue);
  8526. simplify();
  8527. }
  8528. }
  8529. /** Does an XOR of the values in a given range. */
  8530. void invertRange (const Type firstValue,
  8531. const Type numValues)
  8532. {
  8533. SparseSet newItems;
  8534. newItems.addRange (firstValue, numValues);
  8535. int i;
  8536. for (i = getNumRanges(); --i >= 0;)
  8537. {
  8538. const int start = values [i << 1];
  8539. const int end = values [(i << 1) + 1];
  8540. newItems.removeRange (start, end);
  8541. }
  8542. removeRange (firstValue, numValues);
  8543. for (i = newItems.getNumRanges(); --i >= 0;)
  8544. {
  8545. const int start = newItems.values [i << 1];
  8546. const int end = newItems.values [(i << 1) + 1];
  8547. addRange (start, end);
  8548. }
  8549. }
  8550. /** Checks whether any part of a given range overlaps any part of this one. */
  8551. bool overlapsRange (const Type firstValue,
  8552. const Type numValues) throw()
  8553. {
  8554. jassert (numValues >= 0);
  8555. if (numValues > 0)
  8556. {
  8557. for (int i = getNumRanges(); --i >= 0;)
  8558. {
  8559. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8560. return false;
  8561. if (firstValue + numValues > values.getUnchecked (i << 1))
  8562. return true;
  8563. }
  8564. }
  8565. return false;
  8566. }
  8567. /** Checks whether the whole of a given range is contained within this one. */
  8568. bool containsRange (const Type firstValue,
  8569. const Type numValues) throw()
  8570. {
  8571. jassert (numValues >= 0);
  8572. if (numValues > 0)
  8573. {
  8574. for (int i = getNumRanges(); --i >= 0;)
  8575. {
  8576. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8577. return false;
  8578. if (firstValue >= values.getUnchecked (i << 1)
  8579. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8580. return true;
  8581. }
  8582. }
  8583. return false;
  8584. }
  8585. bool operator== (const SparseSet<Type>& other) throw()
  8586. {
  8587. return values == other.values;
  8588. }
  8589. bool operator!= (const SparseSet<Type>& other) throw()
  8590. {
  8591. return values != other.values;
  8592. }
  8593. juce_UseDebuggingNewOperator
  8594. private:
  8595. // alternating start/end values of ranges of values that are present.
  8596. Array<Type> values;
  8597. void simplify() throw()
  8598. {
  8599. jassert ((values.size() & 1) == 0);
  8600. for (int i = values.size(); --i > 0;)
  8601. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8602. values.removeRange (i - 1, 2);
  8603. }
  8604. };
  8605. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8606. /********* End of inlined file: juce_SparseSet.h *********/
  8607. #endif
  8608. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  8609. #endif
  8610. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  8611. #endif
  8612. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  8613. #endif
  8614. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8615. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  8616. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8617. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8618. /**
  8619. Searches through a the files in a directory, returning each file that is found.
  8620. A DirectoryIterator will search through a directory and its subdirectories using
  8621. a wildcard filepattern match.
  8622. If you may be finding a large number of files, this is better than
  8623. using File::findChildFiles() because it doesn't block while it finds them
  8624. all, and this is more memory-efficient.
  8625. It can also guess how far it's got using a wildly inaccurate algorithm.
  8626. */
  8627. class JUCE_API DirectoryIterator
  8628. {
  8629. public:
  8630. /** Creates a DirectoryIterator for a given directory.
  8631. After creating one of these, call its next() method to get the
  8632. first file - e.g. @code
  8633. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  8634. while (iter.next())
  8635. {
  8636. File theFileItFound (iter.getFile());
  8637. ... etc
  8638. }
  8639. @endcode
  8640. @param directory the directory to search in
  8641. @param isRecursive whether all the subdirectories should also be searched
  8642. @param wildCard the file pattern to match
  8643. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  8644. whether to look for files, directories, or both.
  8645. */
  8646. DirectoryIterator (const File& directory,
  8647. bool isRecursive,
  8648. const String& wildCard = JUCE_T("*"),
  8649. const int whatToLookFor = File::findFiles) throw();
  8650. /** Destructor. */
  8651. ~DirectoryIterator() throw();
  8652. /** Call this to move the iterator along to the next file.
  8653. @returns true if a file was found (you can then use getFile() to see what it was) - or
  8654. false if there are no more matching files.
  8655. */
  8656. bool next() throw();
  8657. /** Returns the file that the iterator is currently pointing at.
  8658. The result of this call is only valid after a call to next() has returned true.
  8659. */
  8660. const File getFile() const throw();
  8661. /** Returns a guess of how far through the search the iterator has got.
  8662. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  8663. very accurate.
  8664. */
  8665. float getEstimatedProgress() const throw();
  8666. juce_UseDebuggingNewOperator
  8667. private:
  8668. OwnedArray <File> filesFound;
  8669. OwnedArray <File> dirsFound;
  8670. String wildCard;
  8671. int index;
  8672. const int whatToLookFor;
  8673. DirectoryIterator* subIterator;
  8674. DirectoryIterator (const DirectoryIterator&);
  8675. const DirectoryIterator& operator= (const DirectoryIterator&);
  8676. };
  8677. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8678. /********* End of inlined file: juce_DirectoryIterator.h *********/
  8679. #endif
  8680. #ifndef __JUCE_FILE_JUCEHEADER__
  8681. #endif
  8682. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8683. /********* Start of inlined file: juce_FileInputStream.h *********/
  8684. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8685. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8686. /**
  8687. An input stream that reads from a local file.
  8688. @see InputStream, FileOutputStream, File::createInputStream
  8689. */
  8690. class JUCE_API FileInputStream : public InputStream
  8691. {
  8692. public:
  8693. /** Creates a FileInputStream.
  8694. @param fileToRead the file to read from - if the file can't be accessed for some
  8695. reason, then the stream will just contain no data
  8696. */
  8697. FileInputStream (const File& fileToRead);
  8698. /** Destructor. */
  8699. ~FileInputStream();
  8700. const File& getFile() const throw() { return file; }
  8701. int64 getTotalLength();
  8702. int read (void* destBuffer, int maxBytesToRead);
  8703. bool isExhausted();
  8704. int64 getPosition();
  8705. bool setPosition (int64 pos);
  8706. juce_UseDebuggingNewOperator
  8707. private:
  8708. File file;
  8709. void* fileHandle;
  8710. int64 currentPosition, totalSize;
  8711. bool needToSeek;
  8712. };
  8713. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8714. /********* End of inlined file: juce_FileInputStream.h *********/
  8715. #endif
  8716. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8717. /********* Start of inlined file: juce_FileOutputStream.h *********/
  8718. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8719. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8720. /**
  8721. An output stream that writes into a local file.
  8722. @see OutputStream, FileInputStream, File::createOutputStream
  8723. */
  8724. class JUCE_API FileOutputStream : public OutputStream
  8725. {
  8726. public:
  8727. /** Creates a FileOutputStream.
  8728. If the file doesn't exist, it will first be created. If the file can't be
  8729. created or opened, the failedToOpen() method will return
  8730. true.
  8731. If the file already exists when opened, the stream's write-postion will
  8732. be set to the end of the file. To overwrite an existing file,
  8733. use File::deleteFile() before opening the stream, or use setPosition(0)
  8734. after it's opened (although this won't truncate the file).
  8735. It's better to use File::createOutputStream() to create one of these, rather
  8736. than using the class directly.
  8737. */
  8738. FileOutputStream (const File& fileToWriteTo,
  8739. const int bufferSizeToUse = 16384);
  8740. /** Destructor. */
  8741. ~FileOutputStream();
  8742. /** Returns the file that this stream is writing to.
  8743. */
  8744. const File& getFile() const throw() { return file; }
  8745. /** Returns true if the stream couldn't be opened for some reason.
  8746. */
  8747. bool failedToOpen() const throw() { return fileHandle == 0; }
  8748. void flush();
  8749. int64 getPosition();
  8750. bool setPosition (int64 pos);
  8751. bool write (const void* data, int numBytes);
  8752. juce_UseDebuggingNewOperator
  8753. private:
  8754. File file;
  8755. void* fileHandle;
  8756. int64 currentPosition;
  8757. int bufferSize, bytesInBuffer;
  8758. char* buffer;
  8759. };
  8760. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8761. /********* End of inlined file: juce_FileOutputStream.h *********/
  8762. #endif
  8763. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8764. /********* Start of inlined file: juce_FileSearchPath.h *********/
  8765. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8766. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  8767. /**
  8768. Encapsulates a set of folders that make up a search path.
  8769. @see File
  8770. */
  8771. class JUCE_API FileSearchPath
  8772. {
  8773. public:
  8774. /** Creates an empty search path. */
  8775. FileSearchPath();
  8776. /** Creates a search path from a string of pathnames.
  8777. The path can be semicolon- or comma-separated, e.g.
  8778. "/foo/bar;/foo/moose;/fish/moose"
  8779. The separate folders are tokenised and added to the search path.
  8780. */
  8781. FileSearchPath (const String& path);
  8782. /** Creates a copy of another search path. */
  8783. FileSearchPath (const FileSearchPath& other);
  8784. /** Destructor. */
  8785. ~FileSearchPath();
  8786. /** Uses a string containing a list of pathnames to re-initialise this list.
  8787. This search path is cleared and the semicolon- or comma-separated folders
  8788. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  8789. */
  8790. const FileSearchPath& operator= (const String& path);
  8791. /** Returns the number of folders in this search path.
  8792. @see operator[]
  8793. */
  8794. int getNumPaths() const;
  8795. /** Returns one of the folders in this search path.
  8796. The file returned isn't guaranteed to actually be a valid directory.
  8797. @see getNumPaths
  8798. */
  8799. const File operator[] (const int index) const;
  8800. /** Returns the search path as a semicolon-separated list of directories. */
  8801. const String toString() const;
  8802. /** Adds a new directory to the search path.
  8803. The new directory is added to the end of the list if the insertIndex parameter is
  8804. less than zero, otherwise it is inserted at the given index.
  8805. */
  8806. void add (const File& directoryToAdd,
  8807. const int insertIndex = -1);
  8808. /** Adds a new directory to the search path if it's not already in there. */
  8809. void addIfNotAlreadyThere (const File& directoryToAdd);
  8810. /** Removes a directory from the search path. */
  8811. void remove (const int indexToRemove);
  8812. /** Merges another search path into this one.
  8813. This will remove any duplicate directories.
  8814. */
  8815. void addPath (const FileSearchPath& other);
  8816. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  8817. If the search is intended to be recursive, there's no point having nested folders in the search
  8818. path, because they'll just get searched twice and you'll get duplicate results.
  8819. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  8820. */
  8821. void removeRedundantPaths();
  8822. /** Removes any directories that don't actually exist. */
  8823. void removeNonExistentPaths();
  8824. /** Searches the path for a wildcard.
  8825. This will search all the directories in the search path in order, adding any
  8826. matching files to the results array.
  8827. @param results an array to append the results to
  8828. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  8829. return files, directories, or both.
  8830. @param searchRecursively whether to recursively search the subdirectories too
  8831. @param wildCardPattern a pattern to match against the filenames
  8832. @returns the number of files added to the array
  8833. @see File::findChildFiles
  8834. */
  8835. int findChildFiles (OwnedArray<File>& results,
  8836. const int whatToLookFor,
  8837. const bool searchRecursively,
  8838. const String& wildCardPattern = JUCE_T("*")) const;
  8839. /** Finds out whether a file is inside one of the path's directories.
  8840. This will return true if the specified file is a child of one of the
  8841. directories specified by this path. Note that this doesn't actually do any
  8842. searching or check that the files exist - it just looks at the pathnames
  8843. to work out whether the file would be inside a directory.
  8844. @param fileToCheck the file to look for
  8845. @param checkRecursively if true, then this will return true if the file is inside a
  8846. subfolder of one of the path's directories (at any depth). If false
  8847. it will only return true if the file is actually a direct child
  8848. of one of the directories.
  8849. @see File::isAChildOf
  8850. */
  8851. bool isFileInPath (const File& fileToCheck,
  8852. const bool checkRecursively) const;
  8853. juce_UseDebuggingNewOperator
  8854. private:
  8855. StringArray directories;
  8856. void init (const String& path);
  8857. };
  8858. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  8859. /********* End of inlined file: juce_FileSearchPath.h *********/
  8860. #endif
  8861. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8862. /********* Start of inlined file: juce_NamedPipe.h *********/
  8863. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8864. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  8865. /**
  8866. A cross-process pipe that can have data written to and read from it.
  8867. Two or more processes can use these for inter-process communication.
  8868. @see InterprocessConnection
  8869. */
  8870. class JUCE_API NamedPipe
  8871. {
  8872. public:
  8873. /** Creates a NamedPipe. */
  8874. NamedPipe();
  8875. /** Destructor. */
  8876. ~NamedPipe();
  8877. /** Tries to open a pipe that already exists.
  8878. Returns true if it succeeds.
  8879. */
  8880. bool openExisting (const String& pipeName);
  8881. /** Tries to create a new pipe.
  8882. Returns true if it succeeds.
  8883. */
  8884. bool createNewPipe (const String& pipeName);
  8885. /** Closes the pipe, if it's open. */
  8886. void close();
  8887. /** True if the pipe is currently open. */
  8888. bool isOpen() const throw();
  8889. /** Returns the last name that was used to try to open this pipe. */
  8890. const String getName() const throw();
  8891. /** Reads data from the pipe.
  8892. This will block until another thread has written enough data into the pipe to fill
  8893. the number of bytes specified, or until another thread calls the cancelPendingReads()
  8894. method.
  8895. If the operation fails, it returns -1, otherwise, it will return the number of
  8896. bytes read.
  8897. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  8898. this is a maximum timeout for reading from the pipe.
  8899. */
  8900. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  8901. /** Writes some data to the pipe.
  8902. If the operation fails, it returns -1, otherwise, it will return the number of
  8903. bytes written.
  8904. */
  8905. int write (const void* sourceBuffer, int numBytesToWrite,
  8906. int timeOutMilliseconds = 2000);
  8907. /** If any threads are currently blocked on a read operation, this tells them to abort.
  8908. */
  8909. void cancelPendingReads();
  8910. juce_UseDebuggingNewOperator
  8911. private:
  8912. void* internal;
  8913. String currentPipeName;
  8914. NamedPipe (const NamedPipe&);
  8915. const NamedPipe& operator= (const NamedPipe&);
  8916. bool openInternal (const String& pipeName, const bool createPipe);
  8917. };
  8918. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  8919. /********* End of inlined file: juce_NamedPipe.h *********/
  8920. #endif
  8921. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8922. /********* Start of inlined file: juce_BlowFish.h *********/
  8923. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8924. #define __JUCE_BLOWFISH_JUCEHEADER__
  8925. /**
  8926. BlowFish encryption class.
  8927. */
  8928. class JUCE_API BlowFish
  8929. {
  8930. public:
  8931. /** Creates an object that can encode/decode based on the specified key.
  8932. The key data can be up to 72 bytes long.
  8933. */
  8934. BlowFish (const uint8* keyData, int keyBytes);
  8935. /** Creates a copy of another blowfish object. */
  8936. BlowFish (const BlowFish& other);
  8937. /** Copies another blowfish object. */
  8938. const BlowFish& operator= (const BlowFish& other);
  8939. /** Destructor. */
  8940. ~BlowFish();
  8941. /** Encrypts a pair of 32-bit integers. */
  8942. void encrypt (uint32& data1, uint32& data2) const;
  8943. /** Decrypts a pair of 32-bit integers. */
  8944. void decrypt (uint32& data1, uint32& data2) const;
  8945. juce_UseDebuggingNewOperator
  8946. private:
  8947. uint32 p[18];
  8948. uint32* s[4];
  8949. uint32 F (uint32 x) const;
  8950. };
  8951. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  8952. /********* End of inlined file: juce_BlowFish.h *********/
  8953. #endif
  8954. #ifndef __JUCE_MD5_JUCEHEADER__
  8955. /********* Start of inlined file: juce_MD5.h *********/
  8956. #ifndef __JUCE_MD5_JUCEHEADER__
  8957. #define __JUCE_MD5_JUCEHEADER__
  8958. /**
  8959. MD5 checksum class.
  8960. Create one of these with a block of source data or a string, and it calculates the
  8961. MD5 checksum of that data.
  8962. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  8963. */
  8964. class JUCE_API MD5
  8965. {
  8966. public:
  8967. /** Creates a null MD5 object. */
  8968. MD5();
  8969. /** Creates a copy of another MD5. */
  8970. MD5 (const MD5& other);
  8971. /** Copies another MD5. */
  8972. const MD5& operator= (const MD5& other);
  8973. /** Creates a checksum for a block of binary data. */
  8974. MD5 (const MemoryBlock& data);
  8975. /** Creates a checksum for a block of binary data. */
  8976. MD5 (const char* data, const int numBytes);
  8977. /** Creates a checksum for a string. */
  8978. MD5 (const String& text);
  8979. /** Creates a checksum for the input from a stream.
  8980. This will read up to the given number of bytes from the stream, and produce the
  8981. checksum of that. If the number of bytes to read is negative, it'll read
  8982. until the stream is exhausted.
  8983. */
  8984. MD5 (InputStream& input, int numBytesToRead = -1);
  8985. /** Creates a checksum for a file. */
  8986. MD5 (const File& file);
  8987. /** Destructor. */
  8988. ~MD5();
  8989. /** Returns the checksum as a 16-byte block of data. */
  8990. const MemoryBlock getRawChecksumData() const;
  8991. /** Returns the checksum as a 32-digit hex string. */
  8992. const String toHexString() const;
  8993. /** Compares this to another MD5. */
  8994. bool operator== (const MD5& other) const;
  8995. /** Compares this to another MD5. */
  8996. bool operator!= (const MD5& other) const;
  8997. juce_UseDebuggingNewOperator
  8998. private:
  8999. uint8 result [16];
  9000. struct ProcessContext
  9001. {
  9002. uint8 buffer [64];
  9003. uint32 state [4];
  9004. uint32 count [2];
  9005. ProcessContext();
  9006. void processBlock (const uint8* const data, int dataSize);
  9007. void transform (const uint8* const buffer);
  9008. void finish (uint8* const result);
  9009. };
  9010. void processStream (InputStream& input, int numBytesToRead);
  9011. };
  9012. #endif // __JUCE_MD5_JUCEHEADER__
  9013. /********* End of inlined file: juce_MD5.h *********/
  9014. #endif
  9015. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9016. /********* Start of inlined file: juce_Primes.h *********/
  9017. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9018. #define __JUCE_PRIMES_JUCEHEADER__
  9019. /**
  9020. Prime number creation class.
  9021. This class contains static methods for generating and testing prime numbers.
  9022. @see BitArray
  9023. */
  9024. class JUCE_API Primes
  9025. {
  9026. public:
  9027. /** Creates a random prime number with a given bit-length.
  9028. The certainty parameter specifies how many iterations to use when testing
  9029. for primality. A safe value might be anything over about 20-30.
  9030. The randomSeeds parameter lets you optionally pass it a set of values with
  9031. which to seed the random number generation, improving the security of the
  9032. keys generated.
  9033. */
  9034. static const BitArray createProbablePrime (int bitLength,
  9035. int certainty,
  9036. const int* randomSeeds = 0,
  9037. int numRandomSeeds = 0) throw();
  9038. /** Tests a number to see if it's prime.
  9039. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9040. whether the number is prime.
  9041. The certainty parameter specifies how many iterations to use when testing - a
  9042. safe value might be anything over about 20-30.
  9043. */
  9044. static bool isProbablyPrime (const BitArray& number,
  9045. int certainty) throw();
  9046. };
  9047. #endif // __JUCE_PRIMES_JUCEHEADER__
  9048. /********* End of inlined file: juce_Primes.h *********/
  9049. #endif
  9050. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9051. /********* Start of inlined file: juce_RSAKey.h *********/
  9052. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9053. #define __JUCE_RSAKEY_JUCEHEADER__
  9054. /**
  9055. RSA public/private key-pair encryption class.
  9056. An object of this type makes up one half of a public/private RSA key pair. Use the
  9057. createKeyPair() method to create a matching pair for encoding/decoding.
  9058. */
  9059. class JUCE_API RSAKey
  9060. {
  9061. public:
  9062. /** Creates a null key object.
  9063. Initialise a pair of objects for use with the createKeyPair() method.
  9064. */
  9065. RSAKey() throw();
  9066. /** Loads a key from an encoded string representation.
  9067. This reloads a key from a string created by the toString() method.
  9068. */
  9069. RSAKey (const String& stringRepresentation) throw();
  9070. /** Destructor. */
  9071. ~RSAKey() throw();
  9072. /** Turns the key into a string representation.
  9073. This can be reloaded using the constructor that takes a string.
  9074. */
  9075. const String toString() const throw();
  9076. /** Encodes or decodes a value.
  9077. Call this on the public key object to encode some data, then use the matching
  9078. private key object to decode it.
  9079. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9080. */
  9081. bool applyToValue (BitArray& value) const throw();
  9082. /** Creates a public/private key-pair.
  9083. Each key will perform one-way encryption that can only be reversed by
  9084. using the other key.
  9085. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9086. sizes are more secure, but this method will take longer to execute.
  9087. The randomSeeds parameter lets you optionally pass it a set of values with
  9088. which to seed the random number generation, improving the security of the
  9089. keys generated.
  9090. */
  9091. static void createKeyPair (RSAKey& publicKey,
  9092. RSAKey& privateKey,
  9093. const int numBits,
  9094. const int* randomSeeds = 0,
  9095. const int numRandomSeeds = 0) throw();
  9096. juce_UseDebuggingNewOperator
  9097. protected:
  9098. BitArray part1, part2;
  9099. };
  9100. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9101. /********* End of inlined file: juce_RSAKey.h *********/
  9102. #endif
  9103. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9104. /********* Start of inlined file: juce_Socket.h *********/
  9105. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9106. #define __JUCE_SOCKET_JUCEHEADER__
  9107. /**
  9108. A wrapper for a streaming (TCP) socket.
  9109. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9110. sockets, you could also try the InterprocessConnection class.
  9111. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9112. */
  9113. class JUCE_API StreamingSocket
  9114. {
  9115. public:
  9116. /** Creates an uninitialised socket.
  9117. To connect it, use the connect() method, after which you can read() or write()
  9118. to it.
  9119. To wait for other sockets to connect to this one, the createListener() method
  9120. enters "listener" mode, and can be used to spawn new sockets for each connection
  9121. that comes along.
  9122. */
  9123. StreamingSocket();
  9124. /** Destructor. */
  9125. ~StreamingSocket();
  9126. /** Binds the socket to the specified local port.
  9127. @returns true on success; false may indicate that another socket is already bound
  9128. on the same port
  9129. */
  9130. bool bindToPort (const int localPortNumber);
  9131. /** Tries to connect the socket to hostname:port.
  9132. If timeOutMillisecs is 0, then this method will block until the operating system
  9133. rejects the connection (which could take a long time).
  9134. @returns true if it succeeds.
  9135. @see isConnected
  9136. */
  9137. bool connect (const String& remoteHostname,
  9138. const int remotePortNumber,
  9139. const int timeOutMillisecs = 3000);
  9140. /** True if the socket is currently connected. */
  9141. bool isConnected() const throw() { return connected; }
  9142. /** Closes the connection. */
  9143. void close();
  9144. /** Returns the name of the currently connected host. */
  9145. const String& getHostName() const throw() { return hostName; }
  9146. /** Returns the port number that's currently open. */
  9147. int getPort() const throw() { return portNumber; }
  9148. /** True if the socket is connected to this machine rather than over the network. */
  9149. bool isLocal() const throw();
  9150. /** Waits until the socket is ready for reading or writing.
  9151. If readyForReading is true, it will wait until the socket is ready for
  9152. reading; if false, it will wait until it's ready for writing.
  9153. If the timeout is < 0, it will wait forever, or else will give up after
  9154. the specified time.
  9155. If the socket is ready on return, this returns 1. If it times-out before
  9156. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9157. */
  9158. int waitUntilReady (const bool readyForReading,
  9159. const int timeoutMsecs) const;
  9160. /** Reads bytes from the socket (blocking).
  9161. Note that this method will block unless you have checked the socket is ready
  9162. for reading before calling it (see the waitUntilReady() method).
  9163. @returns the number of bytes read, or -1 if there was an error.
  9164. */
  9165. int read (void* destBuffer, const int maxBytesToRead);
  9166. /** Writes bytes to the socket from a buffer.
  9167. Note that this method will block unless you have checked the socket is ready
  9168. for writing before calling it (see the waitUntilReady() method).
  9169. @returns the number of bytes written, or -1 if there was an error.
  9170. */
  9171. int write (const void* sourceBuffer, const int numBytesToWrite);
  9172. /** Puts this socket into "listener" mode.
  9173. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9174. which will spawn new sockets for each new connection, so that these can
  9175. be handled in parallel by other threads.
  9176. This returns true if it manages to open the socket successfully.
  9177. @see waitForNextConnection
  9178. */
  9179. bool createListener (const int portNumber);
  9180. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9181. socket.
  9182. The object that gets returned will be owned by the caller.
  9183. This method can only be called after using createListener().
  9184. @see createListener
  9185. */
  9186. StreamingSocket* waitForNextConnection() const;
  9187. juce_UseDebuggingNewOperator
  9188. private:
  9189. String hostName;
  9190. int volatile portNumber, handle;
  9191. bool connected, isListener;
  9192. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9193. StreamingSocket (const StreamingSocket&);
  9194. const StreamingSocket& operator= (const StreamingSocket&);
  9195. };
  9196. /**
  9197. A wrapper for a datagram (UDP) socket.
  9198. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9199. sockets, you could also try the InterprocessConnection class.
  9200. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9201. */
  9202. class JUCE_API DatagramSocket
  9203. {
  9204. public:
  9205. /**
  9206. Creates an (uninitialised) datagram socket.
  9207. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9208. the port number is assigned by the operating system.
  9209. To use the socket for sending, call the connect() method. This will not immediately
  9210. make a connection, but will save the destination you've provided. After this, you can
  9211. call read() or write().
  9212. To wait for other sockets to connect to this one, call waitForNextConnection().
  9213. */
  9214. DatagramSocket (const int localPortNumber);
  9215. /** Destructor. */
  9216. ~DatagramSocket();
  9217. /** Binds the socket to the specified local port.
  9218. @returns true on success; false may indicate that another socket is already bound
  9219. on the same port
  9220. */
  9221. bool bindToPort (const int localPortNumber);
  9222. /** Tries to connect the socket to hostname:port.
  9223. If timeOutMillisecs is 0, then this method will block until the operating system
  9224. rejects the connection (which could take a long time).
  9225. @returns true if it succeeds.
  9226. @see isConnected
  9227. */
  9228. bool connect (const String& remoteHostname,
  9229. const int remotePortNumber,
  9230. const int timeOutMillisecs = 3000);
  9231. /** True if the socket is currently connected. */
  9232. bool isConnected() const throw() { return connected; }
  9233. /** Closes the connection. */
  9234. void close();
  9235. /** Returns the name of the currently connected host. */
  9236. const String& getHostName() const throw() { return hostName; }
  9237. /** Returns the port number that's currently open. */
  9238. int getPort() const throw() { return portNumber; }
  9239. /** True if the socket is connected to this machine rather than over the network. */
  9240. bool isLocal() const throw();
  9241. /** Waits until the socket is ready for reading or writing.
  9242. If readyForReading is true, it will wait until the socket is ready for
  9243. reading; if false, it will wait until it's ready for writing.
  9244. If the timeout is < 0, it will wait forever, or else will give up after
  9245. the specified time.
  9246. If the socket is ready on return, this returns 1. If it times-out before
  9247. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9248. */
  9249. int waitUntilReady (const bool readyForReading,
  9250. const int timeoutMsecs) const;
  9251. /** Reads bytes from the socket (blocking).
  9252. Note that this method will block unless you have checked the socket is ready
  9253. for reading before calling it (see the waitUntilReady() method).
  9254. @returns the number of bytes read, or -1 if there was an error.
  9255. */
  9256. int read (void* destBuffer, const int maxBytesToRead);
  9257. /** Writes bytes to the socket from a buffer.
  9258. Note that this method will block unless you have checked the socket is ready
  9259. for writing before calling it (see the waitUntilReady() method).
  9260. @returns the number of bytes written, or -1 if there was an error.
  9261. */
  9262. int write (const void* sourceBuffer, const int numBytesToWrite);
  9263. /** This waits for incoming data to be sent, and returns a socket that can be used
  9264. to read it.
  9265. The object that gets returned is owned by the caller, and can't be used for
  9266. sending, but can be used to read the data.
  9267. */
  9268. DatagramSocket* waitForNextConnection() const;
  9269. juce_UseDebuggingNewOperator
  9270. private:
  9271. String hostName;
  9272. int volatile portNumber, handle;
  9273. bool connected;
  9274. void* serverAddress;
  9275. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9276. DatagramSocket (const DatagramSocket&);
  9277. const DatagramSocket& operator= (const DatagramSocket&);
  9278. };
  9279. #endif // __JUCE_SOCKET_JUCEHEADER__
  9280. /********* End of inlined file: juce_Socket.h *********/
  9281. #endif
  9282. #ifndef __JUCE_URL_JUCEHEADER__
  9283. /********* Start of inlined file: juce_URL.h *********/
  9284. #ifndef __JUCE_URL_JUCEHEADER__
  9285. #define __JUCE_URL_JUCEHEADER__
  9286. /**
  9287. Represents a URL and has a bunch of useful functions to manipulate it.
  9288. This class can be used to launch URLs in browsers, and also to create
  9289. InputStreams that can read from remote http or ftp sources.
  9290. */
  9291. class JUCE_API URL
  9292. {
  9293. public:
  9294. /** Creates an empty URL. */
  9295. URL() throw();
  9296. /** Creates a URL from a string. */
  9297. URL (const String& url);
  9298. /** Creates a copy of another URL. */
  9299. URL (const URL& other);
  9300. /** Destructor. */
  9301. ~URL() throw();
  9302. /** Copies this URL from another one. */
  9303. const URL& operator= (const URL& other);
  9304. /** Returns a string version of the URL.
  9305. If includeGetParameters is true and any parameters have been set with the
  9306. withParameter() method, then the string will have these appended on the
  9307. end and url-encoded.
  9308. */
  9309. const String toString (const bool includeGetParameters) const;
  9310. /** True if it seems to be valid. */
  9311. bool isWellFormed() const;
  9312. /** Returns a copy of this URL, with a GET parameter added to the end.
  9313. Any control characters in the value will be encoded.
  9314. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  9315. would produce a new url whose toString(true) method would return
  9316. "www.fish.com?amount=some+fish".
  9317. */
  9318. const URL withParameter (const String& parameterName,
  9319. const String& parameterValue) const;
  9320. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  9321. When performing a POST where one of your parameters is a binary file, this
  9322. lets you specify the file.
  9323. Note that the filename is stored, but the file itself won't actually be read
  9324. until this URL is later used to create a network input stream.
  9325. */
  9326. const URL withFileToUpload (const String& parameterName,
  9327. const File& fileToUpload,
  9328. const String& mimeType) const;
  9329. /** Returns a set of all the parameters encoded into the url.
  9330. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  9331. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  9332. The values returned will have been cleaned up to remove any escape characters.
  9333. @see getNamedParameter, withParameter
  9334. */
  9335. const StringPairArray& getParameters() const throw();
  9336. /** Returns the set of files that should be uploaded as part of a POST operation.
  9337. This is the set of files that were added to the URL with the withFileToUpload()
  9338. method.
  9339. */
  9340. const StringPairArray& getFilesToUpload() const throw();
  9341. /** Returns the set of mime types associated with each of the upload files.
  9342. */
  9343. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  9344. /** Tries to launch the system's default browser to open the URL.
  9345. Returns true if this seems to have worked.
  9346. */
  9347. bool launchInDefaultBrowser() const;
  9348. /** Takes a guess as to whether a string might be a valid website address.
  9349. This isn't foolproof!
  9350. */
  9351. static bool isProbablyAWebsiteURL (const String& possibleURL);
  9352. /** Takes a guess as to whether a string might be a valid email address.
  9353. This isn't foolproof!
  9354. */
  9355. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  9356. /** This callback function can be used by the createInputStream() method.
  9357. It allows your app to receive progress updates during a lengthy POST operation. If you
  9358. want to continue the operation, this should return true, or false to abort.
  9359. */
  9360. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  9361. /** Attempts to open a stream that can read from this URL.
  9362. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  9363. the paramters, otherwise it'll encode them into the
  9364. URL and do a 'GET'.
  9365. @param progressCallback if this is non-zero, it lets you supply a callback function
  9366. to keep track of the operation's progress. This can be useful
  9367. for lengthy POST operations, so that you can provide user feedback.
  9368. @param progressCallbackContext if a callback is specified, this value will be passed to
  9369. the function
  9370. @param extraHeaders if not empty, this string is appended onto the headers that
  9371. are used for the request. It must therefore be a valid set of HTML
  9372. header directives, separated by newlines.
  9373. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  9374. a negative number, it will be infinite. Otherwise it specifies a
  9375. time in milliseconds.
  9376. */
  9377. InputStream* createInputStream (const bool usePostCommand,
  9378. OpenStreamProgressCallback* const progressCallback = 0,
  9379. void* const progressCallbackContext = 0,
  9380. const String& extraHeaders = String::empty,
  9381. const int connectionTimeOutMs = 0) const;
  9382. /** Tries to download the entire contents of this URL into a binary data block.
  9383. If it succeeds, this will return true and append the data it read onto the end
  9384. of the memory block.
  9385. @param destData the memory block to append the new data to
  9386. @param usePostCommand whether to use a POST command to get the data (uses
  9387. a GET command if this is false)
  9388. @see readEntireTextStream, readEntireXmlStream
  9389. */
  9390. bool readEntireBinaryStream (MemoryBlock& destData,
  9391. const bool usePostCommand = false) const;
  9392. /** Tries to download the entire contents of this URL as a string.
  9393. If it fails, this will return an empty string, otherwise it will return the
  9394. contents of the downloaded file. If you need to distinguish between a read
  9395. operation that fails and one that returns an empty string, you'll need to use
  9396. a different method, such as readEntireBinaryStream().
  9397. @param usePostCommand whether to use a POST command to get the data (uses
  9398. a GET command if this is false)
  9399. @see readEntireBinaryStream, readEntireXmlStream
  9400. */
  9401. const String readEntireTextStream (const bool usePostCommand = false) const;
  9402. /** Tries to download the entire contents of this URL and parse it as XML.
  9403. If it fails, or if the text that it reads can't be parsed as XML, this will
  9404. return 0.
  9405. When it returns a valid XmlElement object, the caller is responsibile for deleting
  9406. this object when no longer needed.
  9407. @param usePostCommand whether to use a POST command to get the data (uses
  9408. a GET command if this is false)
  9409. @see readEntireBinaryStream, readEntireTextStream
  9410. */
  9411. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  9412. /** Adds escape sequences to a string to encode any characters that aren't
  9413. legal in a URL.
  9414. E.g. any spaces will be replaced with "%20".
  9415. This is the opposite of removeEscapeChars().
  9416. If isParameter is true, it means that the string is going to be used
  9417. as a parameter, so it also encodes '$' and ',' (which would otherwise
  9418. be legal in a URL.
  9419. @see removeEscapeChars
  9420. */
  9421. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  9422. const bool isParameter);
  9423. /** Replaces any escape character sequences in a string with their original
  9424. character codes.
  9425. E.g. any instances of "%20" will be replaced by a space.
  9426. This is the opposite of addEscapeChars().
  9427. @see addEscapeChars
  9428. */
  9429. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  9430. juce_UseDebuggingNewOperator
  9431. private:
  9432. String url;
  9433. StringPairArray parameters, filesToUpload, mimeTypes;
  9434. };
  9435. #endif // __JUCE_URL_JUCEHEADER__
  9436. /********* End of inlined file: juce_URL.h *********/
  9437. #endif
  9438. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9439. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9440. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9441. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9442. /** Wraps another input stream, and reads from it using an intermediate buffer
  9443. If you're using an input stream such as a file input stream, and making lots of
  9444. small read accesses to it, it's probably sensible to wrap it in one of these,
  9445. so that the source stream gets accessed in larger chunk sizes, meaning less
  9446. work for the underlying stream.
  9447. */
  9448. class JUCE_API BufferedInputStream : public InputStream
  9449. {
  9450. public:
  9451. /** Creates a BufferedInputStream from an input source.
  9452. @param sourceStream the source stream to read from
  9453. @param bufferSize the size of reservoir to use to buffer the source
  9454. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9455. deleted by this object when it is itself deleted.
  9456. */
  9457. BufferedInputStream (InputStream* const sourceStream,
  9458. const int bufferSize,
  9459. const bool deleteSourceWhenDestroyed) throw();
  9460. /** Destructor.
  9461. This may also delete the source stream, if that option was chosen when the
  9462. buffered stream was created.
  9463. */
  9464. ~BufferedInputStream() throw();
  9465. int64 getTotalLength();
  9466. int64 getPosition();
  9467. bool setPosition (int64 newPosition);
  9468. int read (void* destBuffer, int maxBytesToRead);
  9469. const String readString();
  9470. bool isExhausted();
  9471. juce_UseDebuggingNewOperator
  9472. private:
  9473. InputStream* const source;
  9474. const bool deleteSourceWhenDestroyed;
  9475. int bufferSize;
  9476. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9477. char* buffer;
  9478. void ensureBuffered();
  9479. BufferedInputStream (const BufferedInputStream&);
  9480. const BufferedInputStream& operator= (const BufferedInputStream&);
  9481. };
  9482. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9483. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9484. #endif
  9485. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9486. /********* Start of inlined file: juce_FileInputSource.h *********/
  9487. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9488. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9489. /********* Start of inlined file: juce_InputSource.h *********/
  9490. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9491. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9492. /**
  9493. A lightweight object that can create a stream to read some kind of resource.
  9494. This may be used to refer to a file, or some other kind of source, allowing a
  9495. caller to create an input stream that can read from it when required.
  9496. @see FileInputSource
  9497. */
  9498. class JUCE_API InputSource
  9499. {
  9500. public:
  9501. InputSource() throw() {}
  9502. /** Destructor. */
  9503. virtual ~InputSource() {}
  9504. /** Returns a new InputStream to read this item.
  9505. @returns an inputstream that the caller will delete, or 0 if
  9506. the filename isn't found.
  9507. */
  9508. virtual InputStream* createInputStream() = 0;
  9509. /** Returns a new InputStream to read an item, relative.
  9510. @param relatedItemPath the relative pathname of the resource that is required
  9511. @returns an inputstream that the caller will delete, or 0 if
  9512. the item isn't found.
  9513. */
  9514. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9515. /** Returns a hash code that uniquely represents this item.
  9516. */
  9517. virtual int64 hashCode() const = 0;
  9518. juce_UseDebuggingNewOperator
  9519. };
  9520. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9521. /********* End of inlined file: juce_InputSource.h *********/
  9522. /**
  9523. A type of InputSource that represents a normal file.
  9524. @see InputSource
  9525. */
  9526. class JUCE_API FileInputSource : public InputSource
  9527. {
  9528. public:
  9529. FileInputSource (const File& file) throw();
  9530. ~FileInputSource();
  9531. InputStream* createInputStream();
  9532. InputStream* createInputStreamFor (const String& relatedItemPath);
  9533. int64 hashCode() const;
  9534. juce_UseDebuggingNewOperator
  9535. private:
  9536. const File file;
  9537. FileInputSource (const FileInputSource&);
  9538. const FileInputSource& operator= (const FileInputSource&);
  9539. };
  9540. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9541. /********* End of inlined file: juce_FileInputSource.h *********/
  9542. #endif
  9543. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9544. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9545. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9546. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9547. /**
  9548. A stream which uses zlib to compress the data written into it.
  9549. @see GZIPDecompressorInputStream
  9550. */
  9551. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9552. {
  9553. public:
  9554. /** Creates a compression stream.
  9555. @param destStream the stream into which the compressed data should
  9556. be written
  9557. @param compressionLevel how much to compress the data, between 1 and 9, where
  9558. 1 is the fastest/lowest compression, and 9 is the
  9559. slowest/highest compression. Any value outside this range
  9560. indicates that a default compression level should be used.
  9561. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9562. this stream is destroyed
  9563. @param noWrap this is used internally by the ZipFile class
  9564. and should be ignored by user applications
  9565. */
  9566. GZIPCompressorOutputStream (OutputStream* const destStream,
  9567. int compressionLevel = 0,
  9568. const bool deleteDestStreamWhenDestroyed = false,
  9569. const bool noWrap = false);
  9570. /** Destructor. */
  9571. ~GZIPCompressorOutputStream();
  9572. void flush();
  9573. int64 getPosition();
  9574. bool setPosition (int64 newPosition);
  9575. bool write (const void* destBuffer, int howMany);
  9576. juce_UseDebuggingNewOperator
  9577. private:
  9578. OutputStream* const destStream;
  9579. const bool deleteDestStream;
  9580. uint8* buffer;
  9581. void* helper;
  9582. bool doNextBlock();
  9583. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9584. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9585. };
  9586. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9587. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9588. #endif
  9589. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9590. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9591. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9592. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9593. /**
  9594. This stream will decompress a source-stream using zlib.
  9595. Tip: if you're reading lots of small items from one of these streams, you
  9596. can increase the performance enormously by passing it through a
  9597. BufferedInputStream, so that it has to read larger blocks less often.
  9598. @see GZIPCompressorOutputStream
  9599. */
  9600. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9601. {
  9602. public:
  9603. /** Creates a decompressor stream.
  9604. @param sourceStream the stream to read from
  9605. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9606. when this object is destroyed
  9607. @param noWrap this is used internally by the ZipFile class
  9608. and should be ignored by user applications
  9609. @param uncompressedStreamLength if the creator knows the length that the
  9610. uncompressed stream will be, then it can supply this
  9611. value, which will be returned by getTotalLength()
  9612. */
  9613. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9614. const bool deleteSourceWhenDestroyed,
  9615. const bool noWrap = false,
  9616. const int64 uncompressedStreamLength = -1);
  9617. /** Destructor. */
  9618. ~GZIPDecompressorInputStream();
  9619. int64 getPosition();
  9620. bool setPosition (int64 pos);
  9621. int64 getTotalLength();
  9622. bool isExhausted();
  9623. int read (void* destBuffer, int maxBytesToRead);
  9624. juce_UseDebuggingNewOperator
  9625. private:
  9626. InputStream* const sourceStream;
  9627. const int64 uncompressedStreamLength;
  9628. const bool deleteSourceWhenDestroyed, noWrap;
  9629. bool isEof;
  9630. int activeBufferSize;
  9631. int64 originalSourcePos, currentPos;
  9632. uint8* buffer;
  9633. void* helper;
  9634. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9635. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9636. };
  9637. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9638. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9639. #endif
  9640. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9641. #endif
  9642. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9643. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9644. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9645. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9646. /**
  9647. Allows a block of data and to be accessed as a stream.
  9648. This can either be used to refer to a shared block of memory, or can make its
  9649. own internal copy of the data when the MemoryInputStream is created.
  9650. */
  9651. class JUCE_API MemoryInputStream : public InputStream
  9652. {
  9653. public:
  9654. /** Creates a MemoryInputStream.
  9655. @param sourceData the block of data to use as the stream's source
  9656. @param sourceDataSize the number of bytes in the source data block
  9657. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9658. the source data, so this data shouldn't be changed
  9659. for the lifetime of the stream; if this parameter is
  9660. true, the stream will make its own copy of the
  9661. data and use that.
  9662. */
  9663. MemoryInputStream (const void* const sourceData,
  9664. const int sourceDataSize,
  9665. const bool keepInternalCopyOfData) throw();
  9666. /** Destructor. */
  9667. ~MemoryInputStream() throw();
  9668. int64 getPosition();
  9669. bool setPosition (int64 pos);
  9670. int64 getTotalLength();
  9671. bool isExhausted();
  9672. int read (void* destBuffer, int maxBytesToRead);
  9673. juce_UseDebuggingNewOperator
  9674. private:
  9675. const char* data;
  9676. int dataSize, position;
  9677. MemoryBlock internalCopy;
  9678. };
  9679. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9680. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9681. #endif
  9682. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9683. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9684. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9685. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9686. /** Writes data to an internal memory buffer, which grows as required.
  9687. The data that was written into the stream can then be accessed later as
  9688. a contiguous block of memory.
  9689. */
  9690. class JUCE_API MemoryOutputStream : public OutputStream
  9691. {
  9692. public:
  9693. /** Creates a memory stream ready for writing into.
  9694. @param initialSize the intial amount of space to allocate for writing into
  9695. @param granularity the increments by which the internal storage will be increased
  9696. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9697. place that the data gets stored. If it's zero, the stream
  9698. will allocate its own storage internally, which you can
  9699. access using getData() and getDataSize()
  9700. */
  9701. MemoryOutputStream (const int initialSize = 256,
  9702. const int granularity = 256,
  9703. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9704. /** Destructor.
  9705. This will free any data that was written to it.
  9706. */
  9707. ~MemoryOutputStream() throw();
  9708. /** Returns a pointer to the data that has been written to the stream.
  9709. @see getDataSize
  9710. */
  9711. const char* getData() throw();
  9712. /** Returns the number of bytes of data that have been written to the stream.
  9713. @see getData
  9714. */
  9715. int getDataSize() const throw();
  9716. /** Resets the stream, clearing any data that has been written to it so far. */
  9717. void reset() throw();
  9718. void flush();
  9719. bool write (const void* buffer, int howMany);
  9720. int64 getPosition();
  9721. bool setPosition (int64 newPosition);
  9722. juce_UseDebuggingNewOperator
  9723. private:
  9724. MemoryBlock* data;
  9725. int position, size, blockSize;
  9726. bool ownsMemoryBlock;
  9727. };
  9728. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9729. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9730. #endif
  9731. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9732. /********* Start of inlined file: juce_SubregionStream.h *********/
  9733. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9734. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9735. /** Wraps another input stream, and reads from a specific part of it.
  9736. This lets you take a subsection of a stream and present it as an entire
  9737. stream in its own right.
  9738. */
  9739. class JUCE_API SubregionStream : public InputStream
  9740. {
  9741. public:
  9742. /** Creates a SubregionStream from an input source.
  9743. @param sourceStream the source stream to read from
  9744. @param startPositionInSourceStream this is the position in the source stream that
  9745. corresponds to position 0 in this stream
  9746. @param lengthOfSourceStream this specifies the maximum number of bytes
  9747. from the source stream that will be passed through
  9748. by this stream. When the position of this stream
  9749. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9750. If the length passed in here is greater than the length
  9751. of the source stream (as returned by getTotalLength()),
  9752. then the smaller value will be used.
  9753. Passing a negative value for this parameter means it
  9754. will keep reading until the source's end-of-stream.
  9755. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9756. deleted by this object when it is itself deleted.
  9757. */
  9758. SubregionStream (InputStream* const sourceStream,
  9759. const int64 startPositionInSourceStream,
  9760. const int64 lengthOfSourceStream,
  9761. const bool deleteSourceWhenDestroyed) throw();
  9762. /** Destructor.
  9763. This may also delete the source stream, if that option was chosen when the
  9764. buffered stream was created.
  9765. */
  9766. ~SubregionStream() throw();
  9767. int64 getTotalLength();
  9768. int64 getPosition();
  9769. bool setPosition (int64 newPosition);
  9770. int read (void* destBuffer, int maxBytesToRead);
  9771. bool isExhausted();
  9772. juce_UseDebuggingNewOperator
  9773. private:
  9774. InputStream* const source;
  9775. const bool deleteSourceWhenDestroyed;
  9776. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9777. SubregionStream (const SubregionStream&);
  9778. const SubregionStream& operator= (const SubregionStream&);
  9779. };
  9780. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9781. /********* End of inlined file: juce_SubregionStream.h *********/
  9782. #endif
  9783. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9784. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9785. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9786. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9787. /** A timer for measuring performance of code and dumping the results to a file.
  9788. e.g. @code
  9789. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9790. for (;;)
  9791. {
  9792. pc.start();
  9793. doSomethingFishy();
  9794. pc.stop();
  9795. }
  9796. @endcode
  9797. In this example, the time of each period between calling start/stop will be
  9798. measured and averaged over 50 runs, and the results printed to a file
  9799. every 50 times round the loop.
  9800. */
  9801. class JUCE_API PerformanceCounter
  9802. {
  9803. public:
  9804. /** Creates a PerformanceCounter object.
  9805. @param counterName the name used when printing out the statistics
  9806. @param runsPerPrintout the number of start/stop iterations before calling
  9807. printStatistics()
  9808. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9809. the results are just written to the debugger output
  9810. */
  9811. PerformanceCounter (const String& counterName,
  9812. int runsPerPrintout = 100,
  9813. const File& loggingFile = File::nonexistent);
  9814. /** Destructor. */
  9815. ~PerformanceCounter();
  9816. /** Starts timing.
  9817. @see stop
  9818. */
  9819. void start();
  9820. /** Stops timing and prints out the results.
  9821. The number of iterations before doing a printout of the
  9822. results is set in the constructor.
  9823. @see start
  9824. */
  9825. void stop();
  9826. /** Dumps the current metrics to the debugger output and to a file.
  9827. As well as using Logger::outputDebugString to print the results,
  9828. this will write then to the file specified in the constructor (if
  9829. this was valid).
  9830. */
  9831. void printStatistics();
  9832. juce_UseDebuggingNewOperator
  9833. private:
  9834. String name;
  9835. int numRuns, runsPerPrint;
  9836. double totalTime;
  9837. int64 started;
  9838. File outputFile;
  9839. };
  9840. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9841. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9842. #endif
  9843. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9844. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9845. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9846. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9847. /**
  9848. A collection of miscellaneous platform-specific utilities.
  9849. */
  9850. class JUCE_API PlatformUtilities
  9851. {
  9852. public:
  9853. /** Plays the operating system's default alert 'beep' sound. */
  9854. static void beep();
  9855. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9856. const String& emailSubject,
  9857. const String& bodyText,
  9858. const StringArray& filesToAttach);
  9859. #if JUCE_MAC || DOXYGEN
  9860. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9861. static const String cfStringToJuceString (CFStringRef cfString);
  9862. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9863. static CFStringRef juceStringToCFString (const String& s);
  9864. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9865. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9866. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9867. static const String makePathFromFSRef (FSRef* file);
  9868. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9869. their precomposed equivalents.
  9870. */
  9871. static const String convertToPrecomposedUnicode (const String& s);
  9872. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9873. static OSType getTypeOfFile (const String& filename);
  9874. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9875. static bool isBundle (const String& filename);
  9876. #endif
  9877. #if JUCE_WIN32 || DOXYGEN
  9878. // Some registry helper functions:
  9879. /** WIN32 ONLY - Returns a string from the registry.
  9880. The path is a string for the entire path of a value in the registry,
  9881. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9882. */
  9883. static const String getRegistryValue (const String& regValuePath,
  9884. const String& defaultValue = String::empty);
  9885. /** WIN32 ONLY - Sets a registry value as a string.
  9886. This will take care of creating any groups needed to get to the given
  9887. registry value.
  9888. */
  9889. static void setRegistryValue (const String& regValuePath,
  9890. const String& value);
  9891. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9892. static bool registryValueExists (const String& regValuePath);
  9893. /** WIN32 ONLY - Deletes a registry value. */
  9894. static void deleteRegistryValue (const String& regValuePath);
  9895. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9896. static void deleteRegistryKey (const String& regKeyPath);
  9897. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9898. In a normal Juce application this will be set to the module handle
  9899. of the application executable.
  9900. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9901. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9902. to set the correct module handle in your DllMain() function, because
  9903. the win32 system relies on the correct instance handle when opening windows.
  9904. */
  9905. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9906. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9907. @see getCurrentModuleInstanceHandle()
  9908. */
  9909. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  9910. /** WIN32 ONLY - Gets the command-line params as a string.
  9911. This is needed to avoid unicode problems with the argc type params.
  9912. */
  9913. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  9914. #endif
  9915. /** Clears the floating point unit's flags.
  9916. Only has an effect under win32, currently.
  9917. */
  9918. static void fpuReset();
  9919. #if JUCE_LINUX || JUCE_WIN32
  9920. /** Loads a dynamically-linked library into the process's address space.
  9921. @param pathOrFilename the platform-dependent name and search path
  9922. @returns a handle which can be used by getProcedureEntryPoint(), or
  9923. zero if it fails.
  9924. @see freeDynamicLibrary, getProcedureEntryPoint
  9925. */
  9926. static void* loadDynamicLibrary (const String& pathOrFilename);
  9927. /** Frees a dynamically-linked library.
  9928. @param libraryHandle a handle created by loadDynamicLibrary
  9929. @see loadDynamicLibrary, getProcedureEntryPoint
  9930. */
  9931. static void freeDynamicLibrary (void* libraryHandle);
  9932. /** Finds a procedure call in a dynamically-linked library.
  9933. @param libraryHandle a library handle returned by loadDynamicLibrary
  9934. @param procedureName the name of the procedure call to try to load
  9935. @returns a pointer to the function if found, or 0 if it fails
  9936. @see loadDynamicLibrary
  9937. */
  9938. static void* getProcedureEntryPoint (void* libraryHandle,
  9939. const String& procedureName);
  9940. #endif
  9941. #if JUCE_LINUX || DOXYGEN
  9942. #endif
  9943. };
  9944. #if JUCE_MAC
  9945. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  9946. using RAII.
  9947. */
  9948. class ScopedAutoReleasePool
  9949. {
  9950. public:
  9951. ScopedAutoReleasePool();
  9952. ~ScopedAutoReleasePool();
  9953. private:
  9954. void* pool;
  9955. };
  9956. /**
  9957. A wrapper class for picking up events from an Apple IR remote control device.
  9958. To use it, just create a subclass of this class, implementing the buttonPressed()
  9959. callback, then call start() and stop() to start or stop receiving events.
  9960. */
  9961. class JUCE_API AppleRemoteDevice
  9962. {
  9963. public:
  9964. AppleRemoteDevice();
  9965. virtual ~AppleRemoteDevice();
  9966. /** The set of buttons that may be pressed.
  9967. @see buttonPressed
  9968. */
  9969. enum ButtonType
  9970. {
  9971. menuButton = 0, /**< The menu button (if it's held for a short time). */
  9972. playButton, /**< The play button. */
  9973. plusButton, /**< The plus or volume-up button. */
  9974. minusButton, /**< The minus or volume-down button. */
  9975. rightButton, /**< The right button (if it's held for a short time). */
  9976. leftButton, /**< The left button (if it's held for a short time). */
  9977. rightButton_Long, /**< The right button (if it's held for a long time). */
  9978. leftButton_Long, /**< The menu button (if it's held for a long time). */
  9979. menuButton_Long, /**< The menu button (if it's held for a long time). */
  9980. playButtonSleepMode,
  9981. switched
  9982. };
  9983. /** Override this method to receive the callback about a button press.
  9984. The callback will happen on the application's message thread.
  9985. Some buttons trigger matching up and down events, in which the isDown parameter
  9986. will be true and then false. Others only send a single event when the
  9987. button is pressed.
  9988. */
  9989. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  9990. /** Starts the device running and responding to events.
  9991. Returns true if it managed to open the device.
  9992. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  9993. and will not be available to any other part of the system. If
  9994. false, it will be shared with other apps.
  9995. @see stop
  9996. */
  9997. bool start (const bool inExclusiveMode) throw();
  9998. /** Stops the device running.
  9999. @see start
  10000. */
  10001. void stop() throw();
  10002. /** Returns true if the device has been started successfully.
  10003. */
  10004. bool isActive() const throw();
  10005. /** Returns the ID number of the remote, if it has sent one.
  10006. */
  10007. int getRemoteId() const throw() { return remoteId; }
  10008. juce_UseDebuggingNewOperator
  10009. /** @internal */
  10010. void handleCallbackInternal();
  10011. private:
  10012. void* device;
  10013. void* queue;
  10014. int remoteId;
  10015. bool open (const bool openInExclusiveMode) throw();
  10016. };
  10017. #endif
  10018. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10019. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10020. #endif
  10021. #ifndef __JUCE_UUID_JUCEHEADER__
  10022. /********* Start of inlined file: juce_Uuid.h *********/
  10023. #ifndef __JUCE_UUID_JUCEHEADER__
  10024. #define __JUCE_UUID_JUCEHEADER__
  10025. /**
  10026. A universally unique 128-bit identifier.
  10027. This class generates very random unique numbers based on the system time
  10028. and MAC addresses if any are available. It's extremely unlikely that two identical
  10029. UUIDs would ever be created by chance.
  10030. The class includes methods for saving the ID as a string or as raw binary data.
  10031. */
  10032. class JUCE_API Uuid
  10033. {
  10034. public:
  10035. /** Creates a new unique ID. */
  10036. Uuid();
  10037. /** Destructor. */
  10038. ~Uuid() throw();
  10039. /** Creates a copy of another UUID. */
  10040. Uuid (const Uuid& other);
  10041. /** Copies another UUID. */
  10042. Uuid& operator= (const Uuid& other);
  10043. /** Returns true if the ID is zero. */
  10044. bool isNull() const throw();
  10045. /** Compares two UUIDs. */
  10046. bool operator== (const Uuid& other) const;
  10047. /** Compares two UUIDs. */
  10048. bool operator!= (const Uuid& other) const;
  10049. /** Returns a stringified version of this UUID.
  10050. A Uuid object can later be reconstructed from this string using operator= or
  10051. the constructor that takes a string parameter.
  10052. @returns a 32 character hex string.
  10053. */
  10054. const String toString() const;
  10055. /** Creates an ID from an encoded string version.
  10056. @see toString
  10057. */
  10058. Uuid (const String& uuidString);
  10059. /** Copies from a stringified UUID.
  10060. The string passed in should be one that was created with the toString() method.
  10061. */
  10062. Uuid& operator= (const String& uuidString);
  10063. /** Returns a pointer to the internal binary representation of the ID.
  10064. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10065. the constructor or operator= method that takes an array of uint8s.
  10066. */
  10067. const uint8* getRawData() const throw() { return value.asBytes; }
  10068. /** Creates a UUID from a 16-byte array.
  10069. @see getRawData
  10070. */
  10071. Uuid (const uint8* const rawData);
  10072. /** Sets this UUID from 16-bytes of raw data. */
  10073. Uuid& operator= (const uint8* const rawData);
  10074. juce_UseDebuggingNewOperator
  10075. private:
  10076. union
  10077. {
  10078. uint8 asBytes [16];
  10079. int asInt[4];
  10080. int64 asInt64[2];
  10081. } value;
  10082. };
  10083. #endif // __JUCE_UUID_JUCEHEADER__
  10084. /********* End of inlined file: juce_Uuid.h *********/
  10085. #endif
  10086. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10087. /********* Start of inlined file: juce_ZipFile.h *********/
  10088. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10089. #define __JUCE_ZIPFILE_JUCEHEADER__
  10090. /**
  10091. Decodes a ZIP file from a stream.
  10092. This can enumerate the items in a ZIP file and can create suitable stream objects
  10093. to read each one.
  10094. */
  10095. class JUCE_API ZipFile
  10096. {
  10097. public:
  10098. /** Creates a ZipFile for a given stream.
  10099. @param inputStream the stream to read from
  10100. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10101. will be deleted when this ZipFile object is deleted
  10102. */
  10103. ZipFile (InputStream* const inputStream,
  10104. const bool deleteStreamWhenDestroyed) throw();
  10105. /** Creates a ZipFile based for a file. */
  10106. ZipFile (const File& file);
  10107. /** Creates a ZipFile for an input source.
  10108. The inputSource object will be owned by the zip file, which will delete
  10109. it later when not needed.
  10110. */
  10111. ZipFile (InputSource* const inputSource);
  10112. /** Destructor. */
  10113. ~ZipFile() throw();
  10114. /**
  10115. Contains information about one of the entries in a ZipFile.
  10116. @see ZipFile::getEntry
  10117. */
  10118. struct ZipEntry
  10119. {
  10120. /** The name of the file, which may also include a partial pathname. */
  10121. String filename;
  10122. /** The file's original size. */
  10123. unsigned int uncompressedSize;
  10124. /** The last time the file was modified. */
  10125. Time fileTime;
  10126. };
  10127. /** Returns the number of items in the zip file. */
  10128. int getNumEntries() const throw();
  10129. /** Returns a structure that describes one of the entries in the zip file.
  10130. This may return zero if the index is out of range.
  10131. @see ZipFile::ZipEntry
  10132. */
  10133. const ZipEntry* getEntry (const int index) const throw();
  10134. /** Returns the index of the first entry with a given filename.
  10135. This uses a case-sensitive comparison to look for a filename in the
  10136. list of entries. It might return -1 if no match is found.
  10137. @see ZipFile::ZipEntry
  10138. */
  10139. int getIndexOfFileName (const String& fileName) const throw();
  10140. /** Returns a structure that describes one of the entries in the zip file.
  10141. This uses a case-sensitive comparison to look for a filename in the
  10142. list of entries. It might return 0 if no match is found.
  10143. @see ZipFile::ZipEntry
  10144. */
  10145. const ZipEntry* getEntry (const String& fileName) const throw();
  10146. /** Sorts the list of entries, based on the filename.
  10147. */
  10148. void sortEntriesByFilename();
  10149. /** Creates a stream that can read from one of the zip file's entries.
  10150. The stream that is returned must be deleted by the caller (and
  10151. zero might be returned if a stream can't be opened for some reason).
  10152. The stream must not be used after the ZipFile object that created
  10153. has been deleted.
  10154. */
  10155. InputStream* createStreamForEntry (const int index);
  10156. /** Uncompresses all of the files in the zip file.
  10157. This will expand all the entires into a target directory. The relative
  10158. paths of the entries are used.
  10159. @param targetDirectory the root folder to uncompress to
  10160. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10161. */
  10162. void uncompressTo (const File& targetDirectory,
  10163. const bool shouldOverwriteFiles = true);
  10164. juce_UseDebuggingNewOperator
  10165. private:
  10166. VoidArray entries;
  10167. friend class ZipInputStream;
  10168. CriticalSection lock;
  10169. InputStream* inputStream;
  10170. InputSource* inputSource;
  10171. bool deleteStreamWhenDestroyed;
  10172. int numEntries, centralRecStart;
  10173. #ifdef JUCE_DEBUG
  10174. int numOpenStreams;
  10175. #endif
  10176. void init();
  10177. int findEndOfZipEntryTable (InputStream* in);
  10178. ZipFile (const ZipFile&);
  10179. const ZipFile& operator= (const ZipFile&);
  10180. };
  10181. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10182. /********* End of inlined file: juce_ZipFile.h *********/
  10183. #endif
  10184. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10185. #endif
  10186. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10187. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10188. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10189. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10190. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10191. string into a localised version using the LocalisedStrings class.
  10192. @see LocalisedStrings
  10193. */
  10194. #define TRANS(stringLiteral) \
  10195. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10196. /**
  10197. Used to convert strings to localised foreign-language versions.
  10198. This is basically a look-up table of strings and their translated equivalents.
  10199. It can be loaded from a text file, so that you can supply a set of localised
  10200. versions of strings that you use in your app.
  10201. To use it in your code, simply call the translate() method on each string that
  10202. might have foreign versions, and if none is found, the method will just return
  10203. the original string.
  10204. The translation file should start with some lines specifying a description of
  10205. the language it contains, and also a list of ISO country codes where it might
  10206. be appropriate to use the file. After that, each line of the file should contain
  10207. a pair of quoted strings with an '=' sign.
  10208. E.g. for a french translation, the file might be:
  10209. @code
  10210. language: French
  10211. countries: fr be mc ch lu
  10212. "hello" = "bonjour"
  10213. "goodbye" = "au revoir"
  10214. @endcode
  10215. If the strings need to contain a quote character, they can use '\"' instead, and
  10216. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10217. (you can use this to add comments).
  10218. Note that this is a singleton class, so don't create or destroy the object directly.
  10219. There's also a TRANS(text) macro defined to make it easy to use the this.
  10220. E.g. @code
  10221. printSomething (TRANS("hello"));
  10222. @endcode
  10223. This macro is used in the Juce classes themselves, so your application has a chance to
  10224. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10225. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10226. code).
  10227. */
  10228. class JUCE_API LocalisedStrings
  10229. {
  10230. public:
  10231. /** Creates a set of translations from the text of a translation file.
  10232. When you create one of these, you can call setCurrentMappings() to make it
  10233. the set of mappings that the system's using.
  10234. */
  10235. LocalisedStrings (const String& fileContents) throw();
  10236. /** Creates a set of translations from a file.
  10237. When you create one of these, you can call setCurrentMappings() to make it
  10238. the set of mappings that the system's using.
  10239. */
  10240. LocalisedStrings (const File& fileToLoad) throw();
  10241. /** Destructor. */
  10242. ~LocalisedStrings() throw();
  10243. /** Selects the current set of mappings to be used by the system.
  10244. The object you pass in will be automatically deleted when no longer needed, so
  10245. don't keep a pointer to it. You can also pass in zero to remove the current
  10246. mappings.
  10247. See also the TRANS() macro, which uses the current set to do its translation.
  10248. @see translateWithCurrentMappings
  10249. */
  10250. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10251. /** Returns the currently selected set of mappings.
  10252. This is the object that was last passed to setCurrentMappings(). It may
  10253. be 0 if none has been created.
  10254. */
  10255. static LocalisedStrings* getCurrentMappings() throw();
  10256. /** Tries to translate a string using the currently selected set of mappings.
  10257. If no mapping has been set, or if the mapping doesn't contain a translation
  10258. for the string, this will just return the original string.
  10259. See also the TRANS() macro, which uses this method to do its translation.
  10260. @see setCurrentMappings, getCurrentMappings
  10261. */
  10262. static const String translateWithCurrentMappings (const String& text) throw();
  10263. /** Tries to translate a string using the currently selected set of mappings.
  10264. If no mapping has been set, or if the mapping doesn't contain a translation
  10265. for the string, this will just return the original string.
  10266. See also the TRANS() macro, which uses this method to do its translation.
  10267. @see setCurrentMappings, getCurrentMappings
  10268. */
  10269. static const String translateWithCurrentMappings (const char* text) throw();
  10270. /** Attempts to look up a string and return its localised version.
  10271. If the string isn't found in the list, the original string will be returned.
  10272. */
  10273. const String translate (const String& text) const throw();
  10274. /** Returns the name of the language specified in the translation file.
  10275. This is specified in the file using a line starting with "language:", e.g.
  10276. @code
  10277. language: german
  10278. @endcode
  10279. */
  10280. const String getLanguageName() const throw() { return languageName; }
  10281. /** Returns the list of suitable country codes listed in the translation file.
  10282. These is specified in the file using a line starting with "countries:", e.g.
  10283. @code
  10284. countries: fr be mc ch lu
  10285. @endcode
  10286. The country codes are supposed to be 2-character ISO complient codes.
  10287. */
  10288. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10289. juce_UseDebuggingNewOperator
  10290. private:
  10291. String languageName;
  10292. StringArray countryCodes;
  10293. StringPairArray translations;
  10294. void loadFromText (const String& fileContents) throw();
  10295. };
  10296. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10297. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10298. #endif
  10299. #ifndef __JUCE_STRING_JUCEHEADER__
  10300. #endif
  10301. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10302. #endif
  10303. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10304. #endif
  10305. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10306. /********* Start of inlined file: juce_XmlDocument.h *********/
  10307. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10308. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10309. /**
  10310. Parses a text-based XML document and creates an XmlElement object from it.
  10311. The parser will parse DTDs to load external entities but won't
  10312. check the document for validity against the DTD.
  10313. e.g.
  10314. @code
  10315. XmlDocument myDocument (File ("myfile.xml"));
  10316. XmlElement* mainElement = myDocument.getDocumentElement();
  10317. if (mainElement == 0)
  10318. {
  10319. String error = myDocument.getLastParseError();
  10320. }
  10321. else
  10322. {
  10323. ..use the element
  10324. }
  10325. @endcode
  10326. @see XmlElement
  10327. */
  10328. class JUCE_API XmlDocument
  10329. {
  10330. public:
  10331. /** Creates an XmlDocument from the xml text.
  10332. The text doesn't actually get parsed until the getDocumentElement() method is
  10333. called.
  10334. */
  10335. XmlDocument (const String& documentText) throw();
  10336. /** Creates an XmlDocument from a file.
  10337. The text doesn't actually get parsed until the getDocumentElement() method is
  10338. called.
  10339. */
  10340. XmlDocument (const File& file);
  10341. /** Destructor. */
  10342. ~XmlDocument() throw();
  10343. /** Creates an XmlElement object to represent the main document node.
  10344. This method will do the actual parsing of the text, and if there's a
  10345. parse error, it may returns 0 (and you can find out the error using
  10346. the getLastParseError() method).
  10347. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10348. first section of the file, and will only
  10349. return the outer document element - this
  10350. allows quick checking of large files to
  10351. see if they contain the correct type of
  10352. tag, without having to parse the entire file
  10353. @returns a new XmlElement which the caller will need to delete, or null if
  10354. there was an error.
  10355. @see getLastParseError
  10356. */
  10357. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10358. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10359. @returns the error, or an empty string if there was no error.
  10360. */
  10361. const String& getLastParseError() const throw();
  10362. /** Sets an input source object to use for parsing documents that reference external entities.
  10363. If the document has been created from a file, this probably won't be needed, but
  10364. if you're parsing some text and there might be a DTD that references external
  10365. files, you may need to create a custom input source that can retrieve the
  10366. other files it needs.
  10367. The object that is passed-in will be deleted automatically when no longer needed.
  10368. @see InputSource
  10369. */
  10370. void setInputSource (InputSource* const newSource) throw();
  10371. juce_UseDebuggingNewOperator
  10372. private:
  10373. String originalText;
  10374. const tchar* input;
  10375. bool outOfData, errorOccurred;
  10376. bool identifierLookupTable [128];
  10377. String lastError, dtdText;
  10378. StringArray tokenisedDTD;
  10379. bool needToLoadDTD;
  10380. InputSource* inputSource;
  10381. void setLastError (const String& desc, const bool carryOn) throw();
  10382. void skipHeader() throw();
  10383. void skipNextWhiteSpace() throw();
  10384. tchar readNextChar() throw();
  10385. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10386. void readChildElements (XmlElement* parent) throw();
  10387. int findNextTokenLength() throw();
  10388. void readQuotedString (String& result) throw();
  10389. void readEntity (String& result) throw();
  10390. const String getFileContents (const String& filename) const;
  10391. const String expandEntity (const String& entity);
  10392. const String expandExternalEntity (const String& entity);
  10393. const String getParameterEntity (const String& entity);
  10394. };
  10395. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10396. /********* End of inlined file: juce_XmlDocument.h *********/
  10397. #endif
  10398. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10399. #endif
  10400. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10401. #endif
  10402. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10403. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10404. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10405. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10406. /**
  10407. Acts as a critical section which processes can use to block each other.
  10408. @see CriticalSection
  10409. */
  10410. class JUCE_API InterProcessLock
  10411. {
  10412. public:
  10413. /** Creates a lock object.
  10414. @param name a name that processes will use to identify this lock object
  10415. */
  10416. InterProcessLock (const String& name) throw();
  10417. /** Destructor.
  10418. This will also release the lock if it's currently held by this process.
  10419. */
  10420. ~InterProcessLock() throw();
  10421. /** Attempts to lock the critical section.
  10422. @param timeOutMillisecs how many milliseconds to wait if the lock
  10423. is already held by another process - a value of
  10424. 0 will return immediately, negative values will wait
  10425. forever
  10426. @returns true if the lock could be gained within the timeout period, or
  10427. false if the timeout expired.
  10428. */
  10429. bool enter (int timeOutMillisecs = -1) throw();
  10430. /** Releases the lock if it's currently held by this process.
  10431. */
  10432. void exit() throw();
  10433. juce_UseDebuggingNewOperator
  10434. private:
  10435. void* internal;
  10436. String name;
  10437. int reentrancyLevel;
  10438. InterProcessLock (const InterProcessLock&);
  10439. const InterProcessLock& operator= (const InterProcessLock&);
  10440. };
  10441. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10442. /********* End of inlined file: juce_InterProcessLock.h *********/
  10443. #endif
  10444. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10445. /********* Start of inlined file: juce_Process.h *********/
  10446. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10447. #define __JUCE_PROCESS_JUCEHEADER__
  10448. /** Represents the current executable's process.
  10449. This contains methods for controlling the current application at the
  10450. process-level.
  10451. @see Thread, JUCEApplication
  10452. */
  10453. class JUCE_API Process
  10454. {
  10455. public:
  10456. enum ProcessPriority
  10457. {
  10458. LowPriority = 0,
  10459. NormalPriority = 1,
  10460. HighPriority = 2,
  10461. RealtimePriority = 3
  10462. };
  10463. /** Changes the current process's priority.
  10464. @param priority the process priority, where
  10465. 0=low, 1=normal, 2=high, 3=realtime
  10466. */
  10467. static void setPriority (const ProcessPriority priority);
  10468. /** Kills the current process immediately.
  10469. This is an emergency process terminator that kills the application
  10470. immediately - it's intended only for use only when something goes
  10471. horribly wrong.
  10472. @see JUCEApplication::quit
  10473. */
  10474. static void terminate();
  10475. /** Returns true if this application process is the one that the user is
  10476. currently using.
  10477. */
  10478. static bool isForegroundProcess() throw();
  10479. /** Raises the current process's privilege level.
  10480. Does nothing if this isn't supported by the current OS, or if process
  10481. privilege level is fixed.
  10482. */
  10483. static void raisePrivilege();
  10484. /** Lowers the current process's privilege level.
  10485. Does nothing if this isn't supported by the current OS, or if process
  10486. privilege level is fixed.
  10487. */
  10488. static void lowerPrivilege();
  10489. /** Returns true if this process is being hosted by a debugger.
  10490. */
  10491. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10492. };
  10493. #endif // __JUCE_PROCESS_JUCEHEADER__
  10494. /********* End of inlined file: juce_Process.h *********/
  10495. #endif
  10496. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10497. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10498. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10499. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10500. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10501. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10502. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10503. /**
  10504. Allows threads to wait for events triggered by other threads.
  10505. A thread can call wait() on a WaitableObject, and this will suspend the
  10506. calling thread until another thread wakes it up by calling the signal()
  10507. method.
  10508. */
  10509. class JUCE_API WaitableEvent
  10510. {
  10511. public:
  10512. /** Creates a WaitableEvent object. */
  10513. WaitableEvent() throw();
  10514. /** Destructor.
  10515. If other threads are waiting on this object when it gets deleted, this
  10516. can cause nasty errors, so be careful!
  10517. */
  10518. ~WaitableEvent() throw();
  10519. /** Suspends the calling thread until the event has been signalled.
  10520. This will wait until the object's signal() method is called by another thread,
  10521. or until the timeout expires.
  10522. After the event has been signalled, this method will return true and reset
  10523. the event.
  10524. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10525. value will cause it to wait forever.
  10526. @returns true if the object has been signalled, false if the timeout expires first.
  10527. @see signal, reset
  10528. */
  10529. bool wait (const int timeOutMilliseconds = -1) const throw();
  10530. /** Wakes up any threads that are currently waiting on this object.
  10531. If signal() is called when nothing is waiting, the next thread to call wait()
  10532. will return immediately and reset the signal.
  10533. @see wait, reset
  10534. */
  10535. void signal() const throw();
  10536. /** Resets the event to an unsignalled state.
  10537. If it's not already signalled, this does nothing.
  10538. */
  10539. void reset() const throw();
  10540. juce_UseDebuggingNewOperator
  10541. private:
  10542. void* internal;
  10543. WaitableEvent (const WaitableEvent&);
  10544. const WaitableEvent& operator= (const WaitableEvent&);
  10545. };
  10546. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10547. /********* End of inlined file: juce_WaitableEvent.h *********/
  10548. /********* Start of inlined file: juce_Thread.h *********/
  10549. #ifndef __JUCE_THREAD_JUCEHEADER__
  10550. #define __JUCE_THREAD_JUCEHEADER__
  10551. /**
  10552. Encapsulates a thread.
  10553. Subclasses derive from Thread and implement the run() method, in which they
  10554. do their business. The thread can then be started with the startThread() method
  10555. and controlled with various other methods.
  10556. This class also contains some thread-related static methods, such
  10557. as sleep(), yield(), getCurrentThreadId() etc.
  10558. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10559. MessageManagerLock
  10560. */
  10561. class JUCE_API Thread
  10562. {
  10563. public:
  10564. /**
  10565. Creates a thread.
  10566. When first created, the thread is not running. Use the startThread()
  10567. method to start it.
  10568. */
  10569. Thread (const String& threadName);
  10570. /** Destructor.
  10571. Deleting a Thread object that is running will only give the thread a
  10572. brief opportunity to stop itself cleanly, so it's recommended that you
  10573. should always call stopThread() with a decent timeout before deleting,
  10574. to avoid the thread being forcibly killed (which is a Bad Thing).
  10575. */
  10576. virtual ~Thread();
  10577. /** Must be implemented to perform the thread's actual code.
  10578. Remember that the thread must regularly check the threadShouldExit()
  10579. method whilst running, and if this returns true it should return from
  10580. the run() method as soon as possible to avoid being forcibly killed.
  10581. @see threadShouldExit, startThread
  10582. */
  10583. virtual void run() = 0;
  10584. // Thread control functions..
  10585. /** Starts the thread running.
  10586. This will start the thread's run() method.
  10587. (if it's already started, startThread() won't do anything).
  10588. @see stopThread
  10589. */
  10590. void startThread() throw();
  10591. /** Starts the thread with a given priority.
  10592. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10593. If the thread is already running, its priority will be changed.
  10594. @see startThread, setPriority
  10595. */
  10596. void startThread (const int priority) throw();
  10597. /** Attempts to stop the thread running.
  10598. This method will cause the threadShouldExit() method to return true
  10599. and call notify() in case the thread is currently waiting.
  10600. Hopefully the thread will then respond to this by exiting cleanly, and
  10601. the stopThread method will wait for a given time-period for this to
  10602. happen.
  10603. If the thread is stuck and fails to respond after the time-out, it gets
  10604. forcibly killed, which is a very bad thing to happen, as it could still
  10605. be holding locks, etc. which are needed by other parts of your program.
  10606. @param timeOutMilliseconds The number of milliseconds to wait for the
  10607. thread to finish before killing it by force. A negative
  10608. value in here will wait forever.
  10609. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10610. */
  10611. void stopThread (const int timeOutMilliseconds) throw();
  10612. /** Returns true if the thread is currently active */
  10613. bool isThreadRunning() const throw();
  10614. /** Sets a flag to tell the thread it should stop.
  10615. Calling this means that the threadShouldExit() method will then return true.
  10616. The thread should be regularly checking this to see whether it should exit.
  10617. @see threadShouldExit
  10618. @see waitForThreadToExit
  10619. */
  10620. void signalThreadShouldExit() throw();
  10621. /** Checks whether the thread has been told to stop running.
  10622. Threads need to check this regularly, and if it returns true, they should
  10623. return from their run() method at the first possible opportunity.
  10624. @see signalThreadShouldExit
  10625. */
  10626. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10627. /** Waits for the thread to stop.
  10628. This will waits until isThreadRunning() is false or until a timeout expires.
  10629. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10630. is less than zero, it will wait forever.
  10631. @returns true if the thread exits, or false if the timeout expires first.
  10632. */
  10633. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10634. /** Changes the thread's priority.
  10635. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10636. of 5 is normal.
  10637. */
  10638. void setPriority (const int priority) throw();
  10639. /** Changes the priority of the caller thread.
  10640. Similar to setPriority(), but this static method acts on the caller thread.
  10641. @see setPriority
  10642. */
  10643. static void setCurrentThreadPriority (const int priority) throw();
  10644. /** Sets the affinity mask for the thread.
  10645. This will only have an effect next time the thread is started - i.e. if the
  10646. thread is already running when called, it'll have no effect.
  10647. @see setCurrentThreadAffinityMask
  10648. */
  10649. void setAffinityMask (const uint32 affinityMask) throw();
  10650. /** Changes the affinity mask for the caller thread.
  10651. This will change the affinity mask for the thread that calls this static method.
  10652. @see setAffinityMask
  10653. */
  10654. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10655. // this can be called from any thread that needs to pause..
  10656. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10657. /** Yields the calling thread's current time-slot. */
  10658. static void JUCE_CALLTYPE yield() throw();
  10659. /** Makes the thread wait for a notification.
  10660. This puts the thread to sleep until either the timeout period expires, or
  10661. another thread calls the notify() method to wake it up.
  10662. @returns true if the event has been signalled, false if the timeout expires.
  10663. */
  10664. bool wait (const int timeOutMilliseconds) const throw();
  10665. /** Wakes up the thread.
  10666. If the thread has called the wait() method, this will wake it up.
  10667. @see wait
  10668. */
  10669. void notify() const throw();
  10670. /** A value type used for thread IDs.
  10671. @see getCurrentThreadId(), getThreadId()
  10672. */
  10673. typedef void* ThreadID;
  10674. /** Returns an id that identifies the caller thread.
  10675. To find the ID of a particular thread object, use getThreadId().
  10676. @returns a unique identifier that identifies the calling thread.
  10677. @see getThreadId
  10678. */
  10679. static ThreadID getCurrentThreadId() throw();
  10680. /** Finds the thread object that is currently running.
  10681. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10682. object associated with them, so this will return 0.
  10683. */
  10684. static Thread* getCurrentThread() throw();
  10685. /** Returns the ID of this thread.
  10686. That means the ID of this thread object - not of the thread that's calling the method.
  10687. This can change when the thread is started and stopped, and will be invalid if the
  10688. thread's not actually running.
  10689. @see getCurrentThreadId
  10690. */
  10691. ThreadID getThreadId() const throw();
  10692. /** Returns the name of the thread.
  10693. This is the name that gets set in the constructor.
  10694. */
  10695. const String getThreadName() const throw() { return threadName_; }
  10696. /** Returns the number of currently-running threads.
  10697. @returns the number of Thread objects known to be currently running.
  10698. @see stopAllThreads
  10699. */
  10700. static int getNumRunningThreads() throw();
  10701. /** Tries to stop all currently-running threads.
  10702. This will attempt to stop all the threads known to be running at the moment.
  10703. */
  10704. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10705. juce_UseDebuggingNewOperator
  10706. private:
  10707. const String threadName_;
  10708. void* volatile threadHandle_;
  10709. CriticalSection startStopLock;
  10710. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10711. int threadPriority_;
  10712. ThreadID threadId_;
  10713. uint32 affinityMask_;
  10714. bool volatile threadShouldExit_;
  10715. friend void JUCE_API juce_threadEntryPoint (void*);
  10716. static void threadEntryPoint (Thread* thread) throw();
  10717. Thread (const Thread&);
  10718. const Thread& operator= (const Thread&);
  10719. };
  10720. #endif // __JUCE_THREAD_JUCEHEADER__
  10721. /********* End of inlined file: juce_Thread.h *********/
  10722. /**
  10723. A critical section that allows multiple simultaneous readers.
  10724. Features of this type of lock are:
  10725. - Multiple readers can hold the lock at the same time, but only one writer
  10726. can hold it at once.
  10727. - Writers trying to gain the lock will be blocked until all readers and writers
  10728. have released it
  10729. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  10730. blocked until the writer has obtained and released it
  10731. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  10732. there are no other readers
  10733. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  10734. - Recursive locking is supported.
  10735. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  10736. */
  10737. class JUCE_API ReadWriteLock
  10738. {
  10739. public:
  10740. /**
  10741. Creates a ReadWriteLock object.
  10742. */
  10743. ReadWriteLock() throw();
  10744. /** Destructor.
  10745. If the object is deleted whilst locked, any subsequent behaviour
  10746. is unpredictable.
  10747. */
  10748. ~ReadWriteLock() throw();
  10749. /** Locks this object for reading.
  10750. Multiple threads can simulaneously lock the object for reading, but if another
  10751. thread has it locked for writing, then this will block until it releases the
  10752. lock.
  10753. @see exitRead, ScopedReadLock
  10754. */
  10755. void enterRead() const throw();
  10756. /** Releases the read-lock.
  10757. If the caller thread hasn't got the lock, this can have unpredictable results.
  10758. If the enterRead() method has been called multiple times by the thread, each
  10759. call must be matched by a call to exitRead() before other threads will be allowed
  10760. to take over the lock.
  10761. @see enterRead, ScopedReadLock
  10762. */
  10763. void exitRead() const throw();
  10764. /** Locks this object for writing.
  10765. This will block until any other threads that have it locked for reading or
  10766. writing have released their lock.
  10767. @see exitWrite, ScopedWriteLock
  10768. */
  10769. void enterWrite() const throw();
  10770. /** Tries to lock this object for writing.
  10771. This is like enterWrite(), but doesn't block - it returns true if it manages
  10772. to obtain the lock.
  10773. @see enterWrite
  10774. */
  10775. bool tryEnterWrite() const throw();
  10776. /** Releases the write-lock.
  10777. If the caller thread hasn't got the lock, this can have unpredictable results.
  10778. If the enterWrite() method has been called multiple times by the thread, each
  10779. call must be matched by a call to exit() before other threads will be allowed
  10780. to take over the lock.
  10781. @see enterWrite, ScopedWriteLock
  10782. */
  10783. void exitWrite() const throw();
  10784. juce_UseDebuggingNewOperator
  10785. private:
  10786. CriticalSection accessLock;
  10787. WaitableEvent waitEvent;
  10788. mutable int numWaitingWriters, numWriters;
  10789. mutable Thread::ThreadID writerThreadId;
  10790. mutable Array <Thread::ThreadID> readerThreads;
  10791. ReadWriteLock (const ReadWriteLock&);
  10792. const ReadWriteLock& operator= (const ReadWriteLock&);
  10793. };
  10794. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  10795. /********* End of inlined file: juce_ReadWriteLock.h *********/
  10796. #endif
  10797. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  10798. #endif
  10799. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10800. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  10801. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10802. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10803. /**
  10804. Automatically locks and unlocks a ReadWriteLock object.
  10805. Use one of these as a local variable to control access to a ReadWriteLock.
  10806. e.g. @code
  10807. ReadWriteLock myLock;
  10808. for (;;)
  10809. {
  10810. const ScopedReadLock myScopedLock (myLock);
  10811. // myLock is now locked
  10812. ...do some stuff...
  10813. // myLock gets unlocked here.
  10814. }
  10815. @endcode
  10816. @see ReadWriteLock, ScopedWriteLock
  10817. */
  10818. class JUCE_API ScopedReadLock
  10819. {
  10820. public:
  10821. /** Creates a ScopedReadLock.
  10822. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  10823. when the ScopedReadLock object is deleted, the ReadWriteLock will
  10824. be unlocked.
  10825. Make sure this object is created and deleted by the same thread,
  10826. otherwise there are no guarantees what will happen! Best just to use it
  10827. as a local stack object, rather than creating one with the new() operator.
  10828. */
  10829. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  10830. /** Destructor.
  10831. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  10832. Make sure this object is created and deleted by the same thread,
  10833. otherwise there are no guarantees what will happen!
  10834. */
  10835. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  10836. private:
  10837. const ReadWriteLock& lock_;
  10838. ScopedReadLock (const ScopedReadLock&);
  10839. const ScopedReadLock& operator= (const ScopedReadLock&);
  10840. };
  10841. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10842. /********* End of inlined file: juce_ScopedReadLock.h *********/
  10843. #endif
  10844. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10845. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  10846. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10847. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10848. /**
  10849. Automatically tries to lock and unlock a CriticalSection object.
  10850. Use one of these as a local variable to control access to a CriticalSection.
  10851. e.g. @code
  10852. CriticalSection myCriticalSection;
  10853. for (;;)
  10854. {
  10855. const ScopedTryLock myScopedTryLock (myCriticalSection);
  10856. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  10857. // should test this with the isLocked() method before doing your thread-unsafe
  10858. // action..
  10859. if (myScopedTryLock.isLocked())
  10860. {
  10861. ...do some stuff...
  10862. }
  10863. else
  10864. {
  10865. ..our attempt at locking failed because another thread had already locked it..
  10866. }
  10867. // myCriticalSection gets unlocked here (if it was locked)
  10868. }
  10869. @endcode
  10870. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  10871. */
  10872. class JUCE_API ScopedTryLock
  10873. {
  10874. public:
  10875. /** Creates a ScopedTryLock.
  10876. As soon as it is created, this will try to lock the CriticalSection, and
  10877. when the ScopedTryLock object is deleted, the CriticalSection will
  10878. be unlocked if the lock was successful.
  10879. Make sure this object is created and deleted by the same thread,
  10880. otherwise there are no guarantees what will happen! Best just to use it
  10881. as a local stack object, rather than creating one with the new() operator.
  10882. */
  10883. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  10884. /** Destructor.
  10885. The CriticalSection will be unlocked (if locked) when the destructor is called.
  10886. Make sure this object is created and deleted by the same thread,
  10887. otherwise there are no guarantees what will happen!
  10888. */
  10889. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  10890. /** Lock state
  10891. @return True if the CriticalSection is locked.
  10892. */
  10893. bool isLocked() const throw() { return lockWasSuccessful; }
  10894. private:
  10895. const CriticalSection& lock_;
  10896. const bool lockWasSuccessful;
  10897. ScopedTryLock (const ScopedTryLock&);
  10898. const ScopedTryLock& operator= (const ScopedTryLock&);
  10899. };
  10900. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10901. /********* End of inlined file: juce_ScopedTryLock.h *********/
  10902. #endif
  10903. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10904. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  10905. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10906. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10907. /**
  10908. Automatically locks and unlocks a ReadWriteLock object.
  10909. Use one of these as a local variable to control access to a ReadWriteLock.
  10910. e.g. @code
  10911. ReadWriteLock myLock;
  10912. for (;;)
  10913. {
  10914. const ScopedWriteLock myScopedLock (myLock);
  10915. // myLock is now locked
  10916. ...do some stuff...
  10917. // myLock gets unlocked here.
  10918. }
  10919. @endcode
  10920. @see ReadWriteLock, ScopedReadLock
  10921. */
  10922. class JUCE_API ScopedWriteLock
  10923. {
  10924. public:
  10925. /** Creates a ScopedWriteLock.
  10926. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  10927. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  10928. be unlocked.
  10929. Make sure this object is created and deleted by the same thread,
  10930. otherwise there are no guarantees what will happen! Best just to use it
  10931. as a local stack object, rather than creating one with the new() operator.
  10932. */
  10933. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  10934. /** Destructor.
  10935. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  10936. Make sure this object is created and deleted by the same thread,
  10937. otherwise there are no guarantees what will happen!
  10938. */
  10939. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  10940. private:
  10941. const ReadWriteLock& lock_;
  10942. ScopedWriteLock (const ScopedWriteLock&);
  10943. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  10944. };
  10945. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10946. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  10947. #endif
  10948. #ifndef __JUCE_THREAD_JUCEHEADER__
  10949. #endif
  10950. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10951. /********* Start of inlined file: juce_ThreadPool.h *********/
  10952. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10953. #define __JUCE_THREADPOOL_JUCEHEADER__
  10954. class ThreadPool;
  10955. class ThreadPoolThread;
  10956. /**
  10957. A task that is executed by a ThreadPool object.
  10958. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  10959. its threads.
  10960. The runJob() method needs to be implemented to do the task, and if the code that
  10961. does the work takes a significant time to run, it must keep checking the shouldExit()
  10962. method to see if something is trying to interrupt the job. If shouldExit() returns
  10963. true, the runJob() method must return immediately.
  10964. @see ThreadPool, Thread
  10965. */
  10966. class JUCE_API ThreadPoolJob
  10967. {
  10968. public:
  10969. /** Creates a thread pool job object.
  10970. After creating your job, add it to a thread pool with ThreadPool::addJob().
  10971. */
  10972. ThreadPoolJob (const String& name);
  10973. /** Destructor. */
  10974. virtual ~ThreadPoolJob();
  10975. /** Returns the name of this job.
  10976. @see setJobName
  10977. */
  10978. const String getJobName() const;
  10979. /** Changes the job's name.
  10980. @see getJobName
  10981. */
  10982. void setJobName (const String& newName);
  10983. /** These are the values that can be returned by the runJob() method.
  10984. */
  10985. enum JobStatus
  10986. {
  10987. jobHasFinished = 0, /**< indicates that the job has finished and can be
  10988. removed from the pool. */
  10989. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  10990. should be automatically deleted by the pool. */
  10991. jobNeedsRunningAgain /**< indicates that the job would like to be called
  10992. again when a thread is free. */
  10993. };
  10994. /** Peforms the actual work that this job needs to do.
  10995. Your subclass must implement this method, in which is does its work.
  10996. If the code in this method takes a significant time to run, it must repeatedly check
  10997. the shouldExit() method to see if something is trying to interrupt the job.
  10998. If shouldExit() ever returns true, the runJob() method must return immediately.
  10999. If this method returns jobHasFinished, then the job will be removed from the pool
  11000. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  11001. pool and will get a chance to run again as soon as a thread is free.
  11002. @see shouldExit()
  11003. */
  11004. virtual JobStatus runJob() = 0;
  11005. /** Returns true if this job is currently running its runJob() method. */
  11006. bool isRunning() const throw() { return isActive; }
  11007. /** Returns true if something is trying to interrupt this job and make it stop.
  11008. Your runJob() method must call this whenever it gets a chance, and if it ever
  11009. returns true, the runJob() method must return immediately.
  11010. @see signalJobShouldExit()
  11011. */
  11012. bool shouldExit() const throw() { return shouldStop; }
  11013. /** Calling this will cause the shouldExit() method to return true, and the job
  11014. should (if it's been implemented correctly) stop as soon as possible.
  11015. @see shouldExit()
  11016. */
  11017. void signalJobShouldExit();
  11018. juce_UseDebuggingNewOperator
  11019. private:
  11020. friend class ThreadPool;
  11021. friend class ThreadPoolThread;
  11022. String jobName;
  11023. ThreadPool* pool;
  11024. bool shouldStop, isActive, shouldBeDeleted;
  11025. };
  11026. /**
  11027. A set of threads that will run a list of jobs.
  11028. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11029. will be called by the next pooled thread that becomes free.
  11030. @see ThreadPoolJob, Thread
  11031. */
  11032. class JUCE_API ThreadPool
  11033. {
  11034. public:
  11035. /** Creates a thread pool.
  11036. Once you've created a pool, you can give it some things to do with the addJob()
  11037. method.
  11038. @param numberOfThreads the maximum number of actual threads to run.
  11039. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11040. until there are some jobs to run. If false, then
  11041. all the threads will be fired-up immediately so that
  11042. they're ready for action
  11043. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11044. inactive for this length of time, they will automatically
  11045. be stopped until more jobs come along and they're needed
  11046. */
  11047. ThreadPool (const int numberOfThreads,
  11048. const bool startThreadsOnlyWhenNeeded = true,
  11049. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11050. /** Destructor.
  11051. This will attempt to remove all the jobs before deleting, but if you want to
  11052. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11053. the pool.
  11054. */
  11055. ~ThreadPool();
  11056. /** Adds a job to the queue.
  11057. Once a job has been added, then the next time a thread is free, it will run
  11058. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11059. runJob() method, the pool will either remove the job from the pool or add it to
  11060. the back of the queue to be run again.
  11061. */
  11062. void addJob (ThreadPoolJob* const job);
  11063. /** Tries to remove a job from the pool.
  11064. If the job isn't yet running, this will simply remove it. If it is running, it
  11065. will wait for it to finish.
  11066. If the timeout period expires before the job finishes running, then the job will be
  11067. left in the pool and this will return false. It returns true if the job is sucessfully
  11068. stopped and removed.
  11069. @param job the job to remove
  11070. @param interruptIfRunning if true, then if the job is currently busy, its
  11071. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11072. to interrupt it. If false, then if the job will be allowed to run
  11073. until it stops normally (or the timeout expires)
  11074. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11075. before giving up and returning false
  11076. */
  11077. bool removeJob (ThreadPoolJob* const job,
  11078. const bool interruptIfRunning,
  11079. const int timeOutMilliseconds);
  11080. /** Tries clear all jobs from the pool.
  11081. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11082. methods called to try to interrupt them
  11083. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11084. before giving up and returning false
  11085. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11086. expires while waiting for them to stop
  11087. */
  11088. bool removeAllJobs (const bool interruptRunningJobs,
  11089. const int timeOutMilliseconds);
  11090. /** Returns the number of jobs currently running or queued.
  11091. */
  11092. int getNumJobs() const throw();
  11093. /** Returns one of the jobs in the queue.
  11094. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11095. around in the list, and this method may return 0 if the index is currently out-of-range.
  11096. */
  11097. ThreadPoolJob* getJob (const int index) const;
  11098. /** Returns true if the given job is currently queued or running.
  11099. @see isJobRunning()
  11100. */
  11101. bool contains (const ThreadPoolJob* const job) const throw();
  11102. /** Returns true if the given job is currently being run by a thread.
  11103. */
  11104. bool isJobRunning (const ThreadPoolJob* const job) const;
  11105. /** Waits until a job has finished running and has been removed from the pool.
  11106. This will wait until the job is no longer in the pool - i.e. until its
  11107. runJob() method returns ThreadPoolJob::jobHasFinished.
  11108. If the timeout period expires before the job finishes, this will return false;
  11109. it returns true if the job has finished successfully.
  11110. */
  11111. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11112. const int timeOutMilliseconds) const;
  11113. /** Returns a list of the names of all the jobs currently running or queued.
  11114. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11115. */
  11116. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  11117. /** Changes the priority of all the threads.
  11118. This will call Thread::setPriority() for each thread in the pool.
  11119. */
  11120. void setThreadPriorities (const int newPriority);
  11121. juce_UseDebuggingNewOperator
  11122. private:
  11123. const int numThreads, threadStopTimeout;
  11124. int priority;
  11125. Thread** threads;
  11126. VoidArray jobs;
  11127. CriticalSection lock;
  11128. uint32 lastJobEndTime;
  11129. friend class ThreadPoolThread;
  11130. bool runNextJob();
  11131. ThreadPool (const ThreadPool&);
  11132. const ThreadPool& operator= (const ThreadPool&);
  11133. };
  11134. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11135. /********* End of inlined file: juce_ThreadPool.h *********/
  11136. #endif
  11137. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11138. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11139. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11140. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11141. /**
  11142. Used by the TimeSliceThread class.
  11143. To register your class with a TimeSliceThread, derive from this class and
  11144. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11145. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11146. deleting your client!
  11147. @see TimeSliceThread
  11148. */
  11149. class JUCE_API TimeSliceClient
  11150. {
  11151. public:
  11152. /** Destructor. */
  11153. virtual ~TimeSliceClient() {}
  11154. /** Called back by a TimeSliceThread.
  11155. When you register this class with it, a TimeSliceThread will repeatedly call
  11156. this method.
  11157. The implementation of this method should use its time-slice to do something that's
  11158. quick - never block for longer than absolutely necessary.
  11159. @returns Your method should return true if it needs more time, or false if it's
  11160. not too busy and doesn't need calling back urgently. If all the thread's
  11161. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11162. up to half a second in between callbacks. You can force the TimeSliceThread
  11163. to wake up and poll again immediately by calling its notify() method.
  11164. */
  11165. virtual bool useTimeSlice() = 0;
  11166. };
  11167. /**
  11168. A thread that keeps a list of clients, and calls each one in turn, giving them
  11169. all a chance to run some sort of short task.
  11170. @see TimeSliceClient, Thread
  11171. */
  11172. class JUCE_API TimeSliceThread : public Thread
  11173. {
  11174. public:
  11175. /**
  11176. Creates a TimeSliceThread.
  11177. When first created, the thread is not running. Use the startThread()
  11178. method to start it.
  11179. */
  11180. TimeSliceThread (const String& threadName);
  11181. /** Destructor.
  11182. Deleting a Thread object that is running will only give the thread a
  11183. brief opportunity to stop itself cleanly, so it's recommended that you
  11184. should always call stopThread() with a decent timeout before deleting,
  11185. to avoid the thread being forcibly killed (which is a Bad Thing).
  11186. */
  11187. ~TimeSliceThread();
  11188. /** Adds a client to the list.
  11189. The client's callbacks will start immediately (possibly before the method
  11190. has returned).
  11191. */
  11192. void addTimeSliceClient (TimeSliceClient* const client);
  11193. /** Removes a client from the list.
  11194. This method will make sure that all callbacks to the client have completely
  11195. finished before the method returns.
  11196. */
  11197. void removeTimeSliceClient (TimeSliceClient* const client);
  11198. /** Returns the number of registered clients. */
  11199. int getNumClients() const throw();
  11200. /** Returns one of the registered clients. */
  11201. TimeSliceClient* getClient (const int index) const throw();
  11202. /** @internal */
  11203. void run();
  11204. juce_UseDebuggingNewOperator
  11205. private:
  11206. CriticalSection callbackLock, listLock;
  11207. Array <TimeSliceClient*> clients;
  11208. int index;
  11209. TimeSliceClient* clientBeingCalled;
  11210. bool clientsChanged;
  11211. TimeSliceThread (const TimeSliceThread&);
  11212. const TimeSliceThread& operator= (const TimeSliceThread&);
  11213. };
  11214. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11215. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11216. #endif
  11217. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11218. #endif
  11219. #endif
  11220. /********* End of inlined file: juce_core_includes.h *********/
  11221. // if you're compiling a command-line app, you might want to just include the core headers,
  11222. // so you can set this macro before including juce.h
  11223. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11224. /********* Start of inlined file: juce_app_includes.h *********/
  11225. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11226. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11227. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11228. /********* Start of inlined file: juce_Application.h *********/
  11229. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11230. #define __JUCE_APPLICATION_JUCEHEADER__
  11231. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11232. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11233. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11234. /********* Start of inlined file: juce_Component.h *********/
  11235. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11236. #define __JUCE_COMPONENT_JUCEHEADER__
  11237. /********* Start of inlined file: juce_MouseCursor.h *********/
  11238. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11239. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11240. class Image;
  11241. class RefCountedMouseCursor;
  11242. class ComponentPeer;
  11243. class Component;
  11244. /**
  11245. Represents a mouse cursor image.
  11246. This object can either be used to represent one of the standard mouse
  11247. cursor shapes, or a custom one generated from an image.
  11248. */
  11249. class JUCE_API MouseCursor
  11250. {
  11251. public:
  11252. /** The set of available standard mouse cursors. */
  11253. enum StandardCursorType
  11254. {
  11255. NoCursor = 0, /**< An invisible cursor. */
  11256. NormalCursor, /**< The stardard arrow cursor. */
  11257. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11258. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11259. CrosshairCursor, /**< A pair of crosshairs. */
  11260. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11261. that you're dragging a copy of something. */
  11262. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11263. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11264. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11265. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11266. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11267. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11268. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11269. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11270. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11271. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11272. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11273. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11274. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11275. };
  11276. /** Creates the standard arrow cursor. */
  11277. MouseCursor() throw();
  11278. /** Creates one of the standard mouse cursor */
  11279. MouseCursor (const StandardCursorType type) throw();
  11280. /** Creates a custom cursor from an image.
  11281. @param image the image to use for the cursor - if this is bigger than the
  11282. system can manage, it might get scaled down first, and might
  11283. also have to be turned to black-and-white if it can't do colour
  11284. cursors.
  11285. @param hotSpotX the x position of the cursor's hotspot within the image
  11286. @param hotSpotY the y position of the cursor's hotspot within the image
  11287. */
  11288. MouseCursor (Image& image,
  11289. const int hotSpotX,
  11290. const int hotSpotY) throw();
  11291. /** Creates a copy of another cursor object. */
  11292. MouseCursor (const MouseCursor& other) throw();
  11293. /** Copies this cursor from another object. */
  11294. const MouseCursor& operator= (const MouseCursor& other) throw();
  11295. /** Destructor. */
  11296. ~MouseCursor() throw();
  11297. /** Checks whether two mouse cursors are the same.
  11298. For custom cursors, two cursors created from the same image won't be
  11299. recognised as the same, only MouseCursor objects that have been
  11300. copied from the same object.
  11301. */
  11302. bool operator== (const MouseCursor& other) const throw();
  11303. /** Checks whether two mouse cursors are the same.
  11304. For custom cursors, two cursors created from the same image won't be
  11305. recognised as the same, only MouseCursor objects that have been
  11306. copied from the same object.
  11307. */
  11308. bool operator!= (const MouseCursor& other) const throw();
  11309. /** Makes the system show its default 'busy' cursor.
  11310. This will turn the system cursor to an hourglass or spinning beachball
  11311. until the next time the mouse is moved, or hideWaitCursor() is called.
  11312. This is handy if the message loop is about to block for a couple of
  11313. seconds while busy and you want to give the user feedback about this.
  11314. @see MessageManager::setTimeBeforeShowingWaitCursor
  11315. */
  11316. static void showWaitCursor() throw();
  11317. /** If showWaitCursor has been called, this will return the mouse to its
  11318. normal state.
  11319. This will look at what component is under the mouse, and update the
  11320. cursor to be the correct one for that component.
  11321. @see showWaitCursor
  11322. */
  11323. static void hideWaitCursor() throw();
  11324. juce_UseDebuggingNewOperator
  11325. private:
  11326. RefCountedMouseCursor* cursorHandle;
  11327. friend class Component;
  11328. void showInWindow (ComponentPeer* window) const throw();
  11329. void showInAllWindows() const throw();
  11330. void* getHandle() const throw();
  11331. };
  11332. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11333. /********* End of inlined file: juce_MouseCursor.h *********/
  11334. /********* Start of inlined file: juce_MouseListener.h *********/
  11335. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11336. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11337. /********* Start of inlined file: juce_MouseEvent.h *********/
  11338. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11339. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11340. class Component;
  11341. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11342. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11343. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11344. /**
  11345. Represents the state of the mouse buttons and modifier keys.
  11346. This is used both by mouse events and by KeyPress objects to describe
  11347. the state of keys such as shift, control, alt, etc.
  11348. @see KeyPress, MouseEvent::mods
  11349. */
  11350. class JUCE_API ModifierKeys
  11351. {
  11352. public:
  11353. /** Creates a ModifierKeys object from a raw set of flags.
  11354. @param flags to represent the keys that are down
  11355. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11356. rightButtonModifier, commandModifier, popupMenuClickModifier
  11357. */
  11358. ModifierKeys (const int flags = 0) throw();
  11359. /** Creates a copy of another object. */
  11360. ModifierKeys (const ModifierKeys& other) throw();
  11361. /** Copies this object from another one. */
  11362. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11363. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11364. This is a platform-agnostic way of checking for the operating system's
  11365. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11366. Windows/Linux, it's actually checking for the CTRL key.
  11367. */
  11368. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11369. /** Checks whether the user is trying to launch a pop-up menu.
  11370. This checks for platform-specific modifiers that might indicate that the user
  11371. is following the operating system's normal method of showing a pop-up menu.
  11372. So on Windows/Linux, this method is really testing for a right-click.
  11373. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11374. */
  11375. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11376. /** Checks whether the flag is set for the left mouse-button. */
  11377. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11378. /** Checks whether the flag is set for the right mouse-button.
  11379. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11380. this is platform-independent (and makes your code more explanatory too).
  11381. */
  11382. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11383. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11384. /** Tests for any of the mouse-button flags. */
  11385. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11386. /** Tests for any of the modifier key flags. */
  11387. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11388. /** Checks whether the shift key's flag is set. */
  11389. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11390. /** Checks whether the CTRL key's flag is set.
  11391. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11392. popup-menu modifiers.
  11393. @see isCommandDown, isPopupMenu
  11394. */
  11395. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11396. /** Checks whether the shift key's flag is set. */
  11397. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11398. /** Flags that represent the different keys. */
  11399. enum Flags
  11400. {
  11401. /** Shift key flag. */
  11402. shiftModifier = 1,
  11403. /** CTRL key flag. */
  11404. ctrlModifier = 2,
  11405. /** ALT key flag. */
  11406. altModifier = 4,
  11407. /** Left mouse button flag. */
  11408. leftButtonModifier = 16,
  11409. /** Right mouse button flag. */
  11410. rightButtonModifier = 32,
  11411. /** Middle mouse button flag. */
  11412. middleButtonModifier = 64,
  11413. #if JUCE_MAC
  11414. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11415. commandModifier = 8,
  11416. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11417. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11418. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11419. #else
  11420. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11421. commandModifier = ctrlModifier,
  11422. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11423. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11424. popupMenuClickModifier = rightButtonModifier,
  11425. #endif
  11426. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11427. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11428. /** Represents a combination of all the mouse buttons at once. */
  11429. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11430. };
  11431. /** Returns the raw flags for direct testing. */
  11432. inline int getRawFlags() const throw() { return flags; }
  11433. /** Tests a combination of flags and returns true if any of them are set. */
  11434. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11435. /** Creates a ModifierKeys object to represent the last-known state of the
  11436. keyboard and mouse buttons.
  11437. @see getCurrentModifiersRealtime
  11438. */
  11439. static const ModifierKeys getCurrentModifiers() throw();
  11440. /** Creates a ModifierKeys object to represent the current state of the
  11441. keyboard and mouse buttons.
  11442. This isn't often needed and isn't recommended, but will actively check all the
  11443. mouse and key states rather than just returning their last-known state like
  11444. getCurrentModifiers() does.
  11445. This is only needed in special circumstances for up-to-date modifier information
  11446. at times when the app's event loop isn't running normally.
  11447. */
  11448. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11449. private:
  11450. int flags;
  11451. static int currentModifierFlags;
  11452. friend class ComponentPeer;
  11453. static void updateCurrentModifiers() throw();
  11454. };
  11455. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11456. /********* End of inlined file: juce_ModifierKeys.h *********/
  11457. /**
  11458. Contains position and status information about a mouse event.
  11459. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11460. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11461. */
  11462. class JUCE_API MouseEvent
  11463. {
  11464. public:
  11465. /** Creates a MouseEvent.
  11466. Normally an application will never need to use this.
  11467. @param x the x position of the mouse, relative to the component that is passed-in
  11468. @param y the y position of the mouse, relative to the component that is passed-in
  11469. @param modifiers the key modifiers at the time of the event
  11470. @param originator the component that the mouse event applies to
  11471. @param eventTime the time the event happened
  11472. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11473. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11474. the same as the current mouse-x position.
  11475. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11476. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11477. the same as the current mouse-y position.
  11478. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11479. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11480. the same as the current mouse-event time.
  11481. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11482. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11483. */
  11484. MouseEvent (const int x, const int y,
  11485. const ModifierKeys& modifiers,
  11486. Component* const originator,
  11487. const Time& eventTime,
  11488. const int mouseDownX,
  11489. const int mouseDownY,
  11490. const Time& mouseDownTime,
  11491. const int numberOfClicks,
  11492. const bool mouseWasDragged) throw();
  11493. /** Destructor. */
  11494. ~MouseEvent() throw();
  11495. /** The x-position of the mouse when the event occurred.
  11496. This value is relative to the top-left of the component to which the
  11497. event applies (as indicated by the MouseEvent::eventComponent field).
  11498. */
  11499. int x;
  11500. /** The y-position of the mouse when the event occurred.
  11501. This value is relative to the top-left of the component to which the
  11502. event applies (as indicated by the MouseEvent::eventComponent field).
  11503. */
  11504. int y;
  11505. /** The key modifiers associated with the event.
  11506. This will let you find out which mouse buttons were down, as well as which
  11507. modifier keys were held down.
  11508. When used for mouse-up events, this will indicate the state of the mouse buttons
  11509. just before they were released, so that you can tell which button they let go of.
  11510. */
  11511. ModifierKeys mods;
  11512. /** The component that this event applies to.
  11513. This is usually the component that the mouse was over at the time, but for mouse-drag
  11514. events the mouse could actually be over a different component and the events are
  11515. still sent to the component that the button was originally pressed on.
  11516. The x and y member variables are relative to this component's position.
  11517. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11518. component, this pointer will be updated, but originalComponent remains unchanged.
  11519. @see originalComponent
  11520. */
  11521. Component* eventComponent;
  11522. /** The component that the event first occurred on.
  11523. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11524. component, this value remains unchanged to indicate the first component that received it.
  11525. @see eventComponent
  11526. */
  11527. Component* originalComponent;
  11528. /** The time that this mouse-event occurred.
  11529. */
  11530. Time eventTime;
  11531. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11532. The co-ordinate is relative to the component specified in MouseEvent::component.
  11533. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11534. */
  11535. int getMouseDownX() const throw();
  11536. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11537. The co-ordinate is relative to the component specified in MouseEvent::component.
  11538. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11539. */
  11540. int getMouseDownY() const throw();
  11541. /** Returns the straight-line distance between where the mouse is now and where it
  11542. was the last time the button was pressed.
  11543. This is quite handy for things like deciding whether the user has moved far enough
  11544. for it to be considered a drag operation.
  11545. @see getDistanceFromDragStartX
  11546. */
  11547. int getDistanceFromDragStart() const throw();
  11548. /** Returns the difference between the mouse's current x postion and where it was
  11549. when the button was last pressed.
  11550. @see getDistanceFromDragStart
  11551. */
  11552. int getDistanceFromDragStartX() const throw();
  11553. /** Returns the difference between the mouse's current y postion and where it was
  11554. when the button was last pressed.
  11555. @see getDistanceFromDragStart
  11556. */
  11557. int getDistanceFromDragStartY() const throw();
  11558. /** Returns true if the mouse has just been clicked.
  11559. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11560. the user has dragged the mouse more than a few pixels from the place where the
  11561. mouse-down occurred.
  11562. Once they have dragged it far enough for this method to return false, it will continue
  11563. to return false until the mouse-up, even if they move the mouse back to the same
  11564. position where they originally pressed it. This means that it's very handy for
  11565. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11566. callback to ignore any small movements they might make while clicking.
  11567. @returns true if the mouse wasn't dragged by more than a few pixels between
  11568. the last time the button was pressed and released.
  11569. */
  11570. bool mouseWasClicked() const throw();
  11571. /** For a click event, the number of times the mouse was clicked in succession.
  11572. So for example a double-click event will return 2, a triple-click 3, etc.
  11573. */
  11574. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11575. /** Returns the time that the mouse button has been held down for.
  11576. If called from a mouseDrag or mouseUp callback, this will return the
  11577. number of milliseconds since the corresponding mouseDown event occurred.
  11578. If called in other contexts, e.g. a mouseMove, then the returned value
  11579. may be 0 or an undefined value.
  11580. */
  11581. int getLengthOfMousePress() const throw();
  11582. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11583. The co-ordinates are relative to the top-left of the main monitor.
  11584. @see getMouseDownScreenX, Desktop::getMousePosition
  11585. */
  11586. int getScreenX() const throw();
  11587. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11588. The co-ordinates are relative to the top-left of the main monitor.
  11589. @see getMouseDownScreenY, Desktop::getMousePosition
  11590. */
  11591. int getScreenY() const throw();
  11592. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11593. The co-ordinates are relative to the top-left of the main monitor.
  11594. @see getScreenX, Desktop::getMousePosition
  11595. */
  11596. int getMouseDownScreenX() const throw();
  11597. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11598. The co-ordinates are relative to the top-left of the main monitor.
  11599. @see getScreenY, Desktop::getMousePosition
  11600. */
  11601. int getMouseDownScreenY() const throw();
  11602. /** Creates a version of this event that is relative to a different component.
  11603. The x and y positions of the event that is returned will have been
  11604. adjusted to be relative to the new component.
  11605. */
  11606. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11607. /** Changes the application-wide setting for the double-click time limit.
  11608. This is the maximum length of time between mouse-clicks for it to be
  11609. considered a double-click. It's used by the Component class.
  11610. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11611. */
  11612. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11613. /** Returns the application-wide setting for the double-click time limit.
  11614. This is the maximum length of time between mouse-clicks for it to be
  11615. considered a double-click. It's used by the Component class.
  11616. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11617. */
  11618. static int getDoubleClickTimeout() throw();
  11619. juce_UseDebuggingNewOperator
  11620. private:
  11621. int mouseDownX, mouseDownY;
  11622. Time mouseDownTime;
  11623. int numberOfClicks;
  11624. bool wasMovedSinceMouseDown;
  11625. };
  11626. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11627. /********* End of inlined file: juce_MouseEvent.h *********/
  11628. /**
  11629. A MouseListener can be registered with a component to receive callbacks
  11630. about mouse events that happen to that component.
  11631. @see Component::addMouseListener, Component::removeMouseListener
  11632. */
  11633. class JUCE_API MouseListener
  11634. {
  11635. public:
  11636. /** Destructor. */
  11637. virtual ~MouseListener() {}
  11638. /** Called when the mouse moves inside a component.
  11639. If the mouse button isn't pressed and the mouse moves over a component,
  11640. this will be called to let the component react to this.
  11641. A component will always get a mouseEnter callback before a mouseMove.
  11642. @param e details about the position and status of the mouse event, including
  11643. the source component in which it occurred
  11644. @see mouseEnter, mouseExit, mouseDrag, contains
  11645. */
  11646. virtual void mouseMove (const MouseEvent& e);
  11647. /** Called when the mouse first enters a component.
  11648. If the mouse button isn't pressed and the mouse moves into a component,
  11649. this will be called to let the component react to this.
  11650. When the mouse button is pressed and held down while being moved in
  11651. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11652. mouseDrag messages are sent to the component that the mouse was originally
  11653. clicked on, until the button is released.
  11654. @param e details about the position and status of the mouse event, including
  11655. the source component in which it occurred
  11656. @see mouseExit, mouseDrag, mouseMove, contains
  11657. */
  11658. virtual void mouseEnter (const MouseEvent& e);
  11659. /** Called when the mouse moves out of a component.
  11660. This will be called when the mouse moves off the edge of this
  11661. component.
  11662. If the mouse button was pressed, and it was then dragged off the
  11663. edge of the component and released, then this callback will happen
  11664. when the button is released, after the mouseUp callback.
  11665. @param e details about the position and status of the mouse event, including
  11666. the source component in which it occurred
  11667. @see mouseEnter, mouseDrag, mouseMove, contains
  11668. */
  11669. virtual void mouseExit (const MouseEvent& e);
  11670. /** Called when a mouse button is pressed.
  11671. The MouseEvent object passed in contains lots of methods for finding out
  11672. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11673. were held down at the time.
  11674. Once a button is held down, the mouseDrag method will be called when the
  11675. mouse moves, until the button is released.
  11676. @param e details about the position and status of the mouse event, including
  11677. the source component in which it occurred
  11678. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11679. */
  11680. virtual void mouseDown (const MouseEvent& e);
  11681. /** Called when the mouse is moved while a button is held down.
  11682. When a mouse button is pressed inside a component, that component
  11683. receives mouseDrag callbacks each time the mouse moves, even if the
  11684. mouse strays outside the component's bounds.
  11685. @param e details about the position and status of the mouse event, including
  11686. the source component in which it occurred
  11687. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11688. */
  11689. virtual void mouseDrag (const MouseEvent& e);
  11690. /** Called when a mouse button is released.
  11691. A mouseUp callback is sent to the component in which a button was pressed
  11692. even if the mouse is actually over a different component when the
  11693. button is released.
  11694. The MouseEvent object passed in contains lots of methods for finding out
  11695. which buttons were down just before they were released.
  11696. @param e details about the position and status of the mouse event, including
  11697. the source component in which it occurred
  11698. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11699. */
  11700. virtual void mouseUp (const MouseEvent& e);
  11701. /** Called when a mouse button has been double-clicked on a component.
  11702. The MouseEvent object passed in contains lots of methods for finding out
  11703. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11704. were held down at the time.
  11705. @param e details about the position and status of the mouse event, including
  11706. the source component in which it occurred
  11707. @see mouseDown, mouseUp
  11708. */
  11709. virtual void mouseDoubleClick (const MouseEvent& e);
  11710. /** Called when the mouse-wheel is moved.
  11711. This callback is sent to the component that the mouse is over when the
  11712. wheel is moved.
  11713. If not overridden, the component will forward this message to its parent, so
  11714. that parent components can collect mouse-wheel messages that happen to
  11715. child components which aren't interested in them.
  11716. @param e details about the position and status of the mouse event, including
  11717. the source component in which it occurred
  11718. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11719. value means the wheel has been pushed to the right, negative means it
  11720. was pushed to the left
  11721. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11722. value means the wheel has been pushed upwards, negative means it
  11723. was pushed downwards
  11724. */
  11725. virtual void mouseWheelMove (const MouseEvent& e,
  11726. float wheelIncrementX,
  11727. float wheelIncrementY);
  11728. private:
  11729. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11730. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11731. // if that happens, update your code to use the new one above.
  11732. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11733. };
  11734. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11735. /********* End of inlined file: juce_MouseListener.h *********/
  11736. /********* Start of inlined file: juce_ComponentListener.h *********/
  11737. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11738. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11739. class Component;
  11740. /**
  11741. Gets informed about changes to a component's hierarchy or position.
  11742. To monitor a component for changes, register a subclass of ComponentListener
  11743. with the component using Component::addComponentListener().
  11744. Be sure to deregister listeners before you delete them!
  11745. @see Component::addComponentListener, Component::removeComponentListener
  11746. */
  11747. class JUCE_API ComponentListener
  11748. {
  11749. public:
  11750. /** Destructor. */
  11751. virtual ~ComponentListener() {}
  11752. /** Called when the component's position or size changes.
  11753. @param component the component that was moved or resized
  11754. @param wasMoved true if the component's top-left corner has just moved
  11755. @param wasResized true if the component's width or height has just changed
  11756. @see Component::setBounds, Component::resized, Component::moved
  11757. */
  11758. virtual void componentMovedOrResized (Component& component,
  11759. bool wasMoved,
  11760. bool wasResized);
  11761. /** Called when the component is brought to the top of the z-order.
  11762. @param component the component that was moved
  11763. @see Component::toFront, Component::broughtToFront
  11764. */
  11765. virtual void componentBroughtToFront (Component& component);
  11766. /** Called when the component is made visible or invisible.
  11767. @param component the component that changed
  11768. @see Component::setVisible
  11769. */
  11770. virtual void componentVisibilityChanged (Component& component);
  11771. /** Called when the component has children added or removed.
  11772. @param component the component whose children were changed
  11773. @see Component::childrenChanged, Component::addChildComponent,
  11774. Component::removeChildComponent
  11775. */
  11776. virtual void componentChildrenChanged (Component& component);
  11777. /** Called to indicate that the component's parents have changed.
  11778. When a component is added or removed from its parent, all of its children
  11779. will produce this notification (recursively - so all children of its
  11780. children will also be called as well).
  11781. @param component the component that this listener is registered with
  11782. @see Component::parentHierarchyChanged
  11783. */
  11784. virtual void componentParentHierarchyChanged (Component& component);
  11785. /** Called when the component's name is changed.
  11786. @see Component::setName, Component::getName
  11787. */
  11788. virtual void componentNameChanged (Component& component);
  11789. };
  11790. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11791. /********* End of inlined file: juce_ComponentListener.h *********/
  11792. /********* Start of inlined file: juce_KeyListener.h *********/
  11793. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11794. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11795. /********* Start of inlined file: juce_KeyPress.h *********/
  11796. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11797. #define __JUCE_KEYPRESS_JUCEHEADER__
  11798. /**
  11799. Represents a key press, including any modifier keys that are needed.
  11800. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11801. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11802. */
  11803. class JUCE_API KeyPress
  11804. {
  11805. public:
  11806. /** Creates an (invalid) KeyPress.
  11807. @see isValid
  11808. */
  11809. KeyPress() throw();
  11810. /** Creates a KeyPress for a key and some modifiers.
  11811. e.g.
  11812. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11813. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11814. @param keyCode a code that represents the key - this value must be
  11815. one of special constants listed in this class, or an
  11816. 8-bit character code such as a letter (case is ignored),
  11817. digit or a simple key like "," or ".". Note that this
  11818. isn't the same as the textCharacter parameter, so for example
  11819. a keyCode of 'a' and a shift-key modifier should have a
  11820. textCharacter value of 'A'.
  11821. @param modifiers the modifiers to associate with the keystroke
  11822. @param textCharacter the character that would be printed if someone typed
  11823. this keypress into a text editor. This value may be
  11824. null if the keypress is a non-printing character
  11825. @see getKeyCode, isKeyCode, getModifiers
  11826. */
  11827. KeyPress (const int keyCode,
  11828. const ModifierKeys& modifiers,
  11829. const juce_wchar textCharacter) throw();
  11830. /** Creates a keypress with a keyCode but no modifiers or text character.
  11831. */
  11832. KeyPress (const int keyCode) throw();
  11833. /** Creates a copy of another KeyPress. */
  11834. KeyPress (const KeyPress& other) throw();
  11835. /** Copies this KeyPress from another one. */
  11836. const KeyPress& operator= (const KeyPress& other) throw();
  11837. /** Compares two KeyPress objects. */
  11838. bool operator== (const KeyPress& other) const throw();
  11839. /** Compares two KeyPress objects. */
  11840. bool operator!= (const KeyPress& other) const throw();
  11841. /** Returns true if this is a valid KeyPress.
  11842. A null keypress can be created by the default constructor, in case it's
  11843. needed.
  11844. */
  11845. bool isValid() const throw() { return keyCode != 0; }
  11846. /** Returns the key code itself.
  11847. This will either be one of the special constants defined in this class,
  11848. or an 8-bit character code.
  11849. */
  11850. int getKeyCode() const throw() { return keyCode; }
  11851. /** Returns the key modifiers.
  11852. @see ModifierKeys
  11853. */
  11854. const ModifierKeys getModifiers() const throw() { return mods; }
  11855. /** Returns the character that is associated with this keypress.
  11856. This is the character that you'd expect to see printed if you press this
  11857. keypress in a text editor or similar component.
  11858. */
  11859. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11860. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11861. the modifiers.
  11862. The values for key codes can either be one of the special constants defined in
  11863. this class, or an 8-bit character code.
  11864. @see getKeyCode
  11865. */
  11866. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11867. /** Converts a textual key description to a KeyPress.
  11868. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11869. This isn't designed to cope with any kind of input, but should be given the
  11870. strings that are created by the getTextDescription() method.
  11871. If the string can't be parsed, the object returned will be invalid.
  11872. @see getTextDescription
  11873. */
  11874. static const KeyPress createFromDescription (const String& textVersion) throw();
  11875. /** Creates a textual description of the key combination.
  11876. e.g. "CTRL + C" or "DELETE".
  11877. To store a keypress in a file, use this method, along with createFromDescription()
  11878. to retrieve it later.
  11879. */
  11880. const String getTextDescription() const throw();
  11881. /** Checks whether the user is currently holding down the keys that make up this
  11882. KeyPress.
  11883. Note that this will return false if any extra modifier keys are
  11884. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11885. then it will be false.
  11886. */
  11887. bool isCurrentlyDown() const throw();
  11888. /** Checks whether a particular key is held down, irrespective of modifiers.
  11889. The values for key codes can either be one of the special constants defined in
  11890. this class, or an 8-bit character code.
  11891. */
  11892. static bool isKeyCurrentlyDown (int keyCode) throw();
  11893. // Key codes
  11894. //
  11895. // Note that the actual values of these are platform-specific and may change
  11896. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  11897. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  11898. //
  11899. static const int spaceKey; /**< key-code for the space bar */
  11900. static const int escapeKey; /**< key-code for the escape key */
  11901. static const int returnKey; /**< key-code for the return key*/
  11902. static const int tabKey; /**< key-code for the tab key*/
  11903. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  11904. static const int backspaceKey; /**< key-code for the backspace key */
  11905. static const int insertKey; /**< key-code for the insert key */
  11906. static const int upKey; /**< key-code for the cursor-up key */
  11907. static const int downKey; /**< key-code for the cursor-down key */
  11908. static const int leftKey; /**< key-code for the cursor-left key */
  11909. static const int rightKey; /**< key-code for the cursor-right key */
  11910. static const int pageUpKey; /**< key-code for the page-up key */
  11911. static const int pageDownKey; /**< key-code for the page-down key */
  11912. static const int homeKey; /**< key-code for the home key */
  11913. static const int endKey; /**< key-code for the end key */
  11914. static const int F1Key; /**< key-code for the F1 key */
  11915. static const int F2Key; /**< key-code for the F2 key */
  11916. static const int F3Key; /**< key-code for the F3 key */
  11917. static const int F4Key; /**< key-code for the F4 key */
  11918. static const int F5Key; /**< key-code for the F5 key */
  11919. static const int F6Key; /**< key-code for the F6 key */
  11920. static const int F7Key; /**< key-code for the F7 key */
  11921. static const int F8Key; /**< key-code for the F8 key */
  11922. static const int F9Key; /**< key-code for the F9 key */
  11923. static const int F10Key; /**< key-code for the F10 key */
  11924. static const int F11Key; /**< key-code for the F11 key */
  11925. static const int F12Key; /**< key-code for the F12 key */
  11926. static const int F13Key; /**< key-code for the F13 key */
  11927. static const int F14Key; /**< key-code for the F14 key */
  11928. static const int F15Key; /**< key-code for the F15 key */
  11929. static const int F16Key; /**< key-code for the F16 key */
  11930. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  11931. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  11932. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  11933. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  11934. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  11935. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  11936. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  11937. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  11938. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  11939. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  11940. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  11941. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  11942. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  11943. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  11944. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  11945. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  11946. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  11947. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  11948. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  11949. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  11950. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  11951. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  11952. juce_UseDebuggingNewOperator
  11953. private:
  11954. int keyCode;
  11955. ModifierKeys mods;
  11956. juce_wchar textCharacter;
  11957. };
  11958. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  11959. /********* End of inlined file: juce_KeyPress.h *********/
  11960. class Component;
  11961. /**
  11962. Receives callbacks when keys are pressed.
  11963. You can add a key listener to a component to be informed when that component
  11964. gets key events. See the Component::addListener method for more details.
  11965. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  11966. */
  11967. class JUCE_API KeyListener
  11968. {
  11969. public:
  11970. /** Destructor. */
  11971. virtual ~KeyListener() {}
  11972. /** Called to indicate that a key has been pressed.
  11973. If your implementation returns true, then the key event is considered to have
  11974. been consumed, and will not be passed on to any other components. If it returns
  11975. false, then the key will be passed to other components that might want to use it.
  11976. @param key the keystroke, including modifier keys
  11977. @param originatingComponent the component that received the key event
  11978. @see keyStateChanged, Component::keyPressed
  11979. */
  11980. virtual bool keyPressed (const KeyPress& key,
  11981. Component* originatingComponent) = 0;
  11982. /** Called when any key is pressed or released.
  11983. When this is called, classes that might be interested in
  11984. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  11985. check whether their key has changed.
  11986. If your implementation returns true, then the key event is considered to have
  11987. been consumed, and will not be passed on to any other components. If it returns
  11988. false, then the key will be passed to other components that might want to use it.
  11989. @param originatingComponent the component that received the key event
  11990. @see KeyPress, Component::keyStateChanged
  11991. */
  11992. virtual bool keyStateChanged (Component* originatingComponent);
  11993. };
  11994. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  11995. /********* End of inlined file: juce_KeyListener.h *********/
  11996. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  11997. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  11998. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  11999. class Component;
  12000. /**
  12001. Controls the order in which focus moves between components.
  12002. The default algorithm used by this class to work out the order of traversal
  12003. is as follows:
  12004. - if two components both have an explicit focus order specified, then the
  12005. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12006. method).
  12007. - any component with an explicit focus order greater than 0 comes before ones
  12008. that don't have an order specified.
  12009. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12010. order.
  12011. If you need traversal in a more customised way, you can create a subclass
  12012. of KeyboardFocusTraverser that uses your own algorithm, and use
  12013. Component::createFocusTraverser() to create it.
  12014. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12015. */
  12016. class JUCE_API KeyboardFocusTraverser
  12017. {
  12018. public:
  12019. KeyboardFocusTraverser();
  12020. /** Destructor. */
  12021. virtual ~KeyboardFocusTraverser();
  12022. /** Returns the component that should be given focus after the specified one
  12023. when moving "forwards".
  12024. The default implementation will return the next component which is to the
  12025. right of or below this one.
  12026. This may return 0 if there's no suitable candidate.
  12027. */
  12028. virtual Component* getNextComponent (Component* current);
  12029. /** Returns the component that should be given focus after the specified one
  12030. when moving "backwards".
  12031. The default implementation will return the next component which is to the
  12032. left of or above this one.
  12033. This may return 0 if there's no suitable candidate.
  12034. */
  12035. virtual Component* getPreviousComponent (Component* current);
  12036. /** Returns the component that should receive focus be default within the given
  12037. parent component.
  12038. The default implementation will just return the foremost child component that
  12039. wants focus.
  12040. This may return 0 if there's no suitable candidate.
  12041. */
  12042. virtual Component* getDefaultComponent (Component* parentComponent);
  12043. };
  12044. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12045. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12046. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12047. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12048. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12049. /********* Start of inlined file: juce_Graphics.h *********/
  12050. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12051. #define __JUCE_GRAPHICS_JUCEHEADER__
  12052. /********* Start of inlined file: juce_Font.h *********/
  12053. #ifndef __JUCE_FONT_JUCEHEADER__
  12054. #define __JUCE_FONT_JUCEHEADER__
  12055. /********* Start of inlined file: juce_Typeface.h *********/
  12056. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12057. #define __JUCE_TYPEFACE_JUCEHEADER__
  12058. /********* Start of inlined file: juce_Path.h *********/
  12059. #ifndef __JUCE_PATH_JUCEHEADER__
  12060. #define __JUCE_PATH_JUCEHEADER__
  12061. /********* Start of inlined file: juce_AffineTransform.h *********/
  12062. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12063. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12064. /**
  12065. Represents a 2D affine-transformation matrix.
  12066. An affine transformation is a transformation such as a rotation, scale, shear,
  12067. resize or translation.
  12068. These are used for various 2D transformation tasks, e.g. with Path objects.
  12069. @see Path, Point, Line
  12070. */
  12071. class JUCE_API AffineTransform
  12072. {
  12073. public:
  12074. /** Creates an identity transform. */
  12075. AffineTransform() throw();
  12076. /** Creates a copy of another transform. */
  12077. AffineTransform (const AffineTransform& other) throw();
  12078. /** Creates a transform from a set of raw matrix values.
  12079. The resulting matrix is:
  12080. (mat00 mat01 mat02)
  12081. (mat10 mat11 mat12)
  12082. ( 0 0 1 )
  12083. */
  12084. AffineTransform (const float mat00, const float mat01, const float mat02,
  12085. const float mat10, const float mat11, const float mat12) throw();
  12086. /** Copies from another AffineTransform object */
  12087. const AffineTransform& operator= (const AffineTransform& other) throw();
  12088. /** Compares two transforms. */
  12089. bool operator== (const AffineTransform& other) const throw();
  12090. /** Compares two transforms. */
  12091. bool operator!= (const AffineTransform& other) const throw();
  12092. /** A ready-to-use identity transform, which you can use to append other
  12093. transformations to.
  12094. e.g. @code
  12095. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12096. .scaled (2.0f);
  12097. @endcode
  12098. */
  12099. static const AffineTransform identity;
  12100. /** Transforms a 2D co-ordinate using this matrix. */
  12101. void transformPoint (float& x,
  12102. float& y) const throw();
  12103. /** Transforms a 2D co-ordinate using this matrix. */
  12104. void transformPoint (double& x,
  12105. double& y) const throw();
  12106. /** Returns a new transform which is the same as this one followed by a translation. */
  12107. const AffineTransform translated (const float deltaX,
  12108. const float deltaY) const throw();
  12109. /** Returns a new transform which is a translation. */
  12110. static const AffineTransform translation (const float deltaX,
  12111. const float deltaY) throw();
  12112. /** Returns a transform which is the same as this one followed by a rotation.
  12113. The rotation is specified by a number of radians to rotate clockwise, centred around
  12114. the origin (0, 0).
  12115. */
  12116. const AffineTransform rotated (const float angleInRadians) const throw();
  12117. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12118. The rotation is specified by a number of radians to rotate clockwise, centred around
  12119. the co-ordinates passed in.
  12120. */
  12121. const AffineTransform rotated (const float angleInRadians,
  12122. const float pivotX,
  12123. const float pivotY) const throw();
  12124. /** Returns a new transform which is a rotation about (0, 0). */
  12125. static const AffineTransform rotation (const float angleInRadians) throw();
  12126. /** Returns a new transform which is a rotation about a given point. */
  12127. static const AffineTransform rotation (const float angleInRadians,
  12128. const float pivotX,
  12129. const float pivotY) throw();
  12130. /** Returns a transform which is the same as this one followed by a re-scaling.
  12131. The scaling is centred around the origin (0, 0).
  12132. */
  12133. const AffineTransform scaled (const float factorX,
  12134. const float factorY) const throw();
  12135. /** Returns a new transform which is a re-scale about the origin. */
  12136. static const AffineTransform scale (const float factorX,
  12137. const float factorY) throw();
  12138. /** Returns a transform which is the same as this one followed by a shear.
  12139. The shear is centred around the origin (0, 0).
  12140. */
  12141. const AffineTransform sheared (const float shearX,
  12142. const float shearY) const throw();
  12143. /** Returns a matrix which is the inverse operation of this one.
  12144. Some matrices don't have an inverse - in this case, the method will just return
  12145. an identity transform.
  12146. */
  12147. const AffineTransform inverted() const throw();
  12148. /** Returns the result of concatenating another transformation after this one. */
  12149. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12150. /** Returns true if this transform has no effect on points. */
  12151. bool isIdentity() const throw();
  12152. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12153. bool isSingularity() const throw();
  12154. juce_UseDebuggingNewOperator
  12155. /* The transform matrix is:
  12156. (mat00 mat01 mat02)
  12157. (mat10 mat11 mat12)
  12158. ( 0 0 1 )
  12159. */
  12160. float mat00, mat01, mat02;
  12161. float mat10, mat11, mat12;
  12162. private:
  12163. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12164. const float mat10, const float mat11, const float mat12) const throw();
  12165. };
  12166. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12167. /********* End of inlined file: juce_AffineTransform.h *********/
  12168. /********* Start of inlined file: juce_Point.h *********/
  12169. #ifndef __JUCE_POINT_JUCEHEADER__
  12170. #define __JUCE_POINT_JUCEHEADER__
  12171. /**
  12172. A pair of (x, y) co-ordinates.
  12173. Uses 32-bit floating point accuracy.
  12174. @see Line, Path, AffineTransform
  12175. */
  12176. class JUCE_API Point
  12177. {
  12178. public:
  12179. /** Creates a point with co-ordinates (0, 0). */
  12180. Point() throw();
  12181. /** Creates a copy of another point. */
  12182. Point (const Point& other) throw();
  12183. /** Creates a point from an (x, y) position. */
  12184. Point (const float x, const float y) throw();
  12185. /** Copies this point from another one.
  12186. @see setXY
  12187. */
  12188. const Point& operator= (const Point& other) throw();
  12189. /** Destructor. */
  12190. ~Point() throw();
  12191. /** Returns the point's x co-ordinate. */
  12192. inline float getX() const throw() { return x; }
  12193. /** Returns the point's y co-ordinate. */
  12194. inline float getY() const throw() { return y; }
  12195. /** Changes the point's x and y co-ordinates. */
  12196. void setXY (const float x,
  12197. const float y) throw();
  12198. /** Uses a transform to change the point's co-ordinates.
  12199. @see AffineTransform::transformPoint
  12200. */
  12201. void applyTransform (const AffineTransform& transform) throw();
  12202. juce_UseDebuggingNewOperator
  12203. private:
  12204. float x, y;
  12205. };
  12206. #endif // __JUCE_POINT_JUCEHEADER__
  12207. /********* End of inlined file: juce_Point.h *********/
  12208. /********* Start of inlined file: juce_Justification.h *********/
  12209. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12210. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12211. /**
  12212. Represents a type of justification to be used when positioning graphical items.
  12213. e.g. it indicates whether something should be placed top-left, top-right,
  12214. centred, etc.
  12215. It is used in various places wherever this kind of information is needed.
  12216. */
  12217. class JUCE_API Justification
  12218. {
  12219. public:
  12220. /** Creates a Justification object using a combination of flags. */
  12221. inline Justification (const int flags_) throw() : flags (flags_) {}
  12222. /** Creates a copy of another Justification object. */
  12223. Justification (const Justification& other) throw();
  12224. /** Copies another Justification object. */
  12225. const Justification& operator= (const Justification& other) throw();
  12226. /** Returns the raw flags that are set for this Justification object. */
  12227. inline int getFlags() const throw() { return flags; }
  12228. /** Tests a set of flags for this object.
  12229. @returns true if any of the flags passed in are set on this object.
  12230. */
  12231. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12232. /** Returns just the flags from this object that deal with vertical layout. */
  12233. int getOnlyVerticalFlags() const throw();
  12234. /** Returns just the flags from this object that deal with horizontal layout. */
  12235. int getOnlyHorizontalFlags() const throw();
  12236. /** Adjusts the position of a rectangle to fit it into a space.
  12237. The (x, y) position of the rectangle will be updated to position it inside the
  12238. given space according to the justification flags.
  12239. */
  12240. void applyToRectangle (int& x, int& y,
  12241. const int w, const int h,
  12242. const int spaceX, const int spaceY,
  12243. const int spaceW, const int spaceH) const throw();
  12244. /** Flag values that can be combined and used in the constructor. */
  12245. enum
  12246. {
  12247. /** Indicates that the item should be aligned against the left edge of the available space. */
  12248. left = 1,
  12249. /** Indicates that the item should be aligned against the right edge of the available space. */
  12250. right = 2,
  12251. /** Indicates that the item should be placed in the centre between the left and right
  12252. sides of the available space. */
  12253. horizontallyCentred = 4,
  12254. /** Indicates that the item should be aligned against the top edge of the available space. */
  12255. top = 8,
  12256. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12257. bottom = 16,
  12258. /** Indicates that the item should be placed in the centre between the top and bottom
  12259. sides of the available space. */
  12260. verticallyCentred = 32,
  12261. /** Indicates that lines of text should be spread out to fill the maximum width
  12262. available, so that both margins are aligned vertically.
  12263. */
  12264. horizontallyJustified = 64,
  12265. /** Indicates that the item should be centred vertically and horizontally.
  12266. This is equivalent to (horizontallyCentred | verticallyCentred)
  12267. */
  12268. centred = 36,
  12269. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12270. This is equivalent to (left | verticallyCentred)
  12271. */
  12272. centredLeft = 33,
  12273. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12274. This is equivalent to (right | verticallyCentred)
  12275. */
  12276. centredRight = 34,
  12277. /** Indicates that the item should be centred horizontally and placed at the top.
  12278. This is equivalent to (horizontallyCentred | top)
  12279. */
  12280. centredTop = 12,
  12281. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12282. This is equivalent to (horizontallyCentred | bottom)
  12283. */
  12284. centredBottom = 20,
  12285. /** Indicates that the item should be placed in the top-left corner.
  12286. This is equivalent to (left | top)
  12287. */
  12288. topLeft = 9,
  12289. /** Indicates that the item should be placed in the top-right corner.
  12290. This is equivalent to (right | top)
  12291. */
  12292. topRight = 10,
  12293. /** Indicates that the item should be placed in the bottom-left corner.
  12294. This is equivalent to (left | bottom)
  12295. */
  12296. bottomLeft = 17,
  12297. /** Indicates that the item should be placed in the bottom-left corner.
  12298. This is equivalent to (right | bottom)
  12299. */
  12300. bottomRight = 18
  12301. };
  12302. private:
  12303. int flags;
  12304. };
  12305. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12306. /********* End of inlined file: juce_Justification.h *********/
  12307. /**
  12308. A path is a sequence of lines and curves that may either form a closed shape
  12309. or be open-ended.
  12310. To use a path, you can create an empty one, then add lines and curves to it
  12311. to create shapes, then it can be rendered by a Graphics context or used
  12312. for geometric operations.
  12313. e.g. @code
  12314. Path myPath;
  12315. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12316. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12317. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12318. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12319. // add an ellipse as well, which will form a second sub-path within the path..
  12320. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12321. // double the width of the whole thing..
  12322. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12323. // and draw it to a graphics context with a 5-pixel thick outline.
  12324. g.strokePath (myPath, PathStrokeType (5.0f));
  12325. @endcode
  12326. A path object can actually contain multiple sub-paths, which may themselves
  12327. be open or closed.
  12328. @see PathFlatteningIterator, PathStrokeType, Graphics
  12329. */
  12330. class JUCE_API Path : private ArrayAllocationBase <float>
  12331. {
  12332. public:
  12333. /** Creates an empty path. */
  12334. Path() throw();
  12335. /** Creates a copy of another path. */
  12336. Path (const Path& other) throw();
  12337. /** Destructor. */
  12338. ~Path() throw();
  12339. /** Copies this path from another one. */
  12340. const Path& operator= (const Path& other) throw();
  12341. /** Returns true if the path doesn't contain any lines or curves. */
  12342. bool isEmpty() const throw();
  12343. /** Returns the smallest rectangle that contains all points within the path.
  12344. */
  12345. void getBounds (float& x, float& y,
  12346. float& w, float& h) const throw();
  12347. /** Returns the smallest rectangle that contains all points within the path
  12348. after it's been transformed with the given tranasform matrix.
  12349. */
  12350. void getBoundsTransformed (const AffineTransform& transform,
  12351. float& x, float& y,
  12352. float& w, float& h) const throw();
  12353. /** Checks whether a point lies within the path.
  12354. This is only relevent for closed paths (see closeSubPath()), and
  12355. may produce false results if used on a path which has open sub-paths.
  12356. The path's winding rule is taken into account by this method.
  12357. @see closeSubPath, setUsingNonZeroWinding
  12358. */
  12359. bool contains (const float x,
  12360. const float y) const throw();
  12361. /** Checks whether a line crosses the path.
  12362. This will return positive if the line crosses any of the paths constituent
  12363. lines or curves. It doesn't take into account whether the line is inside
  12364. or outside the path, or whether the path is open or closed.
  12365. */
  12366. bool intersectsLine (const float x1, const float y1,
  12367. const float x2, const float y2) throw();
  12368. /** Removes all lines and curves, resetting the path completely. */
  12369. void clear() throw();
  12370. /** Begins a new subpath with a given starting position.
  12371. This will move the path's current position to the co-ordinates passed in and
  12372. make it ready to draw lines or curves starting from this position.
  12373. After adding whatever lines and curves are needed, you can either
  12374. close the current sub-path using closeSubPath() or call startNewSubPath()
  12375. to move to a new sub-path, leaving the old one open-ended.
  12376. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12377. */
  12378. void startNewSubPath (const float startX,
  12379. const float startY) throw();
  12380. /** Closes a the current sub-path with a line back to its start-point.
  12381. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12382. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12383. to join the final point back to the start.
  12384. This ensures that closes shapes are recognised as such, and this is
  12385. important for tasks like drawing strokes, which needs to know whether to
  12386. draw end-caps or not.
  12387. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12388. */
  12389. void closeSubPath() throw();
  12390. /** Adds a line from the shape's last position to a new end-point.
  12391. This will connect the end-point of the last line or curve that was added
  12392. to a new point, using a straight line.
  12393. See the class description for an example of how to add lines and curves to a path.
  12394. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12395. */
  12396. void lineTo (const float endX,
  12397. const float endY) throw();
  12398. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12399. This will connect the end-point of the last line or curve that was added
  12400. to a new point, using a quadratic spline with one control-point.
  12401. See the class description for an example of how to add lines and curves to a path.
  12402. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12403. */
  12404. void quadraticTo (const float controlPointX,
  12405. const float controlPointY,
  12406. const float endPointX,
  12407. const float endPointY) throw();
  12408. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12409. This will connect the end-point of the last line or curve that was added
  12410. to a new point, using a cubic spline with two control-points.
  12411. See the class description for an example of how to add lines and curves to a path.
  12412. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12413. */
  12414. void cubicTo (const float controlPoint1X,
  12415. const float controlPoint1Y,
  12416. const float controlPoint2X,
  12417. const float controlPoint2Y,
  12418. const float endPointX,
  12419. const float endPointY) throw();
  12420. /** Returns the last point that was added to the path by one of the drawing methods.
  12421. */
  12422. const Point getCurrentPosition() const;
  12423. /** Adds a rectangle to the path.
  12424. The rectangle is added as a new sub-path. (Any currently open paths will be
  12425. left open).
  12426. @see addRoundedRectangle, addTriangle
  12427. */
  12428. void addRectangle (const float x, const float y,
  12429. const float w, const float h) throw();
  12430. /** Adds a rectangle with rounded corners to the path.
  12431. The rectangle is added as a new sub-path. (Any currently open paths will be
  12432. left open).
  12433. @see addRectangle, addTriangle
  12434. */
  12435. void addRoundedRectangle (const float x, const float y,
  12436. const float w, const float h,
  12437. float cornerSize) throw();
  12438. /** Adds a rectangle with rounded corners to the path.
  12439. The rectangle is added as a new sub-path. (Any currently open paths will be
  12440. left open).
  12441. @see addRectangle, addTriangle
  12442. */
  12443. void addRoundedRectangle (const float x, const float y,
  12444. const float w, const float h,
  12445. float cornerSizeX,
  12446. float cornerSizeY) throw();
  12447. /** Adds a triangle to the path.
  12448. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12449. left open).
  12450. Note that whether the vertices are specified in clockwise or anticlockwise
  12451. order will affect how the triangle is filled when it overlaps other
  12452. shapes (the winding order setting will affect this of course).
  12453. */
  12454. void addTriangle (const float x1, const float y1,
  12455. const float x2, const float y2,
  12456. const float x3, const float y3) throw();
  12457. /** Adds a quadrilateral to the path.
  12458. The quad is added as a new closed sub-path. (Any currently open paths will be
  12459. left open).
  12460. Note that whether the vertices are specified in clockwise or anticlockwise
  12461. order will affect how the quad is filled when it overlaps other
  12462. shapes (the winding order setting will affect this of course).
  12463. */
  12464. void addQuadrilateral (const float x1, const float y1,
  12465. const float x2, const float y2,
  12466. const float x3, const float y3,
  12467. const float x4, const float y4) throw();
  12468. /** Adds an ellipse to the path.
  12469. The shape is added as a new sub-path. (Any currently open paths will be
  12470. left open).
  12471. @see addArc
  12472. */
  12473. void addEllipse (const float x, const float y,
  12474. const float width, const float height) throw();
  12475. /** Adds an elliptical arc to the current path.
  12476. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12477. or anti-clockwise according to whether the end angle is greater than the start. This means
  12478. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12479. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12480. @param y the top edge of the rectangle in which the elliptical outline fits
  12481. @param width the width of the rectangle in which the elliptical outline fits
  12482. @param height the height of the rectangle in which the elliptical outline fits
  12483. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12484. top-centre of the ellipse)
  12485. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12486. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12487. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12488. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12489. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12490. it will be added to the current sub-path, continuing from the current postition
  12491. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12492. */
  12493. void addArc (const float x, const float y,
  12494. const float width, const float height,
  12495. const float fromRadians,
  12496. const float toRadians,
  12497. const bool startAsNewSubPath = false) throw();
  12498. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12499. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12500. or anti-clockwise according to whether the end angle is greater than the start. This means
  12501. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12502. @param centreX the centre x of the ellipse
  12503. @param centreY the centre y of the ellipse
  12504. @param radiusX the horizontal radius of the ellipse
  12505. @param radiusY the vertical radius of the ellipse
  12506. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12507. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12508. top-centre of the ellipse)
  12509. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12510. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12511. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12512. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12513. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12514. it will be added to the current sub-path, continuing from the current postition
  12515. @see addArc, arcTo
  12516. */
  12517. void addCentredArc (const float centreX, const float centreY,
  12518. const float radiusX, const float radiusY,
  12519. const float rotationOfEllipse,
  12520. const float fromRadians,
  12521. const float toRadians,
  12522. const bool startAsNewSubPath = false) throw();
  12523. /** Adds a "pie-chart" shape to the path.
  12524. The shape is added as a new sub-path. (Any currently open paths will be
  12525. left open).
  12526. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12527. or anti-clockwise according to whether the end angle is greater than the start. This means
  12528. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12529. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12530. @param y the top edge of the rectangle in which the elliptical outline fits
  12531. @param width the width of the rectangle in which the elliptical outline fits
  12532. @param height the height of the rectangle in which the elliptical outline fits
  12533. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12534. top-centre of the ellipse)
  12535. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12536. top-centre of the ellipse)
  12537. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12538. ellipse at its centre, where this value indicates the inner ellipse's size with
  12539. respect to the outer one.
  12540. @see addArc
  12541. */
  12542. void addPieSegment (const float x, const float y,
  12543. const float width, const float height,
  12544. const float fromRadians,
  12545. const float toRadians,
  12546. const float innerCircleProportionalSize);
  12547. /** Adds a line with a specified thickness.
  12548. The line is added as a new closed sub-path. (Any currently open paths will be
  12549. left open).
  12550. @see addArrow
  12551. */
  12552. void addLineSegment (const float startX, const float startY,
  12553. const float endX, const float endY,
  12554. float lineThickness) throw();
  12555. /** Adds a line with an arrowhead on the end.
  12556. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12557. left open).
  12558. */
  12559. void addArrow (const float startX, const float startY,
  12560. const float endX, const float endY,
  12561. float lineThickness,
  12562. float arrowheadWidth,
  12563. float arrowheadLength) throw();
  12564. /** Adds a star shape to the path.
  12565. */
  12566. void addStar (const float centreX,
  12567. const float centreY,
  12568. const int numberOfPoints,
  12569. const float innerRadius,
  12570. const float outerRadius,
  12571. const float startAngle = 0.0f);
  12572. /** Adds a speech-bubble shape to the path.
  12573. @param bodyX the left of the main body area of the bubble
  12574. @param bodyY the top of the main body area of the bubble
  12575. @param bodyW the width of the main body area of the bubble
  12576. @param bodyH the height of the main body area of the bubble
  12577. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12578. @param arrowTipX the x position that the tip of the arrow should connect to
  12579. @param arrowTipY the y position that the tip of the arrow should connect to
  12580. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12581. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12582. arrow's base should be - this is a proportional distance between 0 and 1.0
  12583. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12584. */
  12585. void addBubble (float bodyX, float bodyY,
  12586. float bodyW, float bodyH,
  12587. float cornerSize,
  12588. float arrowTipX,
  12589. float arrowTipY,
  12590. int whichSide,
  12591. float arrowPositionAlongEdgeProportional,
  12592. float arrowWidth);
  12593. /** Adds another path to this one.
  12594. The new path is added as a new sub-path. (Any currently open paths in this
  12595. path will be left open).
  12596. @param pathToAppend the path to add
  12597. */
  12598. void addPath (const Path& pathToAppend) throw();
  12599. /** Adds another path to this one, transforming it on the way in.
  12600. The new path is added as a new sub-path, its points being transformed by the given
  12601. matrix before being added.
  12602. @param pathToAppend the path to add
  12603. @param transformToApply an optional transform to apply to the incoming vertices
  12604. */
  12605. void addPath (const Path& pathToAppend,
  12606. const AffineTransform& transformToApply) throw();
  12607. /** Swaps the contents of this path with another one.
  12608. The internal data of the two paths is swapped over, so this is much faster than
  12609. copying it to a temp variable and back.
  12610. */
  12611. void swapWithPath (Path& other);
  12612. /** Applies a 2D transform to all the vertices in the path.
  12613. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12614. */
  12615. void applyTransform (const AffineTransform& transform) throw();
  12616. /** Rescales this path to make it fit neatly into a given space.
  12617. This is effectively a quick way of calling
  12618. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12619. @param x the x position of the rectangle to fit the path inside
  12620. @param y the y position of the rectangle to fit the path inside
  12621. @param width the width of the rectangle to fit the path inside
  12622. @param height the height of the rectangle to fit the path inside
  12623. @param preserveProportions if true, it will fit the path into the space without altering its
  12624. horizontal/vertical scale ratio; if false, it will distort the
  12625. path to fill the specified ratio both horizontally and vertically
  12626. @see applyTransform, getTransformToScaleToFit
  12627. */
  12628. void scaleToFit (const float x, const float y,
  12629. const float width, const float height,
  12630. const bool preserveProportions) throw();
  12631. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12632. @param x the x position of the rectangle to fit the path inside
  12633. @param y the y position of the rectangle to fit the path inside
  12634. @param width the width of the rectangle to fit the path inside
  12635. @param height the height of the rectangle to fit the path inside
  12636. @param preserveProportions if true, it will fit the path into the space without altering its
  12637. horizontal/vertical scale ratio; if false, it will distort the
  12638. path to fill the specified ratio both horizontally and vertically
  12639. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12640. than the available rectangle, so this describes how it should be
  12641. positioned within the space.
  12642. @returns an appropriate transformation
  12643. @see applyTransform, scaleToFit
  12644. */
  12645. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12646. const float width, const float height,
  12647. const bool preserveProportions,
  12648. const Justification& justificationType = Justification::centred) const throw();
  12649. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12650. Wherever two lines meet at an angle, this will replace the corner with a curve
  12651. of the given radius.
  12652. */
  12653. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12654. /** Changes the winding-rule to be used when filling the path.
  12655. If set to true (which is the default), then the path uses a non-zero-winding rule
  12656. to determine which points are inside the path. If set to false, it uses an
  12657. alternate-winding rule.
  12658. The winding-rule comes into play when areas of the shape overlap other
  12659. areas, and determines whether the overlapping regions are considered to be
  12660. inside or outside.
  12661. Changing this value just sets a flag - it doesn't affect the contents of the
  12662. path.
  12663. @see isUsingNonZeroWinding
  12664. */
  12665. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12666. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12667. The default for a new path is true.
  12668. @see setUsingNonZeroWinding
  12669. */
  12670. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12671. /** Iterates the lines and curves that a path contains.
  12672. @see Path, PathFlatteningIterator
  12673. */
  12674. class JUCE_API Iterator
  12675. {
  12676. public:
  12677. Iterator (const Path& path);
  12678. ~Iterator();
  12679. /** Moves onto the next element in the path.
  12680. If this returns false, there are no more elements. If it returns true,
  12681. the elementType variable will be set to the type of the current element,
  12682. and some of the x and y variables will be filled in with values.
  12683. */
  12684. bool next();
  12685. enum PathElementType
  12686. {
  12687. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12688. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12689. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12690. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12691. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12692. };
  12693. PathElementType elementType;
  12694. float x1, y1, x2, y2, x3, y3;
  12695. private:
  12696. const Path& path;
  12697. int index;
  12698. Iterator (const Iterator&);
  12699. const Iterator& operator= (const Iterator&);
  12700. };
  12701. /** Loads a stored path from a data stream.
  12702. The data in the stream must have been written using writePathToStream().
  12703. Note that this will append the stored path to whatever is currently in
  12704. this path, so you might need to call clear() beforehand.
  12705. @see loadPathFromData, writePathToStream
  12706. */
  12707. void loadPathFromStream (InputStream& source);
  12708. /** Loads a stored path from a block of data.
  12709. This is similar to loadPathFromStream(), but just reads from a block
  12710. of data. Useful if you're including stored shapes in your code as a
  12711. block of static data.
  12712. @see loadPathFromStream, writePathToStream
  12713. */
  12714. void loadPathFromData (const unsigned char* const data,
  12715. const int numberOfBytes) throw();
  12716. /** Stores the path by writing it out to a stream.
  12717. After writing out a path, you can reload it using loadPathFromStream().
  12718. @see loadPathFromStream, loadPathFromData
  12719. */
  12720. void writePathToStream (OutputStream& destination) const;
  12721. /** Creates a string containing a textual representation of this path.
  12722. @see restoreFromString
  12723. */
  12724. const String toString() const;
  12725. /** Restores this path from a string that was created with the toString() method.
  12726. @see toString()
  12727. */
  12728. void restoreFromString (const String& stringVersion);
  12729. juce_UseDebuggingNewOperator
  12730. private:
  12731. friend class PathFlatteningIterator;
  12732. friend class Path::Iterator;
  12733. int numElements;
  12734. float pathXMin, pathXMax, pathYMin, pathYMax;
  12735. bool useNonZeroWinding;
  12736. static const float lineMarker;
  12737. static const float moveMarker;
  12738. static const float quadMarker;
  12739. static const float cubicMarker;
  12740. static const float closeSubPathMarker;
  12741. };
  12742. #endif // __JUCE_PATH_JUCEHEADER__
  12743. /********* End of inlined file: juce_Path.h *********/
  12744. class Font;
  12745. class Typeface;
  12746. /**
  12747. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12748. @see Typeface, PositionedGlyph, GlyphArrangement
  12749. */
  12750. class JUCE_API TypefaceGlyphInfo
  12751. {
  12752. public:
  12753. /** Returns the path that describes the glyph's outline.
  12754. This is normalised to a height of 1.0, and its origin is the
  12755. left-hand edge of the glyph's baseline.
  12756. */
  12757. const Path& getPath() const throw() { return path; }
  12758. /** Returns the unicode character that this glyph represents. */
  12759. juce_wchar getCharacter() const throw() { return character; }
  12760. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12761. /** Returns the distance to leave between this and a following character.
  12762. The value returned is expressed as a proportion of the font's height.
  12763. */
  12764. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12765. /** Returns the typeface that this glyph belongs to. */
  12766. Typeface* getTypeface() const throw() { return typeface; }
  12767. private:
  12768. friend class Typeface;
  12769. struct KerningPair
  12770. {
  12771. juce_wchar character2;
  12772. float kerningAmount;
  12773. };
  12774. const juce_wchar character;
  12775. const Path path;
  12776. float width;
  12777. MemoryBlock kerningPairs;
  12778. Typeface* const typeface;
  12779. TypefaceGlyphInfo (const juce_wchar character,
  12780. const Path& shape,
  12781. const float horizontalSeparation,
  12782. Typeface* const typeface) throw();
  12783. ~TypefaceGlyphInfo() throw();
  12784. KerningPair& getKerningPair (const int index) const throw();
  12785. int getNumKerningPairs() const throw();
  12786. void addKerningPair (const juce_wchar subsequentCharacter,
  12787. const float extraKerningAmount) throw();
  12788. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12789. };
  12790. /**
  12791. Represents a size-independent system font.
  12792. A Font object represents a particular Typeface along with a specific size,
  12793. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12794. of the shapes of the glyphs and their properties.
  12795. */
  12796. class JUCE_API Typeface : public ReferenceCountedObject
  12797. {
  12798. public:
  12799. /** Tries to load a named system font and to initialise all the glyphs
  12800. appropriately from it.
  12801. @param faceName the name of the typeface, e.g. "Times"
  12802. @param bold whether to try to find a bold version of the font (may not always be available)
  12803. @param italic whether to try to find an italicised version of the font (may not always be available)
  12804. */
  12805. Typeface (const String& faceName,
  12806. const bool bold,
  12807. const bool italic);
  12808. /** Creates a copy of another typeface */
  12809. Typeface (const Typeface& other);
  12810. /** Destructor. */
  12811. ~Typeface();
  12812. /** Copies another typeface over this one. */
  12813. const Typeface& operator= (const Typeface& other) throw();
  12814. /** Returns a unique ID for the typeface.
  12815. This is based on the name and style, so can be used to compare two Typeface objects.
  12816. */
  12817. int hashCode() const throw() { return hash; }
  12818. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12819. const String& getName() const throw() { return typefaceName; }
  12820. /** Returns the font's ascent as a proportion of its height. */
  12821. float getAscent() const throw() { return ascent; }
  12822. /** Returns true if the font is flagged as being bold. */
  12823. bool isBold() const throw() { return bold; }
  12824. /** Returns true if the typeface's 'italic' flag is set. */
  12825. bool isItalic() const throw() { return italic; }
  12826. /** Finds the Path that describes the outline shape of a character.
  12827. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12828. height of the font).
  12829. This may return 0 if the typeface has no characters, but if the character
  12830. that is asked for is not found, it will first try to return a default
  12831. character instead.
  12832. */
  12833. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12834. /** Tries to find the information describing a glyph for this character.
  12835. If there isn't a glyph specifically for the character it will return
  12836. a default glyph instead; if the typeface is empty, it may return a null
  12837. pointer.
  12838. */
  12839. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12840. /** Deletes all the glyphs and kerning data fom the typeface. */
  12841. void clear() throw();
  12842. /** Adds a glyph to the typeface.
  12843. This is typically only called by the platform-specific code that generates
  12844. the typeface from a system font.
  12845. */
  12846. void addGlyph (const juce_wchar character,
  12847. const Path& path,
  12848. const float horizontalSpacing) throw();
  12849. /** Adds a kerning distance to the typeface.
  12850. The extra amount passed in is expressed as a proportion of the font's
  12851. height, normalised to 1.0.
  12852. This is typically only called by the platform-specific code that generates
  12853. the typeface from a system font.
  12854. */
  12855. void addKerningPair (const juce_wchar firstChar,
  12856. const juce_wchar secondChar,
  12857. const float extraAmount) throw();
  12858. /** Sets the typeface's name.
  12859. This is typically only called by the platform-specific code that generates
  12860. the typeface from a system font. Calling this method won't actually affect
  12861. the underlying font being used.
  12862. */
  12863. void setName (const String& name) throw();
  12864. /** Sets the font's ascent value, as a proportion of the font height.
  12865. This is typically only called by the platform-specific code that generates
  12866. the typeface from a system font.
  12867. */
  12868. void setAscent (const float newAscent) throw();
  12869. /** Sets the typeface's 'bold' flag.
  12870. This is typically only called by the platform-specific code that generates
  12871. the typeface from a system font.
  12872. */
  12873. void setBold (const bool shouldBeBold) throw();
  12874. /** Sets the typeface's 'italic' flag.
  12875. This is typically only called by the platform-specific code that generates
  12876. the typeface from a system font.
  12877. */
  12878. void setItalic (const bool shouldBeItalic) throw();
  12879. /** Changes the character index to use as the default character.
  12880. This is the character that gets returned for characters which don't have a
  12881. glyph set for them.
  12882. */
  12883. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12884. /** Creates a typeface from data created using Typeface::serialise().
  12885. This will attempt to load a compressed typeface that was created using
  12886. the Typeface::serialise() method. This is handy if you want to store
  12887. a typeface in your application as a binary blob, and use it without
  12888. having to actually install it on the computer.
  12889. @see Typeface::serialise()
  12890. */
  12891. Typeface (InputStream& serialisedTypefaceStream);
  12892. /** Writes the typeface to a stream (using a proprietary format).
  12893. This lets you save a typeface and reload it using the
  12894. Typeface::Typeface (InputStream&) constructor. The data's saved in
  12895. a compressed format.
  12896. @see Typeface::Typeface (InputStream&)
  12897. */
  12898. void serialise (OutputStream& outputStream);
  12899. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  12900. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  12901. juce_UseDebuggingNewOperator
  12902. private:
  12903. VoidArray glyphs;
  12904. short lookupTable [128];
  12905. String typefaceName;
  12906. int hash;
  12907. float ascent; // as a proportion of the height
  12908. bool bold, italic, isFullyPopulated;
  12909. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  12910. Typeface() throw();
  12911. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  12912. friend class Font;
  12913. friend class TypefaceCache;
  12914. friend class FontGlyphAlphaMap;
  12915. static const Ptr getTypefaceFor (const Font& font) throw();
  12916. // this is a platform-dependent method that will look for the given typeface
  12917. // and set up its kerning tables, etc. accordingly.
  12918. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  12919. // to the typeface immediately, rather than having to add them later on-demand.
  12920. void initialiseTypefaceCharacteristics (const String& fontName,
  12921. bool bold, bool italic,
  12922. bool addAllGlyphsToFont) throw();
  12923. // platform-specific routine to look up and add a glyph to this typeface
  12924. bool findAndAddSystemGlyph (juce_wchar character) throw();
  12925. void updateHashCode() throw();
  12926. };
  12927. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  12928. /********* End of inlined file: juce_Typeface.h *********/
  12929. /**
  12930. Represents a particular font, including its size, style, etc.
  12931. Apart from the typeface to be used, a Font object also dictates whether
  12932. the font is bold, italic, underlined, how big it is, and its kerning and
  12933. horizontal scale factor.
  12934. @see Typeface
  12935. */
  12936. class JUCE_API Font
  12937. {
  12938. public:
  12939. /** A combination of these values is used by the constructor to specify the
  12940. style of font to use.
  12941. */
  12942. enum FontStyleFlags
  12943. {
  12944. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  12945. bold = 1, /**< boldens the font. @see setStyleFlags */
  12946. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  12947. underlined = 4 /**< underlines the font. @see setStyleFlags */
  12948. };
  12949. /** Creates a sans-serif font in a given size.
  12950. @param fontHeight the height in pixels (can be fractional)
  12951. @param styleFlags the style to use - this can be a combination of the
  12952. Font::bold, Font::italic and Font::underlined, or
  12953. just Font::plain for the normal style.
  12954. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12955. */
  12956. Font (const float fontHeight,
  12957. const int styleFlags = plain) throw();
  12958. /** Creates a font with a given typeface and parameters.
  12959. @param typefaceName the name of the typeface to use
  12960. @param fontHeight the height in pixels (can be fractional)
  12961. @param styleFlags the style to use - this can be a combination of the
  12962. Font::bold, Font::italic and Font::underlined, or
  12963. just Font::plain for the normal style.
  12964. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12965. */
  12966. Font (const String& typefaceName,
  12967. const float fontHeight,
  12968. const int styleFlags) throw();
  12969. /** Creates a copy of another Font object. */
  12970. Font (const Font& other) throw();
  12971. /** Creates a font based on a typeface.
  12972. The font object stores its own internal copy of the typeface, so you can safely
  12973. delete the one passed in after calling this.
  12974. */
  12975. Font (const Typeface& typeface) throw();
  12976. /** Creates a basic sans-serif font at a default height.
  12977. You should use one of the other constructors for creating a font that you're planning
  12978. on drawing with - this constructor is here to help initialise objects before changing
  12979. the font's settings later.
  12980. */
  12981. Font() throw();
  12982. /** Copies this font from another one. */
  12983. const Font& operator= (const Font& other) throw();
  12984. bool operator== (const Font& other) const throw();
  12985. bool operator!= (const Font& other) const throw();
  12986. /** Destructor. */
  12987. ~Font() throw();
  12988. /** Changes the name of the typeface family.
  12989. e.g. "Arial", "Courier", etc.
  12990. If a suitable font isn't found on the machine, it'll just use a default instead.
  12991. */
  12992. void setTypefaceName (const String& faceName) throw();
  12993. /** Returns the name of the typeface family that this font uses.
  12994. e.g. "Arial", "Courier", etc.
  12995. */
  12996. const String& getTypefaceName() const throw() { return typefaceName; }
  12997. /** Returns a platform-specific font family that is recommended for sans-serif fonts.
  12998. This is the typeface that will be used when a font is created without
  12999. specifying another name.
  13000. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  13001. setDefaultSansSerifFontName
  13002. */
  13003. static const String getDefaultSansSerifFontName() throw();
  13004. /** Returns a platform-specific font family that is recommended for serif fonts.
  13005. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13006. */
  13007. static const String getDefaultSerifFontName() throw();
  13008. /** Returns a platform-specific font family that is recommended for monospaced fonts.
  13009. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13010. */
  13011. static const String getDefaultMonospacedFontName() throw();
  13012. /** Changes the default sans-serif typeface family name.
  13013. This changes the value that is returned by getDefaultSansSerifFontName(), so
  13014. changing this will change the default system font used.
  13015. @see getDefaultSansSerifFontName
  13016. */
  13017. static void setDefaultSansSerifFontName (const String& name) throw();
  13018. /** Returns the total height of this font.
  13019. This is the maximum height, from the top of the ascent to the bottom of the
  13020. descenders.
  13021. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13022. */
  13023. float getHeight() const throw() { return height; }
  13024. /** Changes the font's height.
  13025. @see getHeight, setHeightWithoutChangingWidth
  13026. */
  13027. void setHeight (float newHeight) throw();
  13028. /** Changes the font's height without changing its width.
  13029. This alters the horizontal scale to compensate for the change in height.
  13030. */
  13031. void setHeightWithoutChangingWidth (float newHeight) throw();
  13032. /** Returns the height of the font above its baseline.
  13033. This is the maximum height from the baseline to the top.
  13034. @see getHeight, getDescent
  13035. */
  13036. float getAscent() const throw();
  13037. /** Returns the amount that the font descends below its baseline.
  13038. This is calculated as (getHeight() - getAscent()).
  13039. @see getAscent, getHeight
  13040. */
  13041. float getDescent() const throw();
  13042. /** Returns the font's style flags.
  13043. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13044. enum, to describe whether the font is bold, italic, etc.
  13045. @see FontStyleFlags
  13046. */
  13047. int getStyleFlags() const throw() { return styleFlags; }
  13048. /** Changes the font's style.
  13049. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13050. enum, to set the font's properties
  13051. @see FontStyleFlags
  13052. */
  13053. void setStyleFlags (const int newFlags) throw();
  13054. /** Makes the font bold or non-bold. */
  13055. void setBold (const bool shouldBeBold) throw();
  13056. /** Returns true if the font is bold. */
  13057. bool isBold() const throw();
  13058. /** Makes the font italic or non-italic. */
  13059. void setItalic (const bool shouldBeItalic) throw();
  13060. /** Returns true if the font is italic. */
  13061. bool isItalic() const throw();
  13062. /** Makes the font underlined or non-underlined. */
  13063. void setUnderline (const bool shouldBeUnderlined) throw();
  13064. /** Returns true if the font is underlined. */
  13065. bool isUnderlined() const throw();
  13066. /** Changes the font's horizontal scale factor.
  13067. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13068. narrower, greater than 1.0 will be stretched out.
  13069. */
  13070. void setHorizontalScale (const float scaleFactor) throw();
  13071. /** Returns the font's horizontal scale.
  13072. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13073. than 1.0 will be stretched out.
  13074. @see setHorizontalScale
  13075. */
  13076. float getHorizontalScale() const throw() { return horizontalScale; }
  13077. /** Changes the font's kerning.
  13078. @param extraKerning a multiple of the font's height that will be added
  13079. to space between the characters. So a value of zero is
  13080. normal spacing, positive values spread the letters out,
  13081. negative values make them closer together.
  13082. */
  13083. void setExtraKerningFactor (const float extraKerning) throw();
  13084. /** Returns the font's kerning.
  13085. This is the extra space added between adjacent characters, as a proportion
  13086. of the font's height.
  13087. A value of zero is normal spacing, positive values will spread the letters
  13088. out more, and negative values make them closer together.
  13089. */
  13090. float getExtraKerningFactor() const throw() { return kerning; }
  13091. /** Changes all the font's characteristics with one call. */
  13092. void setSizeAndStyle (const float newHeight,
  13093. const int newStyleFlags,
  13094. const float newHorizontalScale,
  13095. const float newKerningAmount) throw();
  13096. /** Resets this font's characteristics.
  13097. This is basically like saying "myFont = Font();", because it resets the
  13098. typeface, size, style, etc to a default state. Not very useful to most
  13099. people, its raison d'etre is to help the Graphics class be more efficient.
  13100. */
  13101. void resetToDefaultState() throw();
  13102. /** Returns the total width of a string as it would be drawn using this font.
  13103. For a more accurate floating-point result, use getStringWidthFloat().
  13104. */
  13105. int getStringWidth (const String& text) const throw();
  13106. /** Returns the total width of a string as it would be drawn using this font.
  13107. @see getStringWidth
  13108. */
  13109. float getStringWidthFloat (const String& text) const throw();
  13110. /** Returns the typeface used by this font.
  13111. Note that the object returned may go out of scope if this font is deleted
  13112. or has its style changed.
  13113. */
  13114. Typeface* getTypeface() const throw();
  13115. /** Creates an array of Font objects to represent all the fonts on the system.
  13116. If you just need the names of the typefaces, you can also use
  13117. findAllTypefaceNames() instead.
  13118. @param results the array to which new Font objects will be added.
  13119. */
  13120. static void findFonts (OwnedArray<Font>& results) throw();
  13121. /** Returns a list of all the available typeface names.
  13122. The names returned can be passed into setTypefaceName().
  13123. You can use this instead of findFonts() if you only need their names, and not
  13124. font objects.
  13125. */
  13126. static const StringArray findAllTypefaceNames() throw();
  13127. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13128. in the requested typeface.
  13129. */
  13130. static const String getFallbackFontName() throw();
  13131. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13132. available in whatever font you're trying to use.
  13133. */
  13134. static void setFallbackFontName (const String& name) throw();
  13135. juce_UseDebuggingNewOperator
  13136. private:
  13137. friend class FontGlyphAlphaMap;
  13138. friend class TypefaceCache;
  13139. String typefaceName;
  13140. float height, horizontalScale, kerning;
  13141. mutable float ascent;
  13142. int styleFlags;
  13143. mutable Typeface::Ptr typeface;
  13144. // platform-specific calls
  13145. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13146. friend void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  13147. static void initialiseDefaultFontNames() throw();
  13148. };
  13149. #endif // __JUCE_FONT_JUCEHEADER__
  13150. /********* End of inlined file: juce_Font.h *********/
  13151. /********* Start of inlined file: juce_Rectangle.h *********/
  13152. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13153. #define __JUCE_RECTANGLE_JUCEHEADER__
  13154. /**
  13155. A rectangle, specified using integer co-ordinates.
  13156. @see RectangleList, Path, Line, Point
  13157. */
  13158. class JUCE_API Rectangle
  13159. {
  13160. public:
  13161. /** Creates a rectangle of zero size.
  13162. The default co-ordinates will be (0, 0, 0, 0).
  13163. */
  13164. Rectangle() throw();
  13165. /** Creates a copy of another rectangle. */
  13166. Rectangle (const Rectangle& other) throw();
  13167. /** Creates a rectangle with a given position and size. */
  13168. Rectangle (const int x, const int y,
  13169. const int width, const int height) throw();
  13170. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13171. Rectangle (const int width, const int height) throw();
  13172. /** Destructor. */
  13173. ~Rectangle() throw();
  13174. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13175. inline int getX() const throw() { return x; }
  13176. /** Returns the y co-ordinate of the rectangle's top edge. */
  13177. inline int getY() const throw() { return y; }
  13178. /** Returns the width of the rectangle. */
  13179. inline int getWidth() const throw() { return w; }
  13180. /** Returns the height of the rectangle. */
  13181. inline int getHeight() const throw() { return h; }
  13182. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13183. inline int getRight() const throw() { return x + w; }
  13184. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13185. inline int getBottom() const throw() { return y + h; }
  13186. /** Returns the x co-ordinate of the rectangle's centre. */
  13187. inline int getCentreX() const throw() { return x + (w >> 1); }
  13188. /** Returns the y co-ordinate of the rectangle's centre. */
  13189. inline int getCentreY() const throw() { return y + (h >> 1); }
  13190. /** Returns true if the rectangle's width and height are both zero or less */
  13191. bool isEmpty() const throw();
  13192. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13193. void setPosition (const int x, const int y) throw();
  13194. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13195. void setSize (const int w, const int h) throw();
  13196. /** Changes all the rectangle's co-ordinates. */
  13197. void setBounds (const int newX, const int newY,
  13198. const int newWidth, const int newHeight) throw();
  13199. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13200. void translate (const int deltaX,
  13201. const int deltaY) throw();
  13202. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13203. const Rectangle translated (const int deltaX,
  13204. const int deltaY) const throw();
  13205. /** Expands the rectangle by a given amount.
  13206. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13207. @see expanded, reduce, reduced
  13208. */
  13209. void expand (const int deltaX,
  13210. const int deltaY) throw();
  13211. /** Returns a rectangle that is larger than this one by a given amount.
  13212. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13213. @see expand, reduce, reduced
  13214. */
  13215. const Rectangle expanded (const int deltaX,
  13216. const int deltaY) const throw();
  13217. /** Shrinks the rectangle by a given amount.
  13218. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13219. @see reduced, expand, expanded
  13220. */
  13221. void reduce (const int deltaX,
  13222. const int deltaY) throw();
  13223. /** Returns a rectangle that is smaller than this one by a given amount.
  13224. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13225. @see reduce, expand, expanded
  13226. */
  13227. const Rectangle reduced (const int deltaX,
  13228. const int deltaY) const throw();
  13229. /** Returns true if the two rectangles are identical. */
  13230. bool operator== (const Rectangle& other) const throw();
  13231. /** Returns true if the two rectangles are not identical. */
  13232. bool operator!= (const Rectangle& other) const throw();
  13233. /** Returns true if this co-ordinate is inside the rectangle. */
  13234. bool contains (const int x, const int y) const throw();
  13235. /** Returns true if this other rectangle is completely inside this one. */
  13236. bool contains (const Rectangle& other) const throw();
  13237. /** Returns true if any part of another rectangle overlaps this one. */
  13238. bool intersects (const Rectangle& other) const throw();
  13239. /** Returns the region that is the overlap between this and another rectangle.
  13240. If the two rectangles don't overlap, the rectangle returned will be empty.
  13241. */
  13242. const Rectangle getIntersection (const Rectangle& other) const throw();
  13243. /** Clips a rectangle so that it lies only within this one.
  13244. This is a non-static version of intersectRectangles().
  13245. Returns false if the two regions didn't overlap.
  13246. */
  13247. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13248. /** Returns the smallest rectangle that contains both this one and the one
  13249. passed-in.
  13250. */
  13251. const Rectangle getUnion (const Rectangle& other) const throw();
  13252. /** If this rectangle merged with another one results in a simple rectangle, this
  13253. will set this rectangle to the result, and return true.
  13254. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13255. or if they form a complex region.
  13256. */
  13257. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13258. /** If after removing another rectangle from this one the result is a simple rectangle,
  13259. this will set this object's bounds to be the result, and return true.
  13260. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13261. or if removing the other one would form a complex region.
  13262. */
  13263. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13264. /** Static utility to intersect two sets of rectangular co-ordinates.
  13265. Returns false if the two regions didn't overlap.
  13266. @see intersectRectangle
  13267. */
  13268. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13269. int x2, int y2, int w2, int h2) throw();
  13270. /** Creates a string describing this rectangle.
  13271. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13272. Coupled with the fromString() method, this is very handy for things like
  13273. storing rectangles (particularly component positions) in XML attributes.
  13274. @see fromString
  13275. */
  13276. const String toString() const throw();
  13277. /** Parses a string containing a rectangle's details.
  13278. The string should contain 4 integer tokens, in the form "x y width height". They
  13279. can be comma or whitespace separated.
  13280. This method is intended to go with the toString() method, to form an easy way
  13281. of saving/loading rectangles as strings.
  13282. @see toString
  13283. */
  13284. static const Rectangle fromString (const String& stringVersion);
  13285. juce_UseDebuggingNewOperator
  13286. private:
  13287. friend class RectangleList;
  13288. int x, y, w, h;
  13289. };
  13290. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13291. /********* End of inlined file: juce_Rectangle.h *********/
  13292. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13293. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13294. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13295. /**
  13296. Describes a type of stroke used to render a solid outline along a path.
  13297. A PathStrokeType object can be used directly to create the shape of an outline
  13298. around a path, and is used by Graphics::strokePath to specify the type of
  13299. stroke to draw.
  13300. @see Path, Graphics::strokePath
  13301. */
  13302. class JUCE_API PathStrokeType
  13303. {
  13304. public:
  13305. /** The type of shape to use for the corners between two adjacent line segments. */
  13306. enum JointStyle
  13307. {
  13308. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13309. Note that for angles that curve back on themselves, drawing a
  13310. mitre could require extending the point too far away from the
  13311. path, so a mitre limit is imposed and any corners that exceed it
  13312. are drawn as bevelled instead. */
  13313. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13314. beveled /**< Indicates that corners should be drawn with a line flattening their
  13315. outside edge. */
  13316. };
  13317. /** The type shape to use for the ends of lines. */
  13318. enum EndCapStyle
  13319. {
  13320. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13321. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13322. the thickness of the stroke. */
  13323. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13324. };
  13325. /** Creates a stroke type.
  13326. @param strokeThickness the width of the line to use
  13327. @param jointStyle the type of joints to use for corners
  13328. @param endStyle the type of end-caps to use for the ends of open paths.
  13329. */
  13330. PathStrokeType (const float strokeThickness,
  13331. const JointStyle jointStyle = mitered,
  13332. const EndCapStyle endStyle = butt) throw();
  13333. /** Createes a copy of another stroke type. */
  13334. PathStrokeType (const PathStrokeType& other) throw();
  13335. /** Copies another stroke onto this one. */
  13336. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13337. /** Destructor. */
  13338. ~PathStrokeType() throw();
  13339. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13340. @param destPath the resultant stroked outline shape will be copied into this path.
  13341. Note that it's ok for the source and destination Paths to be
  13342. the same object, so you can easily turn a path into a stroked version
  13343. of itself.
  13344. @param sourcePath the path to use as the source
  13345. @param transform an optional transform to apply to the points from the source path
  13346. as they are being used
  13347. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13348. a higher resolution, which improved the quality if you'll later want
  13349. to enlarge the stroked path
  13350. @see createDashedStroke
  13351. */
  13352. void createStrokedPath (Path& destPath,
  13353. const Path& sourcePath,
  13354. const AffineTransform& transform = AffineTransform::identity,
  13355. const float extraAccuracy = 1.0f) const throw();
  13356. /** Applies this stroke type to a path, creating a dashed line.
  13357. This is similar to createStrokedPath, but uses the array passed in to
  13358. break the stroke up into a series of dashes.
  13359. @param destPath the resultant stroked outline shape will be copied into this path.
  13360. Note that it's ok for the source and destination Paths to be
  13361. the same object, so you can easily turn a path into a stroked version
  13362. of itself.
  13363. @param sourcePath the path to use as the source
  13364. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13365. a line of length 2, then skip a length of 3, then add a line of length 4,
  13366. skip 5, and keep repeating this pattern.
  13367. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13368. an even number, otherwise the pattern will get out of step as it
  13369. repeats.
  13370. @param transform an optional transform to apply to the points from the source path
  13371. as they are being used
  13372. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13373. a higher resolution, which improved the quality if you'll later want
  13374. to enlarge the stroked path
  13375. */
  13376. void createDashedStroke (Path& destPath,
  13377. const Path& sourcePath,
  13378. const float* dashLengths,
  13379. int numDashLengths,
  13380. const AffineTransform& transform = AffineTransform::identity,
  13381. const float extraAccuracy = 1.0f) const throw();
  13382. /** Returns the stroke thickness. */
  13383. float getStrokeThickness() const throw() { return thickness; }
  13384. /** Returns the joint style. */
  13385. JointStyle getJointStyle() const throw() { return jointStyle; }
  13386. /** Returns the end-cap style. */
  13387. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13388. juce_UseDebuggingNewOperator
  13389. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13390. bool operator== (const PathStrokeType& other) const throw();
  13391. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13392. bool operator!= (const PathStrokeType& other) const throw();
  13393. private:
  13394. float thickness;
  13395. JointStyle jointStyle;
  13396. EndCapStyle endStyle;
  13397. };
  13398. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13399. /********* End of inlined file: juce_PathStrokeType.h *********/
  13400. /********* Start of inlined file: juce_Line.h *********/
  13401. #ifndef __JUCE_LINE_JUCEHEADER__
  13402. #define __JUCE_LINE_JUCEHEADER__
  13403. /**
  13404. Represents a line, using 32-bit float co-ordinates.
  13405. This class contains a bunch of useful methods for various geometric
  13406. tasks.
  13407. @see Point, Rectangle, Path, Graphics::drawLine
  13408. */
  13409. class JUCE_API Line
  13410. {
  13411. public:
  13412. /** Creates a line, using (0, 0) as its start and end points. */
  13413. Line() throw();
  13414. /** Creates a copy of another line. */
  13415. Line (const Line& other) throw();
  13416. /** Creates a line based on the co-ordinates of its start and end points. */
  13417. Line (const float startX,
  13418. const float startY,
  13419. const float endX,
  13420. const float endY) throw();
  13421. /** Creates a line from its start and end points. */
  13422. Line (const Point& start,
  13423. const Point& end) throw();
  13424. /** Copies a line from another one. */
  13425. const Line& operator= (const Line& other) throw();
  13426. /** Destructor. */
  13427. ~Line() throw();
  13428. /** Returns the x co-ordinate of the line's start point. */
  13429. inline float getStartX() const throw() { return startX; }
  13430. /** Returns the y co-ordinate of the line's start point. */
  13431. inline float getStartY() const throw() { return startY; }
  13432. /** Returns the x co-ordinate of the line's end point. */
  13433. inline float getEndX() const throw() { return endX; }
  13434. /** Returns the y co-ordinate of the line's end point. */
  13435. inline float getEndY() const throw() { return endY; }
  13436. /** Returns the line's start point. */
  13437. const Point getStart() const throw();
  13438. /** Returns the line's end point. */
  13439. const Point getEnd() const throw();
  13440. /** Changes this line's start point */
  13441. void setStart (const float newStartX,
  13442. const float newStartY) throw();
  13443. /** Changes this line's end point */
  13444. void setEnd (const float newEndX,
  13445. const float newEndY) throw();
  13446. /** Changes this line's start point */
  13447. void setStart (const Point& newStart) throw();
  13448. /** Changes this line's end point */
  13449. void setEnd (const Point& newEnd) throw();
  13450. /** Applies an affine transform to the line's start and end points. */
  13451. void applyTransform (const AffineTransform& transform) throw();
  13452. /** Returns the length of the line. */
  13453. float getLength() const throw();
  13454. /** Returns true if the line's start and end x co-ordinates are the same. */
  13455. bool isVertical() const throw();
  13456. /** Returns true if the line's start and end y co-ordinates are the same. */
  13457. bool isHorizontal() const throw();
  13458. /** Returns the line's angle.
  13459. This value is the number of radians clockwise from the 3 o'clock direction,
  13460. where the line's start point is considered to be at the centre.
  13461. */
  13462. float getAngle() const throw();
  13463. /** Compares two lines. */
  13464. bool operator== (const Line& other) const throw();
  13465. /** Compares two lines. */
  13466. bool operator!= (const Line& other) const throw();
  13467. /** Finds the intersection between two lines.
  13468. @param line the other line
  13469. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13470. where they would meet if they were infinitely long)
  13471. the intersection (if the lines intersect). If the lines
  13472. are parallel, this will just be set to the position
  13473. of one of the line's endpoints.
  13474. @param intersectionY the y co-ordinate of the point where the lines meet
  13475. @returns true if the line segments intersect; false if they dont. Even if they
  13476. don't intersect, the intersection co-ordinates returned will still
  13477. be valid
  13478. */
  13479. bool intersects (const Line& line,
  13480. float& intersectionX,
  13481. float& intersectionY) const throw();
  13482. /** Returns the location of the point which is a given distance along this line.
  13483. @param distanceFromStart the distance to move along the line from its
  13484. start point. This value can be negative or longer
  13485. than the line itself
  13486. @see getPointAlongLineProportionally
  13487. */
  13488. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13489. /** Returns a point which is a certain distance along and to the side of this line.
  13490. This effectively moves a given distance along the line, then another distance
  13491. perpendicularly to this, and returns the resulting position.
  13492. @param distanceFromStart the distance to move along the line from its
  13493. start point. This value can be negative or longer
  13494. than the line itself
  13495. @param perpendicularDistance how far to move sideways from the line. If you're
  13496. looking along the line from its start towards its
  13497. end, then a positive value here will move to the
  13498. right, negative value move to the left.
  13499. */
  13500. const Point getPointAlongLine (const float distanceFromStart,
  13501. const float perpendicularDistance) const throw();
  13502. /** Returns the location of the point which is a given distance along this line
  13503. proportional to the line's length.
  13504. @param proportionOfLength the distance to move along the line from its
  13505. start point, in multiples of the line's length.
  13506. So a value of 0.0 will return the line's start point
  13507. and a value of 1.0 will return its end point. (This value
  13508. can be negative or greater than 1.0).
  13509. @see getPointAlongLine
  13510. */
  13511. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13512. /** Returns the smallest distance between this line segment and a given point.
  13513. So if the point is close to the line, this will return the perpendicular
  13514. distance from the line; if the point is a long way beyond one of the line's
  13515. end-point's, it'll return the straight-line distance to the nearest end-point.
  13516. @param x x position of the point to test
  13517. @param y y position of the point to test
  13518. @returns the point's distance from the line
  13519. @see getPositionAlongLineOfNearestPoint
  13520. */
  13521. float getDistanceFromLine (const float x,
  13522. const float y) const throw();
  13523. /** Finds the point on this line which is nearest to a given point, and
  13524. returns its position as a proportional position along the line.
  13525. @param x x position of the point to test
  13526. @param y y position of the point to test
  13527. @returns a value 0 to 1.0 which is the distance along this line from the
  13528. line's start to the point which is nearest to the point passed-in. To
  13529. turn this number into a position, use getPointAlongLineProportionally().
  13530. @see getDistanceFromLine, getPointAlongLineProportionally
  13531. */
  13532. float findNearestPointTo (const float x,
  13533. const float y) const throw();
  13534. /** Returns true if the given point lies above this line.
  13535. The return value is true if the point's y coordinate is less than the y
  13536. coordinate of this line at the given x (assuming the line extends infinitely
  13537. in both directions).
  13538. */
  13539. bool isPointAbove (const float x, const float y) const throw();
  13540. /** Returns a shortened copy of this line.
  13541. This will chop off part of the start of this line by a certain amount, (leaving the
  13542. end-point the same), and return the new line.
  13543. */
  13544. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13545. /** Returns a shortened copy of this line.
  13546. This will chop off part of the end of this line by a certain amount, (leaving the
  13547. start-point the same), and return the new line.
  13548. */
  13549. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13550. /** Cuts off parts of this line to keep the parts that are either inside or
  13551. outside a path.
  13552. Note that this isn't smart enough to cope with situations where the
  13553. line would need to be cut into multiple pieces to correctly clip against
  13554. a re-entrant shape.
  13555. @param path the path to clip against
  13556. @param keepSectionOutsidePath if true, it's the section outside the path
  13557. that will be kept; if false its the section inside
  13558. the path
  13559. @returns true if the line was changed.
  13560. */
  13561. bool clipToPath (const Path& path,
  13562. const bool keepSectionOutsidePath) throw();
  13563. juce_UseDebuggingNewOperator
  13564. private:
  13565. float startX, startY, endX, endY;
  13566. };
  13567. #endif // __JUCE_LINE_JUCEHEADER__
  13568. /********* End of inlined file: juce_Line.h *********/
  13569. /********* Start of inlined file: juce_Colours.h *********/
  13570. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13571. #define __JUCE_COLOURS_JUCEHEADER__
  13572. /********* Start of inlined file: juce_Colour.h *********/
  13573. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13574. #define __JUCE_COLOUR_JUCEHEADER__
  13575. /********* Start of inlined file: juce_PixelFormats.h *********/
  13576. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13577. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13578. #if JUCE_MSVC
  13579. #pragma pack (push, 1)
  13580. #define PACKED
  13581. #elif JUCE_GCC
  13582. #define PACKED __attribute__((packed))
  13583. #else
  13584. #define PACKED
  13585. #endif
  13586. /**
  13587. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13588. operations with it.
  13589. This is used internally by the imaging classes.
  13590. @see PixelRGB
  13591. */
  13592. class JUCE_API PixelARGB
  13593. {
  13594. public:
  13595. /** Creates a pixel without defining its colour. */
  13596. PixelARGB() throw() {}
  13597. ~PixelARGB() throw() {}
  13598. /** Creates a pixel from a 32-bit argb value.
  13599. */
  13600. PixelARGB (const uint32 argb_) throw()
  13601. : argb (argb_)
  13602. {
  13603. }
  13604. forcedinline uint32 getARGB() const throw() { return argb; }
  13605. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13606. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13607. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13608. forcedinline uint8 getRed() const throw() { return components.r; }
  13609. forcedinline uint8 getGreen() const throw() { return components.g; }
  13610. forcedinline uint8 getBlue() const throw() { return components.b; }
  13611. /** Blends another pixel onto this one.
  13612. This takes into account the opacity of the pixel being overlaid, and blends
  13613. it accordingly.
  13614. */
  13615. template <class Pixel>
  13616. forcedinline void blend (const Pixel& src) throw()
  13617. {
  13618. uint32 sargb = src.getARGB();
  13619. const uint32 alpha = 0x100 - (sargb >> 24);
  13620. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13621. sargb += 0xff00ff00 & (getAG() * alpha);
  13622. argb = sargb;
  13623. }
  13624. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13625. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13626. being used, so this can blend semi-transparently from a PixelRGB argument.
  13627. */
  13628. template <class Pixel>
  13629. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13630. {
  13631. ++extraAlpha;
  13632. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13633. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13634. const uint32 alpha = 0x100 - (sargb >> 24);
  13635. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13636. sargb += 0xff00ff00 & (getAG() * alpha);
  13637. argb = sargb;
  13638. }
  13639. /** Blends another pixel with this one, creating a colour that is somewhere
  13640. between the two, as specified by the amount.
  13641. */
  13642. template <class Pixel>
  13643. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13644. {
  13645. uint32 drb = getRB();
  13646. drb += (((src.getRB() - drb) * amount) >> 8);
  13647. drb &= 0x00ff00ff;
  13648. uint32 dag = getAG();
  13649. dag += (((src.getAG() - dag) * amount) >> 8);
  13650. dag &= 0x00ff00ff;
  13651. dag <<= 8;
  13652. dag |= drb;
  13653. argb = dag;
  13654. }
  13655. /** Copies another pixel colour over this one.
  13656. This doesn't blend it - this colour is simply replaced by the other one.
  13657. */
  13658. template <class Pixel>
  13659. forcedinline void set (const Pixel& src) throw()
  13660. {
  13661. argb = src.getARGB();
  13662. }
  13663. /** Replaces the colour's alpha value with another one. */
  13664. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13665. {
  13666. components.a = newAlpha;
  13667. }
  13668. /** Multiplies the colour's alpha value with another one. */
  13669. forcedinline void multiplyAlpha (int multiplier) throw()
  13670. {
  13671. ++multiplier;
  13672. argb = ((multiplier * getAG()) & 0xff00ff00)
  13673. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13674. }
  13675. forcedinline void multiplyAlpha (const float multiplier) throw()
  13676. {
  13677. multiplyAlpha ((int) (multiplier * 256.0f));
  13678. }
  13679. /** Sets the pixel's colour from individual components. */
  13680. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13681. {
  13682. components.b = b;
  13683. components.g = g;
  13684. components.r = r;
  13685. components.a = a;
  13686. }
  13687. /** Premultiplies the pixel's RGB values by its alpha. */
  13688. forcedinline void premultiply() throw()
  13689. {
  13690. const uint32 alpha = components.a;
  13691. if (alpha < 0xff)
  13692. {
  13693. if (alpha == 0)
  13694. {
  13695. components.b = 0;
  13696. components.g = 0;
  13697. components.r = 0;
  13698. }
  13699. else
  13700. {
  13701. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13702. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13703. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13704. }
  13705. }
  13706. }
  13707. /** Unpremultiplies the pixel's RGB values. */
  13708. forcedinline void unpremultiply() throw()
  13709. {
  13710. const uint32 alpha = components.a;
  13711. if (alpha < 0xff)
  13712. {
  13713. if (alpha == 0)
  13714. {
  13715. components.b = 0;
  13716. components.g = 0;
  13717. components.r = 0;
  13718. }
  13719. else
  13720. {
  13721. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13722. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13723. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13724. }
  13725. }
  13726. }
  13727. forcedinline void desaturate() throw()
  13728. {
  13729. if (components.a < 0xff && components.a > 0)
  13730. {
  13731. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13732. components.r = components.g = components.b
  13733. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13734. }
  13735. else
  13736. {
  13737. components.r = components.g = components.b
  13738. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13739. }
  13740. }
  13741. private:
  13742. union
  13743. {
  13744. uint32 argb;
  13745. struct
  13746. {
  13747. #if JUCE_BIG_ENDIAN
  13748. uint8 a : 8, r : 8, g : 8, b : 8;
  13749. #else
  13750. uint8 b, g, r, a;
  13751. #endif
  13752. } PACKED components;
  13753. };
  13754. } PACKED;
  13755. /**
  13756. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13757. This is used internally by the imaging classes.
  13758. @see PixelARGB
  13759. */
  13760. class JUCE_API PixelRGB
  13761. {
  13762. public:
  13763. /** Creates a pixel without defining its colour. */
  13764. PixelRGB() throw() {}
  13765. ~PixelRGB() throw() {}
  13766. /** Creates a pixel from a 32-bit argb value.
  13767. (The argb format is that used by PixelARGB)
  13768. */
  13769. PixelRGB (const uint32 argb) throw()
  13770. {
  13771. r = (uint8) (argb >> 16);
  13772. g = (uint8) (argb >> 8);
  13773. b = (uint8) (argb);
  13774. }
  13775. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13776. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13777. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13778. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13779. forcedinline uint8 getRed() const throw() { return r; }
  13780. forcedinline uint8 getGreen() const throw() { return g; }
  13781. forcedinline uint8 getBlue() const throw() { return b; }
  13782. /** Blends another pixel onto this one.
  13783. This takes into account the opacity of the pixel being overlaid, and blends
  13784. it accordingly.
  13785. */
  13786. forcedinline void blend (const PixelARGB& src) throw()
  13787. {
  13788. uint32 sargb = src.getARGB();
  13789. const uint32 alpha = 0x100 - (sargb >> 24);
  13790. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13791. sargb += 0x0000ff00 & (g * alpha);
  13792. r = (uint8) (sargb >> 16);
  13793. g = (uint8) (sargb >> 8);
  13794. b = (uint8) sargb;
  13795. }
  13796. forcedinline void blend (const PixelRGB& src) throw()
  13797. {
  13798. set (src);
  13799. }
  13800. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13801. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13802. being used, so this can blend semi-transparently from a PixelRGB argument.
  13803. */
  13804. template <class Pixel>
  13805. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13806. {
  13807. ++extraAlpha;
  13808. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13809. const uint32 sag = extraAlpha * src.getAG();
  13810. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13811. const uint32 alpha = 0x100 - (sargb >> 24);
  13812. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13813. sargb += 0x0000ff00 & (g * alpha);
  13814. b = (uint8) sargb;
  13815. g = (uint8) (sargb >> 8);
  13816. r = (uint8) (sargb >> 16);
  13817. }
  13818. /** Blends another pixel with this one, creating a colour that is somewhere
  13819. between the two, as specified by the amount.
  13820. */
  13821. template <class Pixel>
  13822. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13823. {
  13824. uint32 drb = getRB();
  13825. drb += (((src.getRB() - drb) * amount) >> 8);
  13826. uint32 dag = getAG();
  13827. dag += (((src.getAG() - dag) * amount) >> 8);
  13828. b = (uint8) drb;
  13829. g = (uint8) dag;
  13830. r = (uint8) (drb >> 16);
  13831. }
  13832. /** Copies another pixel colour over this one.
  13833. This doesn't blend it - this colour is simply replaced by the other one.
  13834. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13835. is thrown away.
  13836. */
  13837. template <class Pixel>
  13838. forcedinline void set (const Pixel& src) throw()
  13839. {
  13840. b = src.getBlue();
  13841. g = src.getGreen();
  13842. r = src.getRed();
  13843. }
  13844. /** This method is included for compatibility with the PixelARGB class. */
  13845. forcedinline void setAlpha (const uint8) throw() {}
  13846. /** Multiplies the colour's alpha value with another one. */
  13847. forcedinline void multiplyAlpha (int) throw() {}
  13848. /** Sets the pixel's colour from individual components. */
  13849. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  13850. {
  13851. r = r_;
  13852. g = g_;
  13853. b = b_;
  13854. }
  13855. /** Premultiplies the pixel's RGB values by its alpha. */
  13856. forcedinline void premultiply() throw() {}
  13857. /** Unpremultiplies the pixel's RGB values. */
  13858. forcedinline void unpremultiply() throw() {}
  13859. forcedinline void desaturate() throw()
  13860. {
  13861. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  13862. }
  13863. private:
  13864. #if JUCE_MAC
  13865. uint8 r, g, b;
  13866. #else
  13867. uint8 b, g, r;
  13868. #endif
  13869. } PACKED;
  13870. #if JUCE_MSVC
  13871. #pragma pack (pop)
  13872. #endif
  13873. #undef PACKED
  13874. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  13875. /********* End of inlined file: juce_PixelFormats.h *********/
  13876. /**
  13877. Represents a colour, also including a transparency value.
  13878. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  13879. */
  13880. class JUCE_API Colour
  13881. {
  13882. public:
  13883. /** Creates a transparent black colour. */
  13884. Colour() throw();
  13885. /** Creates a copy of another Colour object. */
  13886. Colour (const Colour& other) throw();
  13887. /** Creates a colour from a 32-bit ARGB value.
  13888. The format of this number is:
  13889. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13890. All components in the range 0x00 to 0xff.
  13891. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13892. @see getPixelARGB
  13893. */
  13894. explicit Colour (const uint32 argb) throw();
  13895. /** Creates an opaque colour using 8-bit red, green and blue values */
  13896. Colour (const uint8 red,
  13897. const uint8 green,
  13898. const uint8 blue) throw();
  13899. /** Creates an opaque colour using 8-bit red, green and blue values */
  13900. static const Colour fromRGB (const uint8 red,
  13901. const uint8 green,
  13902. const uint8 blue) throw();
  13903. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13904. Colour (const uint8 red,
  13905. const uint8 green,
  13906. const uint8 blue,
  13907. const uint8 alpha) throw();
  13908. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13909. static const Colour fromRGBA (const uint8 red,
  13910. const uint8 green,
  13911. const uint8 blue,
  13912. const uint8 alpha) throw();
  13913. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  13914. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  13915. Values outside the valid range will be clipped.
  13916. */
  13917. Colour (const uint8 red,
  13918. const uint8 green,
  13919. const uint8 blue,
  13920. const float alpha) throw();
  13921. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  13922. static const Colour fromRGBAFloat (const uint8 red,
  13923. const uint8 green,
  13924. const uint8 blue,
  13925. const float alpha) throw();
  13926. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13927. The floating point values must be between 0.0 and 1.0.
  13928. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13929. Values outside the valid range will be clipped.
  13930. */
  13931. Colour (const float hue,
  13932. const float saturation,
  13933. const float brightness,
  13934. const uint8 alpha) throw();
  13935. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  13936. All values must be between 0.0 and 1.0.
  13937. Numbers outside the valid range will be clipped.
  13938. */
  13939. Colour (const float hue,
  13940. const float saturation,
  13941. const float brightness,
  13942. const float alpha) throw();
  13943. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13944. The floating point values must be between 0.0 and 1.0.
  13945. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13946. Values outside the valid range will be clipped.
  13947. */
  13948. static const Colour fromHSV (const float hue,
  13949. const float saturation,
  13950. const float brightness,
  13951. const float alpha) throw();
  13952. /** Destructor. */
  13953. ~Colour() throw();
  13954. /** Copies another Colour object. */
  13955. const Colour& operator= (const Colour& other) throw();
  13956. /** Compares two colours. */
  13957. bool operator== (const Colour& other) const throw();
  13958. /** Compares two colours. */
  13959. bool operator!= (const Colour& other) const throw();
  13960. /** Returns the red component of this colour.
  13961. @returns a value between 0x00 and 0xff.
  13962. */
  13963. uint8 getRed() const throw() { return argb.getRed(); }
  13964. /** Returns the green component of this colour.
  13965. @returns a value between 0x00 and 0xff.
  13966. */
  13967. uint8 getGreen() const throw() { return argb.getGreen(); }
  13968. /** Returns the blue component of this colour.
  13969. @returns a value between 0x00 and 0xff.
  13970. */
  13971. uint8 getBlue() const throw() { return argb.getBlue(); }
  13972. /** Returns the red component of this colour as a floating point value.
  13973. @returns a value between 0.0 and 1.0
  13974. */
  13975. float getFloatRed() const throw();
  13976. /** Returns the green component of this colour as a floating point value.
  13977. @returns a value between 0.0 and 1.0
  13978. */
  13979. float getFloatGreen() const throw();
  13980. /** Returns the blue component of this colour as a floating point value.
  13981. @returns a value between 0.0 and 1.0
  13982. */
  13983. float getFloatBlue() const throw();
  13984. /** Returns a premultiplied ARGB pixel object that represents this colour.
  13985. */
  13986. const PixelARGB getPixelARGB() const throw();
  13987. /** Returns a 32-bit integer that represents this colour.
  13988. The format of this number is:
  13989. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13990. */
  13991. uint32 getARGB() const throw();
  13992. /** Returns the colour's alpha (opacity).
  13993. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  13994. */
  13995. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  13996. /** Returns the colour's alpha (opacity) as a floating point value.
  13997. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  13998. */
  13999. float getFloatAlpha() const throw();
  14000. /** Returns true if this colour is completely opaque.
  14001. Equivalent to (getAlpha() == 0xff).
  14002. */
  14003. bool isOpaque() const throw();
  14004. /** Returns true if this colour is completely transparent.
  14005. Equivalent to (getAlpha() == 0x00).
  14006. */
  14007. bool isTransparent() const throw();
  14008. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14009. const Colour withAlpha (const uint8 newAlpha) const throw();
  14010. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14011. const Colour withAlpha (const float newAlpha) const throw();
  14012. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14013. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14014. */
  14015. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14016. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14017. If the foreground colour is semi-transparent, it is blended onto this colour
  14018. accordingly.
  14019. */
  14020. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14021. /** Returns the colour's hue component.
  14022. The value returned is in the range 0.0 to 1.0
  14023. */
  14024. float getHue() const throw();
  14025. /** Returns the colour's saturation component.
  14026. The value returned is in the range 0.0 to 1.0
  14027. */
  14028. float getSaturation() const throw();
  14029. /** Returns the colour's brightness component.
  14030. The value returned is in the range 0.0 to 1.0
  14031. */
  14032. float getBrightness() const throw();
  14033. /** Returns the colour's hue, saturation and brightness components all at once.
  14034. The values returned are in the range 0.0 to 1.0
  14035. */
  14036. void getHSB (float& hue,
  14037. float& saturation,
  14038. float& brightness) const throw();
  14039. /** Returns a copy of this colour with a different hue. */
  14040. const Colour withHue (const float newHue) const throw();
  14041. /** Returns a copy of this colour with a different saturation. */
  14042. const Colour withSaturation (const float newSaturation) const throw();
  14043. /** Returns a copy of this colour with a different brightness.
  14044. @see brighter, darker, withMultipliedBrightness
  14045. */
  14046. const Colour withBrightness (const float newBrightness) const throw();
  14047. /** Returns a copy of this colour with it hue rotated.
  14048. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14049. @see brighter, darker, withMultipliedBrightness
  14050. */
  14051. const Colour withRotatedHue (const float amountToRotate) const throw();
  14052. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14053. The new colour's saturation is (this->getSaturation() * multiplier)
  14054. (the result is clipped to legal limits).
  14055. */
  14056. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14057. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14058. The new colour's saturation is (this->getBrightness() * multiplier)
  14059. (the result is clipped to legal limits).
  14060. */
  14061. const Colour withMultipliedBrightness (const float amount) const throw();
  14062. /** Returns a brighter version of this colour.
  14063. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14064. unchanged, and higher values make it brighter
  14065. @see withMultipliedBrightness
  14066. */
  14067. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14068. /** Returns a darker version of this colour.
  14069. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14070. unchanged, and higher values make it darker
  14071. @see withMultipliedBrightness
  14072. */
  14073. const Colour darker (float amountDarker = 0.4f) const throw();
  14074. /** Returns a colour that will be clearly visible against this colour.
  14075. The amount parameter indicates how contrasting the new colour should
  14076. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14077. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14078. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14079. */
  14080. const Colour contrasting (const float amount = 1.0f) const throw();
  14081. /** Returns a colour that contrasts against two colours.
  14082. Looks for a colour that contrasts with both of the colours passed-in.
  14083. Handy for things like choosing a highlight colour in text editors, etc.
  14084. */
  14085. static const Colour contrasting (const Colour& colour1,
  14086. const Colour& colour2) throw();
  14087. /** Returns an opaque shade of grey.
  14088. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14089. */
  14090. static const Colour greyLevel (const float brightness) throw();
  14091. /** Returns a stringified version of this colour.
  14092. The string can be turned back into a colour using the fromString() method.
  14093. */
  14094. const String toString() const throw();
  14095. /** Reads the colour from a string that was created with toString().
  14096. */
  14097. static const Colour fromString (const String& encodedColourString);
  14098. juce_UseDebuggingNewOperator
  14099. private:
  14100. PixelARGB argb;
  14101. };
  14102. #endif // __JUCE_COLOUR_JUCEHEADER__
  14103. /********* End of inlined file: juce_Colour.h *********/
  14104. /**
  14105. Contains a set of predefined named colours (mostly standard HTML colours)
  14106. @see Colour, Colours::greyLevel
  14107. */
  14108. class Colours
  14109. {
  14110. public:
  14111. static JUCE_API const Colour
  14112. transparentBlack, /**< ARGB = 0x00000000 */
  14113. transparentWhite, /**< ARGB = 0x00ffffff */
  14114. black, /**< ARGB = 0xff000000 */
  14115. white, /**< ARGB = 0xffffffff */
  14116. blue, /**< ARGB = 0xff0000ff */
  14117. grey, /**< ARGB = 0xff808080 */
  14118. green, /**< ARGB = 0xff008000 */
  14119. red, /**< ARGB = 0xffff0000 */
  14120. yellow, /**< ARGB = 0xffffff00 */
  14121. aliceblue, antiquewhite, aqua, aquamarine,
  14122. azure, beige, bisque, blanchedalmond,
  14123. blueviolet, brown, burlywood, cadetblue,
  14124. chartreuse, chocolate, coral, cornflowerblue,
  14125. cornsilk, crimson, cyan, darkblue,
  14126. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14127. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14128. darkorchid, darkred, darksalmon, darkseagreen,
  14129. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14130. deeppink, deepskyblue, dimgrey, dodgerblue,
  14131. firebrick, floralwhite, forestgreen, fuchsia,
  14132. gainsboro, gold, goldenrod, greenyellow,
  14133. honeydew, hotpink, indianred, indigo,
  14134. ivory, khaki, lavender, lavenderblush,
  14135. lemonchiffon, lightblue, lightcoral, lightcyan,
  14136. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14137. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14138. lightsteelblue, lightyellow, lime, limegreen,
  14139. linen, magenta, maroon, mediumaquamarine,
  14140. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14141. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14142. midnightblue, mintcream, mistyrose, navajowhite,
  14143. navy, oldlace, olive, olivedrab,
  14144. orange, orangered, orchid, palegoldenrod,
  14145. palegreen, paleturquoise, palevioletred, papayawhip,
  14146. peachpuff, peru, pink, plum,
  14147. powderblue, purple, rosybrown, royalblue,
  14148. saddlebrown, salmon, sandybrown, seagreen,
  14149. seashell, sienna, silver, skyblue,
  14150. slateblue, slategrey, snow, springgreen,
  14151. steelblue, tan, teal, thistle,
  14152. tomato, turquoise, violet, wheat,
  14153. whitesmoke, yellowgreen;
  14154. /** Attempts to look up a string in the list of known colour names, and return
  14155. the appropriate colour.
  14156. A non-case-sensitive search is made of the list of predefined colours, and
  14157. if a match is found, that colour is returned. If no match is found, the
  14158. colour passed in as the defaultColour parameter is returned.
  14159. */
  14160. static JUCE_API const Colour findColourForName (const String& colourName,
  14161. const Colour& defaultColour);
  14162. private:
  14163. // this isn't a class you should ever instantiate - it's just here for the
  14164. // static values in it.
  14165. Colours();
  14166. };
  14167. #endif // __JUCE_COLOURS_JUCEHEADER__
  14168. /********* End of inlined file: juce_Colours.h *********/
  14169. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14170. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14171. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14172. /********* Start of inlined file: juce_Brush.h *********/
  14173. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14174. #define __JUCE_BRUSH_JUCEHEADER__
  14175. class Path;
  14176. class AffineTransform;
  14177. class LowLevelGraphicsContext;
  14178. class Image;
  14179. class Graphics;
  14180. /**
  14181. A brush is used to fill areas with colours, patterns, or images.
  14182. The Graphics class has an idea of a current brush which it uses to render
  14183. shapes, rectangles, lines, text, etc.
  14184. This is the base class - there are subclasses for useful types of fill pattern,
  14185. and applications can define their own brushes too.
  14186. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14187. */
  14188. class JUCE_API Brush
  14189. {
  14190. protected:
  14191. /** Creates a Brush.
  14192. (Nothing much happens in the base class).
  14193. */
  14194. Brush() throw();
  14195. public:
  14196. /** Destructor. */
  14197. virtual ~Brush() throw();
  14198. /** Creates a copy of whatever class of Brush this is. */
  14199. virtual Brush* createCopy() const throw() = 0;
  14200. /** Does whatever is relevent to transform the geometry of this brush. */
  14201. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14202. /** Does whatever is relevent to change the opacity of this brush. */
  14203. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14204. /** Must return true if this brush won't draw any pixels. */
  14205. virtual bool isInvisible() const throw() = 0;
  14206. virtual void paintPath (LowLevelGraphicsContext& context,
  14207. const Path& path, const AffineTransform& transform) throw() = 0;
  14208. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14209. int x, int y, int w, int h) throw() = 0;
  14210. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14211. const Image& alphaChannelImage, int imageX, int imageY,
  14212. int x, int y, int w, int h) throw() = 0;
  14213. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14214. int x, float y1, float y2) throw();
  14215. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14216. int y, float x1, float x2) throw();
  14217. virtual void paintLine (LowLevelGraphicsContext& context,
  14218. float x1, float y1, float x2, float y2) throw();
  14219. private:
  14220. Brush (const Brush&);
  14221. const Brush& operator= (const Brush&);
  14222. };
  14223. #endif // __JUCE_BRUSH_JUCEHEADER__
  14224. /********* End of inlined file: juce_Brush.h *********/
  14225. /**
  14226. A Brush that fills its area with a solid (or semi-transparent) colour.
  14227. An application won't normally need to use this class directly, as drawing
  14228. with solid colours is taken care of automatically by the Graphics class
  14229. (it actually uses one of these brushes internally when you set the colour
  14230. with the Graphics::setColour() method).
  14231. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14232. */
  14233. class JUCE_API SolidColourBrush : public Brush
  14234. {
  14235. public:
  14236. /** Creates a SolidColourBrush to draw with the given colour.
  14237. The colour can be changed later with the setColour() method.
  14238. */
  14239. SolidColourBrush (const Colour& colour) throw();
  14240. /** Creates a SolidColourBrush set to black.
  14241. The colour can be changed later with the setColour() method.
  14242. */
  14243. SolidColourBrush() throw();
  14244. /** Destructor. */
  14245. ~SolidColourBrush() throw();
  14246. /** Returns the colour currently being used. */
  14247. const Colour& getColour() const throw() { return colour; }
  14248. /** Sets the colour to use for drawing. */
  14249. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14250. Brush* createCopy() const throw();
  14251. void applyTransform (const AffineTransform& transform) throw();
  14252. bool isInvisible() const throw();
  14253. void multiplyOpacity (const float multiple) throw();
  14254. void paintPath (LowLevelGraphicsContext& context,
  14255. const Path& path, const AffineTransform& transform) throw();
  14256. void paintRectangle (LowLevelGraphicsContext& context,
  14257. int x, int y, int w, int h) throw();
  14258. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14259. const Image& alphaChannelImage, int imageX, int imageY,
  14260. int x, int y, int w, int h) throw();
  14261. void paintVerticalLine (LowLevelGraphicsContext& context,
  14262. int x, float y1, float y2) throw();
  14263. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14264. int y, float x1, float x2) throw();
  14265. void paintLine (LowLevelGraphicsContext& context,
  14266. float x1, float y1, float x2, float y2) throw();
  14267. juce_UseDebuggingNewOperator
  14268. private:
  14269. Colour colour;
  14270. SolidColourBrush (const SolidColourBrush&);
  14271. const SolidColourBrush& operator= (const SolidColourBrush&);
  14272. };
  14273. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14274. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14275. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14276. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14277. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14278. /**
  14279. Defines the method used to postion some kind of rectangular object within
  14280. a rectangular viewport.
  14281. Although similar to Justification, this is more specific, and has some extra
  14282. options.
  14283. */
  14284. class JUCE_API RectanglePlacement
  14285. {
  14286. public:
  14287. /** Creates a RectanglePlacement object using a combination of flags. */
  14288. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14289. /** Creates a copy of another Justification object. */
  14290. RectanglePlacement (const RectanglePlacement& other) throw();
  14291. /** Copies another Justification object. */
  14292. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14293. /** Flag values that can be combined and used in the constructor. */
  14294. enum
  14295. {
  14296. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14297. xLeft = 1,
  14298. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14299. xRight = 2,
  14300. /** Indicates that the source should be placed in the centre between the left and right
  14301. sides of the available space. */
  14302. xMid = 4,
  14303. /** Indicates that the source's top edge should be aligned with the top edge of the
  14304. destination rectangle. */
  14305. yTop = 8,
  14306. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14307. destination rectangle. */
  14308. yBottom = 16,
  14309. /** Indicates that the source should be placed in the centre between the top and bottom
  14310. sides of the available space. */
  14311. yMid = 32,
  14312. /** If this flag is set, then the source rectangle will be resized to completely fill
  14313. the destination rectangle, and all other flags are ignored.
  14314. */
  14315. stretchToFit = 64,
  14316. /** If this flag is set, then the source rectangle will be resized so that it is the
  14317. minimum size to completely fill the destination rectangle. This means that some
  14318. of the source rectangle may fall outside the destination.
  14319. If this flag is not set, the source will be given the maximum size at which none
  14320. of it falls outside the destination rectangle.
  14321. */
  14322. fillDestination = 128,
  14323. /** Indicates that the source rectangle can be reduced in size if required, but should
  14324. never be made larger than its original size.
  14325. */
  14326. onlyReduceInSize = 256,
  14327. /** Indicates that the source rectangle can be enlarged if required, but should
  14328. never be made smaller than its original size.
  14329. */
  14330. onlyIncreaseInSize = 512,
  14331. /** Indicates that the source rectangle's size should be left unchanged.
  14332. */
  14333. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14334. /** A shorthand value that is equivalent to (xMid | yMid). */
  14335. centred = 4 + 32
  14336. };
  14337. /** Returns the raw flags that are set for this object. */
  14338. inline int getFlags() const throw() { return flags; }
  14339. /** Tests a set of flags for this object.
  14340. @returns true if any of the flags passed in are set on this object.
  14341. */
  14342. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14343. /** Adjusts the position and size of a rectangle to fit it into a space.
  14344. The source rectangle co-ordinates will be adjusted so that they fit into
  14345. the destination rectangle based on this object's flags.
  14346. */
  14347. void applyTo (double& sourceX,
  14348. double& sourceY,
  14349. double& sourceW,
  14350. double& sourceH,
  14351. const double destinationX,
  14352. const double destinationY,
  14353. const double destinationW,
  14354. const double destinationH) const throw();
  14355. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14356. into the destination rectangle using the current flags.
  14357. */
  14358. const AffineTransform getTransformToFit (float sourceX,
  14359. float sourceY,
  14360. float sourceW,
  14361. float sourceH,
  14362. const float destinationX,
  14363. const float destinationY,
  14364. const float destinationW,
  14365. const float destinationH) const throw();
  14366. private:
  14367. int flags;
  14368. };
  14369. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14370. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14371. class LowLevelGraphicsContext;
  14372. class Image;
  14373. class RectangleList;
  14374. /**
  14375. A graphics context, used for drawing a component or image.
  14376. When a Component needs painting, a Graphics context is passed to its
  14377. Component::paint() method, and this you then call methods within this
  14378. object to actually draw the component's content.
  14379. A Graphics can also be created from an image, to allow drawing directly onto
  14380. that image.
  14381. @see Component::paint
  14382. */
  14383. class JUCE_API Graphics
  14384. {
  14385. public:
  14386. /** Creates a Graphics object to draw directly onto the given image.
  14387. The graphics object that is created will be set up to draw onto the image,
  14388. with the context's clipping area being the entire size of the image, and its
  14389. origin being the image's origin. To draw into a subsection of an image, use the
  14390. reduceClipRegion() and setOrigin() methods.
  14391. Obviously you shouldn't delete the image before this context is deleted.
  14392. */
  14393. Graphics (Image& imageToDrawOnto) throw();
  14394. /** Destructor. */
  14395. ~Graphics() throw();
  14396. /** Changes the current drawing colour.
  14397. This sets the colour that will now be used for drawing operations - it also
  14398. sets the opacity to that of the colour passed-in.
  14399. If a brush is being used when this method is called, the brush will be deselected,
  14400. and any subsequent drawing will be done with a solid colour brush instead.
  14401. @see setOpacity, setBrush, getColour
  14402. */
  14403. void setColour (const Colour& newColour) throw();
  14404. /** Returns the colour that's currently being used.
  14405. This will return the last colour set by setColour(), even if the colour's not
  14406. currently being used for drawing because a brush has been selected instead.
  14407. @see setColour
  14408. */
  14409. const Colour& getCurrentColour() const throw();
  14410. /** Changes the opacity to use with the current colour.
  14411. If a solid colour is being used for drawing, this changes its opacity (and this
  14412. will be reflected by calls to the getColour() method).
  14413. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14414. */
  14415. void setOpacity (const float newOpacity) throw();
  14416. /** Changes the current brush to use for drawing.
  14417. If a null pointer is passed in, the context will revert to using a solid
  14418. colour for drawing (using the last colour set by setColour()).
  14419. If a brush is passed in, a copy of it will be used for subsequent drawing
  14420. operations until setColour() or setBrush() is called.
  14421. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14422. */
  14423. void setBrush (const Brush* const newBrush) throw();
  14424. /** Changes the font to use for subsequent text-drawing functions.
  14425. Note there's also a setFont (float, int) method to quickly change the size and
  14426. style of the current font.
  14427. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14428. */
  14429. void setFont (const Font& newFont) throw();
  14430. /** Changes the size and style of the currently-selected font.
  14431. This is a convenient shortcut that changes the context's current font to a
  14432. different size or style. The typeface won't be changed.
  14433. @see Font
  14434. */
  14435. void setFont (const float newFontHeight,
  14436. const int fontStyleFlags = Font::plain) throw();
  14437. /** Returns the font that's currently being used for text operations.
  14438. @see setFont
  14439. */
  14440. const Font& getCurrentFont() const throw();
  14441. /** Draws a one-line text string.
  14442. This will use the current colour (or brush) to fill the text. The font is the last
  14443. one specified by setFont().
  14444. @param text the string to draw
  14445. @param startX the position to draw the left-hand edge of the text
  14446. @param baselineY the position of the text's baseline
  14447. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14448. */
  14449. void drawSingleLineText (const String& text,
  14450. const int startX,
  14451. const int baselineY) const throw();
  14452. /** Draws text across multiple lines.
  14453. This will break the text onto a new line where there's a new-line or
  14454. carriage-return character, or at a word-boundary when the text becomes wider
  14455. than the size specified by the maximumLineWidth parameter.
  14456. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14457. */
  14458. void drawMultiLineText (const String& text,
  14459. const int startX,
  14460. const int baselineY,
  14461. const int maximumLineWidth) const throw();
  14462. /** Renders a string of text as a vector path.
  14463. This allows a string to be transformed with an arbitrary AffineTransform and
  14464. rendered using the current colour/brush. It's much slower than the normal text methods
  14465. but more accurate.
  14466. @see setFont
  14467. */
  14468. void drawTextAsPath (const String& text,
  14469. const AffineTransform& transform) const throw();
  14470. /** Draws a line of text within a specified rectangle.
  14471. The text will be positioned within the rectangle based on the justification
  14472. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14473. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14474. flag is true).
  14475. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14476. */
  14477. void drawText (const String& text,
  14478. const int x,
  14479. const int y,
  14480. const int width,
  14481. const int height,
  14482. const Justification& justificationType,
  14483. const bool useEllipsesIfTooBig) const throw();
  14484. /** Tries to draw a text string inside a given space.
  14485. This does its best to make the given text readable within the specified rectangle,
  14486. so it useful for labelling things.
  14487. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14488. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14489. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14490. it's been truncated.
  14491. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14492. both horizontally and vertically.
  14493. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14494. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14495. can set this value to 1.0f.
  14496. @see GlyphArrangement::addFittedText
  14497. */
  14498. void drawFittedText (const String& text,
  14499. const int x,
  14500. const int y,
  14501. const int width,
  14502. const int height,
  14503. const Justification& justificationFlags,
  14504. const int maximumNumberOfLines,
  14505. const float minimumHorizontalScale = 0.7f) const throw();
  14506. /** Fills the context's entire clip region with the current colour or brush.
  14507. (See also the fillAll (const Colour&) method which is a quick way of filling
  14508. it with a given colour).
  14509. */
  14510. void fillAll() const throw();
  14511. /** Fills the context's entire clip region with a given colour.
  14512. This leaves the context's current colour and brush unchanged, it just
  14513. uses the specified colour temporarily.
  14514. */
  14515. void fillAll (const Colour& colourToUse) const throw();
  14516. /** Fills a rectangle with the current colour or brush.
  14517. @see drawRect, fillRoundedRectangle
  14518. */
  14519. void fillRect (int x,
  14520. int y,
  14521. int width,
  14522. int height) const throw();
  14523. /** Fills a rectangle with the current colour or brush. */
  14524. void fillRect (const Rectangle& rectangle) const throw();
  14525. /** Fills a rectangle with the current colour or brush.
  14526. This uses sub-pixel positioning so is slower than the fillRect method which
  14527. takes integer co-ordinates.
  14528. */
  14529. void fillRect (const float x,
  14530. const float y,
  14531. const float width,
  14532. const float height) const throw();
  14533. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14534. @see drawRoundedRectangle, Path::addRoundedRectangle
  14535. */
  14536. void fillRoundedRectangle (const float x,
  14537. const float y,
  14538. const float width,
  14539. const float height,
  14540. const float cornerSize) const throw();
  14541. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14542. @see drawRoundedRectangle, Path::addRoundedRectangle
  14543. */
  14544. void fillRoundedRectangle (const Rectangle& rectangle,
  14545. const float cornerSize) const throw();
  14546. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14547. */
  14548. void fillCheckerBoard (int x, int y,
  14549. int width, int height,
  14550. const int checkWidth,
  14551. const int checkHeight,
  14552. const Colour& colour1,
  14553. const Colour& colour2) const throw();
  14554. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14555. The lines are drawn inside the given rectangle, and greater line thicknesses
  14556. extend inwards.
  14557. @see fillRect
  14558. */
  14559. void drawRect (const int x,
  14560. const int y,
  14561. const int width,
  14562. const int height,
  14563. const int lineThickness = 1) const throw();
  14564. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14565. The lines are drawn inside the given rectangle, and greater line thicknesses
  14566. extend inwards.
  14567. @see fillRect
  14568. */
  14569. void drawRect (const float x,
  14570. const float y,
  14571. const float width,
  14572. const float height,
  14573. const float lineThickness = 1.0f) const throw();
  14574. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14575. The lines are drawn inside the given rectangle, and greater line thicknesses
  14576. extend inwards.
  14577. @see fillRect
  14578. */
  14579. void drawRect (const Rectangle& rectangle,
  14580. const int lineThickness = 1) const throw();
  14581. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14582. @see fillRoundedRectangle, Path::addRoundedRectangle
  14583. */
  14584. void drawRoundedRectangle (const float x,
  14585. const float y,
  14586. const float width,
  14587. const float height,
  14588. const float cornerSize,
  14589. const float lineThickness) const throw();
  14590. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14591. @see fillRoundedRectangle, Path::addRoundedRectangle
  14592. */
  14593. void drawRoundedRectangle (const Rectangle& rectangle,
  14594. const float cornerSize,
  14595. const float lineThickness) const throw();
  14596. /** Draws a 3D raised (or indented) bevel using two colours.
  14597. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14598. extend inwards.
  14599. The top-left colour is used for the top- and left-hand edges of the
  14600. bevel; the bottom-right colour is used for the bottom- and right-hand
  14601. edges.
  14602. */
  14603. void drawBevel (const int x,
  14604. const int y,
  14605. const int width,
  14606. const int height,
  14607. const int bevelThickness,
  14608. const Colour& topLeftColour = Colours::white,
  14609. const Colour& bottomRightColour = Colours::black,
  14610. const bool useGradient = true) const throw();
  14611. /** Draws a pixel using the current colour or brush.
  14612. */
  14613. void setPixel (int x, int y) const throw();
  14614. /** Fills an ellipse with the current colour or brush.
  14615. The ellipse is drawn to fit inside the given rectangle.
  14616. @see drawEllipse, Path::addEllipse
  14617. */
  14618. void fillEllipse (const float x,
  14619. const float y,
  14620. const float width,
  14621. const float height) const throw();
  14622. /** Draws an elliptical stroke using the current colour or brush.
  14623. @see fillEllipse, Path::addEllipse
  14624. */
  14625. void drawEllipse (const float x,
  14626. const float y,
  14627. const float width,
  14628. const float height,
  14629. const float lineThickness) const throw();
  14630. /** Draws a line between two points.
  14631. The line is 1 pixel wide and drawn with the current colour or brush.
  14632. */
  14633. void drawLine (float startX,
  14634. float startY,
  14635. float endX,
  14636. float endY) const throw();
  14637. /** Draws a line between two points with a given thickness.
  14638. @see Path::addLineSegment
  14639. */
  14640. void drawLine (const float startX,
  14641. const float startY,
  14642. const float endX,
  14643. const float endY,
  14644. const float lineThickness) const throw();
  14645. /** Draws a line between two points.
  14646. The line is 1 pixel wide and drawn with the current colour or brush.
  14647. */
  14648. void drawLine (const Line& line) const throw();
  14649. /** Draws a line between two points with a given thickness.
  14650. @see Path::addLineSegment
  14651. */
  14652. void drawLine (const Line& line,
  14653. const float lineThickness) const throw();
  14654. /** Draws a dashed line using a custom set of dash-lengths.
  14655. @param startX the line's start x co-ordinate
  14656. @param startY the line's start y co-ordinate
  14657. @param endX the line's end x co-ordinate
  14658. @param endY the line's end y co-ordinate
  14659. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14660. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14661. draw 6 pixels, skip 7 pixels, and then repeat.
  14662. @param numDashLengths the number of elements in the array (this must be an even number).
  14663. @param lineThickness the thickness of the line to draw
  14664. @see PathStrokeType::createDashedStroke
  14665. */
  14666. void drawDashedLine (const float startX,
  14667. const float startY,
  14668. const float endX,
  14669. const float endY,
  14670. const float* const dashLengths,
  14671. const int numDashLengths,
  14672. const float lineThickness = 1.0f) const throw();
  14673. /** Draws a vertical line of pixels at a given x position.
  14674. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14675. positions, and these will be anti-aliased if necessary.
  14676. */
  14677. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14678. /** Draws a horizontal line of pixels at a given y position.
  14679. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14680. positions, and these will be anti-aliased if necessary.
  14681. */
  14682. void drawHorizontalLine (const int y, float left, float right) const throw();
  14683. /** Fills a path using the currently selected colour or brush.
  14684. */
  14685. void fillPath (const Path& path,
  14686. const AffineTransform& transform = AffineTransform::identity) const throw();
  14687. /** Draws a path's outline using the currently selected colour or brush.
  14688. */
  14689. void strokePath (const Path& path,
  14690. const PathStrokeType& strokeType,
  14691. const AffineTransform& transform = AffineTransform::identity) const throw();
  14692. /** Draws a line with an arrowhead.
  14693. @param startX the line's start x co-ordinate
  14694. @param startY the line's start y co-ordinate
  14695. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14696. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14697. @param lineThickness the thickness of the line
  14698. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14699. @param arrowheadLength the length of the arrow head (along the length of the line)
  14700. */
  14701. void drawArrow (const float startX,
  14702. const float startY,
  14703. const float endX,
  14704. const float endY,
  14705. const float lineThickness,
  14706. const float arrowheadWidth,
  14707. const float arrowheadLength) const throw();
  14708. /** Types of rendering quality that can be specified when drawing images.
  14709. @see blendImage, Graphics::setImageResamplingQuality
  14710. */
  14711. enum ResamplingQuality
  14712. {
  14713. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14714. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14715. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14716. };
  14717. /** Changes the quality that will be used when resampling images.
  14718. By default a Graphics object will be set to mediumRenderingQuality.
  14719. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14720. */
  14721. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14722. /** Draws an image.
  14723. This will draw the whole of an image, positioning its top-left corner at the
  14724. given co-ordinates, and keeping its size the same. This is the simplest image
  14725. drawing method - the others give more control over the scaling and clipping
  14726. of the images.
  14727. Images are composited using the context's current opacity, so if you
  14728. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14729. (or setColour() with an opaque colour) before drawing images.
  14730. */
  14731. void drawImageAt (const Image* const imageToDraw,
  14732. const int topLeftX,
  14733. const int topLeftY,
  14734. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14735. /** Draws part of an image, rescaling it to fit in a given target region.
  14736. The specified area of the source image is rescaled and drawn to fill the
  14737. specifed destination rectangle.
  14738. Images are composited using the context's current opacity, so if you
  14739. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14740. (or setColour() with an opaque colour) before drawing images.
  14741. @param imageToDraw the image to overlay
  14742. @param destX the left of the destination rectangle
  14743. @param destY the top of the destination rectangle
  14744. @param destWidth the width of the destination rectangle
  14745. @param destHeight the height of the destination rectangle
  14746. @param sourceX the left of the rectangle to copy from the source image
  14747. @param sourceY the top of the rectangle to copy from the source image
  14748. @param sourceWidth the width of the rectangle to copy from the source image
  14749. @param sourceHeight the height of the rectangle to copy from the source image
  14750. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14751. the source image's alpha channel is used as a mask with
  14752. which to fill the destination using the current colour
  14753. or brush. (If the source is has no alpha channel, then
  14754. it will just fill the target with a solid rectangle)
  14755. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14756. */
  14757. void drawImage (const Image* const imageToDraw,
  14758. int destX,
  14759. int destY,
  14760. int destWidth,
  14761. int destHeight,
  14762. int sourceX,
  14763. int sourceY,
  14764. int sourceWidth,
  14765. int sourceHeight,
  14766. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14767. /** Draws part of an image, having applied an affine transform to it.
  14768. This lets you throw the image around in some wacky ways, rotate it, shear,
  14769. scale it, etc.
  14770. A clipping subregion is specified within the source image and no pixels
  14771. outside this region will be used.
  14772. Images are composited using the context's current opacity, so if you
  14773. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14774. (or setColour() with an opaque colour) before drawing images.
  14775. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14776. are ignored and it is filled with the current brush, masked by its alpha channel.
  14777. @see setImageResamplingQuality, drawImage
  14778. */
  14779. void drawImageTransformed (const Image* const imageToDraw,
  14780. int sourceClipX,
  14781. int sourceClipY,
  14782. int sourceClipWidth,
  14783. int sourceClipHeight,
  14784. const AffineTransform& transform,
  14785. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14786. /** Draws an image to fit within a designated rectangle.
  14787. If the image is too big or too small for the space, it will be rescaled
  14788. to fit as nicely as it can do without affecting its aspect ratio. It will
  14789. then be placed within the target rectangle according to the justification flags
  14790. specified.
  14791. @param imageToDraw the source image to draw
  14792. @param destX top-left of the target rectangle to fit it into
  14793. @param destY top-left of the target rectangle to fit it into
  14794. @param destWidth size of the target rectangle to fit the image into
  14795. @param destHeight size of the target rectangle to fit the image into
  14796. @param placementWithinTarget this specifies how the image should be positioned
  14797. within the target rectangle - see the RectanglePlacement
  14798. class for more details about this.
  14799. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14800. alpha channel will be used as a mask with which to
  14801. draw with the current brush or colour. This is
  14802. similar to fillAlphaMap(), and see also drawImage()
  14803. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14804. */
  14805. void drawImageWithin (const Image* const imageToDraw,
  14806. const int destX,
  14807. const int destY,
  14808. const int destWidth,
  14809. const int destHeight,
  14810. const RectanglePlacement& placementWithinTarget,
  14811. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14812. /** Returns the position of the bounding box for the current clipping region.
  14813. @see getClipRegion, clipRegionIntersects
  14814. */
  14815. const Rectangle getClipBounds() const throw();
  14816. /** Checks whether a rectangle overlaps the context's clipping region.
  14817. If this returns false, no part of the given area can be drawn onto, so this
  14818. method can be used to optimise a component's paint() method, by letting it
  14819. avoid drawing complex objects that aren't within the region being repainted.
  14820. */
  14821. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14822. /** Intersects the current clipping region with another region.
  14823. @returns true if the resulting clipping region is non-zero in size
  14824. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14825. */
  14826. bool reduceClipRegion (const int x, const int y,
  14827. const int width, const int height) throw();
  14828. /** Intersects the current clipping region with a rectangle list region.
  14829. @returns true if the resulting clipping region is non-zero in size
  14830. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14831. */
  14832. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14833. /** Excludes a rectangle to stop it being drawn into. */
  14834. void excludeClipRegion (const int x, const int y,
  14835. const int width, const int height) throw();
  14836. /** Returns true if no drawing can be done because the clip region is zero. */
  14837. bool isClipEmpty() const throw();
  14838. /** Saves the current graphics state on an internal stack.
  14839. To restore the state, use restoreState().
  14840. */
  14841. void saveState() throw();
  14842. /** Restores a graphics state that was previously saved with saveState().
  14843. */
  14844. void restoreState() throw();
  14845. /** Moves the position of the context's origin.
  14846. This changes the position that the context considers to be (0, 0) to
  14847. the specified position.
  14848. So if you call setOrigin (100, 100), then the position that was previously
  14849. referred to as (100, 100) will subsequently be considered to be (0, 0).
  14850. @see reduceClipRegion
  14851. */
  14852. void setOrigin (const int newOriginX,
  14853. const int newOriginY) throw();
  14854. /** Resets the current colour, brush, and font to default settings. */
  14855. void resetToDefaultState() throw();
  14856. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  14857. bool isVectorDevice() const throw();
  14858. juce_UseDebuggingNewOperator
  14859. /** Create a graphics that uses a given low-level renderer.
  14860. For internal use only.
  14861. NB. The context will NOT be deleted by this object when it is deleted.
  14862. */
  14863. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  14864. /** @internal */
  14865. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  14866. private:
  14867. LowLevelGraphicsContext* const context;
  14868. const bool ownsContext;
  14869. struct GraphicsState
  14870. {
  14871. GraphicsState() throw();
  14872. GraphicsState (const GraphicsState&) throw();
  14873. ~GraphicsState() throw();
  14874. Colour colour;
  14875. Brush* brush;
  14876. Font font;
  14877. ResamplingQuality quality;
  14878. };
  14879. GraphicsState* state;
  14880. OwnedArray <GraphicsState> stateStack;
  14881. bool saveStatePending;
  14882. void saveStateIfPending() throw();
  14883. const Graphics& operator= (const Graphics& other);
  14884. Graphics (const Graphics&);
  14885. };
  14886. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  14887. /********* End of inlined file: juce_Graphics.h *********/
  14888. /**
  14889. A graphical effect filter that can be applied to components.
  14890. An ImageEffectFilter can be applied to the image that a component
  14891. paints before it hits the screen.
  14892. This is used for adding effects like shadows, blurs, etc.
  14893. @see Component::setComponentEffect
  14894. */
  14895. class JUCE_API ImageEffectFilter
  14896. {
  14897. public:
  14898. /** Overridden to render the effect.
  14899. The implementation of this method must use the image that is passed in
  14900. as its source, and should render its output to the graphics context passed in.
  14901. @param sourceImage the image that the source component has just rendered with
  14902. its paint() method. The image may or may not have an alpha
  14903. channel, depending on whether the component is opaque.
  14904. @param destContext the graphics context to use to draw the resultant image.
  14905. */
  14906. virtual void applyEffect (Image& sourceImage,
  14907. Graphics& destContext) = 0;
  14908. /** Destructor. */
  14909. virtual ~ImageEffectFilter() {}
  14910. };
  14911. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  14912. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  14913. /********* Start of inlined file: juce_RectangleList.h *********/
  14914. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  14915. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  14916. /**
  14917. Maintains a set of rectangles as a complex region.
  14918. This class allows a set of rectangles to be treated as a solid shape, and can
  14919. add and remove rectangular sections of it, and simplify overlapping or
  14920. adjacent rectangles.
  14921. @see Rectangle
  14922. */
  14923. class JUCE_API RectangleList
  14924. {
  14925. public:
  14926. /** Creates an empty RectangleList */
  14927. RectangleList() throw();
  14928. /** Creates a copy of another list */
  14929. RectangleList (const RectangleList& other) throw();
  14930. /** Creates a list containing just one rectangle. */
  14931. RectangleList (const Rectangle& rect) throw();
  14932. /** Copies this list from another one. */
  14933. const RectangleList& operator= (const RectangleList& other) throw();
  14934. /** Destructor. */
  14935. ~RectangleList() throw();
  14936. /** Returns true if the region is empty. */
  14937. bool isEmpty() const throw();
  14938. /** Returns the number of rectangles in the list. */
  14939. int getNumRectangles() const throw() { return rects.size(); }
  14940. /** Returns one of the rectangles at a particular index.
  14941. @returns the rectangle at the index, or an empty rectangle if the
  14942. index is out-of-range.
  14943. */
  14944. const Rectangle getRectangle (const int index) const throw();
  14945. /** Removes all rectangles to leave an empty region. */
  14946. void clear() throw();
  14947. /** Merges a new rectangle into the list.
  14948. The rectangle being added will first be clipped to remove any parts of it
  14949. that overlap existing rectangles in the list.
  14950. */
  14951. void add (const int x, const int y,
  14952. const int w, const int h) throw();
  14953. /** Merges a new rectangle into the list.
  14954. The rectangle being added will first be clipped to remove any parts of it
  14955. that overlap existing rectangles in the list, and adjacent rectangles will be
  14956. merged into it.
  14957. */
  14958. void add (const Rectangle& rect) throw();
  14959. /** Dumbly adds a rectangle to the list without checking for overlaps.
  14960. This simply adds the rectangle to the end, it doesn't merge it or remove
  14961. any overlapping bits.
  14962. */
  14963. void addWithoutMerging (const Rectangle& rect) throw();
  14964. /** Merges another rectangle list into this one.
  14965. Any overlaps between the two lists will be clipped, so that the result is
  14966. the union of both lists.
  14967. */
  14968. void add (const RectangleList& other) throw();
  14969. /** Removes a rectangular region from the list.
  14970. Any rectangles in the list which overlap this will be clipped and subdivided
  14971. if necessary.
  14972. */
  14973. void subtract (const Rectangle& rect) throw();
  14974. /** Removes all areas in another RectangleList from this one.
  14975. Any rectangles in the list which overlap this will be clipped and subdivided
  14976. if necessary.
  14977. */
  14978. void subtract (const RectangleList& otherList) throw();
  14979. /** Removes any areas of the region that lie outside a given rectangle.
  14980. Any rectangles in the list which overlap this will be clipped and subdivided
  14981. if necessary.
  14982. Returns true if the resulting region is not empty, false if it is empty.
  14983. @see getIntersectionWith
  14984. */
  14985. bool clipTo (const Rectangle& rect) throw();
  14986. /** Removes any areas of the region that lie outside a given rectangle list.
  14987. Any rectangles in this object which overlap the specified list will be clipped
  14988. and subdivided if necessary.
  14989. Returns true if the resulting region is not empty, false if it is empty.
  14990. @see getIntersectionWith
  14991. */
  14992. bool clipTo (const RectangleList& other) throw();
  14993. /** Creates a region which is the result of clipping this one to a given rectangle.
  14994. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  14995. resulting region into the list whose reference is passed-in.
  14996. Returns true if the resulting region is not empty, false if it is empty.
  14997. @see clipTo
  14998. */
  14999. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15000. /** Swaps the contents of this and another list.
  15001. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15002. to swap them.
  15003. */
  15004. void swapWith (RectangleList& otherList) throw();
  15005. /** Checks whether the region contains a given point.
  15006. @returns true if the point lies within one of the rectangles in the list
  15007. */
  15008. bool containsPoint (const int x, const int y) const throw();
  15009. /** Checks whether the region contains the whole of a given rectangle.
  15010. @returns true all parts of the rectangle passed in lie within the region
  15011. defined by this object
  15012. @see intersectsRectangle, containsPoint
  15013. */
  15014. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15015. /** Checks whether the region contains any part of a given rectangle.
  15016. @returns true if any part of the rectangle passed in lies within the region
  15017. defined by this object
  15018. @see containsRectangle
  15019. */
  15020. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15021. /** Checks whether this region intersects any part of another one.
  15022. @see intersectsRectangle
  15023. */
  15024. bool intersects (const RectangleList& other) const throw();
  15025. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15026. const Rectangle getBounds() const throw();
  15027. /** Optimises the list into a minimum number of constituent rectangles.
  15028. This will try to combine any adjacent rectangles into larger ones where
  15029. possible, to simplify lists that might have been fragmented by repeated
  15030. add/subtract calls.
  15031. */
  15032. void consolidate() throw();
  15033. /** Adds an x and y value to all the co-ordinates. */
  15034. void offsetAll (const int dx, const int dy) throw();
  15035. /** Creates a Path object to represent this region. */
  15036. const Path toPath() const throw();
  15037. /** An iterator for accessing all the rectangles in a RectangleList. */
  15038. class Iterator
  15039. {
  15040. public:
  15041. Iterator (const RectangleList& list) throw();
  15042. ~Iterator() throw();
  15043. /** Advances to the next rectangle, and returns true if it's not finished.
  15044. Call this before using getRectangle() to find the rectangle that was returned.
  15045. */
  15046. bool next() throw();
  15047. /** Returns the current rectangle. */
  15048. const Rectangle* getRectangle() const throw() { return current; }
  15049. juce_UseDebuggingNewOperator
  15050. private:
  15051. const Rectangle* current;
  15052. const RectangleList& owner;
  15053. int index;
  15054. Iterator (const Iterator&);
  15055. const Iterator& operator= (const Iterator&);
  15056. };
  15057. juce_UseDebuggingNewOperator
  15058. private:
  15059. friend class Iterator;
  15060. Array <Rectangle> rects;
  15061. };
  15062. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15063. /********* End of inlined file: juce_RectangleList.h *********/
  15064. /********* Start of inlined file: juce_BorderSize.h *********/
  15065. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15066. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15067. /**
  15068. Specifies a set of gaps to be left around the sides of a rectangle.
  15069. This is basically the size of the spaces at the top, bottom, left and right of
  15070. a rectangle. It's used by various component classes to specify borders.
  15071. @see Rectangle
  15072. */
  15073. class JUCE_API BorderSize
  15074. {
  15075. public:
  15076. /** Creates a null border.
  15077. All sizes are left as 0.
  15078. */
  15079. BorderSize() throw();
  15080. /** Creates a copy of another border. */
  15081. BorderSize (const BorderSize& other) throw();
  15082. /** Creates a border with the given gaps. */
  15083. BorderSize (const int topGap,
  15084. const int leftGap,
  15085. const int bottomGap,
  15086. const int rightGap) throw();
  15087. /** Creates a border with the given gap on all sides. */
  15088. BorderSize (const int allGaps) throw();
  15089. /** Destructor. */
  15090. ~BorderSize() throw();
  15091. /** Returns the gap that should be left at the top of the region. */
  15092. int getTop() const throw() { return top; }
  15093. /** Returns the gap that should be left at the top of the region. */
  15094. int getLeft() const throw() { return left; }
  15095. /** Returns the gap that should be left at the top of the region. */
  15096. int getBottom() const throw() { return bottom; }
  15097. /** Returns the gap that should be left at the top of the region. */
  15098. int getRight() const throw() { return right; }
  15099. /** Returns the sum of the top and bottom gaps. */
  15100. int getTopAndBottom() const throw() { return top + bottom; }
  15101. /** Returns the sum of the left and right gaps. */
  15102. int getLeftAndRight() const throw() { return left + right; }
  15103. /** Changes the top gap. */
  15104. void setTop (const int newTopGap) throw();
  15105. /** Changes the left gap. */
  15106. void setLeft (const int newLeftGap) throw();
  15107. /** Changes the bottom gap. */
  15108. void setBottom (const int newBottomGap) throw();
  15109. /** Changes the right gap. */
  15110. void setRight (const int newRightGap) throw();
  15111. /** Returns a rectangle with these borders removed from it. */
  15112. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15113. /** Removes this border from a given rectangle. */
  15114. void subtractFrom (Rectangle& rectangle) const throw();
  15115. /** Returns a rectangle with these borders added around it. */
  15116. const Rectangle addedTo (const Rectangle& original) const throw();
  15117. /** Adds this border around a given rectangle. */
  15118. void addTo (Rectangle& original) const throw();
  15119. bool operator== (const BorderSize& other) const throw();
  15120. bool operator!= (const BorderSize& other) const throw();
  15121. juce_UseDebuggingNewOperator
  15122. private:
  15123. int top, left, bottom, right;
  15124. };
  15125. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15126. /********* End of inlined file: juce_BorderSize.h *********/
  15127. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15128. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15129. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15130. class Component;
  15131. class Graphics;
  15132. /********* Start of inlined file: juce_MessageListener.h *********/
  15133. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15134. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15135. /********* Start of inlined file: juce_Message.h *********/
  15136. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15137. #define __JUCE_MESSAGE_JUCEHEADER__
  15138. class MessageListener;
  15139. class MessageManager;
  15140. /** The base class for objects that can be delivered to a MessageListener.
  15141. The simplest Message object contains a few integer and pointer parameters
  15142. that the user can set, and this is enough for a lot of purposes. For passing more
  15143. complex data, subclasses of Message can also be used.
  15144. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15145. */
  15146. class JUCE_API Message
  15147. {
  15148. public:
  15149. /** Creates an uninitialised message.
  15150. The class's variables will also be left uninitialised.
  15151. */
  15152. Message() throw();
  15153. /** Creates a message object, filling in the member variables.
  15154. The corresponding public member variables will be set from the parameters
  15155. passed in.
  15156. */
  15157. Message (const int intParameter1,
  15158. const int intParameter2,
  15159. const int intParameter3,
  15160. void* const pointerParameter) throw();
  15161. /** Destructor. */
  15162. virtual ~Message() throw();
  15163. // These values can be used for carrying simple data that the application needs to
  15164. // pass around. For more complex messages, just create a subclass.
  15165. int intParameter1; /**< user-defined integer value. */
  15166. int intParameter2; /**< user-defined integer value. */
  15167. int intParameter3; /**< user-defined integer value. */
  15168. void* pointerParameter; /**< user-defined pointer value. */
  15169. juce_UseDebuggingNewOperator
  15170. private:
  15171. friend class MessageListener;
  15172. friend class MessageManager;
  15173. MessageListener* messageRecipient;
  15174. Message (const Message&);
  15175. const Message& operator= (const Message&);
  15176. };
  15177. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15178. /********* End of inlined file: juce_Message.h *********/
  15179. /**
  15180. MessageListener subclasses can post and receive Message objects.
  15181. @see Message, MessageManager, ActionListener, ChangeListener
  15182. */
  15183. class JUCE_API MessageListener
  15184. {
  15185. protected:
  15186. /** Creates a MessageListener. */
  15187. MessageListener() throw();
  15188. public:
  15189. /** Destructor.
  15190. When a MessageListener is deleted, it removes itself from a global list
  15191. of registered listeners, so that the isValidMessageListener() method
  15192. will no longer return true.
  15193. */
  15194. virtual ~MessageListener();
  15195. /** This is the callback method that receives incoming messages.
  15196. This is called by the MessageManager from its dispatch loop.
  15197. @see postMessage
  15198. */
  15199. virtual void handleMessage (const Message& message) = 0;
  15200. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15201. later on.
  15202. This method can be called safely by any thread.
  15203. @param message the message object to send - this will be deleted
  15204. automatically by the message queue, so don't keep any
  15205. references to it after calling this method.
  15206. @see handleMessage
  15207. */
  15208. void postMessage (Message* const message) const throw();
  15209. /** Checks whether this MessageListener has been deleted.
  15210. Although not foolproof, this method is safe to call on dangling or null
  15211. pointers. A list of active MessageListeners is kept internally, so this
  15212. checks whether the object is on this list or not.
  15213. Note that it's possible to get a false-positive here, if an object is
  15214. deleted and another is subsequently created that happens to be at the
  15215. exact same memory location, but I can't think of a good way of avoiding
  15216. this.
  15217. */
  15218. bool isValidMessageListener() const throw();
  15219. };
  15220. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15221. /********* End of inlined file: juce_MessageListener.h *********/
  15222. class ComponentBoundsConstrainer;
  15223. class ComponentDeletionWatcher;
  15224. /**
  15225. The base class for window objects that wrap a component as a real operating
  15226. system object.
  15227. This is an abstract base class - the platform specific code contains default
  15228. implementations of it that create and manage windows.
  15229. @see Component::createNewPeer
  15230. */
  15231. class JUCE_API ComponentPeer : public MessageListener
  15232. {
  15233. public:
  15234. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15235. enum StyleFlags
  15236. {
  15237. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15238. entry on the taskbar (ignored on MacOSX) */
  15239. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15240. tooltip, etc. */
  15241. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15242. through it (may not be possible on some platforms). */
  15243. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15244. title bar and frame\. if not specified, the window will be
  15245. borderless. */
  15246. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15247. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15248. minimise button on it. */
  15249. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15250. maximise button on it. */
  15251. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15252. close button on it. */
  15253. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15254. not be possible on all platforms). */
  15255. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15256. do its own repainting, but only to repaint when the
  15257. performAnyPendingRepaintsNow() method is called. */
  15258. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15259. be used for things like plugin windows, to stop them interfering
  15260. with the host's shortcut keys */
  15261. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15262. };
  15263. /** Creates a peer.
  15264. The component is the one that we intend to represent, and the style flags are
  15265. a combination of the values in the StyleFlags enum
  15266. */
  15267. ComponentPeer (Component* const component,
  15268. const int styleFlags) throw();
  15269. /** Destructor. */
  15270. virtual ~ComponentPeer();
  15271. /** Returns the component being represented by this peer. */
  15272. Component* getComponent() const throw() { return component; }
  15273. /** Returns the set of style flags that were set when the window was created.
  15274. @see Component::addToDesktop
  15275. */
  15276. int getStyleFlags() const throw() { return styleFlags; }
  15277. /** Returns the raw handle to whatever kind of window is being used.
  15278. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15279. but rememeber there's no guarantees what you'll get back.
  15280. */
  15281. virtual void* getNativeHandle() const = 0;
  15282. /** Shows or hides the window. */
  15283. virtual void setVisible (bool shouldBeVisible) = 0;
  15284. /** Changes the title of the window. */
  15285. virtual void setTitle (const String& title) = 0;
  15286. /** Moves the window without changing its size.
  15287. If the native window is contained in another window, then the co-ordinates are
  15288. relative to the parent window's origin, not the screen origin.
  15289. This should result in a callback to handleMovedOrResized().
  15290. */
  15291. virtual void setPosition (int x, int y) = 0;
  15292. /** Resizes the window without changing its position.
  15293. This should result in a callback to handleMovedOrResized().
  15294. */
  15295. virtual void setSize (int w, int h) = 0;
  15296. /** Moves and resizes the window.
  15297. If the native window is contained in another window, then the co-ordinates are
  15298. relative to the parent window's origin, not the screen origin.
  15299. This should result in a callback to handleMovedOrResized().
  15300. */
  15301. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15302. /** Returns the current position and size of the window.
  15303. If the native window is contained in another window, then the co-ordinates are
  15304. relative to the parent window's origin, not the screen origin.
  15305. */
  15306. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15307. /** Returns the x-position of this window, relative to the screen's origin. */
  15308. virtual int getScreenX() const = 0;
  15309. /** Returns the y-position of this window, relative to the screen's origin. */
  15310. virtual int getScreenY() const = 0;
  15311. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15312. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15313. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15314. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15315. /** Minimises the window. */
  15316. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15317. /** True if the window is currently minimised. */
  15318. virtual bool isMinimised() const = 0;
  15319. /** Enable/disable fullscreen mode for the window. */
  15320. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15321. /** True if the window is currently full-screen. */
  15322. virtual bool isFullScreen() const = 0;
  15323. /** Sets the size to restore to if fullscreen mode is turned off. */
  15324. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15325. /** Returns the size to restore to if fullscreen mode is turned off. */
  15326. const Rectangle& getNonFullScreenBounds() const throw();
  15327. /** Attempts to change the icon associated with this window.
  15328. */
  15329. virtual void setIcon (const Image& newIcon) = 0;
  15330. /** Sets a constrainer to use if the peer can resize itself.
  15331. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15332. */
  15333. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15334. /** Returns the current constrainer, if one has been set. */
  15335. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15336. /** Checks if a point is in the window.
  15337. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15338. is false, then this returns false if the point is actually inside a child of this
  15339. window.
  15340. */
  15341. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15342. /** Returns the size of the window frame that's around this window.
  15343. Whether or not the window has a normal window frame depends on the flags
  15344. that were set when the window was created by Component::addToDesktop()
  15345. */
  15346. virtual const BorderSize getFrameSize() const = 0;
  15347. /** This is called when the window's bounds change.
  15348. A peer implementation must call this when the window is moved and resized, so that
  15349. this method can pass the message on to the component.
  15350. */
  15351. void handleMovedOrResized();
  15352. /** This is called if the screen resolution changes.
  15353. A peer implementation must call this if the monitor arrangement changes or the available
  15354. screen size changes.
  15355. */
  15356. void handleScreenSizeChange();
  15357. /** This is called to repaint the component into the given context. */
  15358. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15359. /** Sets this window to either be always-on-top or normal.
  15360. Some kinds of window might not be able to do this, so should return false.
  15361. */
  15362. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15363. /** Brings the window to the top, optionally also giving it focus. */
  15364. virtual void toFront (bool makeActive) = 0;
  15365. /** Moves the window to be just behind another one. */
  15366. virtual void toBehind (ComponentPeer* other) = 0;
  15367. /** Called when the window is brought to the front, either by the OS or by a call
  15368. to toFront().
  15369. */
  15370. void handleBroughtToFront();
  15371. /** True if the window has the keyboard focus. */
  15372. virtual bool isFocused() const = 0;
  15373. /** Tries to give the window keyboard focus. */
  15374. virtual void grabFocus() = 0;
  15375. /** Tells the window that text input may be required at the given position.
  15376. This may cause things like a virtual on-screen keyboard to appear, depending
  15377. on the OS.
  15378. */
  15379. virtual void textInputRequired (int x, int y) = 0;
  15380. /** Called when the window gains keyboard focus. */
  15381. void handleFocusGain();
  15382. /** Called when the window loses keyboard focus. */
  15383. void handleFocusLoss();
  15384. Component* getLastFocusedSubcomponent() const throw();
  15385. /** Called when a key is pressed.
  15386. For keycode info, see the KeyPress class.
  15387. Returns true if the keystroke was used.
  15388. */
  15389. bool handleKeyPress (const int keyCode,
  15390. const juce_wchar textCharacter);
  15391. /** Called whenever a key is pressed or released.
  15392. Returns true if the keystroke was used.
  15393. */
  15394. bool handleKeyUpOrDown();
  15395. /** Called whenever a modifier key is pressed or released. */
  15396. void handleModifierKeysChange();
  15397. /** Invalidates a region of the window to be repainted asynchronously. */
  15398. virtual void repaint (int x, int y, int w, int h) = 0;
  15399. /** This can be called (from the message thread) to cause the immediate redrawing
  15400. of any areas of this window that need repainting.
  15401. You shouldn't ever really need to use this, it's mainly for special purposes
  15402. like supporting audio plugins where the host's event loop is out of our control.
  15403. */
  15404. virtual void performAnyPendingRepaintsNow() = 0;
  15405. void handleMouseEnter (int x, int y, const int64 time);
  15406. void handleMouseMove (int x, int y, const int64 time);
  15407. void handleMouseDown (int x, int y, const int64 time);
  15408. void handleMouseDrag (int x, int y, const int64 time);
  15409. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15410. void handleMouseExit (int x, int y, const int64 time);
  15411. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15412. /** Causes a mouse-move callback to be made asynchronously. */
  15413. void sendFakeMouseMove() throw();
  15414. void handleUserClosingWindow();
  15415. void handleFileDragMove (const StringArray& files, int x, int y);
  15416. void handleFileDragExit (const StringArray& files);
  15417. void handleFileDragDrop (const StringArray& files, int x, int y);
  15418. /** Resets the masking region.
  15419. The subclass should call this every time it's about to call the handlePaint
  15420. method.
  15421. @see addMaskedRegion
  15422. */
  15423. void clearMaskedRegion() throw();
  15424. /** Adds a rectangle to the set of areas not to paint over.
  15425. A component can call this on its peer during its paint() method, to signal
  15426. that the painting code should ignore a given region. The reason
  15427. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15428. The masked region is cleared each time before a paint happens, so a component
  15429. will have to make sure it calls this every time it's painted.
  15430. */
  15431. void addMaskedRegion (int x, int y, int w, int h) throw();
  15432. /** Returns the number of currently-active peers.
  15433. @see getPeer
  15434. */
  15435. static int getNumPeers() throw();
  15436. /** Returns one of the currently-active peers.
  15437. @see getNumPeers
  15438. */
  15439. static ComponentPeer* getPeer (const int index) throw();
  15440. /** Checks if this peer object is valid.
  15441. @see getNumPeers
  15442. */
  15443. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15444. juce_UseDebuggingNewOperator
  15445. protected:
  15446. Component* const component;
  15447. const int styleFlags;
  15448. RectangleList maskedRegion;
  15449. Rectangle lastNonFullscreenBounds;
  15450. uint32 lastPaintTime;
  15451. ComponentBoundsConstrainer* constrainer;
  15452. static void updateCurrentModifiers() throw();
  15453. /** @internal */
  15454. void handleMessage (const Message& message);
  15455. private:
  15456. Component* lastFocusedComponent;
  15457. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15458. Component* lastDragAndDropCompUnderMouse;
  15459. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15460. friend class Component;
  15461. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15462. void setLastDragDropTarget (Component* comp);
  15463. ComponentPeer (const ComponentPeer&);
  15464. const ComponentPeer& operator= (const ComponentPeer&);
  15465. };
  15466. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15467. /********* End of inlined file: juce_ComponentPeer.h *********/
  15468. class LookAndFeel;
  15469. /**
  15470. The base class for all JUCE user-interface objects.
  15471. */
  15472. class JUCE_API Component : public MouseListener,
  15473. protected MessageListener
  15474. {
  15475. public:
  15476. /** Creates a component.
  15477. To get it to actually appear, you'll also need to:
  15478. - Either add it to a parent component or use the addToDesktop() method to
  15479. make it a desktop window
  15480. - Set its size and position to something sensible
  15481. - Use setVisible() to make it visible
  15482. And for it to serve any useful purpose, you'll need to write a
  15483. subclass of Component or use one of the other types of component from
  15484. the library.
  15485. */
  15486. Component() throw();
  15487. /** Destructor.
  15488. Note that when a component is deleted, any child components it might
  15489. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15490. */
  15491. virtual ~Component();
  15492. /** Creates a component, setting its name at the same time.
  15493. @see getName, setName
  15494. */
  15495. Component (const String& componentName) throw();
  15496. /** Returns the name of this component.
  15497. @see setName
  15498. */
  15499. const String& getName() const throw() { return componentName_; }
  15500. /** Sets the name of this component.
  15501. When the name changes, all registered ComponentListeners will receive a
  15502. ComponentListener::componentNameChanged() callback.
  15503. @see getName
  15504. */
  15505. virtual void setName (const String& newName);
  15506. /** Checks whether this Component object has been deleted.
  15507. This will check whether this object is still a valid component, or whether
  15508. it's been deleted.
  15509. It's safe to call this on null or dangling pointers, but note that there is a
  15510. small risk if another new (but different) component has been created at the
  15511. same memory address which this one occupied, this methods can return a
  15512. false positive.
  15513. */
  15514. bool isValidComponent() const throw();
  15515. /** Makes the component visible or invisible.
  15516. This method will show or hide the component.
  15517. Note that components default to being non-visible when first created.
  15518. Also note that visible components won't be seen unless all their parent components
  15519. are also visible.
  15520. This method will call visibilityChanged() and also componentVisibilityChanged()
  15521. for any component listeners that are interested in this component.
  15522. @param shouldBeVisible whether to show or hide the component
  15523. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15524. */
  15525. virtual void setVisible (bool shouldBeVisible);
  15526. /** Tests whether the component is visible or not.
  15527. this doesn't necessarily tell you whether this comp is actually on the screen
  15528. because this depends on whether all the parent components are also visible - use
  15529. isShowing() to find this out.
  15530. @see isShowing, setVisible
  15531. */
  15532. bool isVisible() const throw() { return flags.visibleFlag; }
  15533. /** Called when this component's visiblility changes.
  15534. @see setVisible, isVisible
  15535. */
  15536. virtual void visibilityChanged();
  15537. /** Tests whether this component and all its parents are visible.
  15538. @returns true only if this component and all its parents are visible.
  15539. @see isVisible
  15540. */
  15541. bool isShowing() const throw();
  15542. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15543. To do this, this function will cunningly:
  15544. - take a snapshot of the component as it currently looks
  15545. - call setVisible(false) on the component
  15546. - replace it with a special component that will continue drawing the
  15547. snapshot, animating it and gradually making it more transparent
  15548. - when it's gone, the special component will also be deleted
  15549. As soon as this method returns, the component can be safely removed and deleted
  15550. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15551. component's destructor.
  15552. Passing non-zero x and y values will cause the ghostly component image to
  15553. also whizz off by this distance while fading out. If the scale factor is
  15554. not 1.0, it will also zoom from the component's current size to this new size.
  15555. One thing to be careful about is that the parent component must be able to cope
  15556. with this unknown component type being added to it.
  15557. */
  15558. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15559. const int deltaXToMove = 0,
  15560. const int deltaYToMove = 0,
  15561. const float scaleFactorAtEnd = 1.0f);
  15562. /** Makes this component appear as a window on the desktop.
  15563. Note that before calling this, you should make sure that the component's opacity is
  15564. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15565. system will try to create a special transparent window for it, which will generally take
  15566. a lot more CPU to operate (and might not even be possible on some platforms).
  15567. If the component is inside a parent component at the time this method is called, it
  15568. will be first be removed from that parent. Likewise if a component on the desktop
  15569. is subsequently added to another component, it'll be removed from the desktop.
  15570. @param windowStyleFlags a combination of the flags specified in the
  15571. ComponentPeer::StyleFlags enum, which define the
  15572. window's characteristics.
  15573. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15574. in which the juce component should place itself. On Windows,
  15575. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15576. supported on all platforms, and best left as 0 unless you know
  15577. what you're doing
  15578. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15579. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15580. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15581. */
  15582. virtual void addToDesktop (int windowStyleFlags,
  15583. void* nativeWindowToAttachTo = 0);
  15584. /** If the component is currently showing on the desktop, this will hide it.
  15585. You can also use setVisible() to hide a desktop window temporarily, but
  15586. removeFromDesktop() will free any system resources that are being used up.
  15587. @see addToDesktop, isOnDesktop
  15588. */
  15589. void removeFromDesktop();
  15590. /** Returns true if this component is currently showing on the desktop.
  15591. @see addToDesktop, removeFromDesktop
  15592. */
  15593. bool isOnDesktop() const throw();
  15594. /** Returns the heavyweight window that contains this component.
  15595. If this component is itself on the desktop, this will return the window
  15596. object that it is using. Otherwise, it will return the window of
  15597. its top-level parent component.
  15598. This may return 0 if there isn't a desktop component.
  15599. @see addToDesktop, isOnDesktop
  15600. */
  15601. ComponentPeer* getPeer() const throw();
  15602. /** For components on the desktop, this is called if the system wants to close the window.
  15603. This is a signal that either the user or the system wants the window to close. The
  15604. default implementation of this method will trigger an assertion to warn you that your
  15605. component should do something about it, but you can override this to ignore the event
  15606. if you want.
  15607. */
  15608. virtual void userTriedToCloseWindow();
  15609. /** Called for a desktop component which has just been minimised or un-minimised.
  15610. This will only be called for components on the desktop.
  15611. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15612. */
  15613. virtual void minimisationStateChanged (bool isNowMinimised);
  15614. /** Brings the component to the front of its siblings.
  15615. If some of the component's siblings have had their 'always-on-top' flag set,
  15616. then they will still be kept in front of this one (unless of course this
  15617. one is also 'always-on-top').
  15618. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15619. to the component (see grabKeyboardFocus() for more details)
  15620. @see toBack, toBehind, setAlwaysOnTop
  15621. */
  15622. void toFront (const bool shouldAlsoGainFocus);
  15623. /** Changes this component's z-order to be at the back of all its siblings.
  15624. If the component is set to be 'always-on-top', it will only be moved to the
  15625. back of the other other 'always-on-top' components.
  15626. @see toFront, toBehind, setAlwaysOnTop
  15627. */
  15628. void toBack();
  15629. /** Changes this component's z-order so that it's just behind another component.
  15630. @see toFront, toBack
  15631. */
  15632. void toBehind (Component* const other);
  15633. /** Sets whether the component should always be kept at the front of its siblings.
  15634. @see isAlwaysOnTop
  15635. */
  15636. void setAlwaysOnTop (const bool shouldStayOnTop);
  15637. /** Returns true if this component is set to always stay in front of its siblings.
  15638. @see setAlwaysOnTop
  15639. */
  15640. bool isAlwaysOnTop() const throw();
  15641. /** Returns the x co-ordinate of the component's left edge.
  15642. This is a distance in pixels from the left edge of the component's parent.
  15643. @see getScreenX
  15644. */
  15645. inline int getX() const throw() { return bounds_.getX(); }
  15646. /** Returns the y co-ordinate of the top of this component.
  15647. This is a distance in pixels from the top edge of the component's parent.
  15648. @see getScreenY
  15649. */
  15650. inline int getY() const throw() { return bounds_.getY(); }
  15651. /** Returns the component's width in pixels. */
  15652. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15653. /** Returns the component's height in pixels. */
  15654. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15655. /** Returns the x co-ordinate of the component's right-hand edge.
  15656. This is a distance in pixels from the left edge of the component's parent.
  15657. */
  15658. int getRight() const throw() { return bounds_.getRight(); }
  15659. /** Returns the y co-ordinate of the bottom edge of this component.
  15660. This is a distance in pixels from the top edge of the component's parent.
  15661. */
  15662. int getBottom() const throw() { return bounds_.getBottom(); }
  15663. /** Returns this component's bounding box.
  15664. The rectangle returned is relative to the top-left of the component's parent.
  15665. */
  15666. const Rectangle& getBounds() const throw() { return bounds_; }
  15667. /** Returns the region of this component that's not obscured by other, opaque components.
  15668. The RectangleList that is returned represents the area of this component
  15669. which isn't covered by opaque child components.
  15670. If includeSiblings is true, it will also take into account any siblings
  15671. that may be overlapping the component.
  15672. */
  15673. void getVisibleArea (RectangleList& result,
  15674. const bool includeSiblings) const;
  15675. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15676. @see getX, relativePositionToGlobal
  15677. */
  15678. int getScreenX() const throw();
  15679. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15680. @see getY, relativePositionToGlobal
  15681. */
  15682. int getScreenY() const throw();
  15683. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15684. @see globalPositionToRelative, relativePositionToOtherComponent
  15685. */
  15686. void relativePositionToGlobal (int& x, int& y) const throw();
  15687. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15688. @see relativePositionToGlobal, relativePositionToOtherComponent
  15689. */
  15690. void globalPositionToRelative (int& x, int& y) const throw();
  15691. /** Converts a position relative to this component's top-left into a position
  15692. relative to another component's top-left.
  15693. @see relativePositionToGlobal, globalPositionToRelative
  15694. */
  15695. void relativePositionToOtherComponent (const Component* const targetComponent,
  15696. int& x, int& y) const throw();
  15697. /** Moves the component to a new position.
  15698. Changes the component's top-left position (without changing its size).
  15699. The position is relative to the top-left of the component's parent.
  15700. If the component actually moves, this method will make a synchronous call to moved().
  15701. @see setBounds, ComponentListener::componentMovedOrResized
  15702. */
  15703. void setTopLeftPosition (const int x, const int y);
  15704. /** Moves the component to a new position.
  15705. Changes the position of the component's top-right corner (keeping it the same size).
  15706. The position is relative to the top-left of the component's parent.
  15707. If the component actually moves, this method will make a synchronous call to moved().
  15708. */
  15709. void setTopRightPosition (const int x, const int y);
  15710. /** Changes the size of the component.
  15711. A synchronous call to resized() will be occur if the size actually changes.
  15712. */
  15713. void setSize (const int newWidth, const int newHeight);
  15714. /** Changes the component's position and size.
  15715. The co-ordinates are relative to the top-left of the component's parent, or relative
  15716. to the origin of the screen is the component is on the desktop.
  15717. If this method changes the component's top-left position, it will make a synchronous
  15718. call to moved(). If it changes the size, it will also make a call to resized().
  15719. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15720. */
  15721. void setBounds (int x, int y, int width, int height);
  15722. /** Changes the component's position and size.
  15723. @see setBounds
  15724. */
  15725. void setBounds (const Rectangle& newBounds);
  15726. /** Changes the component's position and size in terms of fractions of its parent's size.
  15727. The values are factors of the parent's size, so for example
  15728. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15729. width and height of the parent, with its top-left position 20% of
  15730. the way across and down the parent.
  15731. */
  15732. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15733. const float proportionalWidth, const float proportionalHeight);
  15734. /** Changes the component's position and size based on the amount of space to leave around it.
  15735. This will position the component within its parent, leaving the specified number of
  15736. pixels around each edge.
  15737. */
  15738. void setBoundsInset (const BorderSize& borders);
  15739. /** Positions the component within a given rectangle, keeping its proportions
  15740. unchanged.
  15741. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15742. rectangle as possible without changing its aspect ratio (the component's
  15743. current size is used to determine its aspect ratio, so a zero-size component
  15744. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15745. too big to fit inside the rectangle.
  15746. It will then be positioned within the rectangle according to the justification flags
  15747. specified.
  15748. */
  15749. void setBoundsToFit (int x, int y, int width, int height,
  15750. const Justification& justification,
  15751. const bool onlyReduceInSize);
  15752. /** Changes the position of the component's centre.
  15753. Leaves the component's size unchanged, but sets the position of its centre
  15754. relative to its parent's top-left.
  15755. */
  15756. void setCentrePosition (const int x, const int y);
  15757. /** Changes the position of the component's centre.
  15758. Leaves the position unchanged, but positions its centre relative to its
  15759. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15760. its parent.
  15761. */
  15762. void setCentreRelative (const float x, const float y);
  15763. /** Changes the component's size and centres it within its parent.
  15764. After changing the size, the component will be moved so that it's
  15765. centred within its parent.
  15766. */
  15767. void centreWithSize (const int width, const int height);
  15768. /** Returns a proportion of the component's width.
  15769. This is a handy equivalent of (getWidth() * proportion).
  15770. */
  15771. int proportionOfWidth (const float proportion) const throw();
  15772. /** Returns a proportion of the component's height.
  15773. This is a handy equivalent of (getHeight() * proportion).
  15774. */
  15775. int proportionOfHeight (const float proportion) const throw();
  15776. /** Returns the width of the component's parent.
  15777. If the component has no parent (i.e. if it's on the desktop), this will return
  15778. the width of the screen.
  15779. */
  15780. int getParentWidth() const throw();
  15781. /** Returns the height of the component's parent.
  15782. If the component has no parent (i.e. if it's on the desktop), this will return
  15783. the height of the screen.
  15784. */
  15785. int getParentHeight() const throw();
  15786. /** Returns the screen co-ordinates of the monitor that contains this component.
  15787. If there's only one monitor, this will return its size - if there are multiple
  15788. monitors, it will return the area of the monitor that contains the component's
  15789. centre.
  15790. */
  15791. const Rectangle getParentMonitorArea() const throw();
  15792. /** Returns the number of child components that this component contains.
  15793. @see getChildComponent, getIndexOfChildComponent
  15794. */
  15795. int getNumChildComponents() const throw();
  15796. /** Returns one of this component's child components, by it index.
  15797. The component with index 0 is at the back of the z-order, the one at the
  15798. front will have index (getNumChildComponents() - 1).
  15799. If the index is out-of-range, this will return a null pointer.
  15800. @see getNumChildComponents, getIndexOfChildComponent
  15801. */
  15802. Component* getChildComponent (const int index) const throw();
  15803. /** Returns the index of this component in the list of child components.
  15804. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15805. values are further towards the front.
  15806. Returns -1 if the component passed-in is not a child of this component.
  15807. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15808. */
  15809. int getIndexOfChildComponent (const Component* const child) const throw();
  15810. /** Adds a child component to this one.
  15811. @param child the new component to add. If the component passed-in is already
  15812. the child of another component, it'll first be removed from that.
  15813. @param zOrder The index in the child-list at which this component should be inserted.
  15814. A value of -1 will insert it in front of the others, 0 is the back.
  15815. @see removeChildComponent, addAndMakeVisible, getChild,
  15816. ComponentListener::componentChildrenChanged
  15817. */
  15818. void addChildComponent (Component* const child,
  15819. int zOrder = -1);
  15820. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15821. Quite a useful function, this is just the same as calling addChildComponent()
  15822. followed by setVisible (true) on the child.
  15823. */
  15824. void addAndMakeVisible (Component* const child,
  15825. int zOrder = -1);
  15826. /** Removes one of this component's child-components.
  15827. If the child passed-in isn't actually a child of this component (either because
  15828. it's invalid or is the child of a different parent), then nothing is done.
  15829. Note that removing a child will not delete it!
  15830. @see addChildComponent, ComponentListener::componentChildrenChanged
  15831. */
  15832. void removeChildComponent (Component* const childToRemove);
  15833. /** Removes one of this component's child-components by index.
  15834. This will return a pointer to the component that was removed, or null if
  15835. the index was out-of-range.
  15836. Note that removing a child will not delete it!
  15837. @see addChildComponent, ComponentListener::componentChildrenChanged
  15838. */
  15839. Component* removeChildComponent (const int childIndexToRemove);
  15840. /** Removes all this component's children.
  15841. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  15842. */
  15843. void removeAllChildren();
  15844. /** Removes all this component's children, and deletes them.
  15845. @see removeAllChildren
  15846. */
  15847. void deleteAllChildren();
  15848. /** Returns the component which this component is inside.
  15849. If this is the highest-level component or hasn't yet been added to
  15850. a parent, this will return null.
  15851. */
  15852. Component* getParentComponent() const throw() { return parentComponent_; }
  15853. /** Searches the parent components for a component of a specified class.
  15854. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  15855. component that can be dynamically cast to a MyComp, or will return 0 if none
  15856. of the parents are suitable.
  15857. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  15858. */
  15859. template <class TargetClass>
  15860. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  15861. {
  15862. (void) dummyParameter;
  15863. Component* p = parentComponent_;
  15864. while (p != 0)
  15865. {
  15866. TargetClass* target = dynamic_cast <TargetClass*> (p);
  15867. if (target != 0)
  15868. return target;
  15869. p = p->parentComponent_;
  15870. }
  15871. return 0;
  15872. }
  15873. /** Returns the highest-level component which contains this one or its parents.
  15874. This will search upwards in the parent-hierarchy from this component, until it
  15875. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  15876. not yet added to a parent), and will return that.
  15877. */
  15878. Component* getTopLevelComponent() const throw();
  15879. /** Checks whether a component is anywhere inside this component or its children.
  15880. This will recursively check through this components children to see if the
  15881. given component is anywhere inside.
  15882. */
  15883. bool isParentOf (const Component* possibleChild) const throw();
  15884. /** Called to indicate that the component's parents have changed.
  15885. When a component is added or removed from its parent, this method will
  15886. be called on all of its children (recursively - so all children of its
  15887. children will also be called as well).
  15888. Subclasses can override this if they need to react to this in some way.
  15889. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  15890. */
  15891. virtual void parentHierarchyChanged();
  15892. /** Subclasses can use this callback to be told when children are added or removed.
  15893. @see parentHierarchyChanged
  15894. */
  15895. virtual void childrenChanged();
  15896. /** Tests whether a given point inside the component.
  15897. Overriding this method allows you to create components which only intercept
  15898. mouse-clicks within a user-defined area.
  15899. This is called to find out whether a particular x, y co-ordinate is
  15900. considered to be inside the component or not, and is used by methods such
  15901. as contains() and getComponentAt() to work out which component
  15902. the mouse is clicked on.
  15903. Components with custom shapes will probably want to override it to perform
  15904. some more complex hit-testing.
  15905. The default implementation of this method returns either true or false,
  15906. depending on the value that was set by calling setInterceptsMouseClicks() (true
  15907. is the default return value).
  15908. Note that the hit-test region is not related to the opacity with which
  15909. areas of a component are painted.
  15910. Applications should never call hitTest() directly - instead use the
  15911. contains() method, because this will also test for occlusion by the
  15912. component's parent.
  15913. Note that for components on the desktop, this method will be ignored, because it's
  15914. not always possible to implement this behaviour on all platforms.
  15915. @param x the x co-ordinate to test, relative to the left hand edge of this
  15916. component. This value is guaranteed to be greater than or equal to
  15917. zero, and less than the component's width
  15918. @param y the y co-ordinate to test, relative to the top edge of this
  15919. component. This value is guaranteed to be greater than or equal to
  15920. zero, and less than the component's height
  15921. @returns true if the click is considered to be inside the component
  15922. @see setInterceptsMouseClicks, contains
  15923. */
  15924. virtual bool hitTest (int x, int y);
  15925. /** Changes the default return value for the hitTest() method.
  15926. Setting this to false is an easy way to make a component pass its mouse-clicks
  15927. through to the components behind it.
  15928. When a component is created, the default setting for this is true.
  15929. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  15930. return false (or true for child components if allowClicksOnChildComponents
  15931. is true)
  15932. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  15933. components can be clicked on as normal but clicks on this component pass
  15934. straight through; if this is false and allowClicksOnThisComponent
  15935. is false, then neither this component nor any child components can
  15936. be clicked on
  15937. @see hitTest, getInterceptsMouseClicks
  15938. */
  15939. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  15940. const bool allowClicksOnChildComponents) throw();
  15941. /** Retrieves the current state of the mouse-click interception flags.
  15942. On return, the two parameters are set to the state used in the last call to
  15943. setInterceptsMouseClicks().
  15944. @see setInterceptsMouseClicks
  15945. */
  15946. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  15947. bool& allowsClicksOnChildComponents) const throw();
  15948. /** Returns true if a given point lies within this component or one of its children.
  15949. Never override this method! Use hitTest to create custom hit regions.
  15950. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15951. @param y the y co-ordinate to test, relative to this component's top edge.
  15952. @returns true if the point is within the component's hit-test area, but only if
  15953. that part of the component isn't clipped by its parent component. Note
  15954. that this won't take into account any overlapping sibling components
  15955. which might be in the way - for that, see reallyContains()
  15956. @see hitTest, reallyContains, getComponentAt
  15957. */
  15958. virtual bool contains (int x, int y);
  15959. /** Returns true if a given point lies in this component, taking any overlapping
  15960. siblings into account.
  15961. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15962. @param y the y co-ordinate to test, relative to this component's top edge.
  15963. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  15964. component, this determines the value that will
  15965. be returned.
  15966. @see contains, getComponentAt
  15967. */
  15968. bool reallyContains (int x, int y,
  15969. const bool returnTrueIfWithinAChild);
  15970. /** Returns the component at a certain point within this one.
  15971. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15972. @param y the y co-ordinate to test, relative to this component's top edge.
  15973. @returns the component that is at this position - which may be 0, this component,
  15974. or one of its children. Note that overlapping siblings that might actually
  15975. be in the way are not taken into account by this method - to account for these,
  15976. instead call getComponentAt on the top-level parent of this component.
  15977. @see hitTest, contains, reallyContains
  15978. */
  15979. Component* getComponentAt (const int x, const int y);
  15980. /** Marks the whole component as needing to be redrawn.
  15981. Calling this will not do any repainting immediately, but will mark the component
  15982. as 'dirty'. At some point in the near future the operating system will send a paint
  15983. message, which will redraw all the dirty regions of all components.
  15984. There's no guarantee about how soon after calling repaint() the redraw will actually
  15985. happen, and other queued events may be delivered before a redraw is done.
  15986. If the setBufferedToImage() method has been used to cause this component
  15987. to use a buffer, the repaint() call will invalidate the component's buffer.
  15988. To redraw just a subsection of the component rather than the whole thing,
  15989. use the repaint (int, int, int, int) method.
  15990. @see paint
  15991. */
  15992. void repaint() throw();
  15993. /** Marks a subsection of this component as needing to be redrawn.
  15994. Calling this will not do any repainting immediately, but will mark the given region
  15995. of the component as 'dirty'. At some point in the near future the operating system
  15996. will send a paint message, which will redraw all the dirty regions of all components.
  15997. There's no guarantee about how soon after calling repaint() the redraw will actually
  15998. happen, and other queued events may be delivered before a redraw is done.
  15999. The region that is passed in will be clipped to keep it within the bounds of this
  16000. component.
  16001. @see repaint()
  16002. */
  16003. void repaint (const int x, const int y,
  16004. const int width, const int height) throw();
  16005. /** Makes the component use an internal buffer to optimise its redrawing.
  16006. Setting this flag to true will cause the component to allocate an
  16007. internal buffer into which it paints itself, so that when asked to
  16008. redraw itself, it can use this buffer rather than actually calling the
  16009. paint() method.
  16010. The buffer is kept until the repaint() method is called directly on
  16011. this component (or until it is resized), when the image is invalidated
  16012. and then redrawn the next time the component is painted.
  16013. Note that only the drawing that happens within the component's paint()
  16014. method is drawn into the buffer, it's child components are not buffered, and
  16015. nor is the paintOverChildren() method.
  16016. @see repaint, paint, createComponentSnapshot
  16017. */
  16018. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16019. /** Generates a snapshot of part of this component.
  16020. This will return a new Image, the size of the rectangle specified,
  16021. containing a snapshot of the specified area of the component and all
  16022. its children.
  16023. The image may or may not have an alpha-channel, depending on whether the
  16024. image is opaque or not.
  16025. If the clipImageToComponentBounds parameter is true and the area is greater than
  16026. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16027. then parts of the component beyond its bounds can be drawn.
  16028. The caller is responsible for deleting the image that is returned.
  16029. @see paintEntireComponent
  16030. */
  16031. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16032. const bool clipImageToComponentBounds = true);
  16033. /** Draws this component and all its subcomponents onto the specified graphics
  16034. context.
  16035. You should very rarely have to use this method, it's simply there in case you need
  16036. to draw a component with a custom graphics context for some reason, e.g. for
  16037. creating a snapshot of the component.
  16038. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16039. on its children in order to render the entire tree.
  16040. The graphics context may be left in an undefined state after this method returns,
  16041. so you may need to reset it if you're going to use it again.
  16042. */
  16043. void paintEntireComponent (Graphics& context);
  16044. /** Adds an effect filter to alter the component's appearance.
  16045. When a component has an effect filter set, then this is applied to the
  16046. results of its paint() method. There are a few preset effects, such as
  16047. a drop-shadow or glow, but they can be user-defined as well.
  16048. The effect that is passed in will not be deleted by the component - the
  16049. caller must take care of deleting it.
  16050. To remove an effect from a component, pass a null pointer in as the parameter.
  16051. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16052. */
  16053. void setComponentEffect (ImageEffectFilter* const newEffect);
  16054. /** Returns the current component effect.
  16055. @see setComponentEffect
  16056. */
  16057. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16058. /** Finds the appropriate look-and-feel to use for this component.
  16059. If the component hasn't had a look-and-feel explicitly set, this will
  16060. return the parent's look-and-feel, or just the default one if there's no
  16061. parent.
  16062. @see setLookAndFeel, lookAndFeelChanged
  16063. */
  16064. LookAndFeel& getLookAndFeel() const throw();
  16065. /** Sets the look and feel to use for this component.
  16066. This will also change the look and feel for any child components that haven't
  16067. had their look set explicitly.
  16068. The object passed in will not be deleted by the component, so it's the caller's
  16069. responsibility to manage it. It may be used at any time until this component
  16070. has been deleted.
  16071. Calling this method will also invoke the sendLookAndFeelChange() method.
  16072. @see getLookAndFeel, lookAndFeelChanged
  16073. */
  16074. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16075. /** Called to let the component react to a change in the look-and-feel setting.
  16076. When the look-and-feel is changed for a component, this will be called in
  16077. all its child components, recursively.
  16078. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16079. an application uses a LookAndFeel class that might have changed internally.
  16080. @see sendLookAndFeelChange, getLookAndFeel
  16081. */
  16082. virtual void lookAndFeelChanged();
  16083. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16084. This will recurse through the children and their children, calling lookAndFeelChanged()
  16085. on them all.
  16086. @see lookAndFeelChanged
  16087. */
  16088. void sendLookAndFeelChange();
  16089. /** Indicates whether any parts of the component might be transparent.
  16090. Components that always paint all of their contents with solid colour and
  16091. thus completely cover any components behind them should use this method
  16092. to tell the repaint system that they are opaque.
  16093. This information is used to optimise drawing, because it means that
  16094. objects underneath opaque windows don't need to be painted.
  16095. By default, components are considered transparent, unless this is used to
  16096. make it otherwise.
  16097. @see isOpaque, getVisibleArea
  16098. */
  16099. void setOpaque (const bool shouldBeOpaque) throw();
  16100. /** Returns true if no parts of this component are transparent.
  16101. @returns the value that was set by setOpaque, (the default being false)
  16102. @see setOpaque
  16103. */
  16104. bool isOpaque() const throw();
  16105. /** Indicates whether the component should be brought to the front when clicked.
  16106. Setting this flag to true will cause the component to be brought to the front
  16107. when the mouse is clicked somewhere inside it or its child components.
  16108. Note that a top-level desktop window might still be brought to the front by the
  16109. operating system when it's clicked, depending on how the OS works.
  16110. By default this is set to false.
  16111. @see setMouseClickGrabsKeyboardFocus
  16112. */
  16113. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16114. /** Indicates whether the component should be brought to the front when clicked-on.
  16115. @see setBroughtToFrontOnMouseClick
  16116. */
  16117. bool isBroughtToFrontOnMouseClick() const throw();
  16118. // Keyboard focus methods
  16119. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16120. By default components aren't actually interested in gaining the
  16121. focus, but this method can be used to turn this on.
  16122. See the grabKeyboardFocus() method for details about the way a component
  16123. is chosen to receive the focus.
  16124. @see grabKeyboardFocus, getWantsKeyboardFocus
  16125. */
  16126. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16127. /** Returns true if the component is interested in getting keyboard focus.
  16128. This returns the flag set by setWantsKeyboardFocus(). The default
  16129. setting is false.
  16130. @see setWantsKeyboardFocus
  16131. */
  16132. bool getWantsKeyboardFocus() const throw();
  16133. /** Chooses whether a click on this component automatically grabs the focus.
  16134. By default this is set to true, but you might want a component which can
  16135. be focused, but where you don't want the user to be able to affect it directly
  16136. by clicking.
  16137. */
  16138. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16139. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16140. See setMouseClickGrabsKeyboardFocus() for more info.
  16141. */
  16142. bool getMouseClickGrabsKeyboardFocus() const throw();
  16143. /** Tries to give keyboard focus to this component.
  16144. When the user clicks on a component or its grabKeyboardFocus()
  16145. method is called, the following procedure is used to work out which
  16146. component should get it:
  16147. - if the component that was clicked on actually wants focus (as indicated
  16148. by calling getWantsKeyboardFocus), it gets it.
  16149. - if the component itself doesn't want focus, it will try to pass it
  16150. on to whichever of its children is the default component, as determined by
  16151. KeyboardFocusTraverser::getDefaultComponent()
  16152. - if none of its children want focus at all, it will pass it up to its
  16153. parent instead, unless it's a top-level component without a parent,
  16154. in which case it just takes the focus itself.
  16155. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16156. getCurrentlyFocusedComponent, focusGained, focusLost,
  16157. keyPressed, keyStateChanged
  16158. */
  16159. void grabKeyboardFocus();
  16160. /** Returns true if this component currently has the keyboard focus.
  16161. @param trueIfChildIsFocused if this is true, then the method returns true if
  16162. either this component or any of its children (recursively)
  16163. have the focus. If false, the method only returns true if
  16164. this component has the focus.
  16165. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16166. focusGained, focusLost
  16167. */
  16168. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16169. /** Returns the component that currently has the keyboard focus.
  16170. @returns the focused component, or null if nothing is focused.
  16171. */
  16172. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16173. /** Tries to move the keyboard focus to one of this component's siblings.
  16174. This will try to move focus to either the next or previous component. (This
  16175. is the method that is used when shifting focus by pressing the tab key).
  16176. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16177. @param moveToNext if true, the focus will move forwards; if false, it will
  16178. move backwards
  16179. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16180. */
  16181. void moveKeyboardFocusToSibling (const bool moveToNext);
  16182. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16183. which focus should be passed from this component.
  16184. The default implementation of this method will return a default
  16185. KeyboardFocusTraverser if this component is a focus container (as determined
  16186. by the setFocusContainer() method). If the component isn't a focus
  16187. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16188. If you overrride this to return a custom KeyboardFocusTraverser, then
  16189. this component and all its sub-components will use the new object to
  16190. make their focusing decisions.
  16191. The method should return a new object, which the caller is required to
  16192. delete when no longer needed.
  16193. */
  16194. virtual KeyboardFocusTraverser* createFocusTraverser();
  16195. /** Returns the focus order of this component, if one has been specified.
  16196. By default components don't have a focus order - in that case, this
  16197. will return 0. Lower numbers indicate that the component will be
  16198. earlier in the focus traversal order.
  16199. To change the order, call setExplicitFocusOrder().
  16200. The focus order may be used by the KeyboardFocusTraverser class as part of
  16201. its algorithm for deciding the order in which components should be traversed.
  16202. See the KeyboardFocusTraverser class for more details on this.
  16203. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16204. */
  16205. int getExplicitFocusOrder() const throw();
  16206. /** Sets the index used in determining the order in which focusable components
  16207. should be traversed.
  16208. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16209. that traversal should use other factors, like the component's position.
  16210. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16211. */
  16212. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16213. /** Indicates whether this component is a parent for components that can have
  16214. their focus traversed.
  16215. This flag is used by the default implementation of the createFocusTraverser()
  16216. method, which uses the flag to find the first parent component (of the currently
  16217. focused one) which wants to be a focus container.
  16218. So using this method to set the flag to 'true' causes this component to
  16219. act as the top level within which focus is passed around.
  16220. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16221. */
  16222. void setFocusContainer (const bool isFocusContainer) throw();
  16223. /** Returns true if this component has been marked as a focus container.
  16224. See setFocusContainer() for more details.
  16225. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16226. */
  16227. bool isFocusContainer() const throw();
  16228. /** Returns true if the component (and all its parents) are enabled.
  16229. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16230. what difference this makes to the component depends on the type. E.g. buttons
  16231. and sliders will choose to draw themselves differently, etc.
  16232. Note that if one of this component's parents is disabled, this will always
  16233. return false, even if this component itself is enabled.
  16234. @see setEnabled, enablementChanged
  16235. */
  16236. bool isEnabled() const throw();
  16237. /** Enables or disables this component.
  16238. Disabling a component will also cause all of its child components to become
  16239. disabled.
  16240. Similarly, enabling a component which is inside a disabled parent
  16241. component won't make any difference until the parent is re-enabled.
  16242. @see isEnabled, enablementChanged
  16243. */
  16244. void setEnabled (const bool shouldBeEnabled);
  16245. /** Callback to indicate that this component has been enabled or disabled.
  16246. This can be triggered by one of the component's parent components
  16247. being enabled or disabled, as well as changes to the component itself.
  16248. The default implementation of this method does nothing; your class may
  16249. wish to repaint itself or something when this happens.
  16250. @see setEnabled, isEnabled
  16251. */
  16252. virtual void enablementChanged();
  16253. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16254. Note that the cursor set by this method can be overridden by the getMouseCursor
  16255. method.
  16256. @see MouseCursor
  16257. */
  16258. void setMouseCursor (const MouseCursor& cursorType) throw();
  16259. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16260. The default implementation will return the cursor that was set by setCursor()
  16261. but can be overridden for more specialised purposes, e.g. returning different
  16262. cursors depending on the mouse position.
  16263. @see MouseCursor
  16264. */
  16265. virtual const MouseCursor getMouseCursor();
  16266. /** Forces the current mouse cursor to be updated.
  16267. If you're overriding the getMouseCursor() method to control which cursor is
  16268. displayed, then this will only be checked each time the user moves the mouse. So
  16269. if you want to force the system to check that the cursor being displayed is
  16270. up-to-date (even if the mouse is just sitting there), call this method.
  16271. This isn't needed if you're only using setMouseCursor().
  16272. */
  16273. void updateMouseCursor() const throw();
  16274. /** Components can override this method to draw their content.
  16275. The paint() method gets called when a region of a component needs redrawing,
  16276. either because the component's repaint() method has been called, or because
  16277. something has happened on the screen that means a section of a window needs
  16278. to be redrawn.
  16279. Any child components will draw themselves over whatever this method draws. If
  16280. you need to paint over the top of your child components, you can also implement
  16281. the paintOverChildren() method to do this.
  16282. If you want to cause a component to redraw itself, this is done asynchronously -
  16283. calling the repaint() method marks a region of the component as "dirty", and the
  16284. paint() method will automatically be called sometime later, by the message thread,
  16285. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16286. you never redraw something synchronously.
  16287. You should never need to call this method directly - to take a snapshot of the
  16288. component you could use createComponentSnapshot() or paintEntireComponent().
  16289. @param g the graphics context that must be used to do the drawing operations.
  16290. @see repaint, paintOverChildren, Graphics
  16291. */
  16292. virtual void paint (Graphics& g);
  16293. /** Components can override this method to draw over the top of their children.
  16294. For most drawing operations, it's better to use the normal paint() method,
  16295. but if you need to overlay something on top of the children, this can be
  16296. used.
  16297. @see paint, Graphics
  16298. */
  16299. virtual void paintOverChildren (Graphics& g);
  16300. /** Called when the mouse moves inside this component.
  16301. If the mouse button isn't pressed and the mouse moves over a component,
  16302. this will be called to let the component react to this.
  16303. A component will always get a mouseEnter callback before a mouseMove.
  16304. @param e details about the position and status of the mouse event
  16305. @see mouseEnter, mouseExit, mouseDrag, contains
  16306. */
  16307. virtual void mouseMove (const MouseEvent& e);
  16308. /** Called when the mouse first enters this component.
  16309. If the mouse button isn't pressed and the mouse moves into a component,
  16310. this will be called to let the component react to this.
  16311. When the mouse button is pressed and held down while being moved in
  16312. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16313. mouseDrag messages are sent to the component that the mouse was originally
  16314. clicked on, until the button is released.
  16315. If you're writing a component that needs to repaint itself when the mouse
  16316. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16317. method.
  16318. @param e details about the position and status of the mouse event
  16319. @see mouseExit, mouseDrag, mouseMove, contains
  16320. */
  16321. virtual void mouseEnter (const MouseEvent& e);
  16322. /** Called when the mouse moves out of this component.
  16323. This will be called when the mouse moves off the edge of this
  16324. component.
  16325. If the mouse button was pressed, and it was then dragged off the
  16326. edge of the component and released, then this callback will happen
  16327. when the button is released, after the mouseUp callback.
  16328. If you're writing a component that needs to repaint itself when the mouse
  16329. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16330. method.
  16331. @param e details about the position and status of the mouse event
  16332. @see mouseEnter, mouseDrag, mouseMove, contains
  16333. */
  16334. virtual void mouseExit (const MouseEvent& e);
  16335. /** Called when a mouse button is pressed while it's over this component.
  16336. The MouseEvent object passed in contains lots of methods for finding out
  16337. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16338. were held down at the time.
  16339. Once a button is held down, the mouseDrag method will be called when the
  16340. mouse moves, until the button is released.
  16341. @param e details about the position and status of the mouse event
  16342. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16343. */
  16344. virtual void mouseDown (const MouseEvent& e);
  16345. /** Called when the mouse is moved while a button is held down.
  16346. When a mouse button is pressed inside a component, that component
  16347. receives mouseDrag callbacks each time the mouse moves, even if the
  16348. mouse strays outside the component's bounds.
  16349. If you want to be able to drag things off the edge of a component
  16350. and have the component scroll when you get to the edges, the
  16351. beginDragAutoRepeat() method might be useful.
  16352. @param e details about the position and status of the mouse event
  16353. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16354. */
  16355. virtual void mouseDrag (const MouseEvent& e);
  16356. /** Called when a mouse button is released.
  16357. A mouseUp callback is sent to the component in which a button was pressed
  16358. even if the mouse is actually over a different component when the
  16359. button is released.
  16360. The MouseEvent object passed in contains lots of methods for finding out
  16361. which buttons were down just before they were released.
  16362. @param e details about the position and status of the mouse event
  16363. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16364. */
  16365. virtual void mouseUp (const MouseEvent& e);
  16366. /** Called when a mouse button has been double-clicked in this component.
  16367. The MouseEvent object passed in contains lots of methods for finding out
  16368. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16369. were held down at the time.
  16370. For altering the time limit used to detect double-clicks,
  16371. see MouseEvent::setDoubleClickTimeout.
  16372. @param e details about the position and status of the mouse event
  16373. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16374. MouseEvent::getDoubleClickTimeout
  16375. */
  16376. virtual void mouseDoubleClick (const MouseEvent& e);
  16377. /** Called when the mouse-wheel is moved.
  16378. This callback is sent to the component that the mouse is over when the
  16379. wheel is moved.
  16380. If not overridden, the component will forward this message to its parent, so
  16381. that parent components can collect mouse-wheel messages that happen to
  16382. child components which aren't interested in them.
  16383. @param e details about the position and status of the mouse event
  16384. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16385. value means the wheel has been pushed to the right, negative means it
  16386. was pushed to the left
  16387. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16388. value means the wheel has been pushed upwards, negative means it
  16389. was pushed downwards
  16390. */
  16391. virtual void mouseWheelMove (const MouseEvent& e,
  16392. float wheelIncrementX,
  16393. float wheelIncrementY);
  16394. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16395. next mouse-drag operation.
  16396. This allows you to make sure that mouseDrag() events sent continuously, even
  16397. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16398. components when the mouse is near an edge.
  16399. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16400. minimum interval between consecutive mouse drag callbacks. The callbacks
  16401. will continue until the mouse is released, and then the interval will be reset,
  16402. so you need to make sure it's called every time you begin a drag event. If it
  16403. is called when the mouse isn't actually being pressed, it will apply to the next
  16404. mouse-drag operation that happens.
  16405. Passing an interval of 0 or less will cancel the auto-repeat.
  16406. @see mouseDrag
  16407. */
  16408. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16409. /** Causes automatic repaints when the mouse enters or exits this component.
  16410. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16411. on the component, it will trigger a repaint.
  16412. This is handy for things like buttons that need to draw themselves differently when
  16413. the mouse moves over them, and it avoids having to override all the different mouse
  16414. callbacks and call repaint().
  16415. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16416. */
  16417. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16418. /** Registers a listener to be told when mouse events occur in this component.
  16419. If you need to get informed about mouse events in a component but can't or
  16420. don't want to override its methods, you can attach any number of listeners
  16421. to the component, and these will get told about the events in addition to
  16422. the component's own callbacks being called.
  16423. Note that a MouseListener can also be attached to more than one component.
  16424. @param newListener the listener to register
  16425. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16426. for events that happen to any child component
  16427. within this component, including deeply-nested
  16428. child components. If false, it will only be
  16429. told about events that this component handles.
  16430. @see MouseListener, removeMouseListener
  16431. */
  16432. void addMouseListener (MouseListener* const newListener,
  16433. const bool wantsEventsForAllNestedChildComponents) throw();
  16434. /** Deregisters a mouse listener.
  16435. @see addMouseListener, MouseListener
  16436. */
  16437. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16438. /** Adds a listener that wants to hear about keypresses that this component receives.
  16439. The listeners that are registered with a component are called by its keyPressed() or
  16440. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16441. If you add an object as a key listener, be careful to remove it when the object
  16442. is deleted, or the component will be left with a dangling pointer.
  16443. @see keyPressed, keyStateChanged, removeKeyListener
  16444. */
  16445. void addKeyListener (KeyListener* const newListener) throw();
  16446. /** Removes a previously-registered key listener.
  16447. @see addKeyListener
  16448. */
  16449. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16450. /** Called when a key is pressed.
  16451. When a key is pressed, the component that has the keyboard focus will have this
  16452. method called. Remember that a component will only be given the focus if its
  16453. setWantsKeyboardFocus() method has been used to enable this.
  16454. If your implementation returns true, the event will be consumed and not passed
  16455. on to any other listeners. If it returns false, the key will be passed to any
  16456. KeyListeners that have been registered with this component. As soon as one of these
  16457. returns true, the process will stop, but if they all return false, the event will
  16458. be passed upwards to this component's parent, and so on.
  16459. The default implementation of this method does nothing and returns false.
  16460. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16461. */
  16462. virtual bool keyPressed (const KeyPress& key);
  16463. /** Called when a key is pressed or released.
  16464. Whenever a key on the keyboard is pressed or released (including modifier keys
  16465. like shift and ctrl), this method will be called on the component that currently
  16466. has the keyboard focus. Remember that a component will only be given the focus if
  16467. its setWantsKeyboardFocus() method has been used to enable this.
  16468. If your implementation returns true, the event will be consumed and not passed
  16469. on to any other listeners. If it returns false, then any KeyListeners that have
  16470. been registered with this component will have their keyStateChanged methods called.
  16471. As soon as one of these returns true, the process will stop, but if they all return
  16472. false, the event will be passed upwards to this component's parent, and so on.
  16473. The default implementation of this method does nothing and returns false.
  16474. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16475. method.
  16476. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16477. */
  16478. virtual bool keyStateChanged();
  16479. /** Called when a modifier key is pressed or released.
  16480. Whenever the shift, control, alt or command keys are pressed or released,
  16481. this method will be called on the component that currently has the keyboard focus.
  16482. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16483. method has been used to enable this.
  16484. The default implementation of this method actually calls its parent's modifierKeysChanged
  16485. method, so that focused components which aren't interested in this will give their
  16486. parents a chance to act on the event instead.
  16487. @see keyStateChanged, ModifierKeys
  16488. */
  16489. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16490. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16491. enum FocusChangeType
  16492. {
  16493. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16494. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16495. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16496. };
  16497. /** Called to indicate that this component has just acquired the keyboard focus.
  16498. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16499. */
  16500. virtual void focusGained (FocusChangeType cause);
  16501. /** Called to indicate that this component has just lost the keyboard focus.
  16502. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16503. */
  16504. virtual void focusLost (FocusChangeType cause);
  16505. /** Called to indicate that one of this component's children has been focused or unfocused.
  16506. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16507. changed. It happens when focus moves from one of this component's children (at any depth)
  16508. to a component that isn't contained in this one, (or vice-versa).
  16509. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16510. */
  16511. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16512. /** Returns true if the mouse is currently over this component.
  16513. If the mouse isn't over the component, this will return false, even if the
  16514. mouse is currently being dragged - so you can use this in your mouseDrag
  16515. method to find out whether it's really over the component or not.
  16516. Note that when the mouse button is being held down, then the only component
  16517. for which this method will return true is the one that was originally
  16518. clicked on.
  16519. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16520. */
  16521. bool isMouseOver() const throw();
  16522. /** Returns true if the mouse button is currently held down in this component.
  16523. Note that this is a test to see whether the mouse is being pressed in this
  16524. component, so it'll return false if called on component A when the mouse
  16525. is actually being dragged in component B.
  16526. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16527. */
  16528. bool isMouseButtonDown() const throw();
  16529. /** True if the mouse is over this component, or if it's being dragged in this component.
  16530. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16531. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16532. */
  16533. bool isMouseOverOrDragging() const throw();
  16534. /** Returns true if a mouse button is currently down.
  16535. Unlike isMouseButtonDown, this will test the current state of the
  16536. buttons without regard to which component (if any) it has been
  16537. pressed in.
  16538. @see isMouseButtonDown, ModifierKeys
  16539. */
  16540. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16541. /** Returns the mouse's current position, relative to this component.
  16542. The co-ordinates are relative to the component's top-left corner.
  16543. */
  16544. void getMouseXYRelative (int& x, int& y) const throw();
  16545. /** Returns the component that's currently underneath the mouse.
  16546. @returns the component or 0 if there isn't one.
  16547. @see contains, getComponentAt
  16548. */
  16549. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16550. /** Allows the mouse to move beyond the edges of the screen.
  16551. Calling this method when the mouse button is currently pressed inside this component
  16552. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16553. the edges of the screen.
  16554. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16555. can be used for things like custom slider controls or dragging objects around, where
  16556. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16557. The unbounded mode is automatically turned off when the mouse button is released, or
  16558. it can be turned off explicitly by calling this method again.
  16559. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16560. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16561. hidden; if true, it will only be hidden when it
  16562. is moved beyond the edge of the screen
  16563. */
  16564. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16565. bool keepCursorVisibleUntilOffscreen = false) throw();
  16566. /** Called when this component's size has been changed.
  16567. A component can implement this method to do things such as laying out its
  16568. child components when its width or height changes.
  16569. The method is called synchronously as a result of the setBounds or setSize
  16570. methods, so repeatedly changing a components size will repeatedly call its
  16571. resized method (unlike things like repainting, where multiple calls to repaint
  16572. are coalesced together).
  16573. If the component is a top-level window on the desktop, its size could also
  16574. be changed by operating-system factors beyond the application's control.
  16575. @see moved, setSize
  16576. */
  16577. virtual void resized();
  16578. /** Called when this component's position has been changed.
  16579. This is called when the position relative to its parent changes, not when
  16580. its absolute position on the screen changes (so it won't be called for
  16581. all child components when a parent component is moved).
  16582. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16583. or any of the other repositioning methods, and like resized(), it will be
  16584. called each time those methods are called.
  16585. If the component is a top-level window on the desktop, its position could also
  16586. be changed by operating-system factors beyond the application's control.
  16587. @see resized, setBounds
  16588. */
  16589. virtual void moved();
  16590. /** Called when one of this component's children is moved or resized.
  16591. If the parent wants to know about changes to its immediate children (not
  16592. to children of its children), this is the method to override.
  16593. @see moved, resized, parentSizeChanged
  16594. */
  16595. virtual void childBoundsChanged (Component* child);
  16596. /** Called when this component's immediate parent has been resized.
  16597. If the component is a top-level window, this indicates that the screen size
  16598. has changed.
  16599. @see childBoundsChanged, moved, resized
  16600. */
  16601. virtual void parentSizeChanged();
  16602. /** Called when this component has been moved to the front of its siblings.
  16603. The component may have been brought to the front by the toFront() method, or
  16604. by the operating system if it's a top-level window.
  16605. @see toFront
  16606. */
  16607. virtual void broughtToFront();
  16608. /** Adds a listener to be told about changes to the component hierarchy or position.
  16609. Component listeners get called when this component's size, position or children
  16610. change - see the ComponentListener class for more details.
  16611. @param newListener the listener to register - if this is already registered, it
  16612. will be ignored.
  16613. @see ComponentListener, removeComponentListener
  16614. */
  16615. void addComponentListener (ComponentListener* const newListener) throw();
  16616. /** Removes a component listener.
  16617. @see addComponentListener
  16618. */
  16619. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16620. /** Dispatches a numbered message to this component.
  16621. This is a quick and cheap way of allowing simple asynchronous messages to
  16622. be sent to components. It's also safe, because if the component that you
  16623. send the message to is a null or dangling pointer, this won't cause an error.
  16624. The command ID is later delivered to the component's handleCommandMessage() method by
  16625. the application's message queue.
  16626. @see handleCommandMessage
  16627. */
  16628. void postCommandMessage (const int commandId) throw();
  16629. /** Called to handle a command that was sent by postCommandMessage().
  16630. This is called by the message thread when a command message arrives, and
  16631. the component can override this method to process it in any way it needs to.
  16632. @see postCommandMessage
  16633. */
  16634. virtual void handleCommandMessage (int commandId);
  16635. /** Runs a component modally, waiting until the loop terminates.
  16636. This method first makes the component visible, brings it to the front and
  16637. gives it the keyboard focus.
  16638. It then runs a loop, dispatching messages from the system message queue, but
  16639. blocking all mouse or keyboard messages from reaching any components other
  16640. than this one and its children.
  16641. This loop continues until the component's exitModalState() method is called (or
  16642. the component is deleted), and then this method returns, returning the value
  16643. passed into exitModalState().
  16644. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16645. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16646. */
  16647. int runModalLoop();
  16648. /** Puts the component into a modal state.
  16649. This makes the component modal, so that messages are blocked from reaching
  16650. any components other than this one and its children, but unlike runModalLoop(),
  16651. this method returns immediately.
  16652. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16653. get the focus, which is usually what you'll want it to do. If not, it will leave
  16654. the focus unchanged.
  16655. @see exitModalState, runModalLoop
  16656. */
  16657. void enterModalState (const bool takeKeyboardFocus = true);
  16658. /** Ends a component's modal state.
  16659. If this component is currently modal, this will turn of its modalness, and return
  16660. a value to the runModalLoop() method that might have be running its modal loop.
  16661. @see runModalLoop, enterModalState, isCurrentlyModal
  16662. */
  16663. void exitModalState (const int returnValue);
  16664. /** Returns true if this component is the modal one.
  16665. It's possible to have nested modal components, e.g. a pop-up dialog box
  16666. that launches another pop-up, but this will only return true for
  16667. the one at the top of the stack.
  16668. @see getCurrentlyModalComponent
  16669. */
  16670. bool isCurrentlyModal() const throw();
  16671. /** Returns the component that is currently modal.
  16672. @returns the modal component, or null if no components are modal
  16673. @see runModalLoop, isCurrentlyModal
  16674. */
  16675. static Component* JUCE_CALLTYPE getCurrentlyModalComponent() throw();
  16676. /** Checks whether there's a modal component somewhere that's stopping this one
  16677. from receiving messages.
  16678. If there is a modal component, its canModalEventBeSentToComponent() method
  16679. will be called to see if it will still allow this component to receive events.
  16680. @see runModalLoop, getCurrentlyModalComponent
  16681. */
  16682. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16683. /** When a component is modal, this callback allows it to choose which other
  16684. components can still receive events.
  16685. When a modal component is active and the user clicks on a non-modal component,
  16686. this method is called on the modal component, and if it returns true, the
  16687. event is allowed to reach its target. If it returns false, the event is blocked
  16688. and the inputAttemptWhenModal() callback is made.
  16689. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16690. implementation just returns false in all cases.
  16691. */
  16692. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16693. /** Called when the user tries to click on a component that is blocked by another
  16694. modal component.
  16695. When a component is modal and the user clicks on one of the other components,
  16696. the modal component will receive this callback.
  16697. The default implementation of this method will play a beep, and bring the currently
  16698. modal component to the front, but it can be overridden to do other tasks.
  16699. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16700. */
  16701. virtual void inputAttemptWhenModal();
  16702. /** Returns one of the component's properties as a string.
  16703. @param keyName the name of the property to retrieve
  16704. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16705. properties, then it will check whether the parent component has
  16706. the key.
  16707. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16708. */
  16709. const String getComponentProperty (const String& keyName,
  16710. const bool useParentComponentIfNotFound,
  16711. const String& defaultReturnValue = String::empty) const throw();
  16712. /** Returns one of the properties as an integer.
  16713. @param keyName the name of the property to retrieve
  16714. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16715. properties, then it will check whether the parent component has
  16716. the key.
  16717. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16718. */
  16719. int getComponentPropertyInt (const String& keyName,
  16720. const bool useParentComponentIfNotFound,
  16721. const int defaultReturnValue = 0) const throw();
  16722. /** Returns one of the properties as an double.
  16723. @param keyName the name of the property to retrieve
  16724. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16725. properties, then it will check whether the parent component has
  16726. the key.
  16727. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16728. */
  16729. double getComponentPropertyDouble (const String& keyName,
  16730. const bool useParentComponentIfNotFound,
  16731. const double defaultReturnValue = 0.0) const throw();
  16732. /** Returns one of the properties as an boolean.
  16733. The result will be true if the string found for this key name can be parsed as a non-zero
  16734. integer.
  16735. @param keyName the name of the property to retrieve
  16736. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16737. properties, then it will check whether the parent component has
  16738. the key.
  16739. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16740. */
  16741. bool getComponentPropertyBool (const String& keyName,
  16742. const bool useParentComponentIfNotFound,
  16743. const bool defaultReturnValue = false) const throw();
  16744. /** Returns one of the properties as an colour.
  16745. @param keyName the name of the property to retrieve
  16746. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16747. properties, then it will check whether the parent component has
  16748. the key.
  16749. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16750. */
  16751. const Colour getComponentPropertyColour (const String& keyName,
  16752. const bool useParentComponentIfNotFound,
  16753. const Colour& defaultReturnValue = Colours::black) const throw();
  16754. /** Sets a named property as a string.
  16755. @param keyName the name of the property to set. (This mustn't be an empty string)
  16756. @param value the new value to set it to
  16757. @see removeComponentProperty
  16758. */
  16759. void setComponentProperty (const String& keyName, const String& value) throw();
  16760. /** Sets a named property to an integer.
  16761. @param keyName the name of the property to set. (This mustn't be an empty string)
  16762. @param value the new value to set it to
  16763. @see removeComponentProperty
  16764. */
  16765. void setComponentProperty (const String& keyName, const int value) throw();
  16766. /** Sets a named property to a double.
  16767. @param keyName the name of the property to set. (This mustn't be an empty string)
  16768. @param value the new value to set it to
  16769. @see removeComponentProperty
  16770. */
  16771. void setComponentProperty (const String& keyName, const double value) throw();
  16772. /** Sets a named property to a boolean.
  16773. @param keyName the name of the property to set. (This mustn't be an empty string)
  16774. @param value the new value to set it to
  16775. @see removeComponentProperty
  16776. */
  16777. void setComponentProperty (const String& keyName, const bool value) throw();
  16778. /** Sets a named property to a colour.
  16779. @param keyName the name of the property to set. (This mustn't be an empty string)
  16780. @param newColour the new colour to set it to
  16781. @see removeComponentProperty
  16782. */
  16783. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16784. /** Deletes a named component property.
  16785. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16786. @see setComponentProperty, getComponentProperty
  16787. */
  16788. void removeComponentProperty (const String& keyName) throw();
  16789. /** Returns the complete set of properties that have been set for this component.
  16790. If no properties have been set, this will return a null pointer.
  16791. @see getComponentProperty, setComponentProperty
  16792. */
  16793. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16794. /** Looks for a colour that has been registered with the given colour ID number.
  16795. If a colour has been set for this ID number using setColour(), then it is
  16796. returned. If none has been set, the method will try calling the component's
  16797. LookAndFeel class's findColour() method. If none has been registered with the
  16798. look-and-feel either, it will just return black.
  16799. The colour IDs for various purposes are stored as enums in the components that
  16800. they are relevent to - for an example, see Slider::ColourIds,
  16801. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16802. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16803. */
  16804. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16805. /** Registers a colour to be used for a particular purpose.
  16806. Changing a colour will cause a synchronous callback to the colourChanged()
  16807. method, which your component can override if it needs to do something when
  16808. colours are altered.
  16809. For more details about colour IDs, see the comments for findColour().
  16810. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16811. */
  16812. void setColour (const int colourId, const Colour& colour);
  16813. /** If a colour has been set with setColour(), this will remove it.
  16814. This allows you to make a colour revert to its default state.
  16815. */
  16816. void removeColour (const int colourId);
  16817. /** Returns true if the specified colour ID has been explicitly set for this
  16818. component using the setColour() method.
  16819. */
  16820. bool isColourSpecified (const int colourId) const throw();
  16821. /** This looks for any colours that have been specified for this component,
  16822. and copies them to the specified target component.
  16823. */
  16824. void copyAllExplicitColoursTo (Component& target) const throw();
  16825. /** This method is called when a colour is changed by the setColour() method.
  16826. @see setColour, findColour
  16827. */
  16828. virtual void colourChanged();
  16829. /** Returns the underlying native window handle for this component.
  16830. This is platform-dependent and strictly for power-users only!
  16831. */
  16832. void* getWindowHandle() const throw();
  16833. /** When created, each component is given a number to uniquely identify it.
  16834. The number is incremented each time a new component is created, so it's a more
  16835. unique way of identifying a component than using its memory location (which
  16836. may be reused after the component is deleted, of course).
  16837. */
  16838. uint32 getComponentUID() const throw() { return componentUID; }
  16839. juce_UseDebuggingNewOperator
  16840. private:
  16841. friend class ComponentPeer;
  16842. friend class InternalDragRepeater;
  16843. static Component* currentlyFocusedComponent;
  16844. static Component* componentUnderMouse;
  16845. String componentName_;
  16846. Component* parentComponent_;
  16847. uint32 componentUID;
  16848. Rectangle bounds_;
  16849. unsigned short numDeepMouseListeners;
  16850. Array <Component*> childComponentList_;
  16851. LookAndFeel* lookAndFeel_;
  16852. MouseCursor cursor_;
  16853. ImageEffectFilter* effect_;
  16854. Image* bufferedImage_;
  16855. VoidArray* mouseListeners_;
  16856. VoidArray* keyListeners_;
  16857. VoidArray* componentListeners_;
  16858. PropertySet* propertySet_;
  16859. struct ComponentFlags
  16860. {
  16861. bool hasHeavyweightPeerFlag : 1;
  16862. bool visibleFlag : 1;
  16863. bool opaqueFlag : 1;
  16864. bool ignoresMouseClicksFlag : 1;
  16865. bool allowChildMouseClicksFlag : 1;
  16866. bool wantsFocusFlag : 1;
  16867. bool isFocusContainerFlag : 1;
  16868. bool dontFocusOnMouseClickFlag : 1;
  16869. bool alwaysOnTopFlag : 1;
  16870. bool bufferToImageFlag : 1;
  16871. bool bringToFrontOnClickFlag : 1;
  16872. bool repaintOnMouseActivityFlag : 1;
  16873. bool draggingFlag : 1;
  16874. bool mouseOverFlag : 1;
  16875. bool mouseInsideFlag : 1;
  16876. bool currentlyModalFlag : 1;
  16877. bool isDisabledFlag : 1;
  16878. bool childCompFocusedFlag : 1;
  16879. #ifdef JUCE_DEBUG
  16880. bool isInsidePaintCall : 1;
  16881. #endif
  16882. };
  16883. union
  16884. {
  16885. uint32 componentFlags_;
  16886. ComponentFlags flags;
  16887. };
  16888. void internalMouseEnter (int x, int y, const int64 time);
  16889. void internalMouseExit (int x, int y, const int64 time);
  16890. void internalMouseDown (int x, int y);
  16891. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16892. void internalMouseDrag (int x, int y, const int64 time);
  16893. void internalMouseMove (int x, int y, const int64 time);
  16894. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  16895. void internalBroughtToFront();
  16896. void internalFocusGain (const FocusChangeType cause);
  16897. void internalFocusLoss (const FocusChangeType cause);
  16898. void internalChildFocusChange (FocusChangeType cause);
  16899. void internalModalInputAttempt();
  16900. void internalModifierKeysChanged();
  16901. void internalChildrenChanged();
  16902. void internalHierarchyChanged();
  16903. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  16904. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  16905. void repaintParent() throw();
  16906. void sendFakeMouseMove() const;
  16907. void takeKeyboardFocus (const FocusChangeType cause);
  16908. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  16909. static void giveAwayFocus();
  16910. void sendEnablementChangeMessage();
  16911. static void* runModalLoopCallback (void*);
  16912. void subtractObscuredRegions (RectangleList& result,
  16913. const int deltaX, const int deltaY,
  16914. const Rectangle& clipRect,
  16915. const Component* const compToAvoid) const throw();
  16916. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  16917. const int deltaX, const int deltaY) const throw();
  16918. // how much of the component is not off the edges of its parents
  16919. const Rectangle getUnclippedArea() const;
  16920. void sendVisibilityChangeMessage();
  16921. // This is included here just to cause a compile error if your code is still handling
  16922. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  16923. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  16924. // implement its methods instead of this Component method).
  16925. virtual void filesDropped (const StringArray&, int, int) {}
  16926. // components aren't allowed to have copy constructors, as this would mess up parent
  16927. // hierarchies. You might need to give your subclasses a private dummy constructor like
  16928. // this one to avoid compiler warnings.
  16929. Component (const Component&);
  16930. const Component& operator= (const Component&);
  16931. protected:
  16932. /** @internal */
  16933. virtual void internalRepaint (int x, int y, int w, int h);
  16934. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  16935. /** Overridden from the MessageListener parent class.
  16936. You can override this if you really need to, but be sure to pass your unwanted messages up
  16937. to this base class implementation, as the Component class needs to send itself messages
  16938. to work properly.
  16939. */
  16940. void handleMessage (const Message&);
  16941. };
  16942. #endif // __JUCE_COMPONENT_JUCEHEADER__
  16943. /********* End of inlined file: juce_Component.h *********/
  16944. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  16945. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16946. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16947. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  16948. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16949. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16950. /** A type used to hold the unique ID for an application command.
  16951. This is a numeric type, so it can be stored as an integer.
  16952. @see ApplicationCommandInfo, ApplicationCommandManager,
  16953. ApplicationCommandTarget, KeyPressMappingSet
  16954. */
  16955. typedef int CommandID;
  16956. /** A set of general-purpose application command IDs.
  16957. Because these commands are likely to be used in most apps, they're defined
  16958. here to help different apps to use the same numeric values for them.
  16959. Of course you don't have to use these, but some of them are used internally by
  16960. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  16961. @see ApplicationCommandInfo, ApplicationCommandManager,
  16962. ApplicationCommandTarget, KeyPressMappingSet
  16963. */
  16964. namespace StandardApplicationCommandIDs
  16965. {
  16966. /** This command ID should be used to send a "Quit the App" command.
  16967. This command is recognised by the JUCEApplication class, so if it is invoked
  16968. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  16969. object will catch it and call JUCEApplication::systemRequestedQuit().
  16970. */
  16971. static const CommandID quit = 0x1001;
  16972. /** The command ID that should be used to send a "Delete" command. */
  16973. static const CommandID del = 0x1002;
  16974. /** The command ID that should be used to send a "Cut" command. */
  16975. static const CommandID cut = 0x1003;
  16976. /** The command ID that should be used to send a "Copy to clipboard" command. */
  16977. static const CommandID copy = 0x1004;
  16978. /** The command ID that should be used to send a "Paste from clipboard" command. */
  16979. static const CommandID paste = 0x1005;
  16980. /** The command ID that should be used to send a "Select all" command. */
  16981. static const CommandID selectAll = 0x1006;
  16982. /** The command ID that should be used to send a "Deselect all" command. */
  16983. static const CommandID deselectAll = 0x1007;
  16984. }
  16985. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16986. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  16987. /**
  16988. Holds information describing an application command.
  16989. This object is used to pass information about a particular command, such as its
  16990. name, description and other usage flags.
  16991. When an ApplicationCommandTarget is asked to provide information about the commands
  16992. it can perform, this is the structure gets filled-in to describe each one.
  16993. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  16994. ApplicationCommandManager
  16995. */
  16996. struct JUCE_API ApplicationCommandInfo
  16997. {
  16998. ApplicationCommandInfo (const CommandID commandID) throw();
  16999. /** Sets a number of the structures values at once.
  17000. The meanings of each of the parameters is described below, in the appropriate
  17001. member variable's description.
  17002. */
  17003. void setInfo (const String& shortName,
  17004. const String& description,
  17005. const String& categoryName,
  17006. const int flags) throw();
  17007. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17008. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17009. is false, the bit is set.
  17010. */
  17011. void setActive (const bool isActive) throw();
  17012. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17013. */
  17014. void setTicked (const bool isTicked) throw();
  17015. /** Handy method for adding a keypress to the defaultKeypresses array.
  17016. This is just so you can write things like:
  17017. @code
  17018. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17019. @endcode
  17020. instead of
  17021. @code
  17022. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17023. @endcode
  17024. */
  17025. void addDefaultKeypress (const int keyCode,
  17026. const ModifierKeys& modifiers) throw();
  17027. /** The command's unique ID number.
  17028. */
  17029. CommandID commandID;
  17030. /** A short name to describe the command.
  17031. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17032. You can use the setInfo() method to quickly set this and some of the command's
  17033. other properties.
  17034. */
  17035. String shortName;
  17036. /** A longer description of the command.
  17037. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17038. pop-up tooltip describing what the command does.
  17039. You can use the setInfo() method to quickly set this and some of the command's
  17040. other properties.
  17041. */
  17042. String description;
  17043. /** A named category that the command fits into.
  17044. You can give your commands any category you like, and these will be displayed in
  17045. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17046. commands together.
  17047. You can use the setInfo() method to quickly set this and some of the command's
  17048. other properties.
  17049. */
  17050. String categoryName;
  17051. /** A list of zero or more keypresses that should be used as the default keys for
  17052. this command.
  17053. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17054. this list to initialise the default set of key-to-command mappings.
  17055. @see addDefaultKeypress
  17056. */
  17057. Array <KeyPress> defaultKeypresses;
  17058. /** Flags describing the ways in which this command should be used.
  17059. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17060. variable.
  17061. */
  17062. enum CommandFlags
  17063. {
  17064. /** Indicates that the command can't currently be performed.
  17065. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17066. not currently permissable to perform the command. If the flag is set, then
  17067. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17068. command or show themselves as not being enabled.
  17069. @see ApplicationCommandInfo::setActive
  17070. */
  17071. isDisabled = 1 << 0,
  17072. /** Indicates that the command should have a tick next to it on a menu.
  17073. If your command is shown on a menu and this is set, it'll show a tick next to
  17074. it. Other components such as buttons may also use this flag to indicate that it
  17075. is a value that can be toggled, and is currently in the 'on' state.
  17076. @see ApplicationCommandInfo::setTicked
  17077. */
  17078. isTicked = 1 << 1,
  17079. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17080. it will call the command twice, once on key-down and again on key-up.
  17081. @see ApplicationCommandTarget::InvocationInfo
  17082. */
  17083. wantsKeyUpDownCallbacks = 1 << 2,
  17084. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17085. command in its list.
  17086. */
  17087. hiddenFromKeyEditor = 1 << 3,
  17088. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17089. command in its list, but won't allow the assigned keypress to be changed.
  17090. */
  17091. readOnlyInKeyEditor = 1 << 4,
  17092. /** If this flag is present and the command is invoked from a keypress, then any
  17093. buttons or menus that are also connected to the command will not flash to
  17094. indicate that they've been triggered.
  17095. */
  17096. dontTriggerVisualFeedback = 1 << 5
  17097. };
  17098. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17099. You can use the setInfo() method to quickly set this and some of the command's
  17100. other properties.
  17101. */
  17102. int flags;
  17103. };
  17104. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17105. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17106. /**
  17107. A command target publishes a list of command IDs that it can perform.
  17108. An ApplicationCommandManager despatches commands to targets, which must be
  17109. able to provide information about what commands they can handle.
  17110. To create a target, you'll need to inherit from this class, implementing all of
  17111. its pure virtual methods.
  17112. For info about how a target is chosen to receive a command, see
  17113. ApplicationCommandManager::getFirstCommandTarget().
  17114. @see ApplicationCommandManager, ApplicationCommandInfo
  17115. */
  17116. class JUCE_API ApplicationCommandTarget
  17117. {
  17118. public:
  17119. /** Creates a command target. */
  17120. ApplicationCommandTarget();
  17121. /** Destructor. */
  17122. virtual ~ApplicationCommandTarget();
  17123. /**
  17124. */
  17125. struct JUCE_API InvocationInfo
  17126. {
  17127. InvocationInfo (const CommandID commandID) throw();
  17128. /** The UID of the command that should be performed. */
  17129. CommandID commandID;
  17130. /** The command's flags.
  17131. See ApplicationCommandInfo for a description of these flag values.
  17132. */
  17133. int commandFlags;
  17134. /** The types of context in which the command might be called. */
  17135. enum InvocationMethod
  17136. {
  17137. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17138. fromKeyPress, /**< The command is being invoked by a key-press. */
  17139. fromMenu, /**< The command is being invoked by a menu selection. */
  17140. fromButton /**< The command is being invoked by a button click. */
  17141. };
  17142. /** The type of event that triggered this command. */
  17143. InvocationMethod invocationMethod;
  17144. /** If triggered by a keypress or menu, this will be the component that had the
  17145. keyboard focus at the time.
  17146. If triggered by a button, it may be set to that component, or it may be null.
  17147. */
  17148. Component* originatingComponent;
  17149. /** The keypress that was used to invoke it.
  17150. Note that this will be an invalid keypress if the command was invoked
  17151. by some other means than a keyboard shortcut.
  17152. */
  17153. KeyPress keyPress;
  17154. /** True if the callback is being invoked when the key is pressed,
  17155. false if the key is being released.
  17156. @see KeyPressMappingSet::addCommand()
  17157. */
  17158. bool isKeyDown;
  17159. /** If the key is being released, this indicates how long it had been held
  17160. down for.
  17161. (Only relevant if isKeyDown is false.)
  17162. */
  17163. int millisecsSinceKeyPressed;
  17164. };
  17165. /** This must return the next target to try after this one.
  17166. When a command is being sent, and the first target can't handle
  17167. that command, this method is used to determine the next target that should
  17168. be tried.
  17169. It may return 0 if it doesn't know of another target.
  17170. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17171. method to return a parent component that might want to handle it.
  17172. @see invoke
  17173. */
  17174. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17175. /** This must return a complete list of commands that this target can handle.
  17176. Your target should add all the command IDs that it handles to the array that is
  17177. passed-in.
  17178. */
  17179. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17180. /** This must provide details about one of the commands that this target can perform.
  17181. This will be called with one of the command IDs that the target provided in its
  17182. getAllCommands() methods.
  17183. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17184. suitable information about the command. (The commandID field will already have been filled-in
  17185. by the caller).
  17186. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17187. set all the fields at once.
  17188. If the command is currently inactive for some reason, this method must use
  17189. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17190. bit of the ApplicationCommandInfo::flags field).
  17191. Any default key-presses for the command should be appended to the
  17192. ApplicationCommandInfo::defaultKeypresses field.
  17193. Note that if you change something that affects the status of the commands
  17194. that would be returned by this method (e.g. something that makes some commands
  17195. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17196. to cause the manager to refresh its status.
  17197. */
  17198. virtual void getCommandInfo (const CommandID commandID,
  17199. ApplicationCommandInfo& result) = 0;
  17200. /** This must actually perform the specified command.
  17201. If this target is able to perform the command specified by the commandID field of the
  17202. InvocationInfo structure, then it should do so, and must return true.
  17203. If it can't handle this command, it should return false, which tells the caller to pass
  17204. the command on to the next target in line.
  17205. @see invoke, ApplicationCommandManager::invoke
  17206. */
  17207. virtual bool perform (const InvocationInfo& info) = 0;
  17208. /** Makes this target invoke a command.
  17209. Your code can call this method to invoke a command on this target, but normally
  17210. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17211. ApplicationCommandManager::invokeDirectly().
  17212. If this target can perform the given command, it will call its perform() method to
  17213. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17214. to try, and the command will be passed along to it.
  17215. @param invocationInfo this must be correctly filled-in, describing the context for
  17216. the invocation.
  17217. @param asynchronously if false, the command will be performed before this method returns.
  17218. If true, a message will be posted so that the command will be performed
  17219. later on the message thread, and this method will return immediately.
  17220. @see perform, ApplicationCommandManager::invoke
  17221. */
  17222. bool invoke (const InvocationInfo& invocationInfo,
  17223. const bool asynchronously);
  17224. /** Invokes a given command directly on this target.
  17225. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17226. structure.
  17227. */
  17228. bool invokeDirectly (const CommandID commandID,
  17229. const bool asynchronously);
  17230. /** Searches this target and all subsequent ones for the first one that can handle
  17231. the specified command.
  17232. This will use getNextCommandTarget() to determine the chain of targets to try
  17233. after this one.
  17234. */
  17235. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17236. /** Checks whether this command can currently be performed by this target.
  17237. This will return true only if a call to getCommandInfo() doesn't set the
  17238. isDisabled flag to indicate that the command is inactive.
  17239. */
  17240. bool isCommandActive (const CommandID commandID);
  17241. /** If this object is a Component, this method will seach upwards in its current
  17242. UI hierarchy for the next parent component that implements the
  17243. ApplicationCommandTarget class.
  17244. If your target is a Component, this is a very handy method to use in your
  17245. getNextCommandTarget() implementation.
  17246. */
  17247. ApplicationCommandTarget* findFirstTargetParentComponent();
  17248. juce_UseDebuggingNewOperator
  17249. private:
  17250. // (for async invocation of commands)
  17251. class CommandTargetMessageInvoker : public MessageListener
  17252. {
  17253. public:
  17254. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17255. ~CommandTargetMessageInvoker();
  17256. void handleMessage (const Message& message);
  17257. private:
  17258. ApplicationCommandTarget* const owner;
  17259. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17260. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17261. };
  17262. CommandTargetMessageInvoker* messageInvoker;
  17263. friend class CommandTargetMessageInvoker;
  17264. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17265. };
  17266. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17267. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17268. /********* Start of inlined file: juce_ActionListener.h *********/
  17269. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17270. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17271. /**
  17272. Receives callbacks to indicate that some kind of event has occurred.
  17273. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17274. about something that's happened.
  17275. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17276. */
  17277. class JUCE_API ActionListener
  17278. {
  17279. public:
  17280. /** Destructor. */
  17281. virtual ~ActionListener() {}
  17282. /** Overridden by your subclass to receive the callback.
  17283. @param message the string that was specified when the event was triggered
  17284. by a call to ActionListenerList::sendActionMessage()
  17285. */
  17286. virtual void actionListenerCallback (const String& message) = 0;
  17287. };
  17288. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17289. /********* End of inlined file: juce_ActionListener.h *********/
  17290. /**
  17291. An instance of this class is used to specify initialisation and shutdown
  17292. code for the application.
  17293. An application that wants to run in the JUCE framework needs to declare a
  17294. subclass of JUCEApplication and implement its various pure virtual methods.
  17295. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17296. to declare an instance of this class and generate a suitable platform-specific
  17297. main() function.
  17298. e.g. @code
  17299. class MyJUCEApp : public JUCEApplication
  17300. {
  17301. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17302. // objects, which you must create in the initialise() method.
  17303. MyApplicationWindow* myMainWindow;
  17304. public:
  17305. MyJUCEApp()
  17306. : myMainWindow (0)
  17307. {
  17308. // never create any Juce objects in the constructor - do all your initialisation
  17309. // in the initialise() method.
  17310. }
  17311. ~MyJUCEApp()
  17312. {
  17313. // all your shutdown code must have already been done in the shutdown() method -
  17314. // nothing should happen in this destructor.
  17315. }
  17316. void initialise (const String& commandLine)
  17317. {
  17318. myMainWindow = new MyApplicationWindow();
  17319. myMainWindow->setBounds (100, 100, 400, 500);
  17320. myMainWindow->setVisible (true);
  17321. }
  17322. void shutdown()
  17323. {
  17324. delete myMainWindow;
  17325. }
  17326. const String getApplicationName()
  17327. {
  17328. return T("Super JUCE-o-matic");
  17329. }
  17330. const String getApplicationVersion()
  17331. {
  17332. return T("1.0");
  17333. }
  17334. };
  17335. // this creates wrapper code to actually launch the app properly.
  17336. START_JUCE_APPLICATION (MyJUCEApp)
  17337. @endcode
  17338. Because this object will be created before Juce has properly initialised, you must
  17339. NEVER add any member variable objects that will be automatically constructed. Likewise
  17340. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17341. you want to add to the class must be pointers, which you should instantiate during the
  17342. initialise() method, and delete in the shutdown() method.
  17343. @see MessageManager, DeletedAtShutdown
  17344. */
  17345. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17346. private ActionListener
  17347. {
  17348. protected:
  17349. /** Constructs a JUCE app object.
  17350. If subclasses implement a constructor or destructor, they shouldn't call any
  17351. JUCE code in there - put your startup/shutdown code in initialise() and
  17352. shutdown() instead.
  17353. */
  17354. JUCEApplication();
  17355. public:
  17356. /** Destructor.
  17357. If subclasses implement a constructor or destructor, they shouldn't call any
  17358. JUCE code in there - put your startup/shutdown code in initialise() and
  17359. shutdown() instead.
  17360. */
  17361. virtual ~JUCEApplication();
  17362. /** Returns the global instance of the application object being run. */
  17363. static JUCEApplication* getInstance() throw();
  17364. /** Called when the application starts.
  17365. This will be called once to let the application do whatever initialisation
  17366. it needs, create its windows, etc.
  17367. After the method returns, the normal event-dispatch loop will be run,
  17368. until the quit() method is called, at which point the shutdown()
  17369. method will be called to let the application clear up anything it needs
  17370. to delete.
  17371. If during the initialise() method, the application decides not to start-up
  17372. after all, it can just call the quit() method and the event loop won't be run.
  17373. @param commandLineParameters the line passed in does not include the
  17374. name of the executable, just the parameter list.
  17375. @see shutdown, quit
  17376. */
  17377. virtual void initialise (const String& commandLineParameters) = 0;
  17378. /** Returns true if the application hasn't yet completed its initialise() method
  17379. and entered the main event loop.
  17380. This is handy for things like splash screens to know when the app's up-and-running
  17381. properly.
  17382. */
  17383. bool isInitialising() const throw();
  17384. /* Called to allow the application to clear up before exiting.
  17385. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17386. terminate, and this method will get called to allow the app to sort itself
  17387. out.
  17388. Be careful that nothing happens in this method that might rely on messages
  17389. being sent, or any kind of window activity, because the message loop is no
  17390. longer running at this point.
  17391. @see DeletedAtShutdown
  17392. */
  17393. virtual void shutdown() = 0;
  17394. /** Returns the application's name.
  17395. An application must implement this to name itself.
  17396. */
  17397. virtual const String getApplicationName() = 0;
  17398. /** Returns the application's version number.
  17399. An application can implement this to give itself a version.
  17400. (The default implementation of this just returns an empty string).
  17401. */
  17402. virtual const String getApplicationVersion();
  17403. /** Checks whether multiple instances of the app are allowed.
  17404. If you application class returns true for this, more than one instance is
  17405. permitted to run (except on the Mac where this isn't possible).
  17406. If it's false, the second instance won't start, but it you will still get a
  17407. callback to anotherInstanceStarted() to tell you about this - which
  17408. gives you a chance to react to what the user was trying to do.
  17409. */
  17410. virtual bool moreThanOneInstanceAllowed();
  17411. /** Indicates that the user has tried to start up another instance of the app.
  17412. This will get called even if moreThanOneInstanceAllowed() is false.
  17413. */
  17414. virtual void anotherInstanceStarted (const String& commandLine);
  17415. /** Called when the operating system is trying to close the application.
  17416. The default implementation of this method is to call quit(), but it may
  17417. be overloaded to ignore the request or do some other special behaviour
  17418. instead. For example, you might want to offer the user the chance to save
  17419. their changes before quitting, and give them the chance to cancel.
  17420. If you want to send a quit signal to your app, this is the correct method
  17421. to call, because it means that requests that come from the system get handled
  17422. in the same way as those from your own application code. So e.g. you'd
  17423. call this method from a "quit" item on a menu bar.
  17424. */
  17425. virtual void systemRequestedQuit();
  17426. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17427. callback will be triggered, in case you want to log them or do some other
  17428. type of error-handling.
  17429. If the type of exception is derived from the std::exception class, the pointer
  17430. passed-in will be valid. If the exception is of unknown type, this pointer
  17431. will be null.
  17432. */
  17433. virtual void unhandledException (const std::exception* e,
  17434. const String& sourceFilename,
  17435. const int lineNumber);
  17436. /** Signals that the main message loop should stop and the application should terminate.
  17437. This isn't synchronous, it just posts a quit message to the main queue, and
  17438. when this message arrives, the message loop will stop, the shutdown() method
  17439. will be called, and the app will exit.
  17440. Note that this will cause an unconditional quit to happen, so if you need an
  17441. extra level before this, e.g. to give the user the chance to save their work
  17442. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17443. method - see that method's help for more info.
  17444. @see MessageManager, DeletedAtShutdown
  17445. */
  17446. static void quit();
  17447. /** Sets the value that should be returned as the application's exit code when the
  17448. app quits.
  17449. This is the value that's returned by the main() function. Normally you'd leave this
  17450. as 0 unless you want to indicate an error code.
  17451. @see getApplicationReturnValue
  17452. */
  17453. void setApplicationReturnValue (const int newReturnValue) throw();
  17454. /** Returns the value that has been set as the application's exit code.
  17455. @see setApplicationReturnValue
  17456. */
  17457. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17458. /** Returns the application's command line params.
  17459. */
  17460. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  17461. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17462. /** @internal */
  17463. static int main (String& commandLine, JUCEApplication* const newApp);
  17464. /** @internal */
  17465. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17466. /** @internal */
  17467. static void sendUnhandledException (const std::exception* const e,
  17468. const char* const sourceFile,
  17469. const int lineNumber);
  17470. /** @internal */
  17471. ApplicationCommandTarget* getNextCommandTarget();
  17472. /** @internal */
  17473. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17474. /** @internal */
  17475. void getAllCommands (Array <CommandID>& commands);
  17476. /** @internal */
  17477. bool perform (const InvocationInfo& info);
  17478. /** @internal */
  17479. void actionListenerCallback (const String& message);
  17480. private:
  17481. String commandLineParameters;
  17482. int appReturnValue;
  17483. bool stillInitialising;
  17484. static int shutdownAppAndClearUp();
  17485. };
  17486. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17487. /********* End of inlined file: juce_Application.h *********/
  17488. #endif
  17489. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17490. #endif
  17491. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17492. #endif
  17493. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17494. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17495. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17496. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17497. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17498. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17499. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17500. /**
  17501. Has a callback method that is triggered asynchronously.
  17502. This object allows an asynchronous callback function to be triggered, for
  17503. tasks such as coalescing multiple updates into a single callback later on.
  17504. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17505. message thread calling handleAsyncUpdate() as soon as it can.
  17506. */
  17507. class JUCE_API AsyncUpdater
  17508. {
  17509. public:
  17510. /** Creates an AsyncUpdater object. */
  17511. AsyncUpdater() throw();
  17512. /** Destructor.
  17513. If there are any pending callbacks when the object is deleted, these are lost.
  17514. */
  17515. virtual ~AsyncUpdater();
  17516. /** Causes the callback to be triggered at a later time.
  17517. This method returns immediately, having made sure that a callback
  17518. to the handleAsyncUpdate() method will occur as soon as possible.
  17519. If an update callback is already pending but hasn't happened yet, calls
  17520. to this method will be ignored.
  17521. It's thread-safe to call this method from any number of threads without
  17522. needing to worry about locking.
  17523. */
  17524. void triggerAsyncUpdate() throw();
  17525. /** This will stop any pending updates from happening.
  17526. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17527. callback happens, this will cancel the handleAsyncUpdate() callback.
  17528. */
  17529. void cancelPendingUpdate() throw();
  17530. /** If an update has been triggered and is pending, this will invoke it
  17531. synchronously.
  17532. Use this as a kind of "flush" operation - if an update is pending, the
  17533. handleAsyncUpdate() method will be called immediately; if no update is
  17534. pending, then nothing will be done.
  17535. */
  17536. void handleUpdateNowIfNeeded();
  17537. /** Called back to do whatever your class needs to do.
  17538. This method is called by the message thread at the next convenient time
  17539. after the triggerAsyncUpdate() method has been called.
  17540. */
  17541. virtual void handleAsyncUpdate() = 0;
  17542. private:
  17543. class AsyncUpdaterInternal : public MessageListener
  17544. {
  17545. public:
  17546. AsyncUpdaterInternal() throw() {}
  17547. ~AsyncUpdaterInternal() {}
  17548. void handleMessage (const Message&);
  17549. AsyncUpdater* owner;
  17550. private:
  17551. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17552. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17553. };
  17554. AsyncUpdaterInternal internalAsyncHandler;
  17555. bool asyncMessagePending;
  17556. };
  17557. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17558. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17559. /********* Start of inlined file: juce_Desktop.h *********/
  17560. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17561. #define __JUCE_DESKTOP_JUCEHEADER__
  17562. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17563. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17564. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17565. /**
  17566. Classes derived from this will be automatically deleted when the application exits.
  17567. After JUCEApplication::shutdown() has been called, any objects derived from
  17568. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17569. order to that in which they were created.
  17570. So if you've got a singleton and don't want to have to explicitly delete it, just
  17571. inherit from this and it'll be taken care of.
  17572. */
  17573. class JUCE_API DeletedAtShutdown
  17574. {
  17575. protected:
  17576. /** Creates a DeletedAtShutdown object. */
  17577. DeletedAtShutdown() throw();
  17578. /** Destructor.
  17579. It's ok to delete these objects explicitly - it's only the ones left
  17580. dangling at the end that will be deleted automatically.
  17581. */
  17582. virtual ~DeletedAtShutdown();
  17583. public:
  17584. /** Deletes all extant objects.
  17585. This shouldn't be used by applications, as it's called automatically
  17586. in the shutdown code of the JUCEApplication class.
  17587. */
  17588. static void deleteAll();
  17589. private:
  17590. DeletedAtShutdown (const DeletedAtShutdown&);
  17591. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17592. };
  17593. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17594. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17595. /********* Start of inlined file: juce_Timer.h *********/
  17596. #ifndef __JUCE_TIMER_JUCEHEADER__
  17597. #define __JUCE_TIMER_JUCEHEADER__
  17598. class InternalTimerThread;
  17599. /**
  17600. Repeatedly calls a user-defined method at a specified time interval.
  17601. A Timer's timerCallback() method will be repeatedly called at a given
  17602. interval. Initially when a Timer object is created, they will do nothing
  17603. until the startTimer() method is called, then the message thread will
  17604. start calling it back until stopTimer() is called.
  17605. The time interval isn't guaranteed to be precise to any more than maybe
  17606. 10-20ms, and the intervals may end up being much longer than requested if the
  17607. system is busy. Because it's the message thread that is doing the callbacks,
  17608. any messages that take a significant amount of time to process will block
  17609. all the timers for that period.
  17610. If you need to have a single callback that is shared by multiple timers with
  17611. different frequencies, then the MultiTimer class allows you to do that - its
  17612. structure is very similar to the Timer class, but contains multiple timers
  17613. internally, each one identified by an ID number.
  17614. @see MultiTimer
  17615. */
  17616. class JUCE_API Timer
  17617. {
  17618. protected:
  17619. /** Creates a Timer.
  17620. When created, the timer is stopped, so use startTimer() to get it going.
  17621. */
  17622. Timer() throw();
  17623. /** Creates a copy of another timer.
  17624. Note that this timer won't be started, even if the one you're copying
  17625. is running.
  17626. */
  17627. Timer (const Timer& other) throw();
  17628. public:
  17629. /** Destructor. */
  17630. virtual ~Timer();
  17631. /** The user-defined callback routine that actually gets called periodically.
  17632. It's perfectly ok to call startTimer() or stopTimer() from within this
  17633. callback to change the subsequent intervals.
  17634. */
  17635. virtual void timerCallback() = 0;
  17636. /** Starts the timer and sets the length of interval required.
  17637. If the timer is already started, this will reset it, so the
  17638. time between calling this method and the next timer callback
  17639. will not be less than the interval length passed in.
  17640. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17641. rounded up to 1)
  17642. */
  17643. void startTimer (const int intervalInMilliseconds) throw();
  17644. /** Stops the timer.
  17645. No more callbacks will be made after this method returns.
  17646. If this is called from a different thread, any callbacks that may
  17647. be currently executing may be allowed to finish before the method
  17648. returns.
  17649. */
  17650. void stopTimer() throw();
  17651. /** Checks if the timer has been started.
  17652. @returns true if the timer is running.
  17653. */
  17654. bool isTimerRunning() const throw() { return periodMs > 0; }
  17655. /** Returns the timer's interval.
  17656. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17657. */
  17658. int getTimerInterval() const throw() { return periodMs; }
  17659. private:
  17660. friend class InternalTimerThread;
  17661. int countdownMs, periodMs;
  17662. Timer* previous;
  17663. Timer* next;
  17664. const Timer& operator= (const Timer&);
  17665. };
  17666. #endif // __JUCE_TIMER_JUCEHEADER__
  17667. /********* End of inlined file: juce_Timer.h *********/
  17668. /**
  17669. Classes can implement this interface and register themselves with the Desktop class
  17670. to receive callbacks when the currently focused component changes.
  17671. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17672. */
  17673. class JUCE_API FocusChangeListener
  17674. {
  17675. public:
  17676. /** Destructor. */
  17677. virtual ~FocusChangeListener() {}
  17678. /** Callback to indicate that the currently focused component has changed. */
  17679. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17680. };
  17681. /**
  17682. Describes and controls aspects of the computer's desktop.
  17683. */
  17684. class JUCE_API Desktop : private DeletedAtShutdown,
  17685. private Timer,
  17686. private AsyncUpdater
  17687. {
  17688. public:
  17689. /** There's only one dektop object, and this method will return it.
  17690. */
  17691. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17692. /** Returns a list of the positions of all the monitors available.
  17693. The first rectangle in the list will be the main monitor area.
  17694. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17695. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17696. */
  17697. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17698. /** Returns the position and size of the main monitor.
  17699. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17700. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17701. */
  17702. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17703. /** Returns the position and size of the monitor which contains this co-ordinate.
  17704. If none of the monitors contains the point, this will just return the
  17705. main monitor.
  17706. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17707. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17708. */
  17709. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17710. /** Returns the mouse position.
  17711. The co-ordinates are relative to the top-left of the main monitor.
  17712. */
  17713. static void getMousePosition (int& x, int& y) throw();
  17714. /** Makes the mouse pointer jump to a given location.
  17715. The co-ordinates are relative to the top-left of the main monitor.
  17716. */
  17717. static void setMousePosition (int x, int y) throw();
  17718. /** Returns the last position at which a mouse button was pressed.
  17719. */
  17720. static void getLastMouseDownPosition (int& x, int& y) throw();
  17721. /** Returns the number of times the mouse button has been clicked since the
  17722. app started.
  17723. Each mouse-down event increments this number by 1.
  17724. */
  17725. static int getMouseButtonClickCounter() throw();
  17726. /** This lets you prevent the screensaver from becoming active.
  17727. Handy if you're running some sort of presentation app where having a screensaver
  17728. appear would be annoying.
  17729. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17730. won't enable a screensaver unless the user has actually set one up).
  17731. The disablement will only happen while the Juce application is the foreground
  17732. process - if another task is running in front of it, then the screensaver will
  17733. be unaffected.
  17734. @see isScreenSaverEnabled
  17735. */
  17736. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17737. /** Returns true if the screensaver has not been turned off.
  17738. This will return the last value passed into setScreenSaverEnabled(). Note that
  17739. it won't tell you whether the user is actually using a screen saver, just
  17740. whether this app is deliberately preventing one from running.
  17741. @see setScreenSaverEnabled
  17742. */
  17743. static bool isScreenSaverEnabled() throw();
  17744. /** Registers a MouseListener that will receive all mouse events that occur on
  17745. any component.
  17746. @see removeGlobalMouseListener
  17747. */
  17748. void addGlobalMouseListener (MouseListener* const listener) throw();
  17749. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17750. method.
  17751. @see addGlobalMouseListener
  17752. */
  17753. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17754. /** Registers a MouseListener that will receive a callback whenever the focused
  17755. component changes.
  17756. */
  17757. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17758. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17759. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17760. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  17761. The component must already be on the desktop for this method to work. It will
  17762. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  17763. etc will be hidden.
  17764. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  17765. the component that's currently being used will be resized back to the size
  17766. and position it was in before being put into this mode.
  17767. */
  17768. void setKioskModeComponent (Component* componentToUse);
  17769. /** Returns the component that is currently being used in kiosk-mode.
  17770. This is the component that was last set by setKioskModeComponent(). If none
  17771. has been set, this returns 0.
  17772. */
  17773. Component* getKioskModeComponent() const { return kioskModeComponent; }
  17774. /** Returns the number of components that are currently active as top-level
  17775. desktop windows.
  17776. @see getComponent, Component::addToDesktop
  17777. */
  17778. int getNumComponents() const throw();
  17779. /** Returns one of the top-level desktop window components.
  17780. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17781. index is out-of-range.
  17782. @see getNumComponents, Component::addToDesktop
  17783. */
  17784. Component* getComponent (const int index) const throw();
  17785. /** Finds the component at a given screen location.
  17786. This will drill down into top-level windows to find the child component at
  17787. the given position.
  17788. Returns 0 if the co-ordinates are inside a non-Juce window.
  17789. */
  17790. Component* findComponentAt (const int screenX,
  17791. const int screenY) const;
  17792. juce_UseDebuggingNewOperator
  17793. /** Tells this object to refresh its idea of what the screen resolution is.
  17794. (Called internally by the native code).
  17795. */
  17796. void refreshMonitorSizes() throw();
  17797. /** True if the OS supports semitransparent windows */
  17798. static bool canUseSemiTransparentWindows() throw();
  17799. private:
  17800. friend class Component;
  17801. friend class ComponentPeer;
  17802. SortedSet <void*> mouseListeners, focusListeners;
  17803. VoidArray desktopComponents;
  17804. friend class DeletedAtShutdown;
  17805. friend class TopLevelWindowManager;
  17806. Desktop() throw();
  17807. ~Desktop() throw();
  17808. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17809. int lastMouseX, lastMouseY;
  17810. Component* kioskModeComponent;
  17811. Rectangle kioskComponentOriginalBounds;
  17812. void timerCallback();
  17813. void sendMouseMove();
  17814. void resetTimer() throw();
  17815. int getNumDisplayMonitors() const throw();
  17816. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17817. void addDesktopComponent (Component* const c) throw();
  17818. void removeDesktopComponent (Component* const c) throw();
  17819. void componentBroughtToFront (Component* const c) throw();
  17820. void triggerFocusCallback() throw();
  17821. void handleAsyncUpdate();
  17822. Desktop (const Desktop&);
  17823. const Desktop& operator= (const Desktop&);
  17824. };
  17825. #endif // __JUCE_DESKTOP_JUCEHEADER__
  17826. /********* End of inlined file: juce_Desktop.h *********/
  17827. class KeyPressMappingSet;
  17828. class ApplicationCommandManagerListener;
  17829. /**
  17830. One of these objects holds a list of all the commands your app can perform,
  17831. and despatches these commands when needed.
  17832. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  17833. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  17834. to invoke automatically, which means you don't have to handle the result of a menu
  17835. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  17836. which can choose which events they want to handle.
  17837. This architecture also allows for nested ApplicationCommandTargets, so that for example
  17838. you could have two different objects, one inside the other, both of which can respond to
  17839. a "delete" command. Depending on which one has focus, the command will be sent to the
  17840. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  17841. method.
  17842. To set up your app to use commands, you'll need to do the following:
  17843. - Create a global ApplicationCommandManager to hold the list of all possible
  17844. commands. (This will also manage a set of key-mappings for them).
  17845. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  17846. This allows the object to provide a list of commands that it can perform, and
  17847. to handle them.
  17848. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  17849. or ApplicationCommandManager::registerCommand().
  17850. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  17851. method to access the key-mapper object, which you will need to register as a key-listener
  17852. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  17853. about setting this up.
  17854. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  17855. cause these commands to be invoked automatically.
  17856. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  17857. When a command is invoked, the ApplicationCommandManager will try to choose the best
  17858. ApplicationCommandTarget to receive the specified command. To do this it will use the
  17859. current keyboard focus to see which component might be interested, and will search the
  17860. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  17861. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  17862. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  17863. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  17864. point if the command still hasn't been performed, it will be passed to the current
  17865. JUCEApplication object (which is itself an ApplicationCommandTarget).
  17866. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  17867. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  17868. the object yourself.
  17869. @see ApplicationCommandTarget, ApplicationCommandInfo
  17870. */
  17871. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  17872. private FocusChangeListener
  17873. {
  17874. public:
  17875. /** Creates an ApplicationCommandManager.
  17876. Once created, you'll need to register all your app's commands with it, using
  17877. ApplicationCommandManager::registerAllCommandsForTarget() or
  17878. ApplicationCommandManager::registerCommand().
  17879. */
  17880. ApplicationCommandManager();
  17881. /** Destructor.
  17882. Make sure that you don't delete this if pointers to it are still being used by
  17883. objects such as PopupMenus or Buttons.
  17884. */
  17885. virtual ~ApplicationCommandManager();
  17886. /** Clears the current list of all commands.
  17887. Note that this will also clear the contents of the KeyPressMappingSet.
  17888. */
  17889. void clearCommands();
  17890. /** Adds a command to the list of registered commands.
  17891. @see registerAllCommandsForTarget
  17892. */
  17893. void registerCommand (const ApplicationCommandInfo& newCommand);
  17894. /** Adds all the commands that this target publishes to the manager's list.
  17895. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  17896. to get details about all the commands that this target can do, and will call
  17897. registerCommand() to add each one to the manger's list.
  17898. @see registerCommand
  17899. */
  17900. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  17901. /** Removes the command with a specified ID.
  17902. Note that this will also remove any key mappings that are mapped to the command.
  17903. */
  17904. void removeCommand (const CommandID commandID);
  17905. /** This should be called to tell the manager that one of its registered commands may have changed
  17906. its active status.
  17907. Because the command manager only finds out whether a command is active or inactive by querying
  17908. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  17909. allows things like buttons to update their enablement, etc.
  17910. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  17911. for any registered listeners.
  17912. */
  17913. void commandStatusChanged();
  17914. /** Returns the number of commands that have been registered.
  17915. @see registerCommand
  17916. */
  17917. int getNumCommands() const throw() { return commands.size(); }
  17918. /** Returns the details about one of the registered commands.
  17919. The index is between 0 and (getNumCommands() - 1).
  17920. */
  17921. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  17922. /** Returns the details about a given command ID.
  17923. This will search the list of registered commands for one with the given command
  17924. ID number, and return its associated info. If no matching command is found, this
  17925. will return 0.
  17926. */
  17927. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  17928. /** Returns the name field for a command.
  17929. An empty string is returned if no command with this ID has been registered.
  17930. @see getDescriptionOfCommand
  17931. */
  17932. const String getNameOfCommand (const CommandID commandID) const throw();
  17933. /** Returns the description field for a command.
  17934. An empty string is returned if no command with this ID has been registered. If the
  17935. command has no description, this will return its short name field instead.
  17936. @see getNameOfCommand
  17937. */
  17938. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  17939. /** Returns the list of categories.
  17940. This will go through all registered commands, and return a list of all the distict
  17941. categoryName values from their ApplicationCommandInfo structure.
  17942. @see getCommandsInCategory()
  17943. */
  17944. const StringArray getCommandCategories() const throw();
  17945. /** Returns a list of all the command UIDs in a particular category.
  17946. @see getCommandCategories()
  17947. */
  17948. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  17949. /** Returns the manager's internal set of key mappings.
  17950. This object can be used to edit the keypresses. To actually link this object up
  17951. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  17952. class.
  17953. @see KeyPressMappingSet
  17954. */
  17955. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  17956. /** Invokes the given command directly, sending it to the default target.
  17957. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17958. structure.
  17959. */
  17960. bool invokeDirectly (const CommandID commandID,
  17961. const bool asynchronously);
  17962. /** Sends a command to the default target.
  17963. This will choose a target using getFirstCommandTarget(), and send the specified command
  17964. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  17965. first target can't handle the command, it will be passed on to targets further down the
  17966. chain (see ApplicationCommandTarget::invoke() for more info).
  17967. @param invocationInfo this must be correctly filled-in, describing the context for
  17968. the invocation.
  17969. @param asynchronously if false, the command will be performed before this method returns.
  17970. If true, a message will be posted so that the command will be performed
  17971. later on the message thread, and this method will return immediately.
  17972. @see ApplicationCommandTarget::invoke
  17973. */
  17974. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  17975. const bool asynchronously);
  17976. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  17977. Whenever the manager needs to know which target a command should be sent to, it calls
  17978. this method to determine the first one to try.
  17979. By default, this method will return the target that was set by calling setFirstCommandTarget().
  17980. If no target is set, it will return the result of findDefaultComponentTarget().
  17981. If you need to make sure all commands go via your own custom target, then you can
  17982. either use setFirstCommandTarget() to specify a single target, or override this method
  17983. if you need more complex logic to choose one.
  17984. It may return 0 if no targets are available.
  17985. @see getTargetForCommand, invoke, invokeDirectly
  17986. */
  17987. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  17988. /** Sets a target to be returned by getFirstCommandTarget().
  17989. If this is set to 0, then getFirstCommandTarget() will by default return the
  17990. result of findDefaultComponentTarget().
  17991. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  17992. deleting the target object.
  17993. */
  17994. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  17995. /** Tries to find the best target to use to perform a given command.
  17996. This will call getFirstCommandTarget() to find the preferred target, and will
  17997. check whether that target can handle the given command. If it can't, then it'll use
  17998. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  17999. so on until no more are available.
  18000. If no targets are found that can perform the command, this method will return 0.
  18001. If a target is found, then it will get the target to fill-in the upToDateInfo
  18002. structure with the latest info about that command, so that the caller can see
  18003. whether the command is disabled, ticked, etc.
  18004. */
  18005. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18006. ApplicationCommandInfo& upToDateInfo);
  18007. /** Registers a listener that will be called when various events occur. */
  18008. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18009. /** Deregisters a previously-added listener. */
  18010. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18011. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18012. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18013. but is exposed here in case it's useful.
  18014. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18015. windows, etc., and using the findTargetForComponent() method.
  18016. */
  18017. static ApplicationCommandTarget* findDefaultComponentTarget();
  18018. /** Examines this component and all its parents in turn, looking for the first one
  18019. which is a ApplicationCommandTarget.
  18020. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18021. that class.
  18022. */
  18023. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18024. juce_UseDebuggingNewOperator
  18025. private:
  18026. OwnedArray <ApplicationCommandInfo> commands;
  18027. SortedSet <void*> listeners;
  18028. KeyPressMappingSet* keyMappings;
  18029. ApplicationCommandTarget* firstTarget;
  18030. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18031. void handleAsyncUpdate();
  18032. void globalFocusChanged (Component*);
  18033. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18034. // version of this method.
  18035. virtual short getFirstCommandTarget() { return 0; }
  18036. };
  18037. /**
  18038. A listener that receives callbacks from an ApplicationCommandManager when
  18039. commands are invoked or the command list is changed.
  18040. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18041. */
  18042. class JUCE_API ApplicationCommandManagerListener
  18043. {
  18044. public:
  18045. /** Destructor. */
  18046. virtual ~ApplicationCommandManagerListener() {}
  18047. /** Called when an app command is about to be invoked. */
  18048. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18049. /** Called when commands are registered or deregistered from the
  18050. command manager, or when commands are made active or inactive.
  18051. Note that if you're using this to watch for changes to whether a command is disabled,
  18052. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18053. whenever the status of your command might have changed.
  18054. */
  18055. virtual void applicationCommandListChanged() = 0;
  18056. };
  18057. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18058. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18059. #endif
  18060. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18061. #endif
  18062. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18063. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18064. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18065. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18066. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18067. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18068. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18069. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18070. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18071. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18072. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18073. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18074. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18075. /********* Start of inlined file: juce_ChangeListener.h *********/
  18076. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18077. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18078. /**
  18079. Receives callbacks about changes to some kind of object.
  18080. Many objects use a ChangeListenerList to keep a set of listeners which they
  18081. will inform when something changes. A subclass of ChangeListener
  18082. is used to receive these callbacks.
  18083. Note that the major difference between an ActionListener and a ChangeListener
  18084. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18085. callbacks, but ActionListeners perform one callback for every event posted.
  18086. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18087. */
  18088. class JUCE_API ChangeListener
  18089. {
  18090. public:
  18091. /** Destructor. */
  18092. virtual ~ChangeListener() {}
  18093. /** Overridden by your subclass to receive the callback.
  18094. @param objectThatHasChanged the value that was passed to the
  18095. ChangeListenerList::sendChangeMessage() method
  18096. */
  18097. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18098. };
  18099. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18100. /********* End of inlined file: juce_ChangeListener.h *********/
  18101. /**
  18102. A set of ChangeListeners.
  18103. Listeners can be added and removed from the list, and change messages can be
  18104. broadcast to all the listeners.
  18105. @see ChangeListener, ChangeBroadcaster
  18106. */
  18107. class JUCE_API ChangeListenerList : public MessageListener
  18108. {
  18109. public:
  18110. /** Creates an empty list. */
  18111. ChangeListenerList() throw();
  18112. /** Destructor. */
  18113. ~ChangeListenerList() throw();
  18114. /** Adds a listener to the list.
  18115. (Trying to add a listener that's already on the list will have no effect).
  18116. */
  18117. void addChangeListener (ChangeListener* const listener) throw();
  18118. /** Removes a listener from the list.
  18119. If the listener isn't on the list, this won't have any effect.
  18120. */
  18121. void removeChangeListener (ChangeListener* const listener) throw();
  18122. /** Removes all listeners from the list. */
  18123. void removeAllChangeListeners() throw();
  18124. /** Posts an asynchronous change message to all the listeners.
  18125. If a message has already been sent and hasn't yet been delivered, this
  18126. method won't send another - in this way it coalesces multiple frequent
  18127. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18128. with the ActionListener, which posts a new event for every call to its
  18129. sendActionMessage() method.
  18130. Only listeners which are on the list when the change event is delivered
  18131. will receive the event - and this may include listeners that weren't on
  18132. the list when the change message was sent.
  18133. @param objectThatHasChanged this pointer is passed to the
  18134. ChangeListener::changeListenerCallback() method,
  18135. and can be any value the application needs
  18136. @see sendSynchronousChangeMessage
  18137. */
  18138. void sendChangeMessage (void* objectThatHasChanged) throw();
  18139. /** This will synchronously callback all the ChangeListeners.
  18140. Use this if you need to synchronously force a call to all the
  18141. listeners' ChangeListener::changeListenerCallback() methods.
  18142. */
  18143. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18144. /** If a change message has been sent but not yet dispatched, this will
  18145. use sendSynchronousChangeMessage() to make the callback immediately.
  18146. */
  18147. void dispatchPendingMessages();
  18148. /** @internal */
  18149. void handleMessage (const Message&);
  18150. juce_UseDebuggingNewOperator
  18151. private:
  18152. SortedSet <void*> listeners;
  18153. CriticalSection lock;
  18154. void* lastChangedObject;
  18155. bool messagePending;
  18156. ChangeListenerList (const ChangeListenerList&);
  18157. const ChangeListenerList& operator= (const ChangeListenerList&);
  18158. };
  18159. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18160. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18161. /** Manages a list of ChangeListeners, and can send them messages.
  18162. To quickly add methods to your class that can add/remove change
  18163. listeners and broadcast to them, you can derive from this.
  18164. @see ChangeListenerList, ChangeListener
  18165. */
  18166. class JUCE_API ChangeBroadcaster
  18167. {
  18168. public:
  18169. /** Creates an ChangeBroadcaster. */
  18170. ChangeBroadcaster() throw();
  18171. /** Destructor. */
  18172. virtual ~ChangeBroadcaster();
  18173. /** Adds a listener to the list.
  18174. (Trying to add a listener that's already on the list will have no effect).
  18175. */
  18176. void addChangeListener (ChangeListener* const listener) throw();
  18177. /** Removes a listener from the list.
  18178. If the listener isn't on the list, this won't have any effect.
  18179. */
  18180. void removeChangeListener (ChangeListener* const listener) throw();
  18181. /** Removes all listeners from the list. */
  18182. void removeAllChangeListeners() throw();
  18183. /** Broadcasts a change message to all the registered listeners.
  18184. The message will be delivered asynchronously by the event thread, so this
  18185. method will not directly call any of the listeners. For a synchronous
  18186. message, use sendSynchronousChangeMessage().
  18187. @see ChangeListenerList::sendActionMessage
  18188. */
  18189. void sendChangeMessage (void* objectThatHasChanged) throw();
  18190. /** Sends a synchronous change message to all the registered listeners.
  18191. @see ChangeListenerList::sendSynchronousChangeMessage
  18192. */
  18193. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18194. /** If a change message has been sent but not yet dispatched, this will
  18195. use sendSynchronousChangeMessage() to make the callback immediately.
  18196. */
  18197. void dispatchPendingMessages();
  18198. private:
  18199. ChangeListenerList changeListenerList;
  18200. ChangeBroadcaster (const ChangeBroadcaster&);
  18201. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18202. };
  18203. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18204. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18205. /** Wrapper on a file that stores a list of key/value data pairs.
  18206. Useful for storing application settings, etc. See the PropertySet class for
  18207. the interfaces that read and write values.
  18208. Not designed for very large amounts of data, as it keeps all the values in
  18209. memory and writes them out to disk lazily when they are changed.
  18210. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18211. with it, and these will be signalled when a value changes.
  18212. @see PropertySet
  18213. */
  18214. class JUCE_API PropertiesFile : public PropertySet,
  18215. public ChangeBroadcaster,
  18216. private Timer
  18217. {
  18218. public:
  18219. enum FileFormatOptions
  18220. {
  18221. ignoreCaseOfKeyNames = 1,
  18222. storeAsBinary = 2,
  18223. storeAsCompressedBinary = 4,
  18224. storeAsXML = 8
  18225. };
  18226. /**
  18227. Creates a PropertiesFile object.
  18228. @param file the file to use
  18229. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18230. is changed, the object will wait for this amount
  18231. of time and then save the file. If zero, the file
  18232. will be written to disk immediately on being changed
  18233. (which might be slow, as it'll re-write synchronously
  18234. each time a value-change method is called). If it is
  18235. less than zero, the file won't be saved until
  18236. save() or saveIfNeeded() are explicitly called.
  18237. @param options a combination of the flags in the FileFormatOptions
  18238. enum, which specify the type of file to save, and other
  18239. options.
  18240. */
  18241. PropertiesFile (const File& file,
  18242. const int millisecondsBeforeSaving,
  18243. const int options) throw();
  18244. /** Destructor.
  18245. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18246. */
  18247. ~PropertiesFile();
  18248. /** This will flush all the values to disk if they've changed since the last
  18249. time they were saved.
  18250. Returns false if it fails to write to the file for some reason (maybe because
  18251. it's read-only or the directory doesn't exist or something).
  18252. @see save
  18253. */
  18254. bool saveIfNeeded();
  18255. /** This will force a write-to-disk of the current values, regardless of whether
  18256. anything has changed since the last save.
  18257. Returns false if it fails to write to the file for some reason (maybe because
  18258. it's read-only or the directory doesn't exist or something).
  18259. @see saveIfNeeded
  18260. */
  18261. bool save();
  18262. /** Returns true if the properties have been altered since the last time they were
  18263. saved.
  18264. */
  18265. bool needsToBeSaved() const throw();
  18266. /** Returns the file that's being used. */
  18267. const File getFile() const throw();
  18268. /** Handy utility to create a properties file in whatever the standard OS-specific
  18269. location is for these things.
  18270. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18271. creates a PropertiesFile object with the specified properties. See
  18272. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18273. what the parameters do.
  18274. @see getDefaultAppSettingsFile
  18275. */
  18276. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18277. const String& fileNameSuffix,
  18278. const String& folderName,
  18279. const bool commonToAllUsers,
  18280. const int millisecondsBeforeSaving,
  18281. const int propertiesFileOptions);
  18282. /** Handy utility to choose a file in the standard OS-dependent location for application
  18283. settings files.
  18284. So on a Mac, this will return a file called:
  18285. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18286. On Windows it'll return something like:
  18287. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18288. On Linux it'll return
  18289. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18290. If you pass an empty string as the folder name, it'll use the app name for this (or
  18291. omit the folder name on the Mac).
  18292. If commonToAllUsers is true, then this will return the same file for all users of the
  18293. computer, regardless of the current user. If it is false, the file will be specific to
  18294. only the current user. Use this to choose whether you're saving settings that are common
  18295. or user-specific.
  18296. */
  18297. static const File getDefaultAppSettingsFile (const String& applicationName,
  18298. const String& fileNameSuffix,
  18299. const String& folderName,
  18300. const bool commonToAllUsers);
  18301. juce_UseDebuggingNewOperator
  18302. protected:
  18303. virtual void propertyChanged();
  18304. private:
  18305. File file;
  18306. int timerInterval;
  18307. const int options;
  18308. bool needsWriting;
  18309. void timerCallback();
  18310. PropertiesFile (const PropertiesFile&);
  18311. const PropertiesFile& operator= (const PropertiesFile&);
  18312. };
  18313. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18314. /********* End of inlined file: juce_PropertiesFile.h *********/
  18315. /**
  18316. Manages a collection of properties.
  18317. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18318. as a singleton.
  18319. It holds two different PropertiesFile objects internally, one for user-specific
  18320. settings (stored in your user directory), and one for settings that are common to
  18321. all users (stored in a folder accessible to all users).
  18322. The class manages the creation of these files on-demand, allowing access via the
  18323. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18324. methods like testWriteAccess() to check that the files can be saved.
  18325. If you're using one of these as a singleton, then your app's start-up code should
  18326. first of all call setStorageParameters() to tell it the parameters to use to create
  18327. the properties files.
  18328. @see PropertiesFile
  18329. */
  18330. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18331. {
  18332. public:
  18333. /**
  18334. Creates an ApplicationProperties object.
  18335. Before using it, you must call setStorageParameters() to give it the info
  18336. it needs to create the property files.
  18337. */
  18338. ApplicationProperties() throw();
  18339. /** Destructor.
  18340. */
  18341. ~ApplicationProperties();
  18342. juce_DeclareSingleton (ApplicationProperties, false)
  18343. /** Gives the object the information it needs to create the appropriate properties files.
  18344. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18345. info about how these parameters are used.
  18346. */
  18347. void setStorageParameters (const String& applicationName,
  18348. const String& fileNameSuffix,
  18349. const String& folderName,
  18350. const int millisecondsBeforeSaving,
  18351. const int propertiesFileOptions) throw();
  18352. /** Tests whether the files can be successfully written to, and can show
  18353. an error message if not.
  18354. Returns true if none of the tests fail.
  18355. @param testUserSettings if true, the user settings file will be tested
  18356. @param testCommonSettings if true, the common settings file will be tested
  18357. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18358. message box if either of the tests fail
  18359. */
  18360. bool testWriteAccess (const bool testUserSettings,
  18361. const bool testCommonSettings,
  18362. const bool showWarningDialogOnFailure);
  18363. /** Returns the user settings file.
  18364. The first time this is called, it will create and load the properties file.
  18365. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18366. the common settings are used as a second-chance place to look. This is done via the
  18367. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18368. to the fallback for the user settings.
  18369. @see getCommonSettings
  18370. */
  18371. PropertiesFile* getUserSettings() throw();
  18372. /** Returns the common settings file.
  18373. The first time this is called, it will create and load the properties file.
  18374. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18375. read-only (e.g. because the user doesn't have permission to write
  18376. to shared files), then this will return the user settings instead,
  18377. (like getUserSettings() would do). This is handy if you'd like to
  18378. write a value to the common settings, but if that's no possible,
  18379. then you'd rather write to the user settings than none at all.
  18380. If returnUserPropsIfReadOnly is false, this method will always return
  18381. the common settings, even if any changes to them can't be saved.
  18382. @see getUserSettings
  18383. */
  18384. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18385. /** Saves both files if they need to be saved.
  18386. @see PropertiesFile::saveIfNeeded
  18387. */
  18388. bool saveIfNeeded();
  18389. /** Flushes and closes both files if they are open.
  18390. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18391. and closes both files. They will then be re-opened the next time getUserSettings()
  18392. or getCommonSettings() is called.
  18393. */
  18394. void closeFiles();
  18395. juce_UseDebuggingNewOperator
  18396. private:
  18397. PropertiesFile* userProps;
  18398. PropertiesFile* commonProps;
  18399. String appName, fileSuffix, folderName;
  18400. int msBeforeSaving, options;
  18401. int commonSettingsAreReadOnly;
  18402. ApplicationProperties (const ApplicationProperties&);
  18403. const ApplicationProperties& operator= (const ApplicationProperties&);
  18404. void openFiles() throw();
  18405. };
  18406. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18407. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18408. #endif
  18409. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18410. #endif
  18411. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18412. #endif
  18413. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18414. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18415. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18416. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18417. /**
  18418. Handles reading/writing to the system's clipboard.
  18419. */
  18420. class JUCE_API SystemClipboard
  18421. {
  18422. public:
  18423. /** Copies a string of text onto the clipboard */
  18424. static void copyTextToClipboard (const String& text) throw();
  18425. /** Gets the current clipboard's contents.
  18426. Obviously this might have come from another app, so could contain
  18427. anything..
  18428. */
  18429. static const String getTextFromClipboard() throw();
  18430. };
  18431. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18432. /********* End of inlined file: juce_SystemClipboard.h *********/
  18433. #endif
  18434. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18435. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18436. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18437. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18438. /********* Start of inlined file: juce_MidiMessage.h *********/
  18439. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18440. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18441. /**
  18442. Encapsulates a MIDI message.
  18443. @see MidiMessageSequence, MidiOutput, MidiInput
  18444. */
  18445. class JUCE_API MidiMessage
  18446. {
  18447. public:
  18448. /** Creates a 3-byte short midi message.
  18449. @param byte1 message byte 1
  18450. @param byte2 message byte 2
  18451. @param byte3 message byte 3
  18452. @param timeStamp the time to give the midi message - this value doesn't
  18453. use any particular units, so will be application-specific
  18454. */
  18455. MidiMessage (const int byte1,
  18456. const int byte2,
  18457. const int byte3,
  18458. const double timeStamp = 0) throw();
  18459. /** Creates a 2-byte short midi message.
  18460. @param byte1 message byte 1
  18461. @param byte2 message byte 2
  18462. @param timeStamp the time to give the midi message - this value doesn't
  18463. use any particular units, so will be application-specific
  18464. */
  18465. MidiMessage (const int byte1,
  18466. const int byte2,
  18467. const double timeStamp = 0) throw();
  18468. /** Creates a 1-byte short midi message.
  18469. @param byte1 message byte 1
  18470. @param timeStamp the time to give the midi message - this value doesn't
  18471. use any particular units, so will be application-specific
  18472. */
  18473. MidiMessage (const int byte1,
  18474. const double timeStamp = 0) throw();
  18475. /** Creates a midi message from a block of data. */
  18476. MidiMessage (const uint8* const data,
  18477. const int dataSize,
  18478. const double timeStamp = 0) throw();
  18479. /** Reads the next midi message from some data.
  18480. This will read as many bytes from a data stream as it needs to make a
  18481. complete message, and will return the number of bytes it used. This lets
  18482. you read a sequence of midi messages from a file or stream.
  18483. @param data the data to read from
  18484. @param size the maximum number of bytes it's allowed to read
  18485. @param numBytesUsed returns the number of bytes that were actually needed
  18486. @param lastStatusByte in a sequence of midi messages, the initial byte
  18487. can be dropped from a message if it's the same as the
  18488. first byte of the previous message, so this lets you
  18489. supply the byte to use if the first byte of the message
  18490. has in fact been dropped.
  18491. @param timeStamp the time to give the midi message - this value doesn't
  18492. use any particular units, so will be application-specific
  18493. */
  18494. MidiMessage (const uint8* data,
  18495. int size,
  18496. int& numBytesUsed,
  18497. uint8 lastStatusByte,
  18498. double timeStamp = 0) throw();
  18499. /** Creates a copy of another midi message. */
  18500. MidiMessage (const MidiMessage& other) throw();
  18501. /** Creates a copy of another midi message, with a different timestamp. */
  18502. MidiMessage (const MidiMessage& other,
  18503. const double newTimeStamp) throw();
  18504. /** Destructor. */
  18505. ~MidiMessage() throw();
  18506. /** Copies this message from another one. */
  18507. const MidiMessage& operator= (const MidiMessage& other) throw();
  18508. /** Returns a pointer to the raw midi data.
  18509. @see getRawDataSize
  18510. */
  18511. uint8* getRawData() const throw() { return data; }
  18512. /** Returns the number of bytes of data in the message.
  18513. @see getRawData
  18514. */
  18515. int getRawDataSize() const throw() { return size; }
  18516. /** Returns the timestamp associated with this message.
  18517. The units for the timestamp will be application-specific.
  18518. @see setTimeStamp, addToTimeStamp
  18519. */
  18520. double getTimeStamp() const throw() { return timeStamp; }
  18521. /** Changes the message's associated timestamp.
  18522. The units for the timestamp will be application-specific.
  18523. @see addToTimeStamp, getTimeStamp
  18524. */
  18525. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18526. /** Adds a value to the message's timestamp.
  18527. The units for the timestamp will be application-specific.
  18528. */
  18529. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18530. /** Returns the midi channel associated with the message.
  18531. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18532. if it's a sysex)
  18533. @see isForChannel, setChannel
  18534. */
  18535. int getChannel() const throw();
  18536. /** Returns true if the message applies to the given midi channel.
  18537. @param channelNumber the channel number to look for, in the range 1 to 16
  18538. @see getChannel, setChannel
  18539. */
  18540. bool isForChannel (const int channelNumber) const throw();
  18541. /** Changes the message's midi channel.
  18542. This won't do anything for non-channel messages like sysexes.
  18543. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18544. */
  18545. void setChannel (const int newChannelNumber) throw();
  18546. /** Returns true if this is a system-exclusive message.
  18547. */
  18548. bool isSysEx() const throw();
  18549. /** Returns a pointer to the sysex data inside the message.
  18550. If this event isn't a sysex event, it'll return 0.
  18551. @see getSysExDataSize
  18552. */
  18553. const uint8* getSysExData() const throw();
  18554. /** Returns the size of the sysex data.
  18555. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18556. @see getSysExData
  18557. */
  18558. int getSysExDataSize() const throw();
  18559. /** Returns true if this message is a 'key-down' event.
  18560. This will return false for a note-on event with a velocity of 0.
  18561. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18562. */
  18563. bool isNoteOn() const throw();
  18564. /** Creates a key-down message (using a floating-point velocity).
  18565. @param channel the midi channel, in the range 1 to 16
  18566. @param noteNumber the key number, 0 to 127
  18567. @param velocity in the range 0 to 1.0
  18568. @see isNoteOn
  18569. */
  18570. static const MidiMessage noteOn (const int channel,
  18571. const int noteNumber,
  18572. const float velocity) throw();
  18573. /** Creates a key-down message (using an integer velocity).
  18574. @param channel the midi channel, in the range 1 to 16
  18575. @param noteNumber the key number, 0 to 127
  18576. @param velocity in the range 0 to 127
  18577. @see isNoteOn
  18578. */
  18579. static const MidiMessage noteOn (const int channel,
  18580. const int noteNumber,
  18581. const uint8 velocity) throw();
  18582. /** Returns true if this message is a 'key-up' event.
  18583. This will also return true for a note-on event with a velocity of 0.
  18584. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18585. */
  18586. bool isNoteOff() const throw();
  18587. /** Creates a key-up message.
  18588. @param channel the midi channel, in the range 1 to 16
  18589. @param noteNumber the key number, 0 to 127
  18590. @see isNoteOff
  18591. */
  18592. static const MidiMessage noteOff (const int channel,
  18593. const int noteNumber) throw();
  18594. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18595. @see isNoteOn, isNoteOff
  18596. */
  18597. bool isNoteOnOrOff() const throw();
  18598. /** Returns the midi note number for note-on and note-off messages.
  18599. If the message isn't a note-on or off, the value returned will be
  18600. meaningless.
  18601. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18602. */
  18603. int getNoteNumber() const throw();
  18604. /** Changes the midi note number of a note-on or note-off message.
  18605. If the message isn't a note on or off, this will do nothing.
  18606. */
  18607. void setNoteNumber (const int newNoteNumber) throw();
  18608. /** Returns the velocity of a note-on or note-off message.
  18609. The value returned will be in the range 0 to 127.
  18610. If the message isn't a note-on or off event, it will return 0.
  18611. @see getFloatVelocity
  18612. */
  18613. uint8 getVelocity() const throw();
  18614. /** Returns the velocity of a note-on or note-off message.
  18615. The value returned will be in the range 0 to 1.0
  18616. If the message isn't a note-on or off event, it will return 0.
  18617. @see getVelocity, setVelocity
  18618. */
  18619. float getFloatVelocity() const throw();
  18620. /** Changes the velocity of a note-on or note-off message.
  18621. If the message isn't a note on or off, this will do nothing.
  18622. @param newVelocity the new velocity, in the range 0 to 1.0
  18623. @see getFloatVelocity, multiplyVelocity
  18624. */
  18625. void setVelocity (const float newVelocity) throw();
  18626. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18627. If the message isn't a note on or off, this will do nothing.
  18628. @param scaleFactor the value by which to multiply the velocity
  18629. @see setVelocity
  18630. */
  18631. void multiplyVelocity (const float scaleFactor) throw();
  18632. /** Returns true if the message is a program (patch) change message.
  18633. @see getProgramChangeNumber, getGMInstrumentName
  18634. */
  18635. bool isProgramChange() const throw();
  18636. /** Returns the new program number of a program change message.
  18637. If the message isn't a program change, the value returned will be
  18638. nonsense.
  18639. @see isProgramChange, getGMInstrumentName
  18640. */
  18641. int getProgramChangeNumber() const throw();
  18642. /** Creates a program-change message.
  18643. @param channel the midi channel, in the range 1 to 16
  18644. @param programNumber the midi program number, 0 to 127
  18645. @see isProgramChange, getGMInstrumentName
  18646. */
  18647. static const MidiMessage programChange (const int channel,
  18648. const int programNumber) throw();
  18649. /** Returns true if the message is a pitch-wheel move.
  18650. @see getPitchWheelValue, pitchWheel
  18651. */
  18652. bool isPitchWheel() const throw();
  18653. /** Returns the pitch wheel position from a pitch-wheel move message.
  18654. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18655. If called for messages which aren't pitch wheel events, the number returned will be
  18656. nonsense.
  18657. @see isPitchWheel
  18658. */
  18659. int getPitchWheelValue() const throw();
  18660. /** Creates a pitch-wheel move message.
  18661. @param channel the midi channel, in the range 1 to 16
  18662. @param position the wheel position, in the range 0 to 16383
  18663. @see isPitchWheel
  18664. */
  18665. static const MidiMessage pitchWheel (const int channel,
  18666. const int position) throw();
  18667. /** Returns true if the message is an aftertouch event.
  18668. For aftertouch events, use the getNoteNumber() method to find out the key
  18669. that it applies to, and getAftertouchValue() to find out the amount. Use
  18670. getChannel() to find out the channel.
  18671. @see getAftertouchValue, getNoteNumber
  18672. */
  18673. bool isAftertouch() const throw();
  18674. /** Returns the amount of aftertouch from an aftertouch messages.
  18675. The value returned is in the range 0 to 127, and will be nonsense for messages
  18676. other than aftertouch messages.
  18677. @see isAftertouch
  18678. */
  18679. int getAfterTouchValue() const throw();
  18680. /** Creates an aftertouch message.
  18681. @param channel the midi channel, in the range 1 to 16
  18682. @param noteNumber the key number, 0 to 127
  18683. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18684. @see isAftertouch
  18685. */
  18686. static const MidiMessage aftertouchChange (const int channel,
  18687. const int noteNumber,
  18688. const int aftertouchAmount) throw();
  18689. /** Returns true if the message is a channel-pressure change event.
  18690. This is like aftertouch, but common to the whole channel rather than a specific
  18691. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18692. to find out the channel.
  18693. @see channelPressureChange
  18694. */
  18695. bool isChannelPressure() const throw();
  18696. /** Returns the pressure from a channel pressure change message.
  18697. @returns the pressure, in the range 0 to 127
  18698. @see isChannelPressure, channelPressureChange
  18699. */
  18700. int getChannelPressureValue() const throw();
  18701. /** Creates a channel-pressure change event.
  18702. @param channel the midi channel: 1 to 16
  18703. @param pressure the pressure, 0 to 127
  18704. @see isChannelPressure
  18705. */
  18706. static const MidiMessage channelPressureChange (const int channel,
  18707. const int pressure) throw();
  18708. /** Returns true if this is a midi controller message.
  18709. @see getControllerNumber, getControllerValue, controllerEvent
  18710. */
  18711. bool isController() const throw();
  18712. /** Returns the controller number of a controller message.
  18713. The name of the controller can be looked up using the getControllerName() method.
  18714. Note that the value returned is invalid for messages that aren't controller changes.
  18715. @see isController, getControllerName, getControllerValue
  18716. */
  18717. int getControllerNumber() const throw();
  18718. /** Returns the controller value from a controller message.
  18719. A value 0 to 127 is returned to indicate the new controller position.
  18720. Note that the value returned is invalid for messages that aren't controller changes.
  18721. @see isController, getControllerNumber
  18722. */
  18723. int getControllerValue() const throw();
  18724. /** Creates a controller message.
  18725. @param channel the midi channel, in the range 1 to 16
  18726. @param controllerType the type of controller
  18727. @param value the controller value
  18728. @see isController
  18729. */
  18730. static const MidiMessage controllerEvent (const int channel,
  18731. const int controllerType,
  18732. const int value) throw();
  18733. /** Checks whether this message is an all-notes-off message.
  18734. @see allNotesOff
  18735. */
  18736. bool isAllNotesOff() const throw();
  18737. /** Checks whether this message is an all-sound-off message.
  18738. @see allSoundOff
  18739. */
  18740. bool isAllSoundOff() const throw();
  18741. /** Creates an all-notes-off message.
  18742. @param channel the midi channel, in the range 1 to 16
  18743. @see isAllNotesOff
  18744. */
  18745. static const MidiMessage allNotesOff (const int channel) throw();
  18746. /** Creates an all-sound-off message.
  18747. @param channel the midi channel, in the range 1 to 16
  18748. @see isAllSoundOff
  18749. */
  18750. static const MidiMessage allSoundOff (const int channel) throw();
  18751. /** Creates an all-controllers-off message.
  18752. @param channel the midi channel, in the range 1 to 16
  18753. */
  18754. static const MidiMessage allControllersOff (const int channel) throw();
  18755. /** Returns true if this event is a meta-event.
  18756. Meta-events are things like tempo changes, track names, etc.
  18757. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18758. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18759. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18760. */
  18761. bool isMetaEvent() const throw();
  18762. /** Returns a meta-event's type number.
  18763. If the message isn't a meta-event, this will return -1.
  18764. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18765. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18766. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18767. */
  18768. int getMetaEventType() const throw();
  18769. /** Returns a pointer to the data in a meta-event.
  18770. @see isMetaEvent, getMetaEventLength
  18771. */
  18772. const uint8* getMetaEventData() const throw();
  18773. /** Returns the length of the data for a meta-event.
  18774. @see isMetaEvent, getMetaEventData
  18775. */
  18776. int getMetaEventLength() const throw();
  18777. /** Returns true if this is a 'track' meta-event. */
  18778. bool isTrackMetaEvent() const throw();
  18779. /** Returns true if this is an 'end-of-track' meta-event. */
  18780. bool isEndOfTrackMetaEvent() const throw();
  18781. /** Creates an end-of-track meta-event.
  18782. @see isEndOfTrackMetaEvent
  18783. */
  18784. static const MidiMessage endOfTrack() throw();
  18785. /** Returns true if this is an 'track name' meta-event.
  18786. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18787. */
  18788. bool isTrackNameEvent() const throw();
  18789. /** Returns true if this is a 'text' meta-event.
  18790. @see getTextFromTextMetaEvent
  18791. */
  18792. bool isTextMetaEvent() const throw();
  18793. /** Returns the text from a text meta-event.
  18794. @see isTextMetaEvent
  18795. */
  18796. const String getTextFromTextMetaEvent() const throw();
  18797. /** Returns true if this is a 'tempo' meta-event.
  18798. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18799. */
  18800. bool isTempoMetaEvent() const throw();
  18801. /** Returns the tick length from a tempo meta-event.
  18802. @param timeFormat the 16-bit time format value from the midi file's header.
  18803. @returns the tick length (in seconds).
  18804. @see isTempoMetaEvent
  18805. */
  18806. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18807. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18808. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18809. */
  18810. double getTempoSecondsPerQuarterNote() const throw();
  18811. /** Creates a tempo meta-event.
  18812. @see isTempoMetaEvent
  18813. */
  18814. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18815. /** Returns true if this is a 'time-signature' meta-event.
  18816. @see getTimeSignatureInfo
  18817. */
  18818. bool isTimeSignatureMetaEvent() const throw();
  18819. /** Returns the time-signature values from a time-signature meta-event.
  18820. @see isTimeSignatureMetaEvent
  18821. */
  18822. void getTimeSignatureInfo (int& numerator,
  18823. int& denominator) const throw();
  18824. /** Creates a time-signature meta-event.
  18825. @see isTimeSignatureMetaEvent
  18826. */
  18827. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  18828. const int denominator) throw();
  18829. /** Returns true if this is a 'key-signature' meta-event.
  18830. @see getKeySignatureNumberOfSharpsOrFlats
  18831. */
  18832. bool isKeySignatureMetaEvent() const throw();
  18833. /** Returns the key from a key-signature meta-event.
  18834. @see isKeySignatureMetaEvent
  18835. */
  18836. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  18837. /** Returns true if this is a 'channel' meta-event.
  18838. A channel meta-event specifies the midi channel that should be used
  18839. for subsequent meta-events.
  18840. @see getMidiChannelMetaEventChannel
  18841. */
  18842. bool isMidiChannelMetaEvent() const throw();
  18843. /** Returns the channel number from a channel meta-event.
  18844. @returns the channel, in the range 1 to 16.
  18845. @see isMidiChannelMetaEvent
  18846. */
  18847. int getMidiChannelMetaEventChannel() const throw();
  18848. /** Creates a midi channel meta-event.
  18849. @param channel the midi channel, in the range 1 to 16
  18850. @see isMidiChannelMetaEvent
  18851. */
  18852. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  18853. /** Returns true if this is an active-sense message. */
  18854. bool isActiveSense() const throw();
  18855. /** Returns true if this is a midi start event.
  18856. @see midiStart
  18857. */
  18858. bool isMidiStart() const throw();
  18859. /** Creates a midi start event. */
  18860. static const MidiMessage midiStart() throw();
  18861. /** Returns true if this is a midi continue event.
  18862. @see midiContinue
  18863. */
  18864. bool isMidiContinue() const throw();
  18865. /** Creates a midi continue event. */
  18866. static const MidiMessage midiContinue() throw();
  18867. /** Returns true if this is a midi stop event.
  18868. @see midiStop
  18869. */
  18870. bool isMidiStop() const throw();
  18871. /** Creates a midi stop event. */
  18872. static const MidiMessage midiStop() throw();
  18873. /** Returns true if this is a midi clock event.
  18874. @see midiClock, songPositionPointer
  18875. */
  18876. bool isMidiClock() const throw();
  18877. /** Creates a midi clock event. */
  18878. static const MidiMessage midiClock() throw();
  18879. /** Returns true if this is a song-position-pointer message.
  18880. @see getSongPositionPointerMidiBeat, songPositionPointer
  18881. */
  18882. bool isSongPositionPointer() const throw();
  18883. /** Returns the midi beat-number of a song-position-pointer message.
  18884. @see isSongPositionPointer, songPositionPointer
  18885. */
  18886. int getSongPositionPointerMidiBeat() const throw();
  18887. /** Creates a song-position-pointer message.
  18888. The position is a number of midi beats from the start of the song, where 1 midi
  18889. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  18890. are 4 midi beats in a quarter-note.
  18891. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  18892. */
  18893. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  18894. /** Returns true if this is a quarter-frame midi timecode message.
  18895. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  18896. */
  18897. bool isQuarterFrame() const throw();
  18898. /** Returns the sequence number of a quarter-frame midi timecode message.
  18899. This will be a value between 0 and 7.
  18900. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  18901. */
  18902. int getQuarterFrameSequenceNumber() const throw();
  18903. /** Returns the value from a quarter-frame message.
  18904. This will be the lower nybble of the message's data-byte, a value
  18905. between 0 and 15
  18906. */
  18907. int getQuarterFrameValue() const throw();
  18908. /** Creates a quarter-frame MTC message.
  18909. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  18910. @param value a value 0 to 15 for the lower nybble of the message's data byte
  18911. */
  18912. static const MidiMessage quarterFrame (const int sequenceNumber,
  18913. const int value) throw();
  18914. /** SMPTE timecode types.
  18915. Used by the getFullFrameParameters() and fullFrame() methods.
  18916. */
  18917. enum SmpteTimecodeType
  18918. {
  18919. fps24 = 0,
  18920. fps25 = 1,
  18921. fps30drop = 2,
  18922. fps30 = 3
  18923. };
  18924. /** Returns true if this is a full-frame midi timecode message.
  18925. */
  18926. bool isFullFrame() const throw();
  18927. /** Extracts the timecode information from a full-frame midi timecode message.
  18928. You should only call this on messages where you've used isFullFrame() to
  18929. check that they're the right kind.
  18930. */
  18931. void getFullFrameParameters (int& hours,
  18932. int& minutes,
  18933. int& seconds,
  18934. int& frames,
  18935. SmpteTimecodeType& timecodeType) const throw();
  18936. /** Creates a full-frame MTC message.
  18937. */
  18938. static const MidiMessage fullFrame (const int hours,
  18939. const int minutes,
  18940. const int seconds,
  18941. const int frames,
  18942. SmpteTimecodeType timecodeType);
  18943. /** Types of MMC command.
  18944. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  18945. */
  18946. enum MidiMachineControlCommand
  18947. {
  18948. mmc_stop = 1,
  18949. mmc_play = 2,
  18950. mmc_deferredplay = 3,
  18951. mmc_fastforward = 4,
  18952. mmc_rewind = 5,
  18953. mmc_recordStart = 6,
  18954. mmc_recordStop = 7,
  18955. mmc_pause = 9
  18956. };
  18957. /** Checks whether this is an MMC message.
  18958. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  18959. */
  18960. bool isMidiMachineControlMessage() const throw();
  18961. /** For an MMC message, this returns its type.
  18962. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  18963. calling this method.
  18964. */
  18965. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  18966. /** Creates an MMC message.
  18967. */
  18968. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  18969. /** Checks whether this is an MMC "goto" message.
  18970. If it is, the parameters passed-in are set to the time that the message contains.
  18971. @see midiMachineControlGoto
  18972. */
  18973. bool isMidiMachineControlGoto (int& hours,
  18974. int& minutes,
  18975. int& seconds,
  18976. int& frames) const throw();
  18977. /** Creates an MMC "goto" message.
  18978. This messages tells the device to go to a specific frame.
  18979. @see isMidiMachineControlGoto
  18980. */
  18981. static const MidiMessage midiMachineControlGoto (int hours,
  18982. int minutes,
  18983. int seconds,
  18984. int frames);
  18985. /** Creates a master-volume change message.
  18986. @param volume the volume, 0 to 1.0
  18987. */
  18988. static const MidiMessage masterVolume (const float volume) throw();
  18989. /** Creates a system-exclusive message.
  18990. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  18991. */
  18992. static const MidiMessage createSysExMessage (const uint8* sysexData,
  18993. const int dataSize) throw();
  18994. /** Reads a midi variable-length integer.
  18995. @param data the data to read the number from
  18996. @param numBytesUsed on return, this will be set to the number of bytes that were read
  18997. */
  18998. static int readVariableLengthVal (const uint8* data,
  18999. int& numBytesUsed) throw();
  19000. /** Based on the first byte of a short midi message, this uses a lookup table
  19001. to return the message length (either 1, 2, or 3 bytes).
  19002. The value passed in must be 0x80 or higher.
  19003. */
  19004. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19005. /** Returns the name of a midi note number.
  19006. E.g "C", "D#", etc.
  19007. @param noteNumber the midi note number, 0 to 127
  19008. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19009. they'll be flattened, e.g. "Db"
  19010. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19011. e.g. "C#4"
  19012. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19013. number that will be used for middle C's octave
  19014. @see getMidiNoteInHertz
  19015. */
  19016. static const String getMidiNoteName (int noteNumber,
  19017. bool useSharps,
  19018. bool includeOctaveNumber,
  19019. int octaveNumForMiddleC) throw();
  19020. /** Returns the frequency of a midi note number.
  19021. @see getMidiNoteName
  19022. */
  19023. static const double getMidiNoteInHertz (int noteNumber) throw();
  19024. /** Returns the standard name of a GM instrument.
  19025. @param midiInstrumentNumber the program number 0 to 127
  19026. @see getProgramChangeNumber
  19027. */
  19028. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19029. /** Returns the name of a bank of GM instruments.
  19030. @param midiBankNumber the bank, 0 to 15
  19031. */
  19032. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19033. /** Returns the standard name of a channel 10 percussion sound.
  19034. @param midiNoteNumber the key number, 35 to 81
  19035. */
  19036. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19037. /** Returns the name of a controller type number.
  19038. @see getControllerNumber
  19039. */
  19040. static const String getControllerName (int controllerNumber) throw();
  19041. juce_UseDebuggingNewOperator
  19042. private:
  19043. double timeStamp;
  19044. uint8* data;
  19045. int message, size;
  19046. };
  19047. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19048. /********* End of inlined file: juce_MidiMessage.h *********/
  19049. /**
  19050. Holds a sequence of time-stamped midi events.
  19051. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19052. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19053. @see MidiMessage
  19054. */
  19055. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19056. {
  19057. public:
  19058. /** Creates an empty MidiBuffer. */
  19059. MidiBuffer() throw();
  19060. /** Creates a copy of another MidiBuffer. */
  19061. MidiBuffer (const MidiBuffer& other) throw();
  19062. /** Makes a copy of another MidiBuffer. */
  19063. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19064. /** Destructor */
  19065. ~MidiBuffer() throw();
  19066. /** Removes all events from the buffer. */
  19067. void clear() throw();
  19068. /** Removes all events between two times from the buffer.
  19069. All events for which (start <= event position < start + numSamples) will
  19070. be removed.
  19071. */
  19072. void clear (const int start,
  19073. const int numSamples) throw();
  19074. /** Returns true if the buffer is empty.
  19075. To actually retrieve the events, use a MidiBuffer::Iterator object
  19076. */
  19077. bool isEmpty() const throw();
  19078. /** Counts the number of events in the buffer.
  19079. This is actually quite a slow operation, as it has to iterate through all
  19080. the events, so you might prefer to call isEmpty() if that's all you need
  19081. to know.
  19082. */
  19083. int getNumEvents() const throw();
  19084. /** Adds an event to the buffer.
  19085. The sample number will be used to determine the position of the event in
  19086. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19087. ignored.
  19088. If an event is added whose sample position is the same as one or more events
  19089. already in the buffer, the new event will be placed after the existing ones.
  19090. To retrieve events, use a MidiBuffer::Iterator object
  19091. */
  19092. void addEvent (const MidiMessage& midiMessage,
  19093. const int sampleNumber) throw();
  19094. /** Adds an event to the buffer from raw midi data.
  19095. The sample number will be used to determine the position of the event in
  19096. the buffer, which is always kept sorted.
  19097. If an event is added whose sample position is the same as one or more events
  19098. already in the buffer, the new event will be placed after the existing ones.
  19099. The event data will be inspected to calculate the number of bytes in length that
  19100. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19101. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19102. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19103. add an event at all.
  19104. To retrieve events, use a MidiBuffer::Iterator object
  19105. */
  19106. void addEvent (const uint8* const rawMidiData,
  19107. const int maxBytesOfMidiData,
  19108. const int sampleNumber) throw();
  19109. /** Adds some events from another buffer to this one.
  19110. @param otherBuffer the buffer containing the events you want to add
  19111. @param startSample the lowest sample number in the source buffer for which
  19112. events should be added. Any source events whose timestamp is
  19113. less than this will be ignored
  19114. @param numSamples the valid range of samples from the source buffer for which
  19115. events should be added - i.e. events in the source buffer whose
  19116. timestamp is greater than or equal to (startSample + numSamples)
  19117. will be ignored. If this value is less than 0, all events after
  19118. startSample will be taken.
  19119. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19120. that are added to this buffer
  19121. */
  19122. void addEvents (const MidiBuffer& otherBuffer,
  19123. const int startSample,
  19124. const int numSamples,
  19125. const int sampleDeltaToAdd) throw();
  19126. /** Returns the sample number of the first event in the buffer.
  19127. If the buffer's empty, this will just return 0.
  19128. */
  19129. int getFirstEventTime() const throw();
  19130. /** Returns the sample number of the last event in the buffer.
  19131. If the buffer's empty, this will just return 0.
  19132. */
  19133. int getLastEventTime() const throw();
  19134. /**
  19135. Used to iterate through the events in a MidiBuffer.
  19136. Note that altering the buffer while an iterator is using it isn't a
  19137. safe operation.
  19138. @see MidiBuffer
  19139. */
  19140. class Iterator
  19141. {
  19142. public:
  19143. /** Creates an Iterator for this MidiBuffer. */
  19144. Iterator (const MidiBuffer& buffer) throw();
  19145. /** Destructor. */
  19146. ~Iterator() throw();
  19147. /** Repositions the iterator so that the next event retrieved will be the first
  19148. one whose sample position is at greater than or equal to the given position.
  19149. */
  19150. void setNextSamplePosition (const int samplePosition) throw();
  19151. /** Retrieves a copy of the next event from the buffer.
  19152. @param result on return, this will be the message (the MidiMessage's timestamp
  19153. is not set)
  19154. @param samplePosition on return, this will be the position of the event
  19155. @returns true if an event was found, or false if the iterator has reached
  19156. the end of the buffer
  19157. */
  19158. bool getNextEvent (MidiMessage& result,
  19159. int& samplePosition) throw();
  19160. /** Retrieves the next event from the buffer.
  19161. @param midiData on return, this pointer will be set to a block of data containing
  19162. the midi message. Note that to make it fast, this is a pointer
  19163. directly into the MidiBuffer's internal data, so is only valid
  19164. temporarily until the MidiBuffer is altered.
  19165. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19166. midi message
  19167. @param samplePosition on return, this will be the position of the event
  19168. @returns true if an event was found, or false if the iterator has reached
  19169. the end of the buffer
  19170. */
  19171. bool getNextEvent (const uint8* &midiData,
  19172. int& numBytesOfMidiData,
  19173. int& samplePosition) throw();
  19174. juce_UseDebuggingNewOperator
  19175. private:
  19176. const MidiBuffer& buffer;
  19177. const uint8* data;
  19178. Iterator (const Iterator&);
  19179. const Iterator& operator= (const Iterator&);
  19180. };
  19181. juce_UseDebuggingNewOperator
  19182. private:
  19183. friend class MidiBuffer::Iterator;
  19184. int bytesUsed;
  19185. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19186. };
  19187. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19188. /********* End of inlined file: juce_MidiBuffer.h *********/
  19189. #endif
  19190. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19191. /********* Start of inlined file: juce_MidiFile.h *********/
  19192. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19193. #define __JUCE_MIDIFILE_JUCEHEADER__
  19194. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19195. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19196. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19197. /**
  19198. A sequence of timestamped midi messages.
  19199. This allows the sequence to be manipulated, and also to be read from and
  19200. written to a standard midi file.
  19201. @see MidiMessage, MidiFile
  19202. */
  19203. class JUCE_API MidiMessageSequence
  19204. {
  19205. public:
  19206. /** Creates an empty midi sequence object. */
  19207. MidiMessageSequence();
  19208. /** Creates a copy of another sequence. */
  19209. MidiMessageSequence (const MidiMessageSequence& other);
  19210. /** Replaces this sequence with another one. */
  19211. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19212. /** Destructor. */
  19213. ~MidiMessageSequence();
  19214. /** Structure used to hold midi events in the sequence.
  19215. These structures act as 'handles' on the events as they are moved about in
  19216. the list, and make it quick to find the matching note-offs for note-on events.
  19217. @see MidiMessageSequence::getEventPointer
  19218. */
  19219. class MidiEventHolder
  19220. {
  19221. public:
  19222. /** Destructor. */
  19223. ~MidiEventHolder();
  19224. /** The message itself, whose timestamp is used to specify the event's time.
  19225. */
  19226. MidiMessage message;
  19227. /** The matching note-off event (if this is a note-on event).
  19228. If this isn't a note-on, this pointer will be null.
  19229. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19230. note-offs up-to-date after events have been moved around in the sequence
  19231. or deleted.
  19232. */
  19233. MidiEventHolder* noteOffObject;
  19234. juce_UseDebuggingNewOperator
  19235. private:
  19236. friend class MidiMessageSequence;
  19237. MidiEventHolder (const MidiMessage& message);
  19238. };
  19239. /** Clears the sequence. */
  19240. void clear();
  19241. /** Returns the number of events in the sequence. */
  19242. int getNumEvents() const;
  19243. /** Returns a pointer to one of the events. */
  19244. MidiEventHolder* getEventPointer (const int index) const;
  19245. /** Returns the time of the note-up that matches the note-on at this index.
  19246. If the event at this index isn't a note-on, it'll just return 0.
  19247. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19248. */
  19249. double getTimeOfMatchingKeyUp (const int index) const;
  19250. /** Returns the index of the note-up that matches the note-on at this index.
  19251. If the event at this index isn't a note-on, it'll just return -1.
  19252. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19253. */
  19254. int getIndexOfMatchingKeyUp (const int index) const;
  19255. /** Returns the index of an event. */
  19256. int getIndexOf (MidiEventHolder* const event) const;
  19257. /** Returns the index of the first event on or after the given timestamp.
  19258. If the time is beyond the end of the sequence, this will return the
  19259. number of events.
  19260. */
  19261. int getNextIndexAtTime (const double timeStamp) const;
  19262. /** Returns the timestamp of the first event in the sequence.
  19263. @see getEndTime
  19264. */
  19265. double getStartTime() const;
  19266. /** Returns the timestamp of the last event in the sequence.
  19267. @see getStartTime
  19268. */
  19269. double getEndTime() const;
  19270. /** Returns the timestamp of the event at a given index.
  19271. If the index is out-of-range, this will return 0.0
  19272. */
  19273. double getEventTime (const int index) const;
  19274. /** Inserts a midi message into the sequence.
  19275. The index at which the new message gets inserted will depend on its timestamp,
  19276. because the sequence is kept sorted.
  19277. Remember to call updateMatchedPairs() after adding note-on events.
  19278. @param newMessage the new message to add (an internal copy will be made)
  19279. @param timeAdjustment an optional value to add to the timestamp of the message
  19280. that will be inserted
  19281. @see updateMatchedPairs
  19282. */
  19283. void addEvent (const MidiMessage& newMessage,
  19284. double timeAdjustment = 0);
  19285. /** Deletes one of the events in the sequence.
  19286. Remember to call updateMatchedPairs() after removing events.
  19287. @param index the index of the event to delete
  19288. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19289. if the event you're removing is a note-on
  19290. */
  19291. void deleteEvent (const int index,
  19292. const bool deleteMatchingNoteUp);
  19293. /** Merges another sequence into this one.
  19294. Remember to call updateMatchedPairs() after using this method.
  19295. @param other the sequence to add from
  19296. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19297. as they are read from the other sequence
  19298. @param firstAllowableDestTime events will not be added if their time is earlier
  19299. than this time. (This is after their time has been adjusted
  19300. by the timeAdjustmentDelta)
  19301. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19302. or greater than this time. (This is after their time has
  19303. been adjusted by the timeAdjustmentDelta)
  19304. */
  19305. void addSequence (const MidiMessageSequence& other,
  19306. double timeAdjustmentDelta,
  19307. double firstAllowableDestTime,
  19308. double endOfAllowableDestTimes);
  19309. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19310. Call this after moving messages about or deleting/adding messages, and it
  19311. will scan the list and make sure all the note-offs in the MidiEventHolder
  19312. structures are pointing at the correct ones.
  19313. */
  19314. void updateMatchedPairs();
  19315. /** Copies all the messages for a particular midi channel to another sequence.
  19316. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19317. @param destSequence the sequence that the chosen events should be copied to
  19318. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19319. channel) will also be copied across.
  19320. @see extractSysExMessages
  19321. */
  19322. void extractMidiChannelMessages (const int channelNumberToExtract,
  19323. MidiMessageSequence& destSequence,
  19324. const bool alsoIncludeMetaEvents) const;
  19325. /** Copies all midi sys-ex messages to another sequence.
  19326. @param destSequence this is the sequence to which any sys-exes in this sequence
  19327. will be added
  19328. @see extractMidiChannelMessages
  19329. */
  19330. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19331. /** Removes any messages in this sequence that have a specific midi channel.
  19332. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19333. */
  19334. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19335. /** Removes any sys-ex messages from this sequence.
  19336. */
  19337. void deleteSysExMessages();
  19338. /** Adds an offset to the timestamps of all events in the sequence.
  19339. @param deltaTime the amount to add to each timestamp.
  19340. */
  19341. void addTimeToMessages (const double deltaTime);
  19342. /** Scans through the sequence to determine the state of any midi controllers at
  19343. a given time.
  19344. This will create a sequence of midi controller changes that can be
  19345. used to set all midi controllers to the state they would be in at the
  19346. specified time within this sequence.
  19347. As well as controllers, it will also recreate the midi program number
  19348. and pitch bend position.
  19349. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19350. for other channels will be ignored.
  19351. @param time the time at which you want to find out the state - there are
  19352. no explicit units for this time measurement, it's the same units
  19353. as used for the timestamps of the messages
  19354. @param resultMessages an array to which midi controller-change messages will be added. This
  19355. will be the minimum number of controller changes to recreate the
  19356. state at the required time.
  19357. */
  19358. void createControllerUpdatesForTime (const int channelNumber,
  19359. const double time,
  19360. OwnedArray<MidiMessage>& resultMessages);
  19361. juce_UseDebuggingNewOperator
  19362. /** @internal */
  19363. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19364. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19365. private:
  19366. friend class MidiComparator;
  19367. friend class MidiFile;
  19368. OwnedArray <MidiEventHolder> list;
  19369. void sort();
  19370. };
  19371. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19372. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19373. /**
  19374. Reads/writes standard midi format files.
  19375. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19376. can then get the individual midi tracks from it using the getTrack() method.
  19377. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19378. to it using the addTrack() method, and then call its writeTo() method to stream
  19379. it out.
  19380. @see MidiMessageSequence
  19381. */
  19382. class JUCE_API MidiFile
  19383. {
  19384. public:
  19385. /** Creates an empty MidiFile object.
  19386. */
  19387. MidiFile() throw();
  19388. /** Destructor. */
  19389. ~MidiFile() throw();
  19390. /** Returns the number of tracks in the file.
  19391. @see getTrack, addTrack
  19392. */
  19393. int getNumTracks() const throw();
  19394. /** Returns a pointer to one of the tracks in the file.
  19395. @returns a pointer to the track, or 0 if the index is out-of-range
  19396. @see getNumTracks, addTrack
  19397. */
  19398. const MidiMessageSequence* getTrack (const int index) const throw();
  19399. /** Adds a midi track to the file.
  19400. This will make its own internal copy of the sequence that is passed-in.
  19401. @see getNumTracks, getTrack
  19402. */
  19403. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19404. /** Removes all midi tracks from the file.
  19405. @see getNumTracks
  19406. */
  19407. void clear() throw();
  19408. /** Returns the raw time format code that will be written to a stream.
  19409. After reading a midi file, this method will return the time-format that
  19410. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19411. or setSmpteTimeFormat() methods.
  19412. If the value returned is positive, it indicates the number of midi ticks
  19413. per quarter-note - see setTicksPerQuarterNote().
  19414. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19415. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19416. */
  19417. short getTimeFormat() const throw();
  19418. /** Sets the time format to use when this file is written to a stream.
  19419. If this is called, the file will be written as bars/beats using the
  19420. specified resolution, rather than SMPTE absolute times, as would be
  19421. used if setSmpteTimeFormat() had been called instead.
  19422. @param ticksPerQuarterNote e.g. 96, 960
  19423. @see setSmpteTimeFormat
  19424. */
  19425. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19426. /** Sets the time format to use when this file is written to a stream.
  19427. If this is called, the file will be written using absolute times, rather
  19428. than bars/beats as would be the case if setTicksPerBeat() had been called
  19429. instead.
  19430. @param framesPerSecond must be 24, 25, 29 or 30
  19431. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19432. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19433. timing, setSmpteTimeFormat (25, 40)
  19434. @see setTicksPerBeat
  19435. */
  19436. void setSmpteTimeFormat (const int framesPerSecond,
  19437. const int subframeResolution) throw();
  19438. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19439. Useful for finding the positions of all the tempo changes in a file.
  19440. @param tempoChangeEvents a list to which all the events will be added
  19441. */
  19442. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19443. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19444. Useful for finding the positions of all the tempo changes in a file.
  19445. @param timeSigEvents a list to which all the events will be added
  19446. */
  19447. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19448. /** Returns the latest timestamp in any of the tracks.
  19449. (Useful for finding the length of the file).
  19450. */
  19451. double getLastTimestamp() const;
  19452. /** Reads a midi file format stream.
  19453. After calling this, you can get the tracks that were read from the file by using the
  19454. getNumTracks() and getTrack() methods.
  19455. The timestamps of the midi events in the tracks will represent their positions in
  19456. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19457. method.
  19458. @returns true if the stream was read successfully
  19459. */
  19460. bool readFrom (InputStream& sourceStream);
  19461. /** Writes the midi tracks as a standard midi file.
  19462. @returns true if the operation succeeded.
  19463. */
  19464. bool writeTo (OutputStream& destStream);
  19465. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19466. This will use the midi time format and tempo/time signature info in the
  19467. tracks to convert all the timestamps to absolute values in seconds.
  19468. */
  19469. void convertTimestampTicksToSeconds();
  19470. juce_UseDebuggingNewOperator
  19471. /** @internal */
  19472. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19473. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19474. private:
  19475. MidiMessageSequence* tracks [128];
  19476. short numTracks, timeFormat;
  19477. MidiFile (const MidiFile&);
  19478. const MidiFile& operator= (const MidiFile&);
  19479. void readNextTrack (const char* data, int size);
  19480. void writeTrack (OutputStream& mainOut, const int trackNum);
  19481. };
  19482. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19483. /********* End of inlined file: juce_MidiFile.h *********/
  19484. #endif
  19485. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19486. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19487. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19488. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19489. class MidiKeyboardState;
  19490. /**
  19491. Receives events from a MidiKeyboardState object.
  19492. @see MidiKeyboardState
  19493. */
  19494. class JUCE_API MidiKeyboardStateListener
  19495. {
  19496. public:
  19497. MidiKeyboardStateListener() throw() {}
  19498. virtual ~MidiKeyboardStateListener() {}
  19499. /** Called when one of the MidiKeyboardState's keys is pressed.
  19500. This will be called synchronously when the state is either processing a
  19501. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19502. when a note is being played with its MidiKeyboardState::noteOn() method.
  19503. Note that this callback could happen from an audio callback thread, so be
  19504. careful not to block, and avoid any UI activity in the callback.
  19505. */
  19506. virtual void handleNoteOn (MidiKeyboardState* source,
  19507. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19508. /** Called when one of the MidiKeyboardState's keys is released.
  19509. This will be called synchronously when the state is either processing a
  19510. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19511. when a note is being played with its MidiKeyboardState::noteOff() method.
  19512. Note that this callback could happen from an audio callback thread, so be
  19513. careful not to block, and avoid any UI activity in the callback.
  19514. */
  19515. virtual void handleNoteOff (MidiKeyboardState* source,
  19516. int midiChannel, int midiNoteNumber) = 0;
  19517. };
  19518. /**
  19519. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19520. This object can parse a stream of midi events, using them to update its idea
  19521. of which keys are pressed for each individiual midi channel.
  19522. When keys go up or down, it can broadcast these events to listener objects.
  19523. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19524. methods, and midi messages for these events will be merged into the
  19525. midi stream that gets processed by processNextMidiBuffer().
  19526. */
  19527. class JUCE_API MidiKeyboardState
  19528. {
  19529. public:
  19530. MidiKeyboardState();
  19531. ~MidiKeyboardState();
  19532. /** Resets the state of the object.
  19533. All internal data for all the channels is reset, but no events are sent as a
  19534. result.
  19535. If you want to release any keys that are currently down, and to send out note-up
  19536. midi messages for this, use the allNotesOff() method instead.
  19537. */
  19538. void reset();
  19539. /** Returns true if the given midi key is currently held down for the given midi channel.
  19540. The channel number must be between 1 and 16. If you want to see if any notes are
  19541. on for a range of channels, use the isNoteOnForChannels() method.
  19542. */
  19543. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19544. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19545. The channel mask has a bit set for each midi channel you want to test for - bit
  19546. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19547. If a note is on for at least one of the specified channels, this returns true.
  19548. */
  19549. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19550. /** Turns a specified note on.
  19551. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19552. next call to processNextMidiBuffer().
  19553. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19554. gone down.
  19555. */
  19556. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19557. /** Turns a specified note off.
  19558. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19559. next call to processNextMidiBuffer().
  19560. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19561. gone up.
  19562. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19563. */
  19564. void noteOff (const int midiChannel, const int midiNoteNumber);
  19565. /** This will turn off any currently-down notes for the given midi channel.
  19566. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19567. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19568. and events being added to the midi stream.
  19569. */
  19570. void allNotesOff (const int midiChannel);
  19571. /** Looks at a key-up/down event and uses it to update the state of this object.
  19572. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19573. instead.
  19574. */
  19575. void processNextMidiEvent (const MidiMessage& message);
  19576. /** Scans a midi stream for up/down events and adds its own events to it.
  19577. This will look for any up/down events and use them to update the internal state,
  19578. synchronously making suitable callbacks to the listeners.
  19579. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19580. and noteOff() calls will be added into the buffer.
  19581. Only the section of the buffer whose timestamps are between startSample and
  19582. (startSample + numSamples) will be affected, and any events added will be placed
  19583. between these times.
  19584. If you're going to use this method, you'll need to keep calling it regularly for
  19585. it to work satisfactorily.
  19586. To process a single midi event at a time, use the processNextMidiEvent() method
  19587. instead.
  19588. */
  19589. void processNextMidiBuffer (MidiBuffer& buffer,
  19590. const int startSample,
  19591. const int numSamples,
  19592. const bool injectIndirectEvents);
  19593. /** Registers a listener for callbacks when keys go up or down.
  19594. @see removeListener
  19595. */
  19596. void addListener (MidiKeyboardStateListener* const listener) throw();
  19597. /** Deregisters a listener.
  19598. @see addListener
  19599. */
  19600. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19601. juce_UseDebuggingNewOperator
  19602. private:
  19603. CriticalSection lock;
  19604. uint16 noteStates [128];
  19605. MidiBuffer eventsToAdd;
  19606. VoidArray listeners;
  19607. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19608. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19609. MidiKeyboardState (const MidiKeyboardState&);
  19610. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19611. };
  19612. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19613. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19614. #endif
  19615. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19616. #endif
  19617. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19618. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19619. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19620. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19621. /********* Start of inlined file: juce_MidiInput.h *********/
  19622. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19623. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19624. class MidiInput;
  19625. /**
  19626. Receives midi messages from a midi input device.
  19627. This class is overridden to handle incoming midi messages. See the MidiInput
  19628. class for more details.
  19629. @see MidiInput
  19630. */
  19631. class JUCE_API MidiInputCallback
  19632. {
  19633. public:
  19634. /** Destructor. */
  19635. virtual ~MidiInputCallback() {}
  19636. /** Receives an incoming message.
  19637. A MidiInput object will call this method when a midi event arrives. It'll be
  19638. called on a high-priority system thread, so avoid doing anything time-consuming
  19639. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19640. for queueing incoming messages for use later.
  19641. @param source the MidiInput object that generated the message
  19642. @param message the incoming message. The message's timestamp is set to a value
  19643. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19644. time when the message arrived.
  19645. */
  19646. virtual void handleIncomingMidiMessage (MidiInput* source,
  19647. const MidiMessage& message) = 0;
  19648. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19649. If a long sysex message is broken up into multiple packets, this callback is made
  19650. for each packet that arrives until the message is finished, at which point
  19651. the normal handleIncomingMidiMessage() callback will be made with the entire
  19652. message.
  19653. The message passed in will contain the start of a sysex, but won't be finished
  19654. with the terminating 0xf7 byte.
  19655. */
  19656. virtual void handlePartialSysexMessage (MidiInput* source,
  19657. const uint8* messageData,
  19658. const int numBytesSoFar,
  19659. const double timestamp)
  19660. {
  19661. // (this bit is just to avoid compiler warnings about unused variables)
  19662. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19663. }
  19664. };
  19665. /**
  19666. Represents a midi input device.
  19667. To create one of these, use the static getDevices() method to find out what inputs are
  19668. available, and then use the openDevice() method to try to open one.
  19669. @see MidiOutput
  19670. */
  19671. class JUCE_API MidiInput
  19672. {
  19673. public:
  19674. /** Returns a list of the available midi input devices.
  19675. You can open one of the devices by passing its index into the
  19676. openDevice() method.
  19677. @see getDefaultDeviceIndex, openDevice
  19678. */
  19679. static const StringArray getDevices();
  19680. /** Returns the index of the default midi input device to use.
  19681. This refers to the index in the list returned by getDevices().
  19682. */
  19683. static int getDefaultDeviceIndex();
  19684. /** Tries to open one of the midi input devices.
  19685. This will return a MidiInput object if it manages to open it. You can then
  19686. call start() and stop() on this device, and delete it when no longer needed.
  19687. If the device can't be opened, this will return a null pointer.
  19688. @param deviceIndex the index of a device from the list returned by getDevices()
  19689. @param callback the object that will receive the midi messages from this device.
  19690. @see MidiInputCallback, getDevices
  19691. */
  19692. static MidiInput* openDevice (int deviceIndex,
  19693. MidiInputCallback* callback);
  19694. #if JUCE_LINUX || DOXYGEN
  19695. /** LINUX ONLY - This will try to create a new midi input device.
  19696. This will attempt to create a new midi input device with the specified name,
  19697. for other apps to connect to.
  19698. Returns 0 if a device can't be created.
  19699. @param deviceName the name to use for the new device
  19700. @param callback the object that will receive the midi messages from this device.
  19701. */
  19702. static MidiInput* createNewDevice (const String& deviceName,
  19703. MidiInputCallback* callback);
  19704. #endif
  19705. /** Destructor. */
  19706. ~MidiInput();
  19707. /** Returns the name of this device.
  19708. */
  19709. const String getName() const throw() { return name; }
  19710. /** Allows you to set a custom name for the device, in case you don't like the name
  19711. it was given when created.
  19712. */
  19713. void setName (const String& newName) throw() { name = newName; }
  19714. /** Starts the device running.
  19715. After calling this, the device will start sending midi messages to the
  19716. MidiInputCallback object that was specified when the openDevice() method
  19717. was called.
  19718. @see stop
  19719. */
  19720. void start();
  19721. /** Stops the device running.
  19722. @see start
  19723. */
  19724. void stop();
  19725. juce_UseDebuggingNewOperator
  19726. private:
  19727. String name;
  19728. void* internal;
  19729. MidiInput (const String& name);
  19730. MidiInput (const MidiInput&);
  19731. };
  19732. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19733. /********* End of inlined file: juce_MidiInput.h *********/
  19734. /**
  19735. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19736. processing by a block-based audio callback.
  19737. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19738. so it can easily use a midi input or keyboard component as its source.
  19739. @see MidiMessage, MidiInput
  19740. */
  19741. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19742. public MidiInputCallback
  19743. {
  19744. public:
  19745. /** Creates a MidiMessageCollector. */
  19746. MidiMessageCollector();
  19747. /** Destructor. */
  19748. ~MidiMessageCollector();
  19749. /** Clears any messages from the queue.
  19750. You need to call this method before starting to use the collector, so that
  19751. it knows the correct sample rate to use.
  19752. */
  19753. void reset (const double sampleRate);
  19754. /** Takes an incoming real-time message and adds it to the queue.
  19755. The message's timestamp is taken, and it will be ready for retrieval as part
  19756. of the block returned by the next call to removeNextBlockOfMessages().
  19757. This method is fully thread-safe when overlapping calls are made with
  19758. removeNextBlockOfMessages().
  19759. */
  19760. void addMessageToQueue (const MidiMessage& message);
  19761. /** Removes all the pending messages from the queue as a buffer.
  19762. This will also correct the messages' timestamps to make sure they're in
  19763. the range 0 to numSamples - 1.
  19764. This call should be made regularly by something like an audio processing
  19765. callback, because the time that it happens is used in calculating the
  19766. midi event positions.
  19767. This method is fully thread-safe when overlapping calls are made with
  19768. addMessageToQueue().
  19769. */
  19770. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19771. const int numSamples);
  19772. /** @internal */
  19773. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19774. /** @internal */
  19775. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19776. /** @internal */
  19777. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19778. juce_UseDebuggingNewOperator
  19779. private:
  19780. double lastCallbackTime;
  19781. CriticalSection midiCallbackLock;
  19782. MidiBuffer incomingMessages;
  19783. double sampleRate;
  19784. MidiMessageCollector (const MidiMessageCollector&);
  19785. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19786. };
  19787. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19788. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19789. #endif
  19790. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19791. #endif
  19792. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19793. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19794. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19795. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19796. /**
  19797. A set of routines to convert buffers of 32-bit floating point data to and from
  19798. various integer formats.
  19799. */
  19800. class JUCE_API AudioDataConverters
  19801. {
  19802. public:
  19803. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19804. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19805. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19806. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19807. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19808. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19809. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19810. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19811. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19812. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19813. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19814. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19815. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19816. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19817. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19818. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19819. enum DataFormat
  19820. {
  19821. int16LE,
  19822. int16BE,
  19823. int24LE,
  19824. int24BE,
  19825. int32LE,
  19826. int32BE,
  19827. float32LE,
  19828. float32BE,
  19829. };
  19830. static void convertFloatToFormat (const DataFormat destFormat,
  19831. const float* source, void* dest, int numSamples);
  19832. static void convertFormatToFloat (const DataFormat sourceFormat,
  19833. const void* source, float* dest, int numSamples);
  19834. static void interleaveSamples (const float** source, float* dest,
  19835. const int numSamples, const int numChannels);
  19836. static void deinterleaveSamples (const float* source, float** dest,
  19837. const int numSamples, const int numChannels);
  19838. };
  19839. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19840. /********* End of inlined file: juce_AudioDataConverters.h *********/
  19841. #endif
  19842. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19843. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  19844. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19845. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19846. class AudioFormatReader;
  19847. class AudioFormatWriter;
  19848. /**
  19849. A multi-channel buffer of 32-bit floating point audio samples.
  19850. */
  19851. class JUCE_API AudioSampleBuffer
  19852. {
  19853. public:
  19854. /** Creates a buffer with a specified number of channels and samples.
  19855. The contents of the buffer will initially be undefined, so use clear() to
  19856. set all the samples to zero.
  19857. The buffer will allocate its memory internally, and this will be released
  19858. when the buffer is deleted.
  19859. */
  19860. AudioSampleBuffer (const int numChannels,
  19861. const int numSamples) throw();
  19862. /** Creates a buffer using a pre-allocated block of memory.
  19863. Note that if the buffer is resized or its number of channels is changed, it
  19864. will re-allocate memory internally and copy the existing data to this new area,
  19865. so it will then stop directly addressing this memory.
  19866. @param dataToReferTo a pre-allocated array containing pointers to the data
  19867. for each channel that should be used by this buffer. The
  19868. buffer will only refer to this memory, it won't try to delete
  19869. it when the buffer is deleted or resized.
  19870. @param numChannels the number of channels to use - this must correspond to the
  19871. number of elements in the array passed in
  19872. @param numSamples the number of samples to use - this must correspond to the
  19873. size of the arrays passed in
  19874. */
  19875. AudioSampleBuffer (float** dataToReferTo,
  19876. const int numChannels,
  19877. const int numSamples) throw();
  19878. /** Copies another buffer.
  19879. This buffer will make its own copy of the other's data, unless the buffer was created
  19880. using an external data buffer, in which case boths buffers will just point to the same
  19881. shared block of data.
  19882. */
  19883. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  19884. /** Copies another buffer onto this one.
  19885. This buffer's size will be changed to that of the other buffer.
  19886. */
  19887. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  19888. /** Destructor.
  19889. This will free any memory allocated by the buffer.
  19890. */
  19891. virtual ~AudioSampleBuffer() throw();
  19892. /** Returns the number of channels of audio data that this buffer contains.
  19893. @see getSampleData
  19894. */
  19895. int getNumChannels() const throw() { return numChannels; }
  19896. /** Returns the number of samples allocated in each of the buffer's channels.
  19897. @see getSampleData
  19898. */
  19899. int getNumSamples() const throw() { return size; }
  19900. /** Returns a pointer to a sample in one of the buffer's channels.
  19901. For speed, this doesn't check whether the channel and sample number
  19902. are legal, so be careful when using it!
  19903. */
  19904. float* getSampleData (const int channelNumber,
  19905. const int sampleOffset = 0) const throw();
  19906. /** Chages the buffer's size or number of channels.
  19907. This can expand or contract the buffer's length, and add or remove channels.
  19908. If keepExistingContent is true, it will try to preserve as much of the
  19909. old data as it can in the new buffer.
  19910. If clearExtraSpace is true, then any extra channels or space that is
  19911. allocated will be also be cleared. If false, then this space is left
  19912. uninitialised.
  19913. If avoidReallocating is true, then changing the buffer's size won't reduce the
  19914. amount of memory that is currently allocated (but it will still increase it if
  19915. the new size is bigger than the amount it currently has). If this is false, then
  19916. a new allocation will be done so that the buffer uses takes up the minimum amount
  19917. of memory that it needs.
  19918. */
  19919. void setSize (const int newNumChannels,
  19920. const int newNumSamples,
  19921. const bool keepExistingContent = false,
  19922. const bool clearExtraSpace = false,
  19923. const bool avoidReallocating = false) throw();
  19924. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  19925. There's also a constructor that lets you specify arrays like this, but this
  19926. lets you change the channels dynamically.
  19927. Note that if the buffer is resized or its number of channels is changed, it
  19928. will re-allocate memory internally and copy the existing data to this new area,
  19929. so it will then stop directly addressing this memory.
  19930. @param dataToReferTo a pre-allocated array containing pointers to the data
  19931. for each channel that should be used by this buffer. The
  19932. buffer will only refer to this memory, it won't try to delete
  19933. it when the buffer is deleted or resized.
  19934. @param numChannels the number of channels to use - this must correspond to the
  19935. number of elements in the array passed in
  19936. @param numSamples the number of samples to use - this must correspond to the
  19937. size of the arrays passed in
  19938. */
  19939. void setDataToReferTo (float** dataToReferTo,
  19940. const int numChannels,
  19941. const int numSamples) throw();
  19942. /** Clears all the samples in all channels. */
  19943. void clear() throw();
  19944. /** Clears a specified region of all the channels.
  19945. For speed, this doesn't check whether the channel and sample number
  19946. are in-range, so be careful!
  19947. */
  19948. void clear (const int startSample,
  19949. const int numSamples) throw();
  19950. /** Clears a specified region of just one channel.
  19951. For speed, this doesn't check whether the channel and sample number
  19952. are in-range, so be careful!
  19953. */
  19954. void clear (const int channel,
  19955. const int startSample,
  19956. const int numSamples) throw();
  19957. /** Applies a gain multiple to a region of one channel.
  19958. For speed, this doesn't check whether the channel and sample number
  19959. are in-range, so be careful!
  19960. */
  19961. void applyGain (const int channel,
  19962. const int startSample,
  19963. int numSamples,
  19964. const float gain) throw();
  19965. /** Applies a gain multiple to a region of all the channels.
  19966. For speed, this doesn't check whether the sample numbers
  19967. are in-range, so be careful!
  19968. */
  19969. void applyGain (const int startSample,
  19970. const int numSamples,
  19971. const float gain) throw();
  19972. /** Applies a range of gains to a region of a channel.
  19973. The gain that is applied to each sample will vary from
  19974. startGain on the first sample to endGain on the last Sample,
  19975. so it can be used to do basic fades.
  19976. For speed, this doesn't check whether the sample numbers
  19977. are in-range, so be careful!
  19978. */
  19979. void applyGainRamp (const int channel,
  19980. const int startSample,
  19981. int numSamples,
  19982. float startGain,
  19983. float endGain) throw();
  19984. /** Adds samples from another buffer to this one.
  19985. @param destChannel the channel within this buffer to add the samples to
  19986. @param destStartSample the start sample within this buffer's channel
  19987. @param source the source buffer to add from
  19988. @param sourceChannel the channel within the source buffer to read from
  19989. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  19990. @param numSamples the number of samples to process
  19991. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  19992. added to this buffer's samples
  19993. @see copyFrom
  19994. */
  19995. void addFrom (const int destChannel,
  19996. const int destStartSample,
  19997. const AudioSampleBuffer& source,
  19998. const int sourceChannel,
  19999. const int sourceStartSample,
  20000. int numSamples,
  20001. const float gainToApplyToSource = 1.0f) throw();
  20002. /** Adds samples from an array of floats to one of the channels.
  20003. @param destChannel the channel within this buffer to add the samples to
  20004. @param destStartSample the start sample within this buffer's channel
  20005. @param source the source data to use
  20006. @param numSamples the number of samples to process
  20007. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20008. added to this buffer's samples
  20009. @see copyFrom
  20010. */
  20011. void addFrom (const int destChannel,
  20012. const int destStartSample,
  20013. const float* source,
  20014. int numSamples,
  20015. const float gainToApplyToSource = 1.0f) throw();
  20016. /** Adds samples from an array of floats, applying a gain ramp to them.
  20017. @param destChannel the channel within this buffer to add the samples to
  20018. @param destStartSample the start sample within this buffer's channel
  20019. @param source the source data to use
  20020. @param numSamples the number of samples to process
  20021. @param startGain the gain to apply to the first sample (this is multiplied with
  20022. the source samples before they are added to this buffer)
  20023. @param endGain the gain to apply to the final sample. The gain is linearly
  20024. interpolated between the first and last samples.
  20025. */
  20026. void addFromWithRamp (const int destChannel,
  20027. const int destStartSample,
  20028. const float* source,
  20029. int numSamples,
  20030. float startGain,
  20031. float endGain) throw();
  20032. /** Copies samples from another buffer to this one.
  20033. @param destChannel the channel within this buffer to copy the samples to
  20034. @param destStartSample the start sample within this buffer's channel
  20035. @param source the source buffer to read from
  20036. @param sourceChannel the channel within the source buffer to read from
  20037. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20038. @param numSamples the number of samples to process
  20039. @see addFrom
  20040. */
  20041. void copyFrom (const int destChannel,
  20042. const int destStartSample,
  20043. const AudioSampleBuffer& source,
  20044. const int sourceChannel,
  20045. const int sourceStartSample,
  20046. int numSamples) throw();
  20047. /** Copies samples from an array of floats into one of the channels.
  20048. @param destChannel the channel within this buffer to copy the samples to
  20049. @param destStartSample the start sample within this buffer's channel
  20050. @param source the source buffer to read from
  20051. @param numSamples the number of samples to process
  20052. @see addFrom
  20053. */
  20054. void copyFrom (const int destChannel,
  20055. const int destStartSample,
  20056. const float* source,
  20057. int numSamples) throw();
  20058. /** Finds the highest and lowest sample values in a given range.
  20059. @param channel the channel to read from
  20060. @param startSample the start sample within the channel
  20061. @param numSamples the number of samples to check
  20062. @param minVal on return, the lowest value that was found
  20063. @param maxVal on return, the highest value that was found
  20064. */
  20065. void findMinMax (const int channel,
  20066. const int startSample,
  20067. int numSamples,
  20068. float& minVal,
  20069. float& maxVal) const throw();
  20070. /** Finds the highest absolute sample value within a region of a channel.
  20071. */
  20072. float getMagnitude (const int channel,
  20073. const int startSample,
  20074. const int numSamples) const throw();
  20075. /** Finds the highest absolute sample value within a region on all channels.
  20076. */
  20077. float getMagnitude (const int startSample,
  20078. const int numSamples) const throw();
  20079. /** Returns the root mean squared level for a region of a channel.
  20080. */
  20081. float getRMSLevel (const int channel,
  20082. const int startSample,
  20083. const int numSamples) const throw();
  20084. /** Fills a section of the buffer using an AudioReader as its source.
  20085. This will convert the reader's fixed- or floating-point data to
  20086. the buffer's floating-point format, and will try to intelligently
  20087. cope with mismatches between the number of channels in the reader
  20088. and the buffer.
  20089. @see writeToAudioWriter
  20090. */
  20091. void readFromAudioReader (AudioFormatReader* reader,
  20092. const int startSample,
  20093. const int numSamples,
  20094. const int readerStartSample,
  20095. const bool useReaderLeftChan,
  20096. const bool useReaderRightChan) throw();
  20097. /** Writes a section of this buffer to an audio writer.
  20098. This saves you having to mess about with channels or floating/fixed
  20099. point conversion.
  20100. @see readFromAudioReader
  20101. */
  20102. void writeToAudioWriter (AudioFormatWriter* writer,
  20103. const int startSample,
  20104. const int numSamples) const throw();
  20105. juce_UseDebuggingNewOperator
  20106. private:
  20107. int numChannels, size, allocatedBytes;
  20108. float** channels;
  20109. float* allocatedData;
  20110. };
  20111. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20112. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20113. #endif
  20114. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20115. /********* Start of inlined file: juce_IIRFilter.h *********/
  20116. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20117. #define __JUCE_IIRFILTER_JUCEHEADER__
  20118. /**
  20119. An IIR filter that can perform low, high, or band-pass filtering on an
  20120. audio signal.
  20121. @see IIRFilterAudioSource
  20122. */
  20123. class JUCE_API IIRFilter
  20124. {
  20125. public:
  20126. /** Creates a filter.
  20127. Initially the filter is inactive, so will have no effect on samples that
  20128. you process with it. Use the appropriate method to turn it into the type
  20129. of filter needed.
  20130. */
  20131. IIRFilter() throw();
  20132. /** Creates a copy of another filter. */
  20133. IIRFilter (const IIRFilter& other) throw();
  20134. /** Destructor. */
  20135. ~IIRFilter() throw();
  20136. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20137. Note that this clears the processing state, but the type of filter and
  20138. its coefficients aren't changed. To put a filter into an inactive state, use
  20139. the makeInactive() method.
  20140. */
  20141. void reset() throw();
  20142. /** Performs the filter operation on the given set of samples.
  20143. */
  20144. void processSamples (float* const samples,
  20145. const int numSamples) throw();
  20146. /** Processes a single sample, without any locking or checking.
  20147. Use this if you need fast processing of a single value, but be aware that
  20148. this isn't thread-safe in the way that processSamples() is.
  20149. */
  20150. float processSingleSampleRaw (const float sample) throw();
  20151. /** Sets the filter up to act as a low-pass filter.
  20152. */
  20153. void makeLowPass (const double sampleRate,
  20154. const double frequency) throw();
  20155. /** Sets the filter up to act as a high-pass filter.
  20156. */
  20157. void makeHighPass (const double sampleRate,
  20158. const double frequency) throw();
  20159. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20160. The gain is a scale factor that the low frequencies are multiplied by, so values
  20161. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20162. attenuate them.
  20163. */
  20164. void makeLowShelf (const double sampleRate,
  20165. const double cutOffFrequency,
  20166. const double Q,
  20167. const float gainFactor) throw();
  20168. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20169. The gain is a scale factor that the high frequencies are multiplied by, so values
  20170. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20171. attenuate them.
  20172. */
  20173. void makeHighShelf (const double sampleRate,
  20174. const double cutOffFrequency,
  20175. const double Q,
  20176. const float gainFactor) throw();
  20177. /** Sets the filter up to act as a band pass filter centred around a
  20178. frequency, with a variable Q and gain.
  20179. The gain is a scale factor that the centre frequencies are multiplied by, so
  20180. values greater than 1.0 will boost the centre frequencies, values less than
  20181. 1.0 will attenuate them.
  20182. */
  20183. void makeBandPass (const double sampleRate,
  20184. const double centreFrequency,
  20185. const double Q,
  20186. const float gainFactor) throw();
  20187. /** Clears the filter's coefficients so that it becomes inactive.
  20188. */
  20189. void makeInactive() throw();
  20190. /** Makes this filter duplicate the set-up of another one.
  20191. */
  20192. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20193. juce_UseDebuggingNewOperator
  20194. protected:
  20195. CriticalSection processLock;
  20196. void setCoefficients (double c1, double c2, double c3,
  20197. double c4, double c5, double c6) throw();
  20198. bool active;
  20199. float coefficients[6];
  20200. float x1, x2, y1, y2;
  20201. // (use the copyCoefficientsFrom() method instead of this operator)
  20202. const IIRFilter& operator= (const IIRFilter&);
  20203. };
  20204. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20205. /********* End of inlined file: juce_IIRFilter.h *********/
  20206. #endif
  20207. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20208. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20209. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20210. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20211. /**
  20212. A subclass of AudioPlayHead can supply information about the position and
  20213. status of a moving play head during audio playback.
  20214. One of these can be supplied to an AudioProcessor object so that it can find
  20215. out about the position of the audio that it is rendering.
  20216. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20217. */
  20218. class JUCE_API AudioPlayHead
  20219. {
  20220. protected:
  20221. AudioPlayHead() {}
  20222. public:
  20223. virtual ~AudioPlayHead() {}
  20224. /** Frame rate types. */
  20225. enum FrameRateType
  20226. {
  20227. fps24 = 0,
  20228. fps25 = 1,
  20229. fps2997 = 2,
  20230. fps30 = 3,
  20231. fps2997drop = 4,
  20232. fps30drop = 5,
  20233. fpsUnknown = 99
  20234. };
  20235. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20236. */
  20237. struct CurrentPositionInfo
  20238. {
  20239. /** The tempo in BPM */
  20240. double bpm;
  20241. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20242. int timeSigNumerator;
  20243. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20244. int timeSigDenominator;
  20245. /** The current play position, in seconds from the start of the edit. */
  20246. double timeInSeconds;
  20247. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20248. double editOriginTime;
  20249. /** The current play position in pulses-per-quarter-note.
  20250. This is the number of quarter notes since the edit start.
  20251. */
  20252. double ppqPosition;
  20253. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20254. This is the number of quarter notes from the start of the edit to the
  20255. start of the current bar.
  20256. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20257. it's not available, the value will be 0.
  20258. */
  20259. double ppqPositionOfLastBarStart;
  20260. /** The video frame rate, if applicable. */
  20261. FrameRateType frameRate;
  20262. /** True if the transport is currently playing. */
  20263. bool isPlaying;
  20264. /** True if the transport is currently recording.
  20265. (When isRecording is true, then isPlaying will also be true).
  20266. */
  20267. bool isRecording;
  20268. };
  20269. /** Fills-in the given structure with details about the transport's
  20270. position at the start of the current processing block.
  20271. */
  20272. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20273. };
  20274. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20275. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20276. #endif
  20277. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20278. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20279. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20280. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20281. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20282. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20283. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20284. class AudioProcessor;
  20285. /**
  20286. Base class for the component that acts as the GUI for an AudioProcessor.
  20287. Derive your editor component from this class, and create an instance of it
  20288. by overriding the AudioProcessor::createEditor() method.
  20289. @see AudioProcessor, GenericAudioProcessorEditor
  20290. */
  20291. class JUCE_API AudioProcessorEditor : public Component
  20292. {
  20293. protected:
  20294. /** Creates an editor for the specified processor.
  20295. */
  20296. AudioProcessorEditor (AudioProcessor* const owner);
  20297. public:
  20298. /** Destructor. */
  20299. ~AudioProcessorEditor();
  20300. /** Returns a pointer to the processor that this editor represents. */
  20301. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20302. private:
  20303. AudioProcessor* const owner;
  20304. };
  20305. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20306. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20307. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20308. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20309. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20310. class AudioProcessor;
  20311. /**
  20312. Base class for listeners that want to know about changes to an AudioProcessor.
  20313. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20314. @see AudioProcessor
  20315. */
  20316. class JUCE_API AudioProcessorListener
  20317. {
  20318. public:
  20319. /** Destructor. */
  20320. virtual ~AudioProcessorListener() {}
  20321. /** Receives a callback when a parameter is changed.
  20322. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20323. many audio processors will change their parameter during their audio callback.
  20324. This means that not only has your handler code got to be completely thread-safe,
  20325. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20326. this event on your message thread, use this callback to trigger an AsyncUpdater
  20327. or ChangeBroadcaster which you can respond to on the message thread.
  20328. */
  20329. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20330. int parameterIndex,
  20331. float newValue) = 0;
  20332. /** Called to indicate that something else in the plugin has changed, like its
  20333. program, number of parameters, etc.
  20334. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20335. call it during their audio callback. This means that not only has your handler code
  20336. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20337. blocking. If you need to handle this event on your message thread, use this callback
  20338. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20339. message thread.
  20340. */
  20341. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20342. /** Indicates that a parameter change gesture has started.
  20343. E.g. if the user is dragging a slider, this would be called when they first
  20344. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20345. called when they release it.
  20346. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20347. call it during their audio callback. This means that not only has your handler code
  20348. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20349. blocking. If you need to handle this event on your message thread, use this callback
  20350. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20351. message thread.
  20352. @see audioProcessorParameterChangeGestureEnd
  20353. */
  20354. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20355. int parameterIndex);
  20356. /** Indicates that a parameter change gesture has finished.
  20357. E.g. if the user is dragging a slider, this would be called when they release
  20358. the mouse button.
  20359. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20360. call it during their audio callback. This means that not only has your handler code
  20361. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20362. blocking. If you need to handle this event on your message thread, use this callback
  20363. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20364. message thread.
  20365. @see audioPluginParameterChangeGestureStart
  20366. */
  20367. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20368. int parameterIndex);
  20369. };
  20370. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20371. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20372. /**
  20373. Base class for audio processing filters or plugins.
  20374. This is intended to act as a base class of audio filter that is general enough to
  20375. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20376. It is also used by the plugin hosting code as the wrapper around an instance
  20377. of a loaded plugin.
  20378. Derive your filter class from this base class, and if you're building a plugin,
  20379. you should implement a global function called createPluginFilter() which creates
  20380. and returns a new instance of your subclass.
  20381. */
  20382. class JUCE_API AudioProcessor
  20383. {
  20384. protected:
  20385. /** Constructor.
  20386. You can also do your initialisation tasks in the initialiseFilterInfo()
  20387. call, which will be made after this object has been created.
  20388. */
  20389. AudioProcessor();
  20390. public:
  20391. /** Destructor. */
  20392. virtual ~AudioProcessor();
  20393. /** Returns the name of this processor.
  20394. */
  20395. virtual const String getName() const = 0;
  20396. /** Called before playback starts, to let the filter prepare itself.
  20397. The sample rate is the target sample rate, and will remain constant until
  20398. playback stops.
  20399. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20400. samples that will be processed for each callback, but isn't any kind
  20401. of guarantee. The actual block sizes that the host uses may be different
  20402. each time the callback happens, and may be more or less than this value.
  20403. */
  20404. virtual void prepareToPlay (double sampleRate,
  20405. int estimatedSamplesPerBlock) = 0;
  20406. /** Called after playback has stopped, to let the filter free up any resources it
  20407. no longer needs.
  20408. */
  20409. virtual void releaseResources() = 0;
  20410. /** Renders the next block.
  20411. When this method is called, the buffer contains a number of channels which is
  20412. at least as great as the maximum number of input and output channels that
  20413. this filter is using. It will be filled with the filter's input data and
  20414. should be replaced with the filter's output.
  20415. So for example if your filter has 2 input channels and 4 output channels, then
  20416. the buffer will contain 4 channels, the first two being filled with the
  20417. input data. Your filter should read these, do its processing, and replace
  20418. the contents of all 4 channels with its output.
  20419. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20420. all filled with data, and your filter should overwrite the first 2 of these
  20421. with its output. But be VERY careful not to write anything to the last 3
  20422. channels, as these might be mapped to memory that the host assumes is read-only!
  20423. Note that if you have more outputs than inputs, then only those channels that
  20424. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20425. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20426. but the last two channels may contain garbage, so you should be careful not to
  20427. let this pass through without being overwritten or cleared.
  20428. Also note that the buffer may have more channels than are strictly necessary,
  20429. but your should only read/write from the ones that your filter is supposed to
  20430. be using.
  20431. The number of samples in these buffers is NOT guaranteed to be the same for every
  20432. callback, and may be more or less than the estimated value given to prepareToPlay().
  20433. Your code must be able to cope with variable-sized blocks, or you're going to get
  20434. clicks and crashes!
  20435. If the filter is receiving a midi input, then the midiMessages array will be filled
  20436. with the midi messages for this block. Each message's timestamp will indicate the
  20437. message's time, as a number of samples from the start of the block.
  20438. Any messages left in the midi buffer when this method has finished are assumed to
  20439. be the filter's midi output. This means that your filter should be careful to
  20440. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20441. Be very careful about what you do in this callback - it's going to be called by
  20442. the audio thread, so any kind of interaction with the UI is absolutely
  20443. out of the question. If you change a parameter in here and need to tell your UI to
  20444. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20445. the UI components register as listeners, and then call sendChangeMessage() inside the
  20446. processBlock() method to send out an asynchronous message. You could also use
  20447. the AsyncUpdater class in a similar way.
  20448. */
  20449. virtual void processBlock (AudioSampleBuffer& buffer,
  20450. MidiBuffer& midiMessages) = 0;
  20451. /** Returns the current AudioPlayHead object that should be used to find
  20452. out the state and position of the playhead.
  20453. You can call this from your processBlock() method, and use the AudioPlayHead
  20454. object to get the details about the time of the start of the block currently
  20455. being processed.
  20456. If the host hasn't supplied a playhead object, this will return 0.
  20457. */
  20458. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20459. /** Returns the current sample rate.
  20460. This can be called from your processBlock() method - it's not guaranteed
  20461. to be valid at any other time, and may return 0 if it's unknown.
  20462. */
  20463. double getSampleRate() const throw() { return sampleRate; }
  20464. /** Returns the current typical block size that is being used.
  20465. This can be called from your processBlock() method - it's not guaranteed
  20466. to be valid at any other time.
  20467. Remember it's not the ONLY block size that may be used when calling
  20468. processBlock, it's just the normal one. The actual block sizes used may be
  20469. larger or smaller than this, and will vary between successive calls.
  20470. */
  20471. int getBlockSize() const throw() { return blockSize; }
  20472. /** Returns the number of input channels that the host will be sending the filter.
  20473. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20474. number of channels that your filter would prefer to have, and this method lets
  20475. you know how many the host is actually using.
  20476. Note that this method is only valid during or after the prepareToPlay()
  20477. method call. Until that point, the number of channels will be unknown.
  20478. */
  20479. int getNumInputChannels() const throw() { return numInputChannels; }
  20480. /** Returns the number of output channels that the host will be sending the filter.
  20481. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20482. number of channels that your filter would prefer to have, and this method lets
  20483. you know how many the host is actually using.
  20484. Note that this method is only valid during or after the prepareToPlay()
  20485. method call. Until that point, the number of channels will be unknown.
  20486. */
  20487. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20488. /** Returns the name of one of the input channels, as returned by the host.
  20489. The host might not supply very useful names for channels, and this might be
  20490. something like "1", "2", "left", "right", etc.
  20491. */
  20492. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20493. /** Returns the name of one of the output channels, as returned by the host.
  20494. The host might not supply very useful names for channels, and this might be
  20495. something like "1", "2", "left", "right", etc.
  20496. */
  20497. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20498. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20499. virtual bool isInputChannelStereoPair (int index) const = 0;
  20500. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20501. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20502. /** This returns the number of samples delay that the filter imposes on the audio
  20503. passing through it.
  20504. The host will call this to find the latency - the filter itself should set this value
  20505. by calling setLatencySamples() as soon as it can during its initialisation.
  20506. */
  20507. int getLatencySamples() const throw() { return latencySamples; }
  20508. /** The filter should call this to set the number of samples delay that it introduces.
  20509. The filter should call this as soon as it can during initialisation, and can call it
  20510. later if the value changes.
  20511. */
  20512. void setLatencySamples (const int newLatency);
  20513. /** Returns true if the processor wants midi messages. */
  20514. virtual bool acceptsMidi() const = 0;
  20515. /** Returns true if the processor produces midi messages. */
  20516. virtual bool producesMidi() const = 0;
  20517. /** This returns a critical section that will automatically be locked while the host
  20518. is calling the processBlock() method.
  20519. Use it from your UI or other threads to lock access to variables that are used
  20520. by the process callback, but obviously be careful not to keep it locked for
  20521. too long, because that could cause stuttering playback. If you need to do something
  20522. that'll take a long time and need the processing to stop while it happens, use the
  20523. suspendProcessing() method instead.
  20524. @see suspendProcessing
  20525. */
  20526. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20527. /** Enables and disables the processing callback.
  20528. If you need to do something time-consuming on a thread and would like to make sure
  20529. the audio processing callback doesn't happen until you've finished, use this
  20530. to disable the callback and re-enable it again afterwards.
  20531. E.g.
  20532. @code
  20533. void loadNewPatch()
  20534. {
  20535. suspendProcessing (true);
  20536. ..do something that takes ages..
  20537. suspendProcessing (false);
  20538. }
  20539. @endcode
  20540. If the host tries to make an audio callback while processing is suspended, the
  20541. filter will return an empty buffer, but won't block the audio thread like it would
  20542. do if you use the getCallbackLock() critical section to synchronise access.
  20543. If you're going to use this, your processBlock() method must call isSuspended() and
  20544. check whether it's suspended or not. If it is, then it should skip doing any real
  20545. processing, either emitting silence or passing the input through unchanged.
  20546. @see getCallbackLock
  20547. */
  20548. void suspendProcessing (const bool shouldBeSuspended);
  20549. /** Returns true if processing is currently suspended.
  20550. @see suspendProcessing
  20551. */
  20552. bool isSuspended() const throw() { return suspended; }
  20553. /** A plugin can override this to be told when it should reset any playing voices.
  20554. The default implementation does nothing, but a host may call this to tell the
  20555. plugin that it should stop any tails or sounds that have been left running.
  20556. */
  20557. virtual void reset();
  20558. /** Returns true if the processor is being run in an offline mode for rendering.
  20559. If the processor is being run live on realtime signals, this returns false.
  20560. If the mode is unknown, this will assume it's realtime and return false.
  20561. This value may be unreliable until the prepareToPlay() method has been called,
  20562. and could change each time prepareToPlay() is called.
  20563. @see setNonRealtime()
  20564. */
  20565. bool isNonRealtime() const throw() { return nonRealtime; }
  20566. /** Called by the host to tell this processor whether it's being used in a non-realime
  20567. capacity for offline rendering or bouncing.
  20568. Whatever value is passed-in will be
  20569. */
  20570. void setNonRealtime (const bool isNonRealtime) throw();
  20571. /** Creates the filter's UI.
  20572. This can return 0 if you want a UI-less filter, in which case the host may create
  20573. a generic UI that lets the user twiddle the parameters directly.
  20574. If you do want to pass back a component, the component should be created and set to
  20575. the correct size before returning it.
  20576. Remember not to do anything silly like allowing your filter to keep a pointer to
  20577. the component that gets created - it could be deleted later without any warning, which
  20578. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20579. The correct way to handle the connection between an editor component and its
  20580. filter is to use something like a ChangeBroadcaster so that the editor can
  20581. register itself as a listener, and be told when a change occurs. This lets them
  20582. safely unregister themselves when they are deleted.
  20583. Here are a few things to bear in mind when writing an editor:
  20584. - Initially there won't be an editor, until the user opens one, or they might
  20585. not open one at all. Your filter mustn't rely on it being there.
  20586. - An editor object may be deleted and a replacement one created again at any time.
  20587. - It's safe to assume that an editor will be deleted before its filter.
  20588. */
  20589. virtual AudioProcessorEditor* createEditor() = 0;
  20590. /** Returns the active editor, if there is one.
  20591. Bear in mind this can return 0, even if an editor has previously been
  20592. opened.
  20593. */
  20594. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20595. /** Returns the active editor, or if there isn't one, it will create one.
  20596. This may call createEditor() internally to create the component.
  20597. */
  20598. AudioProcessorEditor* createEditorIfNeeded();
  20599. /** This must return the correct value immediately after the object has been
  20600. created, and mustn't change the number of parameters later.
  20601. */
  20602. virtual int getNumParameters() = 0;
  20603. /** Returns the name of a particular parameter. */
  20604. virtual const String getParameterName (int parameterIndex) = 0;
  20605. /** Called by the host to find out the value of one of the filter's parameters.
  20606. The host will expect the value returned to be between 0 and 1.0.
  20607. This could be called quite frequently, so try to make your code efficient.
  20608. It's also likely to be called by non-UI threads, so the code in here should
  20609. be thread-aware.
  20610. */
  20611. virtual float getParameter (int parameterIndex) = 0;
  20612. /** Returns the value of a parameter as a text string. */
  20613. virtual const String getParameterText (int parameterIndex) = 0;
  20614. /** The host will call this method to change the value of one of the filter's parameters.
  20615. The host may call this at any time, including during the audio processing
  20616. callback, so the filter has to process this very fast and avoid blocking.
  20617. If you want to set the value of a parameter internally, e.g. from your
  20618. editor component, then don't call this directly - instead, use the
  20619. setParameterNotifyingHost() method, which will also send a message to
  20620. the host telling it about the change. If the message isn't sent, the host
  20621. won't be able to automate your parameters properly.
  20622. The value passed will be between 0 and 1.0.
  20623. */
  20624. virtual void setParameter (int parameterIndex,
  20625. float newValue) = 0;
  20626. /** Your filter can call this when it needs to change one of its parameters.
  20627. This could happen when the editor or some other internal operation changes
  20628. a parameter. This method will call the setParameter() method to change the
  20629. value, and will then send a message to the host telling it about the change.
  20630. Note that to make sure the host correctly handles automation, you should call
  20631. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20632. tell the host when the user has started and stopped changing the parameter.
  20633. */
  20634. void setParameterNotifyingHost (int parameterIndex,
  20635. float newValue);
  20636. /** Returns true if the host can automate this parameter.
  20637. By default, this returns true for all parameters.
  20638. */
  20639. virtual bool isParameterAutomatable (int parameterIndex) const;
  20640. /** Should return true if this parameter is a "meta" parameter.
  20641. A meta-parameter is a parameter that changes other params. It is used
  20642. by some hosts (e.g. AudioUnit hosts).
  20643. By default this returns false.
  20644. */
  20645. virtual bool isMetaParameter (int parameterIndex) const;
  20646. /** Sends a signal to the host to tell it that the user is about to start changing this
  20647. parameter.
  20648. This allows the host to know when a parameter is actively being held by the user, and
  20649. it may use this information to help it record automation.
  20650. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20651. */
  20652. void beginParameterChangeGesture (int parameterIndex);
  20653. /** Tells the host that the user has finished changing this parameter.
  20654. This allows the host to know when a parameter is actively being held by the user, and
  20655. it may use this information to help it record automation.
  20656. A call to this method must follow a call to beginParameterChangeGesture().
  20657. */
  20658. void endParameterChangeGesture (int parameterIndex);
  20659. /** The filter can call this when something (apart from a parameter value) has changed.
  20660. It sends a hint to the host that something like the program, number of parameters,
  20661. etc, has changed, and that it should update itself.
  20662. */
  20663. void updateHostDisplay();
  20664. /** Returns the number of preset programs the filter supports.
  20665. The value returned must be valid as soon as this object is created, and
  20666. must not change over its lifetime.
  20667. This value shouldn't be less than 1.
  20668. */
  20669. virtual int getNumPrograms() = 0;
  20670. /** Returns the number of the currently active program.
  20671. */
  20672. virtual int getCurrentProgram() = 0;
  20673. /** Called by the host to change the current program.
  20674. */
  20675. virtual void setCurrentProgram (int index) = 0;
  20676. /** Must return the name of a given program. */
  20677. virtual const String getProgramName (int index) = 0;
  20678. /** Called by the host to rename a program.
  20679. */
  20680. virtual void changeProgramName (int index, const String& newName) = 0;
  20681. /** The host will call this method when it wants to save the filter's internal state.
  20682. This must copy any info about the filter's state into the block of memory provided,
  20683. so that the host can store this and later restore it using setStateInformation().
  20684. Note that there's also a getCurrentProgramStateInformation() method, which only
  20685. stores the current program, not the state of the entire filter.
  20686. See also the helper function copyXmlToBinary() for storing settings as XML.
  20687. @see getCurrentProgramStateInformation
  20688. */
  20689. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20690. /** The host will call this method if it wants to save the state of just the filter's
  20691. current program.
  20692. Unlike getStateInformation, this should only return the current program's state.
  20693. Not all hosts support this, and if you don't implement it, the base class
  20694. method just calls getStateInformation() instead. If you do implement it, be
  20695. sure to also implement getCurrentProgramStateInformation.
  20696. @see getStateInformation, setCurrentProgramStateInformation
  20697. */
  20698. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20699. /** This must restore the filter's state from a block of data previously created
  20700. using getStateInformation().
  20701. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20702. to restore just the current program, not the state of the entire filter.
  20703. See also the helper function getXmlFromBinary() for loading settings as XML.
  20704. @see setCurrentProgramStateInformation
  20705. */
  20706. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20707. /** The host will call this method if it wants to restore the state of just the filter's
  20708. current program.
  20709. Not all hosts support this, and if you don't implement it, the base class
  20710. method just calls setStateInformation() instead. If you do implement it, be
  20711. sure to also implement getCurrentProgramStateInformation.
  20712. @see setStateInformation, getCurrentProgramStateInformation
  20713. */
  20714. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20715. /** Adds a listener that will be called when an aspect of this processor changes. */
  20716. void addListener (AudioProcessorListener* const newListener) throw();
  20717. /** Removes a previously added listener. */
  20718. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20719. /** Not for public use - this is called before deleting an editor component. */
  20720. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20721. /** Not for public use - this is called to initialise the processor. */
  20722. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20723. /** Not for public use - this is called to initialise the processor before playing. */
  20724. void setPlayConfigDetails (const int numIns, const int numOuts,
  20725. const double sampleRate,
  20726. const int blockSize) throw();
  20727. juce_UseDebuggingNewOperator
  20728. protected:
  20729. /** Helper function that just converts an xml element into a binary blob.
  20730. Use this in your filter's getStateInformation() method if you want to
  20731. store its state as xml.
  20732. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20733. from a binary blob.
  20734. */
  20735. static void copyXmlToBinary (const XmlElement& xml,
  20736. JUCE_NAMESPACE::MemoryBlock& destData);
  20737. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20738. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20739. an XmlElement object that the caller must delete when no longer needed.
  20740. */
  20741. static XmlElement* getXmlFromBinary (const void* data,
  20742. const int sizeInBytes);
  20743. /** @internal */
  20744. AudioPlayHead* playHead;
  20745. /** @internal */
  20746. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20747. private:
  20748. VoidArray listeners;
  20749. AudioProcessorEditor* activeEditor;
  20750. double sampleRate;
  20751. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20752. bool suspended, nonRealtime;
  20753. CriticalSection callbackLock, listenerLock;
  20754. #ifdef JUCE_DEBUG
  20755. BitArray changingParams;
  20756. #endif
  20757. AudioProcessor (const AudioProcessor&);
  20758. const AudioProcessor& operator= (const AudioProcessor&);
  20759. };
  20760. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20761. /********* End of inlined file: juce_AudioProcessor.h *********/
  20762. #endif
  20763. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20764. #endif
  20765. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20766. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20767. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20768. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20769. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20770. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20771. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20772. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20773. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20774. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20775. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20776. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20777. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20778. /********* Start of inlined file: juce_PluginDescription.h *********/
  20779. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20780. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20781. /**
  20782. A small class to represent some facts about a particular type of plugin.
  20783. This class is for storing and managing the details about a plugin without
  20784. actually having to load an instance of it.
  20785. A KnownPluginList contains a list of PluginDescription objects.
  20786. @see KnownPluginList
  20787. */
  20788. class JUCE_API PluginDescription
  20789. {
  20790. public:
  20791. PluginDescription() throw();
  20792. PluginDescription (const PluginDescription& other) throw();
  20793. const PluginDescription& operator= (const PluginDescription& other) throw();
  20794. ~PluginDescription() throw();
  20795. /** The name of the plugin. */
  20796. String name;
  20797. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  20798. */
  20799. String pluginFormatName;
  20800. /** A category, such as "Dynamics", "Reverbs", etc.
  20801. */
  20802. String category;
  20803. /** The manufacturer. */
  20804. String manufacturerName;
  20805. /** The version. This string doesn't have any particular format. */
  20806. String version;
  20807. /** Either the file containing the plugin module, or some other unique way
  20808. of identifying it.
  20809. E.g. for an AU, this would be an ID string that the component manager
  20810. could use to retrieve the plugin. For a VST, it's the file path.
  20811. */
  20812. String fileOrIdentifier;
  20813. /** The last time the plugin file was changed.
  20814. This is handy when scanning for new or changed plugins.
  20815. */
  20816. Time lastFileModTime;
  20817. /** A unique ID for the plugin.
  20818. Note that this might not be unique between formats, e.g. a VST and some
  20819. other format might actually have the same id.
  20820. @see createIdentifierString
  20821. */
  20822. int uid;
  20823. /** True if the plugin identifies itself as a synthesiser. */
  20824. bool isInstrument;
  20825. /** The number of inputs. */
  20826. int numInputChannels;
  20827. /** The number of outputs. */
  20828. int numOutputChannels;
  20829. /** Returns true if the two descriptions refer the the same plugin.
  20830. This isn't quite as simple as them just having the same file (because of
  20831. shell plugins).
  20832. */
  20833. bool isDuplicateOf (const PluginDescription& other) const;
  20834. /** Returns a string that can be saved and used to uniquely identify the
  20835. plugin again.
  20836. This contains less info than the XML encoding, and is independent of the
  20837. plugin's file location, so can be used to store a plugin ID for use
  20838. across different machines.
  20839. */
  20840. const String createIdentifierString() const throw();
  20841. /** Creates an XML object containing these details.
  20842. @see loadFromXml
  20843. */
  20844. XmlElement* createXml() const;
  20845. /** Reloads the info in this structure from an XML record that was previously
  20846. saved with createXML().
  20847. Returns true if the XML was a valid plugin description.
  20848. */
  20849. bool loadFromXml (const XmlElement& xml);
  20850. juce_UseDebuggingNewOperator
  20851. };
  20852. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20853. /********* End of inlined file: juce_PluginDescription.h *********/
  20854. /**
  20855. Base class for an active instance of a plugin.
  20856. This derives from the AudioProcessor class, and adds some extra functionality
  20857. that helps when wrapping dynamically loaded plugins.
  20858. @see AudioProcessor, AudioPluginFormat
  20859. */
  20860. class JUCE_API AudioPluginInstance : public AudioProcessor
  20861. {
  20862. public:
  20863. /** Destructor.
  20864. Make sure that you delete any UI components that belong to this plugin before
  20865. deleting the plugin.
  20866. */
  20867. virtual ~AudioPluginInstance();
  20868. /** Fills-in the appropriate parts of this plugin description object.
  20869. */
  20870. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  20871. juce_UseDebuggingNewOperator
  20872. protected:
  20873. AudioPluginInstance();
  20874. AudioPluginInstance (const AudioPluginInstance&);
  20875. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  20876. };
  20877. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20878. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  20879. class PluginDescription;
  20880. /**
  20881. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  20882. Use the static getNumFormats() and getFormat() calls to find the types
  20883. of format that are available.
  20884. */
  20885. class JUCE_API AudioPluginFormat
  20886. {
  20887. public:
  20888. /** Destructor. */
  20889. virtual ~AudioPluginFormat();
  20890. /** Returns the format name.
  20891. E.g. "VST", "AudioUnit", etc.
  20892. */
  20893. virtual const String getName() const = 0;
  20894. /** This tries to create descriptions for all the plugin types available in
  20895. a binary module file.
  20896. The file will be some kind of DLL or bundle.
  20897. Normally there will only be one type returned, but some plugins
  20898. (e.g. VST shells) can use a single DLL to create a set of different plugin
  20899. subtypes, so in that case, each subtype is returned as a separate object.
  20900. */
  20901. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  20902. const String& fileOrIdentifier) = 0;
  20903. /** Tries to recreate a type from a previously generated PluginDescription.
  20904. @see PluginDescription::createInstance
  20905. */
  20906. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  20907. /** Should do a quick check to see if this file or directory might be a plugin of
  20908. this format.
  20909. This is for searching for potential files, so it shouldn't actually try to
  20910. load the plugin or do anything time-consuming.
  20911. */
  20912. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  20913. /** Returns a readable version of the name of the plugin that this identifier refers to.
  20914. */
  20915. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  20916. /** Checks whether this plugin could possibly be loaded.
  20917. It doesn't actually need to load it, just to check whether the file or component
  20918. still exists.
  20919. */
  20920. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  20921. /** Searches a suggested set of directories for any plugins in this format.
  20922. The path might be ignored, e.g. by AUs, which are found by the OS rather
  20923. than manually.
  20924. */
  20925. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  20926. const bool recursive) = 0;
  20927. /** Returns the typical places to look for this kind of plugin.
  20928. Note that if this returns no paths, it means that the format can't be scanned-for
  20929. (i.e. it's an internal format that doesn't live in files)
  20930. */
  20931. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  20932. juce_UseDebuggingNewOperator
  20933. protected:
  20934. AudioPluginFormat() throw();
  20935. AudioPluginFormat (const AudioPluginFormat&);
  20936. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  20937. };
  20938. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20939. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  20940. /**
  20941. This maintains a list of known AudioPluginFormats.
  20942. @see AudioPluginFormat
  20943. */
  20944. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  20945. {
  20946. public:
  20947. AudioPluginFormatManager() throw();
  20948. /** Destructor. */
  20949. ~AudioPluginFormatManager() throw();
  20950. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  20951. /** Adds any formats that it knows about, e.g. VST.
  20952. */
  20953. void addDefaultFormats();
  20954. /** Returns the number of types of format that are available.
  20955. Use getFormat() to get one of them.
  20956. */
  20957. int getNumFormats() throw();
  20958. /** Returns one of the available formats.
  20959. @see getNumFormats
  20960. */
  20961. AudioPluginFormat* getFormat (const int index) throw();
  20962. /** Adds a format to the list.
  20963. The object passed in will be owned and deleted by the manager.
  20964. */
  20965. void addFormat (AudioPluginFormat* const format) throw();
  20966. /** Tries to load the type for this description, by trying all the formats
  20967. that this manager knows about.
  20968. The caller is responsible for deleting the object that is returned.
  20969. If it can't load the plugin, it returns 0 and leaves a message in the
  20970. errorMessage string.
  20971. */
  20972. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  20973. String& errorMessage) const;
  20974. /** Checks that the file or component for this plugin actually still exists.
  20975. (This won't try to load the plugin)
  20976. */
  20977. bool doesPluginStillExist (const PluginDescription& description) const;
  20978. juce_UseDebuggingNewOperator
  20979. private:
  20980. OwnedArray <AudioPluginFormat> formats;
  20981. AudioPluginFormatManager (const AudioPluginFormatManager&);
  20982. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  20983. };
  20984. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20985. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  20986. /********* Start of inlined file: juce_KnownPluginList.h *********/
  20987. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  20988. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  20989. /********* Start of inlined file: juce_PopupMenu.h *********/
  20990. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  20991. #define __JUCE_POPUPMENU_JUCEHEADER__
  20992. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  20993. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20994. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20995. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  20996. @see PopupMenu::addCustomItem
  20997. */
  20998. class JUCE_API PopupMenuCustomComponent : public Component
  20999. {
  21000. public:
  21001. /** Destructor. */
  21002. ~PopupMenuCustomComponent();
  21003. /** Chooses the size that this component would like to have.
  21004. Note that the size which this method returns isn't necessarily the one that
  21005. the menu will give it, as it will be stretched to fit the other items in
  21006. the menu.
  21007. */
  21008. virtual void getIdealSize (int& idealWidth,
  21009. int& idealHeight) = 0;
  21010. /** Dismisses the menu indicating that this item has been chosen.
  21011. This will cause the menu to exit from its modal state, returning
  21012. this item's id as the result.
  21013. */
  21014. void triggerMenuItem();
  21015. /** Returns true if this item should be highlighted because the mouse is
  21016. over it.
  21017. You can call this method in your paint() method to find out whether
  21018. to draw a highlight.
  21019. */
  21020. bool isItemHighlighted() const throw() { return isHighlighted; }
  21021. protected:
  21022. /** Constructor.
  21023. If isTriggeredAutomatically is true, then the menu will automatically detect
  21024. a click on this component and use that to trigger it. If it's false, then it's
  21025. up to your class to manually trigger the item if it wants to.
  21026. */
  21027. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21028. private:
  21029. friend class MenuItemInfo;
  21030. friend class MenuItemComponent;
  21031. friend class PopupMenuWindow;
  21032. int refCount_;
  21033. bool isHighlighted, isTriggeredAutomatically;
  21034. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21035. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21036. };
  21037. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21038. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21039. /** Creates and displays a popup-menu.
  21040. To show a popup-menu, you create one of these, add some items to it, then
  21041. call its show() method, which returns the id of the item the user selects.
  21042. E.g. @code
  21043. void MyWidget::mouseDown (const MouseEvent& e)
  21044. {
  21045. PopupMenu m;
  21046. m.addItem (1, "item 1");
  21047. m.addItem (2, "item 2");
  21048. const int result = m.show();
  21049. if (result == 0)
  21050. {
  21051. // user dismissed the menu without picking anything
  21052. }
  21053. else if (result == 1)
  21054. {
  21055. // user picked item 1
  21056. }
  21057. else if (result == 2)
  21058. {
  21059. // user picked item 2
  21060. }
  21061. }
  21062. @endcode
  21063. Submenus are easy too: @code
  21064. void MyWidget::mouseDown (const MouseEvent& e)
  21065. {
  21066. PopupMenu subMenu;
  21067. subMenu.addItem (1, "item 1");
  21068. subMenu.addItem (2, "item 2");
  21069. PopupMenu mainMenu;
  21070. mainMenu.addItem (3, "item 3");
  21071. mainMenu.addSubMenu ("other choices", subMenu);
  21072. const int result = m.show();
  21073. ...etc
  21074. }
  21075. @endcode
  21076. */
  21077. class JUCE_API PopupMenu
  21078. {
  21079. public:
  21080. /** Creates an empty popup menu. */
  21081. PopupMenu() throw();
  21082. /** Creates a copy of another menu. */
  21083. PopupMenu (const PopupMenu& other) throw();
  21084. /** Destructor. */
  21085. ~PopupMenu() throw();
  21086. /** Copies this menu from another one. */
  21087. const PopupMenu& operator= (const PopupMenu& other) throw();
  21088. /** Resets the menu, removing all its items. */
  21089. void clear() throw();
  21090. /** Appends a new text item for this menu to show.
  21091. @param itemResultId the number that will be returned from the show() method
  21092. if the user picks this item. The value should never be
  21093. zero, because that's used to indicate that the user didn't
  21094. select anything.
  21095. @param itemText the text to show.
  21096. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21097. picked
  21098. @param isTicked if true, the item will be shown with a tick next to it
  21099. @param iconToUse if this is non-zero, it should be an image that will be
  21100. displayed to the left of the item. This method will take its
  21101. own copy of the image passed-in, so there's no need to keep
  21102. it hanging around.
  21103. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21104. */
  21105. void addItem (const int itemResultId,
  21106. const String& itemText,
  21107. const bool isActive = true,
  21108. const bool isTicked = false,
  21109. const Image* const iconToUse = 0) throw();
  21110. /** Adds an item that represents one of the commands in a command manager object.
  21111. @param commandManager the manager to use to trigger the command and get information
  21112. about it
  21113. @param commandID the ID of the command
  21114. @param displayName if this is non-empty, then this string will be used instead of
  21115. the command's registered name
  21116. */
  21117. void addCommandItem (ApplicationCommandManager* commandManager,
  21118. const int commandID,
  21119. const String& displayName = String::empty) throw();
  21120. /** Appends a text item with a special colour.
  21121. This is the same as addItem(), but specifies a colour to use for the
  21122. text, which will override the default colours that are used by the
  21123. current look-and-feel. See addItem() for a description of the parameters.
  21124. */
  21125. void addColouredItem (const int itemResultId,
  21126. const String& itemText,
  21127. const Colour& itemTextColour,
  21128. const bool isActive = true,
  21129. const bool isTicked = false,
  21130. const Image* const iconToUse = 0) throw();
  21131. /** Appends a custom menu item.
  21132. This will add a user-defined component to use as a menu item. The component
  21133. passed in will be deleted by this menu when it's no longer needed.
  21134. @see PopupMenuCustomComponent
  21135. */
  21136. void addCustomItem (const int itemResultId,
  21137. PopupMenuCustomComponent* const customComponent) throw();
  21138. /** Appends a custom menu item that can't be used to trigger a result.
  21139. This will add a user-defined component to use as a menu item. Unlike the
  21140. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21141. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21142. delete the component when it's finished, so it's the caller's responsibility
  21143. to manage the component that is passed-in.
  21144. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21145. detection of a mouse-click on your component, and use that to trigger the
  21146. menu ID specified in itemResultId. If this is false, the menu item can't
  21147. be triggered, so itemResultId is not used.
  21148. @see PopupMenuCustomComponent
  21149. */
  21150. void addCustomItem (const int itemResultId,
  21151. Component* customComponent,
  21152. int idealWidth, int idealHeight,
  21153. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21154. /** Appends a sub-menu.
  21155. If the menu that's passed in is empty, it will appear as an inactive item.
  21156. */
  21157. void addSubMenu (const String& subMenuName,
  21158. const PopupMenu& subMenu,
  21159. const bool isActive = true,
  21160. Image* const iconToUse = 0,
  21161. const bool isTicked = false) throw();
  21162. /** Appends a separator to the menu, to help break it up into sections.
  21163. The menu class is smart enough not to display separators at the top or bottom
  21164. of the menu, and it will replace mutliple adjacent separators with a single
  21165. one, so your code can be quite free and easy about adding these, and it'll
  21166. always look ok.
  21167. */
  21168. void addSeparator() throw();
  21169. /** Adds a non-clickable text item to the menu.
  21170. This is a bold-font items which can be used as a header to separate the items
  21171. into named groups.
  21172. */
  21173. void addSectionHeader (const String& title) throw();
  21174. /** Returns the number of items that the menu currently contains.
  21175. (This doesn't count separators).
  21176. */
  21177. int getNumItems() const throw();
  21178. /** Returns true if the menu contains a command item that triggers the given command. */
  21179. bool containsCommandItem (const int commandID) const throw();
  21180. /** Returns true if the menu contains any items that can be used. */
  21181. bool containsAnyActiveItems() const throw();
  21182. /** Displays the menu and waits for the user to pick something.
  21183. This will display the menu modally, and return the ID of the item that the
  21184. user picks. If they click somewhere off the menu to get rid of it without
  21185. choosing anything, this will return 0.
  21186. The current location of the mouse will be used as the position to show the
  21187. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21188. on where this point is on the screen, the menu will appear above, below or
  21189. to the side of the point.
  21190. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21191. then when the menu first appears, it will make sure
  21192. that this item is visible. So if the menu has too many
  21193. items to fit on the screen, it will be scrolled to a
  21194. position where this item is visible.
  21195. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21196. than this if some items are too long to fit.
  21197. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21198. vertical column, the menu may be laid out as a series of
  21199. columns - this is the maximum number allowed. To use the
  21200. default value for this (probably about 7), you can pass
  21201. in zero.
  21202. @param standardItemHeight if this is non-zero, it will be used as the standard
  21203. height for menu items (apart from custom items)
  21204. @see showAt
  21205. */
  21206. int show (const int itemIdThatMustBeVisible = 0,
  21207. const int minimumWidth = 0,
  21208. const int maximumNumColumns = 0,
  21209. const int standardItemHeight = 0);
  21210. /** Displays the menu at a specific location.
  21211. This is the same as show(), but uses a specific location (in global screen
  21212. co-ordinates) rather than the current mouse position.
  21213. Note that the co-ordinates don't specify the top-left of the menu - they
  21214. indicate a point of interest, and the menu will position itself nearby to
  21215. this point, trying to keep it fully on-screen.
  21216. @see show()
  21217. */
  21218. int showAt (const int screenX,
  21219. const int screenY,
  21220. const int itemIdThatMustBeVisible = 0,
  21221. const int minimumWidth = 0,
  21222. const int maximumNumColumns = 0,
  21223. const int standardItemHeight = 0);
  21224. /** Displays the menu as if it's attached to a component such as a button.
  21225. This is similar to showAt(), but will position it next to the given component, e.g.
  21226. so that the menu's edge is aligned with that of the component. This is intended for
  21227. things like buttons that trigger a pop-up menu.
  21228. */
  21229. int showAt (Component* componentToAttachTo,
  21230. const int itemIdThatMustBeVisible = 0,
  21231. const int minimumWidth = 0,
  21232. const int maximumNumColumns = 0,
  21233. const int standardItemHeight = 0);
  21234. /** Closes any menus that are currently open.
  21235. This might be useful if you have a situation where your window is being closed
  21236. by some means other than a user action, and you'd like to make sure that menus
  21237. aren't left hanging around.
  21238. */
  21239. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21240. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21241. This can be called before show() if you need a customised menu. Be careful
  21242. not to delete the LookAndFeel object before the menu has been deleted.
  21243. */
  21244. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21245. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21246. These constants can be used either via the LookAndFeel::setColour()
  21247. method for the look and feel that is set for this menu with setLookAndFeel()
  21248. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21249. */
  21250. enum ColourIds
  21251. {
  21252. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21253. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21254. colour is specified when the item is added). */
  21255. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21256. addSectionHeader() method). */
  21257. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21258. highlighted menu item. */
  21259. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21260. highlighted item. */
  21261. };
  21262. /**
  21263. Allows you to iterate through the items in a pop-up menu, and examine
  21264. their properties.
  21265. To use this, just create one and repeatedly call its next() method. When this
  21266. returns true, all the member variables of the iterator are filled-out with
  21267. information describing the menu item. When it returns false, the end of the
  21268. list has been reached.
  21269. */
  21270. class JUCE_API MenuItemIterator
  21271. {
  21272. public:
  21273. /** Creates an iterator that will scan through the items in the specified
  21274. menu.
  21275. Be careful not to add any items to a menu while it is being iterated,
  21276. or things could get out of step.
  21277. */
  21278. MenuItemIterator (const PopupMenu& menu) throw();
  21279. /** Destructor. */
  21280. ~MenuItemIterator() throw();
  21281. /** Returns true if there is another item, and sets up all this object's
  21282. member variables to reflect that item's properties.
  21283. */
  21284. bool next() throw();
  21285. String itemName;
  21286. const PopupMenu* subMenu;
  21287. int itemId;
  21288. bool isSeparator;
  21289. bool isTicked;
  21290. bool isEnabled;
  21291. bool isCustomComponent;
  21292. bool isSectionHeader;
  21293. const Colour* customColour;
  21294. const Image* customImage;
  21295. ApplicationCommandManager* commandManager;
  21296. juce_UseDebuggingNewOperator
  21297. private:
  21298. const PopupMenu& menu;
  21299. int index;
  21300. MenuItemIterator (const MenuItemIterator&);
  21301. const MenuItemIterator& operator= (const MenuItemIterator&);
  21302. };
  21303. juce_UseDebuggingNewOperator
  21304. private:
  21305. friend class PopupMenuWindow;
  21306. friend class MenuItemIterator;
  21307. VoidArray items;
  21308. LookAndFeel* lookAndFeel;
  21309. bool separatorPending;
  21310. void addSeparatorIfPending();
  21311. int showMenu (const int x, const int y, const int w, const int h,
  21312. const int itemIdThatMustBeVisible,
  21313. const int minimumWidth,
  21314. const int maximumNumColumns,
  21315. const int standardItemHeight,
  21316. const bool alignToRectangle,
  21317. Component* const componentAttachedTo) throw();
  21318. friend class MenuBarComponent;
  21319. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21320. const int itemIdThatMustBeVisible,
  21321. const int minimumWidth,
  21322. const int maximumNumColumns,
  21323. const int standardItemHeight,
  21324. const bool alignToRectangle,
  21325. Component* menuBarComponent,
  21326. ApplicationCommandManager** managerOfChosenCommand,
  21327. Component* const componentAttachedTo) throw();
  21328. };
  21329. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21330. /********* End of inlined file: juce_PopupMenu.h *********/
  21331. /**
  21332. Manages a list of plugin types.
  21333. This can be easily edited, saved and loaded, and used to create instances of
  21334. the plugin types in it.
  21335. @see PluginListComponent
  21336. */
  21337. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21338. {
  21339. public:
  21340. /** Creates an empty list.
  21341. */
  21342. KnownPluginList();
  21343. /** Destructor. */
  21344. ~KnownPluginList();
  21345. /** Clears the list. */
  21346. void clear();
  21347. /** Returns the number of types currently in the list.
  21348. @see getType
  21349. */
  21350. int getNumTypes() const throw() { return types.size(); }
  21351. /** Returns one of the types.
  21352. @see getNumTypes
  21353. */
  21354. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21355. /** Looks for a type in the list which comes from this file.
  21356. */
  21357. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21358. /** Looks for a type in the list which matches a plugin type ID.
  21359. The identifierString parameter must have been created by
  21360. PluginDescription::createIdentifierString().
  21361. */
  21362. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21363. /** Adds a type manually from its description. */
  21364. bool addType (const PluginDescription& type);
  21365. /** Removes a type. */
  21366. void removeType (const int index) throw();
  21367. /** Looks for all types that can be loaded from a given file, and adds them
  21368. to the list.
  21369. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21370. re-tested if it's not already in the list, or if the file's modification
  21371. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21372. false, the file will always be reloaded and tested.
  21373. Returns true if any new types were added, and all the types found in this
  21374. file (even if it was already known and hasn't been re-scanned) get returned
  21375. in the array.
  21376. */
  21377. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21378. const bool dontRescanIfAlreadyInList,
  21379. OwnedArray <PluginDescription>& typesFound,
  21380. AudioPluginFormat& formatToUse);
  21381. /** Returns true if the specified file is already known about and if it
  21382. hasn't been modified since our entry was created.
  21383. */
  21384. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21385. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21386. If any types are found in the files, their descriptions are returned in the array.
  21387. */
  21388. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21389. OwnedArray <PluginDescription>& typesFound);
  21390. /** Sort methods used to change the order of the plugins in the list.
  21391. */
  21392. enum SortMethod
  21393. {
  21394. defaultOrder = 0,
  21395. sortAlphabetically,
  21396. sortByCategory,
  21397. sortByManufacturer,
  21398. sortByFileSystemLocation
  21399. };
  21400. /** Adds all the plugin types to a popup menu so that the user can select one.
  21401. Depending on the sort method, it may add sub-menus for categories,
  21402. manufacturers, etc.
  21403. Use getIndexChosenByMenu() to find out the type that was chosen.
  21404. */
  21405. void addToMenu (PopupMenu& menu,
  21406. const SortMethod sortMethod) const;
  21407. /** Converts a menu item index that has been chosen into its index in this list.
  21408. Returns -1 if it's not an ID that was used.
  21409. @see addToMenu
  21410. */
  21411. int getIndexChosenByMenu (const int menuResultCode) const;
  21412. /** Sorts the list. */
  21413. void sort (const SortMethod method);
  21414. /** Creates some XML that can be used to store the state of this list.
  21415. */
  21416. XmlElement* createXml() const;
  21417. /** Recreates the state of this list from its stored XML format.
  21418. */
  21419. void recreateFromXml (const XmlElement& xml);
  21420. juce_UseDebuggingNewOperator
  21421. private:
  21422. OwnedArray <PluginDescription> types;
  21423. KnownPluginList (const KnownPluginList&);
  21424. const KnownPluginList& operator= (const KnownPluginList&);
  21425. };
  21426. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21427. /********* End of inlined file: juce_KnownPluginList.h *********/
  21428. /**
  21429. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21430. Use one of these objects if you want to wire-up a set of AudioProcessors
  21431. and play back the result.
  21432. Processors can be added to the graph as "nodes" using addNode(), and once
  21433. added, you can connect any of their input or output channels to other
  21434. nodes using addConnection().
  21435. To play back a graph through an audio device, you might want to use an
  21436. AudioProcessorPlayer object.
  21437. */
  21438. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21439. public AsyncUpdater
  21440. {
  21441. public:
  21442. /** Creates an empty graph.
  21443. */
  21444. AudioProcessorGraph();
  21445. /** Destructor.
  21446. Any processor objects that have been added to the graph will also be deleted.
  21447. */
  21448. ~AudioProcessorGraph();
  21449. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21450. To create a node, call AudioProcessorGraph::addNode().
  21451. */
  21452. class Node : public ReferenceCountedObject
  21453. {
  21454. public:
  21455. /** Destructor.
  21456. */
  21457. ~Node();
  21458. /** The ID number assigned to this node.
  21459. This is assigned by the graph that owns it, and can't be changed.
  21460. */
  21461. const uint32 id;
  21462. /** The actual processor object that this node represents.
  21463. */
  21464. AudioProcessor* const processor;
  21465. /** A set of user-definable properties that are associated with this node.
  21466. This can be used to attach values to the node for whatever purpose seems
  21467. useful. For example, you might store an x and y position if your application
  21468. is displaying the nodes on-screen.
  21469. */
  21470. PropertySet properties;
  21471. /** A convenient typedef for referring to a pointer to a node object.
  21472. */
  21473. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21474. juce_UseDebuggingNewOperator
  21475. private:
  21476. friend class AudioProcessorGraph;
  21477. bool isPrepared;
  21478. Node (const uint32 id, AudioProcessor* const processor) throw();
  21479. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21480. void unprepare();
  21481. Node (const Node&);
  21482. const Node& operator= (const Node&);
  21483. };
  21484. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21485. To create a connection, use AudioProcessorGraph::addConnection().
  21486. */
  21487. struct Connection
  21488. {
  21489. public:
  21490. /** The ID number of the node which is the input source for this connection.
  21491. @see AudioProcessorGraph::getNodeForId
  21492. */
  21493. uint32 sourceNodeId;
  21494. /** The index of the output channel of the source node from which this
  21495. connection takes its data.
  21496. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21497. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21498. index of an audio output channel in the source node.
  21499. */
  21500. int sourceChannelIndex;
  21501. /** The ID number of the node which is the destination for this connection.
  21502. @see AudioProcessorGraph::getNodeForId
  21503. */
  21504. uint32 destNodeId;
  21505. /** The index of the input channel of the destination node to which this
  21506. connection delivers its data.
  21507. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21508. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21509. index of an audio input channel in the destination node.
  21510. */
  21511. int destChannelIndex;
  21512. juce_UseDebuggingNewOperator
  21513. private:
  21514. };
  21515. /** Deletes all nodes and connections from this graph.
  21516. Any processor objects in the graph will be deleted.
  21517. */
  21518. void clear();
  21519. /** Returns the number of nodes in the graph. */
  21520. int getNumNodes() const throw() { return nodes.size(); }
  21521. /** Returns a pointer to one of the nodes in the graph.
  21522. This will return 0 if the index is out of range.
  21523. @see getNodeForId
  21524. */
  21525. Node* getNode (const int index) const throw() { return nodes [index]; }
  21526. /** Searches the graph for a node with the given ID number and returns it.
  21527. If no such node was found, this returns 0.
  21528. @see getNode
  21529. */
  21530. Node* getNodeForId (const uint32 nodeId) const throw();
  21531. /** Adds a node to the graph.
  21532. This creates a new node in the graph, for the specified processor. Once you have
  21533. added a processor to the graph, the graph owns it and will delete it later when
  21534. it is no longer needed.
  21535. The optional nodeId parameter lets you specify an ID to use for the node, but
  21536. if the value is already in use, this new node will overwrite the old one.
  21537. If this succeeds, it returns a pointer to the newly-created node.
  21538. */
  21539. Node* addNode (AudioProcessor* const newProcessor,
  21540. uint32 nodeId = 0);
  21541. /** Deletes a node within the graph which has the specified ID.
  21542. This will also delete any connections that are attached to this node.
  21543. */
  21544. bool removeNode (const uint32 nodeId);
  21545. /** Returns the number of connections in the graph. */
  21546. int getNumConnections() const throw() { return connections.size(); }
  21547. /** Returns a pointer to one of the connections in the graph. */
  21548. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21549. /** Searches for a connection between some specified channels.
  21550. If no such connection is found, this returns 0.
  21551. */
  21552. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21553. const int sourceChannelIndex,
  21554. const uint32 destNodeId,
  21555. const int destChannelIndex) const throw();
  21556. /** Returns true if there is a connection between any of the channels of
  21557. two specified nodes.
  21558. */
  21559. bool isConnected (const uint32 possibleSourceNodeId,
  21560. const uint32 possibleDestNodeId) const throw();
  21561. /** Returns true if it would be legal to connect the specified points.
  21562. */
  21563. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21564. const uint32 destNodeId, const int destChannelIndex) const throw();
  21565. /** Attempts to connect two specified channels of two nodes.
  21566. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21567. to an audio one or other such nonsense), then it'll return false.
  21568. */
  21569. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21570. const uint32 destNodeId, const int destChannelIndex);
  21571. /** Deletes the connection with the specified index.
  21572. Returns true if a connection was actually deleted.
  21573. */
  21574. void removeConnection (const int index);
  21575. /** Deletes any connection between two specified points.
  21576. Returns true if a connection was actually deleted.
  21577. */
  21578. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21579. const uint32 destNodeId, const int destChannelIndex);
  21580. /** Removes all connections from the specified node.
  21581. */
  21582. bool disconnectNode (const uint32 nodeId);
  21583. /** Performs a sanity checks of all the connections.
  21584. This might be useful if some of the processors are doing things like changing
  21585. their channel counts, which could render some connections obsolete.
  21586. */
  21587. bool removeIllegalConnections();
  21588. /** A special number that represents the midi channel of a node.
  21589. This is used as a channel index value if you want to refer to the midi input
  21590. or output instead of an audio channel.
  21591. */
  21592. static const int midiChannelIndex;
  21593. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21594. in order to use the audio that comes into and out of the graph itself.
  21595. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21596. node in the graph which delivers the audio that is coming into the parent
  21597. graph. This allows you to stream the data to other nodes and process the
  21598. incoming audio.
  21599. Likewise, one of these in "output" mode can be sent data which it will add to
  21600. the sum of data being sent to the graph's output.
  21601. @see AudioProcessorGraph
  21602. */
  21603. class AudioGraphIOProcessor : public AudioPluginInstance
  21604. {
  21605. public:
  21606. /** Specifies the mode in which this processor will operate.
  21607. */
  21608. enum IODeviceType
  21609. {
  21610. audioInputNode, /**< In this mode, the processor has output channels
  21611. representing all the audio input channels that are
  21612. coming into its parent audio graph. */
  21613. audioOutputNode, /**< In this mode, the processor has input channels
  21614. representing all the audio output channels that are
  21615. going out of its parent audio graph. */
  21616. midiInputNode, /**< In this mode, the processor has a midi output which
  21617. delivers the same midi data that is arriving at its
  21618. parent graph. */
  21619. midiOutputNode /**< In this mode, the processor has a midi input and
  21620. any data sent to it will be passed out of the parent
  21621. graph. */
  21622. };
  21623. /** Returns the mode of this processor. */
  21624. IODeviceType getType() const throw() { return type; }
  21625. /** Returns the parent graph to which this processor belongs, or 0 if it
  21626. hasn't yet been added to one. */
  21627. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21628. /** True if this is an audio or midi input. */
  21629. bool isInput() const throw();
  21630. /** True if this is an audio or midi output. */
  21631. bool isOutput() const throw();
  21632. AudioGraphIOProcessor (const IODeviceType type);
  21633. ~AudioGraphIOProcessor();
  21634. const String getName() const;
  21635. void fillInPluginDescription (PluginDescription& d) const;
  21636. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21637. void releaseResources();
  21638. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21639. const String getInputChannelName (const int channelIndex) const;
  21640. const String getOutputChannelName (const int channelIndex) const;
  21641. bool isInputChannelStereoPair (int index) const;
  21642. bool isOutputChannelStereoPair (int index) const;
  21643. bool acceptsMidi() const;
  21644. bool producesMidi() const;
  21645. AudioProcessorEditor* createEditor();
  21646. int getNumParameters();
  21647. const String getParameterName (int);
  21648. float getParameter (int);
  21649. const String getParameterText (int);
  21650. void setParameter (int, float);
  21651. int getNumPrograms();
  21652. int getCurrentProgram();
  21653. void setCurrentProgram (int);
  21654. const String getProgramName (int);
  21655. void changeProgramName (int, const String&);
  21656. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21657. void setStateInformation (const void* data, int sizeInBytes);
  21658. /** @internal */
  21659. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21660. juce_UseDebuggingNewOperator
  21661. private:
  21662. const IODeviceType type;
  21663. AudioProcessorGraph* graph;
  21664. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21665. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21666. };
  21667. // AudioProcessor methods:
  21668. const String getName() const;
  21669. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21670. void releaseResources();
  21671. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21672. const String getInputChannelName (const int channelIndex) const;
  21673. const String getOutputChannelName (const int channelIndex) const;
  21674. bool isInputChannelStereoPair (int index) const;
  21675. bool isOutputChannelStereoPair (int index) const;
  21676. bool acceptsMidi() const;
  21677. bool producesMidi() const;
  21678. AudioProcessorEditor* createEditor() { return 0; }
  21679. int getNumParameters() { return 0; }
  21680. const String getParameterName (int) { return String::empty; }
  21681. float getParameter (int) { return 0; }
  21682. const String getParameterText (int) { return String::empty; }
  21683. void setParameter (int, float) { }
  21684. int getNumPrograms() { return 0; }
  21685. int getCurrentProgram() { return 0; }
  21686. void setCurrentProgram (int) { }
  21687. const String getProgramName (int) { return String::empty; }
  21688. void changeProgramName (int, const String&) { }
  21689. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21690. void setStateInformation (const void* data, int sizeInBytes);
  21691. /** @internal */
  21692. void handleAsyncUpdate();
  21693. juce_UseDebuggingNewOperator
  21694. private:
  21695. ReferenceCountedArray <Node> nodes;
  21696. OwnedArray <Connection> connections;
  21697. int lastNodeId;
  21698. AudioSampleBuffer renderingBuffers;
  21699. OwnedArray <MidiBuffer> midiBuffers;
  21700. CriticalSection renderLock;
  21701. VoidArray renderingOps;
  21702. friend class AudioGraphIOProcessor;
  21703. AudioSampleBuffer* currentAudioInputBuffer;
  21704. AudioSampleBuffer currentAudioOutputBuffer;
  21705. MidiBuffer* currentMidiInputBuffer;
  21706. MidiBuffer currentMidiOutputBuffer;
  21707. void clearRenderingSequence();
  21708. void buildRenderingSequence();
  21709. bool isAnInputTo (const uint32 possibleInputId,
  21710. const uint32 possibleDestinationId,
  21711. const int recursionCheck) const throw();
  21712. AudioProcessorGraph (const AudioProcessorGraph&);
  21713. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21714. };
  21715. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21716. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21717. #endif
  21718. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21719. #endif
  21720. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21721. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21722. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21723. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21724. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21725. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21726. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21727. class AudioIODevice;
  21728. /**
  21729. One of these is passed to an AudioIODevice object to stream the audio data
  21730. in and out.
  21731. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21732. method on its own high-priority audio thread, when it needs to send or receive
  21733. the next block of data.
  21734. @see AudioIODevice, AudioDeviceManager
  21735. */
  21736. class JUCE_API AudioIODeviceCallback
  21737. {
  21738. public:
  21739. /** Destructor. */
  21740. virtual ~AudioIODeviceCallback() {}
  21741. /** Processes a block of incoming and outgoing audio data.
  21742. The subclass's implementation should use the incoming audio for whatever
  21743. purposes it needs to, and must fill all the output channels with the next
  21744. block of output data before returning.
  21745. The channel data is arranged with the same array indices as the channel name
  21746. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21747. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21748. associated channel, so remember to check for this.
  21749. @param inputChannelData a set of arrays containing the audio data for each
  21750. incoming channel - this data is valid until the function
  21751. returns. There will be one channel of data for each input
  21752. channel that was enabled when the audio device was opened
  21753. (see AudioIODevice::open())
  21754. @param numInputChannels the number of pointers to channel data in the
  21755. inputChannelData array.
  21756. @param outputChannelData a set of arrays which need to be filled with the data
  21757. that should be sent to each outgoing channel of the device.
  21758. There will be one channel of data for each output channel
  21759. that was enabled when the audio device was opened (see
  21760. AudioIODevice::open())
  21761. The initial contents of the array is undefined, so the
  21762. callback function must fill all the channels with zeros if
  21763. its output is silence. Failing to do this could cause quite
  21764. an unpleasant noise!
  21765. @param numOutputChannels the number of pointers to channel data in the
  21766. outputChannelData array.
  21767. @param numSamples the number of samples in each channel of the input and
  21768. output arrays. The number of samples will depend on the
  21769. audio device's buffer size and will usually remain constant,
  21770. although this isn't guaranteed, so make sure your code can
  21771. cope with reasonable changes in the buffer size from one
  21772. callback to the next.
  21773. */
  21774. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21775. int numInputChannels,
  21776. float** outputChannelData,
  21777. int numOutputChannels,
  21778. int numSamples) = 0;
  21779. /** Called to indicate that the device is about to start calling back.
  21780. This will be called just before the audio callbacks begin, either when this
  21781. callback has just been added to an audio device, or after the device has been
  21782. restarted because of a sample-rate or block-size change.
  21783. You can use this opportunity to find out the sample rate and block size
  21784. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21785. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21786. @param device the audio IO device that will be used to drive the callback.
  21787. Note that if you're going to store this this pointer, it is
  21788. only valid until the next time that audioDeviceStopped is called.
  21789. */
  21790. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21791. /** Called to indicate that the device has stopped.
  21792. */
  21793. virtual void audioDeviceStopped() = 0;
  21794. };
  21795. /**
  21796. Base class for an audio device with synchronised input and output channels.
  21797. Subclasses of this are used to implement different protocols such as DirectSound,
  21798. ASIO, CoreAudio, etc.
  21799. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21800. documentation for that class for more info.
  21801. For an easier way of managing audio devices and their settings, have a look at the
  21802. AudioDeviceManager class.
  21803. @see AudioIODeviceType, AudioDeviceManager
  21804. */
  21805. class JUCE_API AudioIODevice
  21806. {
  21807. public:
  21808. /** Destructor. */
  21809. virtual ~AudioIODevice();
  21810. /** Returns the device's name, (as set in the constructor). */
  21811. const String& getName() const throw() { return name; }
  21812. /** Returns the type of the device.
  21813. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21814. */
  21815. const String& getTypeName() const throw() { return typeName; }
  21816. /** Returns the names of all the available output channels on this device.
  21817. To find out which of these are currently in use, call getActiveOutputChannels().
  21818. */
  21819. virtual const StringArray getOutputChannelNames() = 0;
  21820. /** Returns the names of all the available input channels on this device.
  21821. To find out which of these are currently in use, call getActiveInputChannels().
  21822. */
  21823. virtual const StringArray getInputChannelNames() = 0;
  21824. /** Returns the number of sample-rates this device supports.
  21825. To find out which rates are available on this device, use this method to
  21826. find out how many there are, and getSampleRate() to get the rates.
  21827. @see getSampleRate
  21828. */
  21829. virtual int getNumSampleRates() = 0;
  21830. /** Returns one of the sample-rates this device supports.
  21831. To find out which rates are available on this device, use getNumSampleRates() to
  21832. find out how many there are, and getSampleRate() to get the individual rates.
  21833. The sample rate is set by the open() method.
  21834. (Note that for DirectSound some rates might not work, depending on combinations
  21835. of i/o channels that are being opened).
  21836. @see getNumSampleRates
  21837. */
  21838. virtual double getSampleRate (int index) = 0;
  21839. /** Returns the number of sizes of buffer that are available.
  21840. @see getBufferSizeSamples, getDefaultBufferSize
  21841. */
  21842. virtual int getNumBufferSizesAvailable() = 0;
  21843. /** Returns one of the possible buffer-sizes.
  21844. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21845. @returns a number of samples
  21846. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21847. */
  21848. virtual int getBufferSizeSamples (int index) = 0;
  21849. /** Returns the default buffer-size to use.
  21850. @returns a number of samples
  21851. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21852. */
  21853. virtual int getDefaultBufferSize() = 0;
  21854. /** Tries to open the device ready to play.
  21855. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21856. input channel should be enabled
  21857. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  21858. output channel should be enabled
  21859. @param sampleRate the sample rate to try to use - to find out which rates are
  21860. available, see getNumSampleRates() and getSampleRate()
  21861. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  21862. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  21863. @returns an error description if there's a problem, or an empty string if it succeeds in
  21864. opening the device
  21865. @see close
  21866. */
  21867. virtual const String open (const BitArray& inputChannels,
  21868. const BitArray& outputChannels,
  21869. double sampleRate,
  21870. int bufferSizeSamples) = 0;
  21871. /** Closes and releases the device if it's open. */
  21872. virtual void close() = 0;
  21873. /** Returns true if the device is still open.
  21874. A device might spontaneously close itself if something goes wrong, so this checks if
  21875. it's still open.
  21876. */
  21877. virtual bool isOpen() = 0;
  21878. /** Starts the device actually playing.
  21879. This must be called after the device has been opened.
  21880. @param callback the callback to use for streaming the data.
  21881. @see AudioIODeviceCallback, open
  21882. */
  21883. virtual void start (AudioIODeviceCallback* callback) = 0;
  21884. /** Stops the device playing.
  21885. Once a device has been started, this will stop it. Any pending calls to the
  21886. callback class will be flushed before this method returns.
  21887. */
  21888. virtual void stop() = 0;
  21889. /** Returns true if the device is still calling back.
  21890. The device might mysteriously stop, so this checks whether it's
  21891. still playing.
  21892. */
  21893. virtual bool isPlaying() = 0;
  21894. /** Returns the last error that happened if anything went wrong. */
  21895. virtual const String getLastError() = 0;
  21896. /** Returns the buffer size that the device is currently using.
  21897. If the device isn't actually open, this value doesn't really mean much.
  21898. */
  21899. virtual int getCurrentBufferSizeSamples() = 0;
  21900. /** Returns the sample rate that the device is currently using.
  21901. If the device isn't actually open, this value doesn't really mean much.
  21902. */
  21903. virtual double getCurrentSampleRate() = 0;
  21904. /** Returns the device's current physical bit-depth.
  21905. If the device isn't actually open, this value doesn't really mean much.
  21906. */
  21907. virtual int getCurrentBitDepth() = 0;
  21908. /** Returns a mask showing which of the available output channels are currently
  21909. enabled.
  21910. @see getOutputChannelNames
  21911. */
  21912. virtual const BitArray getActiveOutputChannels() const = 0;
  21913. /** Returns a mask showing which of the available input channels are currently
  21914. enabled.
  21915. @see getInputChannelNames
  21916. */
  21917. virtual const BitArray getActiveInputChannels() const = 0;
  21918. /** Returns the device's output latency.
  21919. This is the delay in samples between a callback getting a block of data, and
  21920. that data actually getting played.
  21921. */
  21922. virtual int getOutputLatencyInSamples() = 0;
  21923. /** Returns the device's input latency.
  21924. This is the delay in samples between some audio actually arriving at the soundcard,
  21925. and the callback getting passed this block of data.
  21926. */
  21927. virtual int getInputLatencyInSamples() = 0;
  21928. /** True if this device can show a pop-up control panel for editing its settings.
  21929. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  21930. to display it.
  21931. */
  21932. virtual bool hasControlPanel() const;
  21933. /** Shows a device-specific control panel if there is one.
  21934. This should only be called for devices which return true from hasControlPanel().
  21935. */
  21936. virtual bool showControlPanel();
  21937. protected:
  21938. /** Creates a device, setting its name and type member variables. */
  21939. AudioIODevice (const String& deviceName,
  21940. const String& typeName);
  21941. /** @internal */
  21942. String name, typeName;
  21943. };
  21944. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21945. /********* End of inlined file: juce_AudioIODevice.h *********/
  21946. /**
  21947. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  21948. To use one of these, just make it the callback used by your AudioIODevice, and
  21949. give it a processor to use by calling setProcessor().
  21950. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  21951. input to send both streams through the processor.
  21952. @see AudioProcessor, AudioProcessorGraph
  21953. */
  21954. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  21955. public MidiInputCallback
  21956. {
  21957. public:
  21958. /**
  21959. */
  21960. AudioProcessorPlayer();
  21961. /** Destructor. */
  21962. virtual ~AudioProcessorPlayer();
  21963. /** Sets the processor that should be played.
  21964. The processor that is passed in will not be deleted or owned by this object.
  21965. To stop anything playing, pass in 0 to this method.
  21966. */
  21967. void setProcessor (AudioProcessor* const processorToPlay);
  21968. /** Returns the current audio processor that is being played.
  21969. */
  21970. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  21971. /** Returns a midi message collector that you can pass midi messages to if you
  21972. want them to be injected into the midi stream that is being sent to the
  21973. processor.
  21974. */
  21975. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  21976. /** @internal */
  21977. void audioDeviceIOCallback (const float** inputChannelData,
  21978. int totalNumInputChannels,
  21979. float** outputChannelData,
  21980. int totalNumOutputChannels,
  21981. int numSamples);
  21982. /** @internal */
  21983. void audioDeviceAboutToStart (AudioIODevice* device);
  21984. /** @internal */
  21985. void audioDeviceStopped();
  21986. /** @internal */
  21987. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  21988. juce_UseDebuggingNewOperator
  21989. private:
  21990. AudioProcessor* processor;
  21991. CriticalSection lock;
  21992. double sampleRate;
  21993. int blockSize;
  21994. bool isPrepared;
  21995. int numInputChans, numOutputChans;
  21996. float* channels [128];
  21997. AudioSampleBuffer tempBuffer;
  21998. MidiBuffer incomingMidi;
  21999. MidiMessageCollector messageCollector;
  22000. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22001. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22002. };
  22003. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22004. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22005. #endif
  22006. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22007. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22008. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22009. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22010. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22011. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22012. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22013. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22014. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22015. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22016. class EditableProperty;
  22017. /**
  22018. A base class for a component that goes in a PropertyPanel and displays one of
  22019. an item's properties.
  22020. Subclasses of this are used to display a property in various forms, e.g. a
  22021. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22022. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22023. A subclass must implement the refresh() method which will be called to tell the
  22024. component to update itself, and is also responsible for calling this it when the
  22025. item that it refers to is changed.
  22026. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22027. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22028. */
  22029. class JUCE_API PropertyComponent : public Component
  22030. {
  22031. public:
  22032. /** Creates a PropertyComponent.
  22033. @param propertyName the name is stored as this component's name, and is
  22034. used as the name displayed next to this component in
  22035. a property panel
  22036. @param preferredHeight the height that the component should be given - some
  22037. items may need to be larger than a normal row height.
  22038. This value can also be set if a subclass changes the
  22039. preferredHeight member variable.
  22040. */
  22041. PropertyComponent (const String& propertyName,
  22042. const int preferredHeight = 25);
  22043. /** Destructor. */
  22044. ~PropertyComponent();
  22045. /** Returns this item's preferred height.
  22046. This value is specified either in the constructor or by a subclass changing the
  22047. preferredHeight member variable.
  22048. */
  22049. int getPreferredHeight() const throw() { return preferredHeight; }
  22050. /** Updates the property component if the item it refers to has changed.
  22051. A subclass must implement this method, and other objects may call it to
  22052. force it to refresh itself.
  22053. The subclass should be economical in the amount of work is done, so for
  22054. example it should check whether it really needs to do a repaint rather than
  22055. just doing one every time this method is called, as it may be called when
  22056. the value being displayed hasn't actually changed.
  22057. */
  22058. virtual void refresh() = 0;
  22059. /** The default paint method fills the background and draws a label for the
  22060. item's name.
  22061. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22062. */
  22063. void paint (Graphics& g);
  22064. /** The default resize method positions any child component to the right of this
  22065. one, based on the look and feel's default label size.
  22066. */
  22067. void resized();
  22068. /** By default, this just repaints the component. */
  22069. void enablementChanged();
  22070. juce_UseDebuggingNewOperator
  22071. protected:
  22072. /** Used by the PropertyPanel to determine how high this component needs to be.
  22073. A subclass can update this value in its constructor but shouldn't alter it later
  22074. as changes won't necessarily be picked up.
  22075. */
  22076. int preferredHeight;
  22077. };
  22078. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22079. /********* End of inlined file: juce_PropertyComponent.h *********/
  22080. /********* Start of inlined file: juce_Viewport.h *********/
  22081. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22082. #define __JUCE_VIEWPORT_JUCEHEADER__
  22083. /********* Start of inlined file: juce_ScrollBar.h *********/
  22084. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22085. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22086. /********* Start of inlined file: juce_Button.h *********/
  22087. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22088. #define __JUCE_BUTTON_JUCEHEADER__
  22089. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22090. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22091. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22092. /********* Start of inlined file: juce_TooltipClient.h *********/
  22093. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22094. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22095. /**
  22096. Components that want to use pop-up tooltips should implement this interface.
  22097. A TooltipWindow will wait for the mouse to hover over a component that
  22098. implements the TooltipClient interface, and when it finds one, it will display
  22099. the tooltip returned by its getTooltip() method.
  22100. @see TooltipWindow, SettableTooltipClient
  22101. */
  22102. class JUCE_API TooltipClient
  22103. {
  22104. public:
  22105. /** Destructor. */
  22106. virtual ~TooltipClient() {}
  22107. /** Returns the string that this object wants to show as its tooltip. */
  22108. virtual const String getTooltip() = 0;
  22109. };
  22110. /**
  22111. An implementation of TooltipClient that stores the tooltip string and a method
  22112. for changing it.
  22113. This makes it easy to add a tooltip to a custom component, by simply adding this
  22114. as a base class and calling setTooltip().
  22115. Many of the Juce widgets already use this as a base class to implement their
  22116. tooltips.
  22117. @see TooltipClient, TooltipWindow
  22118. */
  22119. class JUCE_API SettableTooltipClient : public TooltipClient
  22120. {
  22121. public:
  22122. /** Destructor. */
  22123. virtual ~SettableTooltipClient() {}
  22124. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22125. virtual const String getTooltip() { return tooltipString; }
  22126. juce_UseDebuggingNewOperator
  22127. protected:
  22128. String tooltipString;
  22129. };
  22130. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22131. /********* End of inlined file: juce_TooltipClient.h *********/
  22132. /**
  22133. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22134. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22135. object.
  22136. The TooltipWindow object will then stay invisible, waiting until the mouse
  22137. hovers for the specified length of time - it will then see if it's currently
  22138. over a component which implements the TooltipClient interface, and if so,
  22139. it will make itself visible to show the tooltip in the appropriate place.
  22140. @see TooltipClient, SettableTooltipClient
  22141. */
  22142. class JUCE_API TooltipWindow : public Component,
  22143. private Timer
  22144. {
  22145. public:
  22146. /** Creates a tooltip window.
  22147. Make sure your app only creates one instance of this class, otherwise you'll
  22148. get multiple overlaid tooltips appearing. The window will initially be invisible
  22149. and will make itself visible when it needs to display a tip.
  22150. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22151. methods.
  22152. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22153. otherwise the tooltip will be added to the given parent
  22154. component.
  22155. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22156. before a tooltip will be shown
  22157. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22158. */
  22159. TooltipWindow (Component* parentComponent = 0,
  22160. const int millisecondsBeforeTipAppears = 700);
  22161. /** Destructor. */
  22162. ~TooltipWindow();
  22163. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22164. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22165. methods.
  22166. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22167. */
  22168. enum ColourIds
  22169. {
  22170. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22171. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22172. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22173. };
  22174. juce_UseDebuggingNewOperator
  22175. private:
  22176. const int millisecondsBeforeTipAppears;
  22177. int mouseX, mouseY, mouseClicks;
  22178. unsigned int lastMouseMoveTime, lastHideTime;
  22179. Component* lastComponentUnderMouse;
  22180. bool changedCompsSinceShown;
  22181. String tip;
  22182. void paint (Graphics& g);
  22183. void mouseEnter (const MouseEvent& e);
  22184. void timerCallback();
  22185. void showFor (Component* const c);
  22186. void hide();
  22187. TooltipWindow (const TooltipWindow&);
  22188. const TooltipWindow& operator= (const TooltipWindow&);
  22189. };
  22190. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22191. /********* End of inlined file: juce_TooltipWindow.h *********/
  22192. class Button;
  22193. /**
  22194. Used to receive callbacks when a button is clicked.
  22195. @see Button::addButtonListener, Button::removeButtonListener
  22196. */
  22197. class JUCE_API ButtonListener
  22198. {
  22199. public:
  22200. /** Destructor. */
  22201. virtual ~ButtonListener() {}
  22202. /** Called when the button is clicked. */
  22203. virtual void buttonClicked (Button* button) = 0;
  22204. /** Called when the button's state changes. */
  22205. virtual void buttonStateChanged (Button*) {}
  22206. };
  22207. /**
  22208. A base class for buttons.
  22209. This contains all the logic for button behaviours such as enabling/disabling,
  22210. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22211. and radio groups, etc.
  22212. @see TextButton, DrawableButton, ToggleButton
  22213. */
  22214. class JUCE_API Button : public Component,
  22215. public SettableTooltipClient,
  22216. public ApplicationCommandManagerListener,
  22217. private KeyListener
  22218. {
  22219. protected:
  22220. /** Creates a button.
  22221. @param buttonName the text to put in the button (the component's name is also
  22222. initially set to this string, but these can be changed later
  22223. using the setName() and setButtonText() methods)
  22224. */
  22225. Button (const String& buttonName);
  22226. public:
  22227. /** Destructor. */
  22228. virtual ~Button();
  22229. /** Changes the button's text.
  22230. @see getButtonText
  22231. */
  22232. void setButtonText (const String& newText) throw();
  22233. /** Returns the text displayed in the button.
  22234. @see setButtonText
  22235. */
  22236. const String getButtonText() const throw() { return text; }
  22237. /** Returns true if the button is currently being held down by the mouse.
  22238. @see isOver
  22239. */
  22240. bool isDown() const throw();
  22241. /** Returns true if the mouse is currently over the button.
  22242. This will be also be true if the mouse is being held down.
  22243. @see isDown
  22244. */
  22245. bool isOver() const throw();
  22246. /** A button has an on/off state associated with it, and this changes that.
  22247. By default buttons are 'off' and for simple buttons that you click to perform
  22248. an action you won't change this. Toggle buttons, however will want to
  22249. change their state when turned on or off.
  22250. @param shouldBeOn whether to set the button's toggle state to be on or
  22251. off. If it's a member of a button group, this will
  22252. always try to turn it on, and to turn off any other
  22253. buttons in the group
  22254. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22255. the button will be repainted but no notification will
  22256. be sent
  22257. @see getToggleState, setRadioGroupId
  22258. */
  22259. void setToggleState (const bool shouldBeOn,
  22260. const bool sendChangeNotification);
  22261. /** Returns true if the button in 'on'.
  22262. By default buttons are 'off' and for simple buttons that you click to perform
  22263. an action you won't change this. Toggle buttons, however will want to
  22264. change their state when turned on or off.
  22265. @see setToggleState
  22266. */
  22267. bool getToggleState() const throw() { return isOn; }
  22268. /** This tells the button to automatically flip the toggle state when
  22269. the button is clicked.
  22270. If set to true, then before the clicked() callback occurs, the toggle-state
  22271. of the button is flipped.
  22272. */
  22273. void setClickingTogglesState (const bool shouldToggle) throw();
  22274. /** Returns true if this button is set to be an automatic toggle-button.
  22275. This returns the last value that was passed to setClickingTogglesState().
  22276. */
  22277. bool getClickingTogglesState() const throw();
  22278. /** Enables the button to act as a member of a mutually-exclusive group
  22279. of 'radio buttons'.
  22280. If the group ID is set to a non-zero number, then this button will
  22281. act as part of a group of buttons with the same ID, only one of
  22282. which can be 'on' at the same time. Note that when it's part of
  22283. a group, clicking a toggle-button that's 'on' won't turn it off.
  22284. To find other buttons with the same ID, this button will search through
  22285. its sibling components for ToggleButtons, so all the buttons for a
  22286. particular group must be placed inside the same parent component.
  22287. Set the group ID back to zero if you want it to act as a normal toggle
  22288. button again.
  22289. @see getRadioGroupId
  22290. */
  22291. void setRadioGroupId (const int newGroupId);
  22292. /** Returns the ID of the group to which this button belongs.
  22293. (See setRadioGroupId() for an explanation of this).
  22294. */
  22295. int getRadioGroupId() const throw() { return radioGroupId; }
  22296. /** Registers a listener to receive events when this button's state changes.
  22297. If the listener is already registered, this will not register it again.
  22298. @see removeButtonListener
  22299. */
  22300. void addButtonListener (ButtonListener* const newListener) throw();
  22301. /** Removes a previously-registered button listener
  22302. @see addButtonListener
  22303. */
  22304. void removeButtonListener (ButtonListener* const listener) throw();
  22305. /** Causes the button to act as if it's been clicked.
  22306. This will asynchronously make the button draw itself going down and up, and
  22307. will then call back the clicked() method as if mouse was clicked on it.
  22308. @see clicked
  22309. */
  22310. virtual void triggerClick();
  22311. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22312. When the button is pressed, it will use the given manager to trigger the
  22313. command ID.
  22314. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22315. before this button is. To disable the command triggering, call this method and
  22316. pass 0 for the parameters.
  22317. If generateTooltip is true, then the button's tooltip will be automatically
  22318. generated based on the name of this command and its current shortcut key.
  22319. @see addShortcut, getCommandID
  22320. */
  22321. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22322. const int commandID,
  22323. const bool generateTooltip);
  22324. /** Returns the command ID that was set by setCommandToTrigger().
  22325. */
  22326. int getCommandID() const throw() { return commandID; }
  22327. /** Assigns a shortcut key to trigger the button.
  22328. The button registers itself with its top-level parent component for keypresses.
  22329. Note that a different way of linking buttons to keypresses is by using the
  22330. setKeyPressToTrigger() method to invoke a command - the difference being that
  22331. setting a shortcut allows the button to be temporarily linked to a keypress
  22332. only while it's on-screen.
  22333. @see clearShortcuts
  22334. */
  22335. void addShortcut (const KeyPress& key);
  22336. /** Removes all key shortcuts that had been set for this button.
  22337. @see addShortcut
  22338. */
  22339. void clearShortcuts();
  22340. /** Returns true if the given keypress is a shortcut for this button.
  22341. @see addShortcut
  22342. */
  22343. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22344. /** Sets an auto-repeat speed for the button when it is held down.
  22345. (Auto-repeat is disabled by default).
  22346. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22347. triggering the next click. If this is zero, auto-repeat
  22348. is disabled
  22349. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22350. triggered
  22351. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22352. get faster, the longer the button is held down, up to the
  22353. minimum interval specified here
  22354. */
  22355. void setRepeatSpeed (const int initialDelayInMillisecs,
  22356. const int repeatDelayInMillisecs,
  22357. const int minimumDelayInMillisecs = -1) throw();
  22358. /** Sets whether the button click should happen when the mouse is pressed or released.
  22359. By default the button is only considered to have been clicked when the mouse is
  22360. released, but setting this to true will make it call the clicked() method as soon
  22361. as the button is pressed.
  22362. This is useful if the button is being used to show a pop-up menu, as it allows
  22363. the click to be used as a drag onto the menu.
  22364. */
  22365. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22366. /** Returns the number of milliseconds since the last time the button
  22367. went into the 'down' state.
  22368. */
  22369. uint32 getMillisecondsSinceButtonDown() const throw();
  22370. /** (overridden from Component to do special stuff). */
  22371. void setVisible (bool shouldBeVisible);
  22372. /** Sets the tooltip for this button.
  22373. @see TooltipClient, TooltipWindow
  22374. */
  22375. void setTooltip (const String& newTooltip);
  22376. // (implementation of the TooltipClient method)
  22377. const String getTooltip();
  22378. /** A combination of these flags are used by setConnectedEdges().
  22379. */
  22380. enum ConnectedEdgeFlags
  22381. {
  22382. ConnectedOnLeft = 1,
  22383. ConnectedOnRight = 2,
  22384. ConnectedOnTop = 4,
  22385. ConnectedOnBottom = 8
  22386. };
  22387. /** Hints about which edges of the button might be connected to adjoining buttons.
  22388. The value passed in is a bitwise combination of any of the values in the
  22389. ConnectedEdgeFlags enum.
  22390. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22391. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22392. without rounded corners on the edges that connect. It's only a hint, so the
  22393. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22394. button.
  22395. */
  22396. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22397. /** Returns the set of flags passed into setConnectedEdges(). */
  22398. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22399. /** Indicates whether the button adjoins another one on its left edge.
  22400. @see setConnectedEdges
  22401. */
  22402. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22403. /** Indicates whether the button adjoins another one on its right edge.
  22404. @see setConnectedEdges
  22405. */
  22406. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22407. /** Indicates whether the button adjoins another one on its top edge.
  22408. @see setConnectedEdges
  22409. */
  22410. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22411. /** Indicates whether the button adjoins another one on its bottom edge.
  22412. @see setConnectedEdges
  22413. */
  22414. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22415. /** Used by setState(). */
  22416. enum ButtonState
  22417. {
  22418. buttonNormal,
  22419. buttonOver,
  22420. buttonDown
  22421. };
  22422. /** Can be used to force the button into a particular state.
  22423. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22424. from happening.
  22425. The state that you set here will only last until it is automatically changed when the mouse
  22426. enters or exits the button, or the mouse-button is pressed or released.
  22427. */
  22428. void setState (const ButtonState newState);
  22429. juce_UseDebuggingNewOperator
  22430. protected:
  22431. /** This method is called when the button has been clicked.
  22432. Subclasses can override this to perform whatever they actions they need
  22433. to do.
  22434. Alternatively, a ButtonListener can be added to the button, and these listeners
  22435. will be called when the click occurs.
  22436. @see triggerClick
  22437. */
  22438. virtual void clicked();
  22439. /** This method is called when the button has been clicked.
  22440. By default it just calls clicked(), but you might want to override it to handle
  22441. things like clicking when a modifier key is pressed, etc.
  22442. @see ModifierKeys
  22443. */
  22444. virtual void clicked (const ModifierKeys& modifiers);
  22445. /** Subclasses should override this to actually paint the button's contents.
  22446. It's better to use this than the paint method, because it gives you information
  22447. about the over/down state of the button.
  22448. @param g the graphics context to use
  22449. @param isMouseOverButton true if the button is either in the 'over' or
  22450. 'down' state
  22451. @param isButtonDown true if the button should be drawn in the 'down' position
  22452. */
  22453. virtual void paintButton (Graphics& g,
  22454. bool isMouseOverButton,
  22455. bool isButtonDown) = 0;
  22456. /** Called when the button's up/down/over state changes.
  22457. Subclasses can override this if they need to do something special when the button
  22458. goes up or down.
  22459. @see isDown, isOver
  22460. */
  22461. virtual void buttonStateChanged();
  22462. /** @internal */
  22463. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22464. /** @internal */
  22465. void handleCommandMessage (int commandId);
  22466. /** @internal */
  22467. void mouseEnter (const MouseEvent& e);
  22468. /** @internal */
  22469. void mouseExit (const MouseEvent& e);
  22470. /** @internal */
  22471. void mouseDown (const MouseEvent& e);
  22472. /** @internal */
  22473. void mouseDrag (const MouseEvent& e);
  22474. /** @internal */
  22475. void mouseUp (const MouseEvent& e);
  22476. /** @internal */
  22477. bool keyPressed (const KeyPress& key);
  22478. /** @internal */
  22479. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22480. /** @internal */
  22481. bool keyStateChanged (Component* originatingComponent);
  22482. /** @internal */
  22483. void paint (Graphics& g);
  22484. /** @internal */
  22485. void parentHierarchyChanged();
  22486. /** @internal */
  22487. void focusGained (FocusChangeType cause);
  22488. /** @internal */
  22489. void focusLost (FocusChangeType cause);
  22490. /** @internal */
  22491. void enablementChanged();
  22492. /** @internal */
  22493. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22494. /** @internal */
  22495. void applicationCommandListChanged();
  22496. private:
  22497. Array <KeyPress> shortcuts;
  22498. Component* keySource;
  22499. String text;
  22500. SortedSet <void*> buttonListeners;
  22501. friend class InternalButtonRepeatTimer;
  22502. Timer* repeatTimer;
  22503. uint32 buttonPressTime, lastTimeCallbackTime;
  22504. ApplicationCommandManager* commandManagerToUse;
  22505. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22506. int radioGroupId, commandID, connectedEdgeFlags;
  22507. ButtonState buttonState;
  22508. bool isOn : 1;
  22509. bool clickTogglesState : 1;
  22510. bool needsToRelease : 1;
  22511. bool needsRepainting : 1;
  22512. bool isKeyDown : 1;
  22513. bool triggerOnMouseDown : 1;
  22514. bool generateTooltip : 1;
  22515. void repeatTimerCallback() throw();
  22516. Timer& getRepeatTimer() throw();
  22517. ButtonState updateState (const MouseEvent* const e) throw();
  22518. bool isShortcutPressed() const throw();
  22519. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22520. void flashButtonState() throw();
  22521. void sendClickMessage (const ModifierKeys& modifiers);
  22522. void sendStateMessage();
  22523. Button (const Button&);
  22524. const Button& operator= (const Button&);
  22525. };
  22526. #endif // __JUCE_BUTTON_JUCEHEADER__
  22527. /********* End of inlined file: juce_Button.h *********/
  22528. class ScrollBar;
  22529. /**
  22530. A class for receiving events from a ScrollBar.
  22531. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22532. method, and it will be called when the bar's position changes.
  22533. @see ScrollBar::addListener, ScrollBar::removeListener
  22534. */
  22535. class JUCE_API ScrollBarListener
  22536. {
  22537. public:
  22538. /** Destructor. */
  22539. virtual ~ScrollBarListener() {}
  22540. /** Called when a ScrollBar is moved.
  22541. @param scrollBarThatHasMoved the bar that has moved
  22542. @param newRangeStart the new range start of this bar
  22543. */
  22544. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22545. const double newRangeStart) = 0;
  22546. };
  22547. /**
  22548. A scrollbar component.
  22549. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22550. sets the range of values it can represent. Then you can use setCurrentRange() to
  22551. change the position and size of the scrollbar's 'thumb'.
  22552. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22553. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22554. they moved it to.
  22555. The scrollbar will adjust its own visibility according to whether its thumb size
  22556. allows it to actually be scrolled.
  22557. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22558. instead of handling a scrollbar directly.
  22559. @see ScrollBarListener
  22560. */
  22561. class JUCE_API ScrollBar : public Component,
  22562. public AsyncUpdater,
  22563. private Timer
  22564. {
  22565. public:
  22566. /** Creates a Scrollbar.
  22567. @param isVertical whether it should be a vertical or horizontal bar
  22568. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22569. */
  22570. ScrollBar (const bool isVertical,
  22571. const bool buttonsAreVisible = true);
  22572. /** Destructor. */
  22573. ~ScrollBar();
  22574. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22575. bool isVertical() const throw() { return vertical; }
  22576. /** Changes the scrollbar's direction.
  22577. You'll also need to resize the bar appropriately - this just changes its internal
  22578. layout.
  22579. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22580. */
  22581. void setOrientation (const bool shouldBeVertical) throw();
  22582. /** Shows or hides the scrollbar's buttons. */
  22583. void setButtonVisibility (const bool buttonsAreVisible);
  22584. /** Tells the scrollbar whether to make itself invisible when not needed.
  22585. The default behaviour is for a scrollbar to become invisible when the thumb
  22586. fills the whole of its range (i.e. when it can't be moved). Setting this
  22587. value to false forces the bar to always be visible.
  22588. */
  22589. void setAutoHide (const bool shouldHideWhenFullRange);
  22590. /** Sets the minimum and maximum values that the bar will move between.
  22591. The bar's thumb will always be constrained so that the top of the thumb
  22592. will be >= minimum, and the bottom of the thumb <= maximum.
  22593. @see setCurrentRange
  22594. */
  22595. void setRangeLimits (const double minimum,
  22596. const double maximum) throw();
  22597. /** Returns the lower value that the thumb can be set to.
  22598. This is the value set by setRangeLimits().
  22599. */
  22600. double getMinimumRangeLimit() const throw() { return minimum; }
  22601. /** Returns the upper value that the thumb can be set to.
  22602. This is the value set by setRangeLimits().
  22603. */
  22604. double getMaximumRangeLimit() const throw() { return maximum; }
  22605. /** Changes the position of the scrollbar's 'thumb'.
  22606. This sets both the position and size of the thumb - to just set the position without
  22607. changing the size, you can use setCurrentRangeStart().
  22608. If this method call actually changes the scrollbar's position, it will trigger an
  22609. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22610. are registered.
  22611. @param newStart the top (or left) of the thumb, in the range
  22612. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22613. value is beyond these limits, it will be clipped.
  22614. @param newSize the size of the thumb, such that
  22615. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22616. size is beyond these limits, it will be clipped.
  22617. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22618. */
  22619. void setCurrentRange (double newStart,
  22620. double newSize) throw();
  22621. /** Moves the bar's thumb position.
  22622. This will move the thumb position without changing the thumb size. Note
  22623. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22624. If this method call actually changes the scrollbar's position, it will trigger an
  22625. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22626. are registered.
  22627. @see setCurrentRange
  22628. */
  22629. void setCurrentRangeStart (double newStart) throw();
  22630. /** Returns the position of the top of the thumb.
  22631. @see setCurrentRangeStart
  22632. */
  22633. double getCurrentRangeStart() const throw() { return rangeStart; }
  22634. /** Returns the current size of the thumb.
  22635. @see setCurrentRange
  22636. */
  22637. double getCurrentRangeSize() const throw() { return rangeSize; }
  22638. /** Sets the amount by which the up and down buttons will move the bar.
  22639. The value here is in terms of the total range, and is added or subtracted
  22640. from the thumb position when the user clicks an up/down (or left/right) button.
  22641. */
  22642. void setSingleStepSize (const double newSingleStepSize) throw();
  22643. /** Moves the scrollbar by a number of single-steps.
  22644. This will move the bar by a multiple of its single-step interval (as
  22645. specified using the setSingleStepSize() method).
  22646. A positive value here will move the bar down or to the right, a negative
  22647. value moves it up or to the left.
  22648. */
  22649. void moveScrollbarInSteps (const int howManySteps) throw();
  22650. /** Moves the scroll bar up or down in pages.
  22651. This will move the bar by a multiple of its current thumb size, effectively
  22652. doing a page-up or down.
  22653. A positive value here will move the bar down or to the right, a negative
  22654. value moves it up or to the left.
  22655. */
  22656. void moveScrollbarInPages (const int howManyPages) throw();
  22657. /** Scrolls to the top (or left).
  22658. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22659. */
  22660. void scrollToTop() throw();
  22661. /** Scrolls to the bottom (or right).
  22662. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22663. */
  22664. void scrollToBottom() throw();
  22665. /** Changes the delay before the up and down buttons autorepeat when they are held
  22666. down.
  22667. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22668. @see Button::setRepeatSpeed
  22669. */
  22670. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22671. const int repeatDelayInMillisecs,
  22672. const int minimumDelayInMillisecs = -1) throw();
  22673. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22674. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22675. methods.
  22676. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22677. */
  22678. enum ColourIds
  22679. {
  22680. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22681. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22682. 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. */
  22683. };
  22684. /** Registers a listener that will be called when the scrollbar is moved. */
  22685. void addListener (ScrollBarListener* const listener) throw();
  22686. /** Deregisters a previously-registered listener. */
  22687. void removeListener (ScrollBarListener* const listener) throw();
  22688. /** @internal */
  22689. bool keyPressed (const KeyPress& key);
  22690. /** @internal */
  22691. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22692. /** @internal */
  22693. void lookAndFeelChanged();
  22694. /** @internal */
  22695. void handleAsyncUpdate();
  22696. /** @internal */
  22697. void mouseDown (const MouseEvent& e);
  22698. /** @internal */
  22699. void mouseDrag (const MouseEvent& e);
  22700. /** @internal */
  22701. void mouseUp (const MouseEvent& e);
  22702. /** @internal */
  22703. void paint (Graphics& g);
  22704. /** @internal */
  22705. void resized();
  22706. juce_UseDebuggingNewOperator
  22707. private:
  22708. double minimum, maximum;
  22709. double rangeStart, rangeSize;
  22710. double singleStepSize, dragStartRange;
  22711. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22712. int dragStartMousePos, lastMousePos;
  22713. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22714. bool vertical, isDraggingThumb, alwaysVisible;
  22715. Button* upButton;
  22716. Button* downButton;
  22717. SortedSet <void*> listeners;
  22718. void updateThumbPosition() throw();
  22719. void timerCallback();
  22720. ScrollBar (const ScrollBar&);
  22721. const ScrollBar& operator= (const ScrollBar&);
  22722. };
  22723. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22724. /********* End of inlined file: juce_ScrollBar.h *********/
  22725. /**
  22726. A Viewport is used to contain a larger child component, and allows the child
  22727. to be automatically scrolled around.
  22728. To use a Viewport, just create one and set the component that goes inside it
  22729. using the setViewedComponent() method. When the child component changes size,
  22730. the Viewport will adjust its scrollbars accordingly.
  22731. A subclass of the viewport can be created which will receive calls to its
  22732. visibleAreaChanged() method when the subcomponent changes position or size.
  22733. */
  22734. class JUCE_API Viewport : public Component,
  22735. private ComponentListener,
  22736. private ScrollBarListener
  22737. {
  22738. public:
  22739. /** Creates a Viewport.
  22740. The viewport is initially empty - use the setViewedComponent() method to
  22741. add a child component for it to manage.
  22742. */
  22743. Viewport (const String& componentName = String::empty);
  22744. /** Destructor. */
  22745. ~Viewport();
  22746. /** Sets the component that this viewport will contain and scroll around.
  22747. This will add the given component to this Viewport and position it at
  22748. (0, 0).
  22749. (Don't add or remove any child components directly using the normal
  22750. Component::addChildComponent() methods).
  22751. @param newViewedComponent the component to add to this viewport (this pointer
  22752. may be null). The component passed in will be deleted
  22753. by the Viewport when it's no longer needed
  22754. @see getViewedComponent
  22755. */
  22756. void setViewedComponent (Component* const newViewedComponent);
  22757. /** Returns the component that's currently being used inside the Viewport.
  22758. @see setViewedComponent
  22759. */
  22760. Component* getViewedComponent() const throw() { return contentComp; }
  22761. /** Changes the position of the viewed component.
  22762. The inner component will be moved so that the pixel at the top left of
  22763. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22764. within the inner component.
  22765. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22766. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22767. */
  22768. void setViewPosition (const int xPixelsOffset,
  22769. const int yPixelsOffset);
  22770. /** Changes the view position as a proportion of the distance it can move.
  22771. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22772. visible area in the top-left, and (1, 1) would put it as far down and
  22773. to the right as it's possible to go whilst keeping the child component
  22774. on-screen.
  22775. */
  22776. void setViewPositionProportionately (const double proportionX,
  22777. const double proportionY);
  22778. /** Returns the position within the child component of the top-left of its visible area.
  22779. @see getViewWidth, setViewPosition
  22780. */
  22781. int getViewPositionX() const throw() { return lastVX; }
  22782. /** Returns the position within the child component of the top-left of its visible area.
  22783. @see getViewHeight, setViewPosition
  22784. */
  22785. int getViewPositionY() const throw() { return lastVY; }
  22786. /** Returns the width of the visible area of the child component.
  22787. This may be less than the width of this Viewport if there's a vertical scrollbar
  22788. or if the child component is itself smaller.
  22789. */
  22790. int getViewWidth() const throw() { return lastVW; }
  22791. /** Returns the height of the visible area of the child component.
  22792. This may be less than the height of this Viewport if there's a horizontal scrollbar
  22793. or if the child component is itself smaller.
  22794. */
  22795. int getViewHeight() const throw() { return lastVH; }
  22796. /** Returns the width available within this component for the contents.
  22797. This will be the width of the viewport component minus the width of a
  22798. vertical scrollbar (if visible).
  22799. */
  22800. int getMaximumVisibleWidth() const throw();
  22801. /** Returns the height available within this component for the contents.
  22802. This will be the height of the viewport component minus the space taken up
  22803. by a horizontal scrollbar (if visible).
  22804. */
  22805. int getMaximumVisibleHeight() const throw();
  22806. /** Callback method that is called when the visible area changes.
  22807. This will be called when the visible area is moved either be scrolling or
  22808. by calls to setViewPosition(), etc.
  22809. */
  22810. virtual void visibleAreaChanged (int visibleX, int visibleY,
  22811. int visibleW, int visibleH);
  22812. /** Turns scrollbars on or off.
  22813. If set to false, the scrollbars won't ever appear. When true (the default)
  22814. they will appear only when needed.
  22815. */
  22816. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  22817. const bool showHorizontalScrollbarIfNeeded);
  22818. /** True if the vertical scrollbar is enabled.
  22819. @see setScrollBarsShown
  22820. */
  22821. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  22822. /** True if the horizontal scrollbar is enabled.
  22823. @see setScrollBarsShown
  22824. */
  22825. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  22826. /** Changes the width of the scrollbars.
  22827. If this isn't specified, the default width from the LookAndFeel class will be used.
  22828. @see LookAndFeel::getDefaultScrollbarWidth
  22829. */
  22830. void setScrollBarThickness (const int thickness);
  22831. /** Returns the thickness of the scrollbars.
  22832. @see setScrollBarThickness
  22833. */
  22834. int getScrollBarThickness() const throw();
  22835. /** Changes the distance that a single-step click on a scrollbar button
  22836. will move the viewport.
  22837. */
  22838. void setSingleStepSizes (const int stepX, const int stepY);
  22839. /** Shows or hides the buttons on any scrollbars that are used.
  22840. @see ScrollBar::setButtonVisibility
  22841. */
  22842. void setScrollBarButtonVisibility (const bool buttonsVisible);
  22843. /** Returns a pointer to the scrollbar component being used.
  22844. Handy if you need to customise the bar somehow.
  22845. */
  22846. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  22847. /** Returns a pointer to the scrollbar component being used.
  22848. Handy if you need to customise the bar somehow.
  22849. */
  22850. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  22851. juce_UseDebuggingNewOperator
  22852. /** @internal */
  22853. void resized();
  22854. /** @internal */
  22855. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  22856. /** @internal */
  22857. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22858. /** @internal */
  22859. bool keyPressed (const KeyPress& key);
  22860. /** @internal */
  22861. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  22862. /** @internal */
  22863. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22864. private:
  22865. Component* contentComp;
  22866. int lastVX, lastVY, lastVW, lastVH;
  22867. int scrollBarThickness;
  22868. int singleStepX, singleStepY;
  22869. bool showHScrollbar, showVScrollbar;
  22870. Component* contentHolder;
  22871. ScrollBar* verticalScrollBar;
  22872. ScrollBar* horizontalScrollBar;
  22873. void updateVisibleRegion();
  22874. Viewport (const Viewport&);
  22875. const Viewport& operator= (const Viewport&);
  22876. };
  22877. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  22878. /********* End of inlined file: juce_Viewport.h *********/
  22879. /**
  22880. A panel that holds a list of PropertyComponent objects.
  22881. This panel displays a list of PropertyComponents, and allows them to be organised
  22882. into collapsible sections.
  22883. To use, simply create one of these and add your properties to it with addProperties()
  22884. or addSection().
  22885. @see PropertyComponent
  22886. */
  22887. class JUCE_API PropertyPanel : public Component
  22888. {
  22889. public:
  22890. /** Creates an empty property panel. */
  22891. PropertyPanel();
  22892. /** Destructor. */
  22893. ~PropertyPanel();
  22894. /** Deletes all property components from the panel.
  22895. */
  22896. void clear();
  22897. /** Adds a set of properties to the panel.
  22898. The components in the list will be owned by this object and will be automatically
  22899. deleted later on when no longer needed.
  22900. These properties are added without them being inside a named section. If you
  22901. want them to be kept together in a collapsible section, use addSection() instead.
  22902. */
  22903. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  22904. /** Adds a set of properties to the panel.
  22905. These properties are added at the bottom of the list, under a section heading with
  22906. a plus/minus button that allows it to be opened and closed.
  22907. The components in the list will be owned by this object and will be automatically
  22908. deleted later on when no longer needed.
  22909. To add properies without them being in a section, use addProperties().
  22910. */
  22911. void addSection (const String& sectionTitle,
  22912. const Array <PropertyComponent*>& newPropertyComponents,
  22913. const bool shouldSectionInitiallyBeOpen = true);
  22914. /** Calls the refresh() method of all PropertyComponents in the panel */
  22915. void refreshAll() const;
  22916. /** Returns a list of all the names of sections in the panel.
  22917. These are the sections that have been added with addSection().
  22918. */
  22919. const StringArray getSectionNames() const;
  22920. /** Returns true if the section at this index is currently open.
  22921. The index is from 0 up to the number of items returned by getSectionNames().
  22922. */
  22923. bool isSectionOpen (const int sectionIndex) const;
  22924. /** Opens or closes one of the sections.
  22925. The index is from 0 up to the number of items returned by getSectionNames().
  22926. */
  22927. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  22928. /** Enables or disables one of the sections.
  22929. The index is from 0 up to the number of items returned by getSectionNames().
  22930. */
  22931. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  22932. /** Saves the current state of open/closed sections so it can be restored later.
  22933. The caller is responsible for deleting the object that is returned.
  22934. To restore this state, use restoreOpennessState().
  22935. @see restoreOpennessState
  22936. */
  22937. XmlElement* getOpennessState() const;
  22938. /** Restores a previously saved arrangement of open/closed sections.
  22939. This will try to restore a snapshot of the panel's state that was created by
  22940. the getOpennessState() method. If any of the sections named in the original
  22941. XML aren't present, they will be ignored.
  22942. @see getOpennessState
  22943. */
  22944. void restoreOpennessState (const XmlElement& newState);
  22945. /** Sets a message to be displayed when there are no properties in the panel.
  22946. The default message is "nothing selected".
  22947. */
  22948. void setMessageWhenEmpty (const String& newMessage);
  22949. /** Returns the message that is displayed when there are no properties.
  22950. @see setMessageWhenEmpty
  22951. */
  22952. const String& getMessageWhenEmpty() const throw();
  22953. /** @internal */
  22954. void paint (Graphics& g);
  22955. /** @internal */
  22956. void resized();
  22957. juce_UseDebuggingNewOperator
  22958. private:
  22959. Viewport* viewport;
  22960. Component* propertyHolderComponent;
  22961. String messageWhenEmpty;
  22962. void updatePropHolderLayout() const;
  22963. void updatePropHolderLayout (const int width) const;
  22964. };
  22965. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  22966. /********* End of inlined file: juce_PropertyPanel.h *********/
  22967. /**
  22968. A type of UI component that displays the parameters of an AudioProcessor as
  22969. a simple list of sliders.
  22970. This can be used for showing an editor for a processor that doesn't supply
  22971. its own custom editor.
  22972. @see AudioProcessor
  22973. */
  22974. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  22975. {
  22976. public:
  22977. GenericAudioProcessorEditor (AudioProcessor* const owner);
  22978. ~GenericAudioProcessorEditor();
  22979. void paint (Graphics& g);
  22980. void resized();
  22981. juce_UseDebuggingNewOperator
  22982. private:
  22983. PropertyPanel* panel;
  22984. };
  22985. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22986. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22987. #endif
  22988. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22989. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  22990. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22991. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22992. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  22993. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22994. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22995. /********* Start of inlined file: juce_AudioSource.h *********/
  22996. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22997. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  22998. /**
  22999. Used by AudioSource::getNextAudioBlock().
  23000. */
  23001. struct JUCE_API AudioSourceChannelInfo
  23002. {
  23003. /** The destination buffer to fill with audio data.
  23004. When the AudioSource::getNextAudioBlock() method is called, the active section
  23005. of this buffer should be filled with whatever output the source produces.
  23006. Only the samples specified by the startSample and numSamples members of this structure
  23007. should be affected by the call.
  23008. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23009. method can be treated as the input if the source is performing some kind of filter operation,
  23010. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23011. a handy way of doing this.
  23012. The number of channels in the buffer could be anything, so the AudioSource
  23013. must cope with this in whatever way is appropriate for its function.
  23014. */
  23015. AudioSampleBuffer* buffer;
  23016. /** The first sample in the buffer from which the callback is expected
  23017. to write data. */
  23018. int startSample;
  23019. /** The number of samples in the buffer which the callback is expected to
  23020. fill with data. */
  23021. int numSamples;
  23022. /** Convenient method to clear the buffer if the source is not producing any data. */
  23023. void clearActiveBufferRegion() const
  23024. {
  23025. if (buffer != 0)
  23026. buffer->clear (startSample, numSamples);
  23027. }
  23028. };
  23029. /**
  23030. Base class for objects that can produce a continuous stream of audio.
  23031. @see AudioFormatReaderSource, ResamplingAudioSource
  23032. */
  23033. class JUCE_API AudioSource
  23034. {
  23035. protected:
  23036. /** Creates an AudioSource. */
  23037. AudioSource() throw() {}
  23038. public:
  23039. /** Destructor. */
  23040. virtual ~AudioSource() {}
  23041. /** Tells the source to prepare for playing.
  23042. The source can use this opportunity to initialise anything it needs to.
  23043. Note that this method could be called more than once in succession without
  23044. a matching call to releaseResources(), so make sure your code is robust and
  23045. can handle that kind of situation.
  23046. @param samplesPerBlockExpected the number of samples that the source
  23047. will be expected to supply each time its
  23048. getNextAudioBlock() method is called. This
  23049. number may vary slightly, because it will be dependent
  23050. on audio hardware callbacks, and these aren't
  23051. guaranteed to always use a constant block size, so
  23052. the source should be able to cope with small variations.
  23053. @param sampleRate the sample rate that the output will be used at - this
  23054. is needed by sources such as tone generators.
  23055. @see releaseResources, getNextAudioBlock
  23056. */
  23057. virtual void prepareToPlay (int samplesPerBlockExpected,
  23058. double sampleRate) = 0;
  23059. /** Allows the source to release anything it no longer needs after playback has stopped.
  23060. This will be called when the source is no longer going to have its getNextAudioBlock()
  23061. method called, so it should release any spare memory, etc. that it might have
  23062. allocated during the prepareToPlay() call.
  23063. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23064. releaseResources(), and it may be called more than once in succession, so make sure your
  23065. code is robust and doesn't make any assumptions about when it will be called.
  23066. @see prepareToPlay, getNextAudioBlock
  23067. */
  23068. virtual void releaseResources() = 0;
  23069. /** Called repeatedly to fetch subsequent blocks of audio data.
  23070. After calling the prepareToPlay() method, this callback will be made each
  23071. time the audio playback hardware (or whatever other destination the audio
  23072. data is going to) needs another block of data.
  23073. It will generally be called on a high-priority system thread, or possibly even
  23074. an interrupt, so be careful not to do too much work here, as that will cause
  23075. audio glitches!
  23076. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23077. */
  23078. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23079. };
  23080. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23081. /********* End of inlined file: juce_AudioSource.h *********/
  23082. /**
  23083. A type of AudioSource which can be repositioned.
  23084. The basic AudioSource just streams continuously with no idea of a current
  23085. time or length, so the PositionableAudioSource is used for a finite stream
  23086. that has a current read position.
  23087. @see AudioSource, AudioTransportSource
  23088. */
  23089. class JUCE_API PositionableAudioSource : public AudioSource
  23090. {
  23091. protected:
  23092. /** Creates the PositionableAudioSource. */
  23093. PositionableAudioSource() throw() {}
  23094. public:
  23095. /** Destructor */
  23096. ~PositionableAudioSource() {}
  23097. /** Tells the stream to move to a new position.
  23098. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23099. should return samples from this position.
  23100. Note that this may be called on a different thread to getNextAudioBlock(),
  23101. so the subclass should make sure it's synchronised.
  23102. */
  23103. virtual void setNextReadPosition (int newPosition) = 0;
  23104. /** Returns the position from which the next block will be returned.
  23105. @see setNextReadPosition
  23106. */
  23107. virtual int getNextReadPosition() const = 0;
  23108. /** Returns the total length of the stream (in samples). */
  23109. virtual int getTotalLength() const = 0;
  23110. /** Returns true if this source is actually playing in a loop. */
  23111. virtual bool isLooping() const = 0;
  23112. };
  23113. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23114. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23115. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23116. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23117. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23118. class AudioFormat;
  23119. /**
  23120. Reads samples from an audio file stream.
  23121. A subclass that reads a specific type of audio format will be created by
  23122. an AudioFormat object.
  23123. @see AudioFormat, AudioFormatWriter
  23124. */
  23125. class JUCE_API AudioFormatReader
  23126. {
  23127. protected:
  23128. /** Creates an AudioFormatReader object.
  23129. @param sourceStream the stream to read from - this will be deleted
  23130. by this object when it is no longer needed. (Some
  23131. specialised readers might not use this parameter and
  23132. can leave it as 0).
  23133. @param formatName the description that will be returned by the getFormatName()
  23134. method
  23135. */
  23136. AudioFormatReader (InputStream* const sourceStream,
  23137. const String& formatName);
  23138. public:
  23139. /** Destructor. */
  23140. virtual ~AudioFormatReader();
  23141. /** Returns a description of what type of format this is.
  23142. E.g. "AIFF"
  23143. */
  23144. const String getFormatName() const throw() { return formatName; }
  23145. /** Reads samples from the stream.
  23146. @param destSamples an array of buffers into which the sample data for each
  23147. channel will be written.
  23148. If the format is fixed-point, each channel will be written
  23149. as an array of 32-bit signed integers using the full
  23150. range -0x80000000 to 0x7fffffff, regardless of the source's
  23151. bit-depth. If it is a floating-point format, you should cast
  23152. the resulting array to a (float**) to get the values (in the
  23153. range -1.0 to 1.0 or beyond)
  23154. If the format is stereo, then destSamples[0] is the left channel
  23155. data, and destSamples[1] is the right channel.
  23156. The array passed in should be zero-terminated, and it's ok to
  23157. pass in an array with a different number of channels than
  23158. the number in the stream, so if you pass in an array with only
  23159. one channel and the stream is stereo, the reader will
  23160. put a merged sum of the stereo channels into the single
  23161. destination channel.
  23162. @param startSample the offset into the audio stream from which the samples
  23163. should be read, as a number of samples from the start of the
  23164. stream. It's ok for this to be beyond the start or end of the
  23165. available data - any samples that can't be read will be padded
  23166. with zeros.
  23167. @param numSamples the number of samples to read. If this is greater than the
  23168. number of samples available, the result will be padded with
  23169. zeros
  23170. @returns true if the operation succeeded, false if there was an error. Note
  23171. that reading sections of data beyond the extent of the stream isn't an
  23172. error - the reader should just return zeros for these regions
  23173. @see readMaxLevels
  23174. */
  23175. virtual bool read (int** destSamples,
  23176. int64 startSample,
  23177. int numSamples) = 0;
  23178. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23179. This will read a block of samples from the stream, and measure the
  23180. highest and lowest sample levels from the channels in that section, returning
  23181. these as normalised floating-point levels.
  23182. @param startSample the offset into the audio stream to start reading from. It's
  23183. ok for this to be beyond the start or end of the stream.
  23184. @param numSamples how many samples to read
  23185. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23186. @param highestLeft on return, this is the highest absolute sample from the left channel
  23187. @param lowestRight on return, this is the lowest absolute sample from the right
  23188. channel (if there is one)
  23189. @param highestRight on return, this is the highest absolute sample from the right
  23190. channel (if there is one)
  23191. @see read
  23192. */
  23193. virtual void readMaxLevels (int64 startSample,
  23194. int64 numSamples,
  23195. float& lowestLeft,
  23196. float& highestLeft,
  23197. float& lowestRight,
  23198. float& highestRight);
  23199. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23200. This will read from the source, either forwards or backwards between two sample
  23201. positions, until it finds a sample whose magnitude lies between two specified levels.
  23202. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23203. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23204. points when you're searching for a continuous range of samples
  23205. @param startSample the first sample to look at
  23206. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23207. the search will go backwards
  23208. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23209. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23210. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23211. of this many consecutive samples, all of which lie
  23212. within the target range. When it finds such a sequence,
  23213. it returns the position of the first in-range sample
  23214. it found (i.e. the earliest one if scanning forwards, the
  23215. latest one if scanning backwards)
  23216. */
  23217. int64 searchForLevel (int64 startSample,
  23218. int64 numSamplesToSearch,
  23219. const double magnitudeRangeMinimum,
  23220. const double magnitudeRangeMaximum,
  23221. const int minimumConsecutiveSamples);
  23222. /** The sample-rate of the stream. */
  23223. double sampleRate;
  23224. /** The number of bits per sample, e.g. 16, 24, 32. */
  23225. unsigned int bitsPerSample;
  23226. /** The total number of samples in the audio stream. */
  23227. int64 lengthInSamples;
  23228. /** The total number of channels in the audio stream. */
  23229. unsigned int numChannels;
  23230. /** Indicates whether the data is floating-point or fixed. */
  23231. bool usesFloatingPointData;
  23232. /** A set of metadata values that the reader has pulled out of the stream.
  23233. Exactly what these values are depends on the format, so you can
  23234. check out the format implementation code to see what kind of stuff
  23235. they understand.
  23236. */
  23237. StringPairArray metadataValues;
  23238. /** The input stream, for use by subclasses. */
  23239. InputStream* input;
  23240. juce_UseDebuggingNewOperator
  23241. private:
  23242. String formatName;
  23243. AudioFormatReader (const AudioFormatReader&);
  23244. const AudioFormatReader& operator= (const AudioFormatReader&);
  23245. };
  23246. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23247. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23248. /**
  23249. A type of AudioSource that will read from an AudioFormatReader.
  23250. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23251. */
  23252. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23253. {
  23254. public:
  23255. /** Creates an AudioFormatReaderSource for a given reader.
  23256. @param sourceReader the reader to use as the data source
  23257. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23258. when this object is deleted; if false it will be
  23259. left up to the caller to manage its lifetime
  23260. */
  23261. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23262. const bool deleteReaderWhenThisIsDeleted);
  23263. /** Destructor. */
  23264. ~AudioFormatReaderSource();
  23265. /** Toggles loop-mode.
  23266. If set to true, it will continuously loop the input source. If false,
  23267. it will just emit silence after the source has finished.
  23268. @see isLooping
  23269. */
  23270. void setLooping (const bool shouldLoop) throw();
  23271. /** Returns whether loop-mode is turned on or not. */
  23272. bool isLooping() const { return looping; }
  23273. /** Returns the reader that's being used. */
  23274. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23275. /** Implementation of the AudioSource method. */
  23276. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23277. /** Implementation of the AudioSource method. */
  23278. void releaseResources();
  23279. /** Implementation of the AudioSource method. */
  23280. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23281. /** Implements the PositionableAudioSource method. */
  23282. void setNextReadPosition (int newPosition);
  23283. /** Implements the PositionableAudioSource method. */
  23284. int getNextReadPosition() const;
  23285. /** Implements the PositionableAudioSource method. */
  23286. int getTotalLength() const;
  23287. juce_UseDebuggingNewOperator
  23288. private:
  23289. AudioFormatReader* reader;
  23290. bool deleteReader;
  23291. int volatile nextPlayPos;
  23292. bool volatile looping;
  23293. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23294. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23295. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23296. };
  23297. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23298. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23299. #endif
  23300. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23301. #endif
  23302. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23303. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23304. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23305. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23306. /**
  23307. Wrapper class to continuously stream audio from an audio source to an
  23308. AudioIODevice.
  23309. This object acts as an AudioIODeviceCallback, so can be attached to an
  23310. output device, and will stream audio from an AudioSource.
  23311. */
  23312. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23313. {
  23314. public:
  23315. /** Creates an empty AudioSourcePlayer. */
  23316. AudioSourcePlayer();
  23317. /** Destructor.
  23318. Make sure this object isn't still being used by an AudioIODevice before
  23319. deleting it!
  23320. */
  23321. virtual ~AudioSourcePlayer();
  23322. /** Changes the current audio source to play from.
  23323. If the source passed in is already being used, this method will do nothing.
  23324. If the source is not null, its prepareToPlay() method will be called
  23325. before it starts being used for playback.
  23326. If there's another source currently playing, its releaseResources() method
  23327. will be called after it has been swapped for the new one.
  23328. @param newSource the new source to use - this will NOT be deleted
  23329. by this object when no longer needed, so it's the
  23330. caller's responsibility to manage it.
  23331. */
  23332. void setSource (AudioSource* newSource);
  23333. /** Returns the source that's playing.
  23334. May return 0 if there's no source.
  23335. */
  23336. AudioSource* getCurrentSource() const throw() { return source; }
  23337. /** Sets a gain to apply to the audio data. */
  23338. void setGain (const float newGain) throw();
  23339. /** Implementation of the AudioIODeviceCallback method. */
  23340. void audioDeviceIOCallback (const float** inputChannelData,
  23341. int totalNumInputChannels,
  23342. float** outputChannelData,
  23343. int totalNumOutputChannels,
  23344. int numSamples);
  23345. /** Implementation of the AudioIODeviceCallback method. */
  23346. void audioDeviceAboutToStart (AudioIODevice* device);
  23347. /** Implementation of the AudioIODeviceCallback method. */
  23348. void audioDeviceStopped();
  23349. juce_UseDebuggingNewOperator
  23350. private:
  23351. CriticalSection readLock;
  23352. AudioSource* source;
  23353. double sampleRate;
  23354. int bufferSize;
  23355. float* channels [128];
  23356. float* outputChans [128];
  23357. const float* inputChans [128];
  23358. AudioSampleBuffer tempBuffer;
  23359. float lastGain, gain;
  23360. AudioSourcePlayer (const AudioSourcePlayer&);
  23361. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23362. };
  23363. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23364. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23365. #endif
  23366. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23367. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23368. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23369. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23370. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23371. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23372. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23373. /**
  23374. An AudioSource which takes another source as input, and buffers it using a thread.
  23375. Create this as a wrapper around another thread, and it will read-ahead with
  23376. a background thread to smooth out playback. You can either create one of these
  23377. directly, or use it indirectly using an AudioTransportSource.
  23378. @see PositionableAudioSource, AudioTransportSource
  23379. */
  23380. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23381. {
  23382. public:
  23383. /** Creates a BufferingAudioSource.
  23384. @param source the input source to read from
  23385. @param deleteSourceWhenDeleted if true, then the input source object will
  23386. be deleted when this object is deleted
  23387. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23388. */
  23389. BufferingAudioSource (PositionableAudioSource* source,
  23390. const bool deleteSourceWhenDeleted,
  23391. int numberOfSamplesToBuffer);
  23392. /** Destructor.
  23393. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23394. flag was set in the constructor.
  23395. */
  23396. ~BufferingAudioSource();
  23397. /** Implementation of the AudioSource method. */
  23398. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23399. /** Implementation of the AudioSource method. */
  23400. void releaseResources();
  23401. /** Implementation of the AudioSource method. */
  23402. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23403. /** Implements the PositionableAudioSource method. */
  23404. void setNextReadPosition (int newPosition);
  23405. /** Implements the PositionableAudioSource method. */
  23406. int getNextReadPosition() const;
  23407. /** Implements the PositionableAudioSource method. */
  23408. int getTotalLength() const { return source->getTotalLength(); }
  23409. /** Implements the PositionableAudioSource method. */
  23410. bool isLooping() const { return source->isLooping(); }
  23411. juce_UseDebuggingNewOperator
  23412. private:
  23413. PositionableAudioSource* source;
  23414. bool deleteSourceWhenDeleted;
  23415. int numberOfSamplesToBuffer;
  23416. AudioSampleBuffer buffer;
  23417. CriticalSection bufferStartPosLock;
  23418. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23419. bool wasSourceLooping;
  23420. double volatile sampleRate;
  23421. friend class SharedBufferingAudioSourceThread;
  23422. bool readNextBufferChunk();
  23423. void readBufferSection (int start, int length, int bufferOffset);
  23424. BufferingAudioSource (const BufferingAudioSource&);
  23425. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23426. };
  23427. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23428. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23429. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23430. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23431. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23432. /**
  23433. A type of AudioSource that takes an input source and changes its sample rate.
  23434. @see AudioSource
  23435. */
  23436. class JUCE_API ResamplingAudioSource : public AudioSource
  23437. {
  23438. public:
  23439. /** Creates a ResamplingAudioSource for a given input source.
  23440. @param inputSource the input source to read from
  23441. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23442. this object is deleted
  23443. */
  23444. ResamplingAudioSource (AudioSource* const inputSource,
  23445. const bool deleteInputWhenDeleted);
  23446. /** Destructor. */
  23447. ~ResamplingAudioSource();
  23448. /** Changes the resampling ratio.
  23449. (This value can be changed at any time, even while the source is running).
  23450. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23451. values will speed it up; lower values will slow it
  23452. down. The ratio must be greater than 0
  23453. */
  23454. void setResamplingRatio (const double samplesInPerOutputSample);
  23455. /** Returns the current resampling ratio.
  23456. This is the value that was set by setResamplingRatio().
  23457. */
  23458. double getResamplingRatio() const throw() { return ratio; }
  23459. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23460. void releaseResources();
  23461. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23462. juce_UseDebuggingNewOperator
  23463. private:
  23464. AudioSource* const input;
  23465. const bool deleteInputWhenDeleted;
  23466. double ratio, lastRatio;
  23467. AudioSampleBuffer buffer;
  23468. int bufferPos, sampsInBuffer;
  23469. double subSampleOffset;
  23470. double coefficients[6];
  23471. CriticalSection ratioLock;
  23472. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23473. void createLowPass (const double proportionalRate);
  23474. struct FilterState
  23475. {
  23476. double x1, x2, y1, y2;
  23477. };
  23478. FilterState filterStates[2];
  23479. void resetFilters();
  23480. void applyFilter (float* samples, int num, FilterState& fs);
  23481. ResamplingAudioSource (const ResamplingAudioSource&);
  23482. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23483. };
  23484. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23485. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23486. /**
  23487. An AudioSource that takes a PositionableAudioSource and allows it to be
  23488. played, stopped, started, etc.
  23489. This can also be told use a buffer and background thread to read ahead, and
  23490. if can correct for different sample-rates.
  23491. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23492. to control playback of an audio file.
  23493. @see AudioSource, AudioSourcePlayer
  23494. */
  23495. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23496. public ChangeBroadcaster
  23497. {
  23498. public:
  23499. /** Creates an AudioTransportSource.
  23500. After creating one of these, use the setSource() method to select an input source.
  23501. */
  23502. AudioTransportSource();
  23503. /** Destructor. */
  23504. ~AudioTransportSource();
  23505. /** Sets the reader that is being used as the input source.
  23506. This will stop playback, reset the position to 0 and change to the new reader.
  23507. The source passed in will not be deleted by this object, so must be managed by
  23508. the caller.
  23509. @param newSource the new input source to use. This may be zero
  23510. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23511. is zero, no reading ahead will be done; if it's
  23512. greater than zero, a BufferingAudioSource will be used
  23513. to do the reading-ahead
  23514. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23515. rate of the source, and playback will be sample-rate
  23516. adjusted to maintain playback at the correct pitch. If
  23517. this is 0, no sample-rate adjustment will be performed
  23518. */
  23519. void setSource (PositionableAudioSource* const newSource,
  23520. int readAheadBufferSize = 0,
  23521. double sourceSampleRateToCorrectFor = 0.0);
  23522. /** Changes the current playback position in the source stream.
  23523. The next time the getNextAudioBlock() method is called, this
  23524. is the time from which it'll read data.
  23525. @see getPosition
  23526. */
  23527. void setPosition (double newPosition);
  23528. /** Returns the position that the next data block will be read from
  23529. This is a time in seconds.
  23530. */
  23531. double getCurrentPosition() const;
  23532. /** Returns true if the player has stopped because its input stream ran out of data.
  23533. */
  23534. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23535. /** Starts playing (if a source has been selected).
  23536. If it starts playing, this will send a message to any ChangeListeners
  23537. that are registered with this object.
  23538. */
  23539. void start();
  23540. /** Stops playing.
  23541. If it's actually playing, this will send a message to any ChangeListeners
  23542. that are registered with this object.
  23543. */
  23544. void stop();
  23545. /** Returns true if it's currently playing. */
  23546. bool isPlaying() const throw() { return playing; }
  23547. /** Changes the gain to apply to the output.
  23548. @param newGain a factor by which to multiply the outgoing samples,
  23549. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23550. */
  23551. void setGain (const float newGain) throw();
  23552. /** Returns the current gain setting.
  23553. @see setGain
  23554. */
  23555. float getGain() const throw() { return gain; }
  23556. /** Implementation of the AudioSource method. */
  23557. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23558. /** Implementation of the AudioSource method. */
  23559. void releaseResources();
  23560. /** Implementation of the AudioSource method. */
  23561. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23562. /** Implements the PositionableAudioSource method. */
  23563. void setNextReadPosition (int newPosition);
  23564. /** Implements the PositionableAudioSource method. */
  23565. int getNextReadPosition() const;
  23566. /** Implements the PositionableAudioSource method. */
  23567. int getTotalLength() const;
  23568. /** Implements the PositionableAudioSource method. */
  23569. bool isLooping() const;
  23570. juce_UseDebuggingNewOperator
  23571. private:
  23572. PositionableAudioSource* source;
  23573. ResamplingAudioSource* resamplerSource;
  23574. BufferingAudioSource* bufferingSource;
  23575. PositionableAudioSource* positionableSource;
  23576. AudioSource* masterSource;
  23577. CriticalSection callbackLock;
  23578. float volatile gain, lastGain;
  23579. bool volatile playing, stopped;
  23580. double sampleRate, sourceSampleRate;
  23581. int blockSize, readAheadBufferSize;
  23582. bool isPrepared, inputStreamEOF;
  23583. AudioTransportSource (const AudioTransportSource&);
  23584. const AudioTransportSource& operator= (const AudioTransportSource&);
  23585. };
  23586. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23587. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23588. #endif
  23589. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23590. #endif
  23591. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23592. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23593. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23594. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23595. /**
  23596. An AudioSource that takes the audio from another source, and re-maps its
  23597. input and output channels to a different arrangement.
  23598. You can use this to increase or decrease the number of channels that an
  23599. audio source uses, or to re-order those channels.
  23600. Call the reset() method before using it to set up a default mapping, and then
  23601. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23602. create an appropriate mapping, otherwise no channels will be connected and
  23603. it'll produce silence.
  23604. @see AudioSource
  23605. */
  23606. class ChannelRemappingAudioSource : public AudioSource
  23607. {
  23608. public:
  23609. /** Creates a remapping source that will pass on audio from the given input.
  23610. @param source the input source to use. Make sure that this doesn't
  23611. get deleted before the ChannelRemappingAudioSource object
  23612. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23613. when this object is deleted, if false, the caller is
  23614. responsible for its deletion
  23615. */
  23616. ChannelRemappingAudioSource (AudioSource* const source,
  23617. const bool deleteSourceWhenDeleted);
  23618. /** Destructor. */
  23619. ~ChannelRemappingAudioSource();
  23620. /** Specifies a number of channels that this audio source must produce from its
  23621. getNextAudioBlock() callback.
  23622. */
  23623. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23624. /** Clears any mapped channels.
  23625. After this, no channels are mapped, so this object will produce silence. Create
  23626. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23627. */
  23628. void clearAllMappings() throw();
  23629. /** Creates an input channel mapping.
  23630. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23631. data will be sent to destChannelIndex of our input source.
  23632. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23633. source specified when this object was created).
  23634. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23635. during our getNextAudioBlock() callback
  23636. */
  23637. void setInputChannelMapping (const int destChannelIndex,
  23638. const int sourceChannelIndex) throw();
  23639. /** Creates an output channel mapping.
  23640. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23641. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23642. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23643. (i.e. the source specified when this object was created).
  23644. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23645. during our getNextAudioBlock() callback
  23646. */
  23647. void setOutputChannelMapping (const int sourceChannelIndex,
  23648. const int destChannelIndex) throw();
  23649. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23650. our input audio source.
  23651. */
  23652. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23653. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23654. source will be sent to.
  23655. */
  23656. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23657. /** Returns an XML object to encapsulate the state of the mappings.
  23658. @see restoreFromXml
  23659. */
  23660. XmlElement* createXml() const throw();
  23661. /** Restores the mappings from an XML object created by createXML().
  23662. @see createXml
  23663. */
  23664. void restoreFromXml (const XmlElement& e) throw();
  23665. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23666. void releaseResources();
  23667. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23668. juce_UseDebuggingNewOperator
  23669. private:
  23670. int requiredNumberOfChannels;
  23671. Array <int> remappedInputs, remappedOutputs;
  23672. AudioSource* const source;
  23673. const bool deleteSourceWhenDeleted;
  23674. AudioSampleBuffer buffer;
  23675. AudioSourceChannelInfo remappedInfo;
  23676. CriticalSection lock;
  23677. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23678. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23679. };
  23680. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23681. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23682. #endif
  23683. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23684. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23685. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23686. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23687. /**
  23688. An AudioSource that performs an IIR filter on another source.
  23689. */
  23690. class JUCE_API IIRFilterAudioSource : public AudioSource
  23691. {
  23692. public:
  23693. /** Creates a IIRFilterAudioSource for a given input source.
  23694. @param inputSource the input source to read from
  23695. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23696. this object is deleted
  23697. */
  23698. IIRFilterAudioSource (AudioSource* const inputSource,
  23699. const bool deleteInputWhenDeleted);
  23700. /** Destructor. */
  23701. ~IIRFilterAudioSource();
  23702. /** Changes the filter to use the same parameters as the one being passed in.
  23703. */
  23704. void setFilterParameters (const IIRFilter& newSettings);
  23705. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23706. void releaseResources();
  23707. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23708. juce_UseDebuggingNewOperator
  23709. private:
  23710. AudioSource* const input;
  23711. const bool deleteInputWhenDeleted;
  23712. OwnedArray <IIRFilter> iirFilters;
  23713. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23714. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23715. };
  23716. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23717. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23718. #endif
  23719. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23720. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23721. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23722. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23723. /**
  23724. An AudioSource that mixes together the output of a set of other AudioSources.
  23725. Input sources can be added and removed while the mixer is running as long as their
  23726. prepareToPlay() and releaseResources() methods are called before and after adding
  23727. them to the mixer.
  23728. */
  23729. class JUCE_API MixerAudioSource : public AudioSource
  23730. {
  23731. public:
  23732. /** Creates a MixerAudioSource.
  23733. */
  23734. MixerAudioSource();
  23735. /** Destructor. */
  23736. ~MixerAudioSource();
  23737. /** Adds an input source to the mixer.
  23738. If the mixer is running you'll need to make sure that the input source
  23739. is ready to play by calling its prepareToPlay() method before adding it.
  23740. If the mixer is stopped, then its input sources will be automatically
  23741. prepared when the mixer's prepareToPlay() method is called.
  23742. @param newInput the source to add to the mixer
  23743. @param deleteWhenRemoved if true, then this source will be deleted when
  23744. the mixer is deleted or when removeAllInputs() is
  23745. called (unless the source is previously removed
  23746. with the removeInputSource method)
  23747. */
  23748. void addInputSource (AudioSource* newInput,
  23749. const bool deleteWhenRemoved);
  23750. /** Removes an input source.
  23751. If the mixer is running, this will remove the source but not call its
  23752. releaseResources() method, so the caller might want to do this manually.
  23753. @param input the source to remove
  23754. @param deleteSource whether to delete this source after it's been removed
  23755. */
  23756. void removeInputSource (AudioSource* input,
  23757. const bool deleteSource);
  23758. /** Removes all the input sources.
  23759. If the mixer is running, this will remove the sources but not call their
  23760. releaseResources() method, so the caller might want to do this manually.
  23761. Any sources which were added with the deleteWhenRemoved flag set will be
  23762. deleted by this method.
  23763. */
  23764. void removeAllInputs();
  23765. /** Implementation of the AudioSource method.
  23766. This will call prepareToPlay() on all its input sources.
  23767. */
  23768. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23769. /** Implementation of the AudioSource method.
  23770. This will call releaseResources() on all its input sources.
  23771. */
  23772. void releaseResources();
  23773. /** Implementation of the AudioSource method. */
  23774. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23775. juce_UseDebuggingNewOperator
  23776. private:
  23777. VoidArray inputs;
  23778. BitArray inputsToDelete;
  23779. CriticalSection lock;
  23780. AudioSampleBuffer tempBuffer;
  23781. double currentSampleRate;
  23782. int bufferSizeExpected;
  23783. MixerAudioSource (const MixerAudioSource&);
  23784. const MixerAudioSource& operator= (const MixerAudioSource&);
  23785. };
  23786. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23787. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23788. #endif
  23789. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23790. #endif
  23791. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23792. #endif
  23793. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23794. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23795. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23796. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23797. /**
  23798. A simple AudioSource that generates a sine wave.
  23799. */
  23800. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  23801. {
  23802. public:
  23803. /** Creates a ToneGeneratorAudioSource. */
  23804. ToneGeneratorAudioSource();
  23805. /** Destructor. */
  23806. ~ToneGeneratorAudioSource();
  23807. /** Sets the signal's amplitude. */
  23808. void setAmplitude (const float newAmplitude);
  23809. /** Sets the signal's frequency. */
  23810. void setFrequency (const double newFrequencyHz);
  23811. /** Implementation of the AudioSource method. */
  23812. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23813. /** Implementation of the AudioSource method. */
  23814. void releaseResources();
  23815. /** Implementation of the AudioSource method. */
  23816. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23817. juce_UseDebuggingNewOperator
  23818. private:
  23819. double frequency, sampleRate;
  23820. double currentPhase, phasePerSample;
  23821. float amplitude;
  23822. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  23823. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  23824. };
  23825. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23826. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23827. #endif
  23828. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23829. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  23830. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23831. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23832. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  23833. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23834. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23835. class AudioDeviceManager;
  23836. class Component;
  23837. /**
  23838. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  23839. To get a list of available audio driver types, use the createDeviceTypes()
  23840. method. Each of the objects returned can then be used to list the available
  23841. devices of that type. E.g.
  23842. @code
  23843. OwnedArray <AudioIODeviceType> types;
  23844. AudioIODeviceType::createDeviceTypes (types);
  23845. for (int i = 0; i < types.size(); ++i)
  23846. {
  23847. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  23848. types[i]->scanForDevices(); // This must be called before getting the list of devices
  23849. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  23850. for (int j = 0; j < deviceNames.size(); ++j)
  23851. {
  23852. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  23853. ...
  23854. }
  23855. }
  23856. @endcode
  23857. For an easier way of managing audio devices and their settings, have a look at the
  23858. AudioDeviceManager class.
  23859. @see AudioIODevice, AudioDeviceManager
  23860. */
  23861. class JUCE_API AudioIODeviceType
  23862. {
  23863. public:
  23864. /** Returns the name of this type of driver that this object manages.
  23865. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  23866. */
  23867. const String& getTypeName() const throw() { return typeName; }
  23868. /** Refreshes the object's cached list of known devices.
  23869. This must be called at least once before calling getDeviceNames() or any of
  23870. the other device creation methods.
  23871. */
  23872. virtual void scanForDevices() = 0;
  23873. /** Returns the list of available devices of this type.
  23874. The scanForDevices() method must have been called to create this list.
  23875. @param wantInputNames only really used by DirectSound where devices are split up
  23876. into inputs and outputs, this indicates whether to use
  23877. the input or output name to refer to a pair of devices.
  23878. */
  23879. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  23880. /** Returns the name of the default device.
  23881. This will be one of the names from the getDeviceNames() list.
  23882. @param forInput if true, this means that a default input device should be
  23883. returned; if false, it should return the default output
  23884. */
  23885. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  23886. /** Returns the index of a given device in the list of device names.
  23887. If asInput is true, it shows the index in the inputs list, otherwise it
  23888. looks for it in the outputs list.
  23889. */
  23890. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  23891. /** Returns true if two different devices can be used for the input and output.
  23892. */
  23893. virtual bool hasSeparateInputsAndOutputs() const = 0;
  23894. /** Creates one of the devices of this type.
  23895. The deviceName must be one of the strings returned by getDeviceNames(), and
  23896. scanForDevices() must have been called before this method is used.
  23897. */
  23898. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  23899. const String& inputDeviceName) = 0;
  23900. struct DeviceSetupDetails
  23901. {
  23902. AudioDeviceManager* manager;
  23903. int minNumInputChannels, maxNumInputChannels;
  23904. int minNumOutputChannels, maxNumOutputChannels;
  23905. bool useStereoPairs;
  23906. };
  23907. /** Destructor. */
  23908. virtual ~AudioIODeviceType();
  23909. protected:
  23910. AudioIODeviceType (const tchar* const typeName);
  23911. private:
  23912. String typeName;
  23913. AudioIODeviceType (const AudioIODeviceType&);
  23914. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  23915. };
  23916. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23917. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  23918. /********* Start of inlined file: juce_MidiOutput.h *********/
  23919. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  23920. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  23921. /**
  23922. Represents a midi output device.
  23923. To create one of these, use the static getDevices() method to find out what
  23924. outputs are available, then use the openDevice() method to try to open one.
  23925. @see MidiInput
  23926. */
  23927. class JUCE_API MidiOutput : private Thread
  23928. {
  23929. public:
  23930. /** Returns a list of the available midi output devices.
  23931. You can open one of the devices by passing its index into the
  23932. openDevice() method.
  23933. @see getDefaultDeviceIndex, openDevice
  23934. */
  23935. static const StringArray getDevices();
  23936. /** Returns the index of the default midi output device to use.
  23937. This refers to the index in the list returned by getDevices().
  23938. */
  23939. static int getDefaultDeviceIndex();
  23940. /** Tries to open one of the midi output devices.
  23941. This will return a MidiOutput object if it manages to open it. You can then
  23942. send messages to this device, and delete it when no longer needed.
  23943. If the device can't be opened, this will return a null pointer.
  23944. @param deviceIndex the index of a device from the list returned by getDevices()
  23945. @see getDevices
  23946. */
  23947. static MidiOutput* openDevice (int deviceIndex);
  23948. #if JUCE_LINUX || DOXYGEN
  23949. /** LINUX ONLY - This will try to create a new midi output device.
  23950. This will attempt to create a new midi output device that other apps can connect
  23951. to and use as their midi input.
  23952. Returns 0 if a device can't be created.
  23953. @param deviceName the name to use for the new device
  23954. */
  23955. static MidiOutput* createNewDevice (const String& deviceName);
  23956. #endif
  23957. /** Destructor. */
  23958. ~MidiOutput();
  23959. /** Makes this device output a midi message.
  23960. @see MidiMessage
  23961. */
  23962. void sendMessageNow (const MidiMessage& message);
  23963. /** Sends a midi reset to the device. */
  23964. void reset();
  23965. /** Returns the current volume setting for this device. */
  23966. bool getVolume (float& leftVol,
  23967. float& rightVol);
  23968. /** Changes the overall volume for this device. */
  23969. void setVolume (float leftVol,
  23970. float rightVol);
  23971. /** This lets you supply a block of messages that will be sent out at some point
  23972. in the future.
  23973. The MidiOutput class has an internal thread that can send out timestamped
  23974. messages - this appends a set of messages to its internal buffer, ready for
  23975. sending.
  23976. This will only work if you've already started the thread with startBackgroundThread().
  23977. A time is supplied, at which the block of messages should be sent. This time uses
  23978. the same time base as Time::getMillisecondCounter(), and must be in the future.
  23979. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  23980. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  23981. samplesPerSecondForBuffer value is needed to convert this sample position to a
  23982. real time.
  23983. */
  23984. void sendBlockOfMessages (const MidiBuffer& buffer,
  23985. const double millisecondCounterToStartAt,
  23986. double samplesPerSecondForBuffer) throw();
  23987. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  23988. */
  23989. void clearAllPendingMessages() throw();
  23990. /** Starts up a background thread so that the device can send blocks of data.
  23991. Call this to get the device ready, before using sendBlockOfMessages().
  23992. */
  23993. void startBackgroundThread() throw();
  23994. /** Stops the background thread, and clears any pending midi events.
  23995. @see startBackgroundThread
  23996. */
  23997. void stopBackgroundThread() throw();
  23998. juce_UseDebuggingNewOperator
  23999. private:
  24000. void* internal;
  24001. struct PendingMessage
  24002. {
  24003. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24004. MidiMessage message;
  24005. PendingMessage* next;
  24006. juce_UseDebuggingNewOperator
  24007. };
  24008. CriticalSection lock;
  24009. PendingMessage* firstMessage;
  24010. MidiOutput() throw();
  24011. MidiOutput (const MidiOutput&);
  24012. void run();
  24013. };
  24014. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24015. /********* End of inlined file: juce_MidiOutput.h *********/
  24016. /********* Start of inlined file: juce_ComboBox.h *********/
  24017. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24018. #define __JUCE_COMBOBOX_JUCEHEADER__
  24019. /********* Start of inlined file: juce_Label.h *********/
  24020. #ifndef __JUCE_LABEL_JUCEHEADER__
  24021. #define __JUCE_LABEL_JUCEHEADER__
  24022. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24023. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24024. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24025. /**
  24026. Object for monitoring a component, and later testing whether it's still valid.
  24027. Slightly obscure, this one, but it's used internally for making sure that
  24028. after some callbacks, a component hasn't been deleted. It's more reliable than
  24029. just using isValidComponent(), which can provide false-positives if a new
  24030. component is created at the same memory location as an old one.
  24031. */
  24032. class JUCE_API ComponentDeletionWatcher
  24033. {
  24034. public:
  24035. /** Creates a watcher for a given component.
  24036. The component must be valid at the time it's passed in.
  24037. */
  24038. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24039. /** Destructor. */
  24040. ~ComponentDeletionWatcher() throw();
  24041. /** Returns true if the component has been deleted since the time that this
  24042. object was created.
  24043. */
  24044. bool hasBeenDeleted() const throw();
  24045. /** Returns the component that's being watched, or null if it has been deleted. */
  24046. const Component* getComponent() const throw();
  24047. juce_UseDebuggingNewOperator
  24048. private:
  24049. const Component* const componentToWatch;
  24050. const uint32 componentUID;
  24051. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24052. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24053. };
  24054. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24055. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24056. /********* Start of inlined file: juce_TextEditor.h *********/
  24057. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24058. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24059. /********* Start of inlined file: juce_UndoManager.h *********/
  24060. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24061. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24062. /********* Start of inlined file: juce_UndoableAction.h *********/
  24063. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24064. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24065. /**
  24066. Used by the UndoManager class to store an action which can be done
  24067. and undone.
  24068. @see UndoManager
  24069. */
  24070. class JUCE_API UndoableAction
  24071. {
  24072. protected:
  24073. /** Creates an action. */
  24074. UndoableAction() throw() {}
  24075. public:
  24076. /** Destructor. */
  24077. virtual ~UndoableAction() {}
  24078. /** Overridden by a subclass to perform the action.
  24079. This method is called by the UndoManager, and shouldn't be used directly by
  24080. applications.
  24081. Be careful not to make any calls in a perform() method that could call
  24082. recursively back into the UndoManager::perform() method
  24083. @returns true if the action could be performed.
  24084. @see UndoManager::perform
  24085. */
  24086. virtual bool perform() = 0;
  24087. /** Overridden by a subclass to undo the action.
  24088. This method is called by the UndoManager, and shouldn't be used directly by
  24089. applications.
  24090. Be careful not to make any calls in an undo() method that could call
  24091. recursively back into the UndoManager::perform() method
  24092. @returns true if the action could be undone without any errors.
  24093. @see UndoManager::perform
  24094. */
  24095. virtual bool undo() = 0;
  24096. /** Returns a value to indicate how much memory this object takes up.
  24097. Because the UndoManager keeps a list of UndoableActions, this is used
  24098. to work out how much space each one will take up, so that the UndoManager
  24099. can work out how many to keep.
  24100. The default value returned here is 10 - units are arbitrary and
  24101. don't have to be accurate.
  24102. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24103. UndoManager::setMaxNumberOfStoredUnits
  24104. */
  24105. virtual int getSizeInUnits() { return 10; }
  24106. };
  24107. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24108. /********* End of inlined file: juce_UndoableAction.h *********/
  24109. /**
  24110. Manages a list of undo/redo commands.
  24111. An UndoManager object keeps a list of past actions and can use these actions
  24112. to move backwards and forwards through an undo history.
  24113. To use it, create subclasses of UndoableAction which perform all the
  24114. actions you need, then when you need to actually perform an action, create one
  24115. and pass it to the UndoManager's perform() method.
  24116. The manager also uses the concept of 'transactions' to group the actions
  24117. together - all actions performed between calls to beginNewTransaction() are
  24118. grouped together and are all undone/redone as a group.
  24119. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24120. when actions are performed or undone.
  24121. @see UndoableAction
  24122. */
  24123. class JUCE_API UndoManager : public ChangeBroadcaster
  24124. {
  24125. public:
  24126. /** Creates an UndoManager.
  24127. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24128. to indicate how much storage it takes up
  24129. (UndoableAction::getSizeInUnits()), so this
  24130. lets you specify the maximum total number of
  24131. units that the undomanager is allowed to
  24132. keep in memory before letting the older actions
  24133. drop off the end of the list.
  24134. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24135. that will be kept, even if this involves exceeding
  24136. the amount of space specified in maxNumberOfUnitsToKeep
  24137. */
  24138. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24139. const int minimumTransactionsToKeep = 30);
  24140. /** Destructor. */
  24141. ~UndoManager();
  24142. /** Deletes all stored actions in the list. */
  24143. void clearUndoHistory();
  24144. /** Returns the current amount of space to use for storing UndoableAction objects.
  24145. @see setMaxNumberOfStoredUnits
  24146. */
  24147. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24148. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24149. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24150. to indicate how much storage it takes up
  24151. (UndoableAction::getSizeInUnits()), so this
  24152. lets you specify the maximum total number of
  24153. units that the undomanager is allowed to
  24154. keep in memory before letting the older actions
  24155. drop off the end of the list.
  24156. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24157. that will be kept, even if this involves exceeding
  24158. the amount of space specified in maxNumberOfUnitsToKeep
  24159. @see getNumberOfUnitsTakenUpByStoredCommands
  24160. */
  24161. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24162. const int minimumTransactionsToKeep);
  24163. /** Performs an action and adds it to the undo history list.
  24164. @param action the action to perform - this will be deleted by the UndoManager
  24165. when no longer needed
  24166. @param actionName if this string is non-empty, the current transaction will be
  24167. given this name; if it's empty, the current transaction name will
  24168. be left unchanged. See setCurrentTransactionName()
  24169. @returns true if the command succeeds - see UndoableAction::perform
  24170. @see beginNewTransaction
  24171. */
  24172. bool perform (UndoableAction* const action,
  24173. const String& actionName = String::empty);
  24174. /** Starts a new group of actions that together will be treated as a single transaction.
  24175. All actions that are passed to the perform() method between calls to this
  24176. method are grouped together and undone/redone together by a single call to
  24177. undo() or redo().
  24178. @param actionName a description of the transaction that is about to be
  24179. performed
  24180. */
  24181. void beginNewTransaction (const String& actionName = String::empty);
  24182. /** Changes the name stored for the current transaction.
  24183. Each transaction is given a name when the beginNewTransaction() method is
  24184. called, but this can be used to change that name without starting a new
  24185. transaction.
  24186. */
  24187. void setCurrentTransactionName (const String& newName);
  24188. /** Returns true if there's at least one action in the list to undo.
  24189. @see getUndoDescription, undo, canRedo
  24190. */
  24191. bool canUndo() const;
  24192. /** Returns the description of the transaction that would be next to get undone.
  24193. The description returned is the one that was passed into beginNewTransaction
  24194. before the set of actions was performed.
  24195. @see undo
  24196. */
  24197. const String getUndoDescription() const;
  24198. /** Tries to roll-back the last transaction.
  24199. @returns true if the transaction can be undone, and false if it fails, or
  24200. if there aren't any transactions to undo
  24201. */
  24202. bool undo();
  24203. /** Tries to roll-back any actions that were added to the current transaction.
  24204. This will perform an undo() only if there are some actions in the undo list
  24205. that were added after the last call to beginNewTransaction().
  24206. This is useful because it lets you call beginNewTransaction(), then
  24207. perform an operation which may or may not actually perform some actions, and
  24208. then call this method to get rid of any actions that might have been done
  24209. without it rolling back the previous transaction if nothing was actually
  24210. done.
  24211. @returns true if any actions were undone.
  24212. */
  24213. bool undoCurrentTransactionOnly();
  24214. /** Returns a list of the UndoableAction objects that have been performed during the
  24215. transaction that is currently open.
  24216. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24217. were to be called now.
  24218. The first item in the list is the earliest action performed.
  24219. */
  24220. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24221. /** Returns true if there's at least one action in the list to redo.
  24222. @see getRedoDescription, redo, canUndo
  24223. */
  24224. bool canRedo() const;
  24225. /** Returns the description of the transaction that would be next to get redone.
  24226. The description returned is the one that was passed into beginNewTransaction
  24227. before the set of actions was performed.
  24228. @see redo
  24229. */
  24230. const String getRedoDescription() const;
  24231. /** Tries to redo the last transaction that was undone.
  24232. @returns true if the transaction can be redone, and false if it fails, or
  24233. if there aren't any transactions to redo
  24234. */
  24235. bool redo();
  24236. juce_UseDebuggingNewOperator
  24237. private:
  24238. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24239. StringArray transactionNames;
  24240. String currentTransactionName;
  24241. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24242. bool newTransaction, reentrancyCheck;
  24243. // disallow copy constructor
  24244. UndoManager (const UndoManager&);
  24245. const UndoManager& operator= (const UndoManager&);
  24246. };
  24247. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24248. /********* End of inlined file: juce_UndoManager.h *********/
  24249. class TextEditor;
  24250. class TextHolderComponent;
  24251. /**
  24252. Receives callbacks from a TextEditor component when it changes.
  24253. @see TextEditor::addListener
  24254. */
  24255. class JUCE_API TextEditorListener
  24256. {
  24257. public:
  24258. /** Destructor. */
  24259. virtual ~TextEditorListener() {}
  24260. /** Called when the user changes the text in some way. */
  24261. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24262. /** Called when the user presses the return key. */
  24263. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24264. /** Called when the user presses the escape key. */
  24265. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24266. /** Called when the text editor loses focus. */
  24267. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24268. };
  24269. /**
  24270. A component containing text that can be edited.
  24271. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24272. fonts and colours.
  24273. @see TextEditorListener, Label
  24274. */
  24275. class JUCE_API TextEditor : public Component,
  24276. public SettableTooltipClient
  24277. {
  24278. public:
  24279. /** Creates a new, empty text editor.
  24280. @param componentName the name to pass to the component for it to use as its name
  24281. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24282. for all characters that are drawn on screen - e.g. to create
  24283. a password-style textbox containing circular blobs instead of text,
  24284. you could set this value to 0x25cf, which is the unicode character
  24285. for a black splodge (not all fonts include this, though), or 0x2022,
  24286. which is a bullet (probably the best choice for linux).
  24287. */
  24288. TextEditor (const String& componentName = String::empty,
  24289. const tchar passwordCharacter = 0);
  24290. /** Destructor. */
  24291. virtual ~TextEditor();
  24292. /** Puts the editor into either multi- or single-line mode.
  24293. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24294. editor.
  24295. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24296. on if you want a multi-line editor with line-breaks.
  24297. @see isMultiLine, setReturnKeyStartsNewLine
  24298. */
  24299. void setMultiLine (const bool shouldBeMultiLine,
  24300. const bool shouldWordWrap = true);
  24301. /** Returns true if the editor is in multi-line mode.
  24302. */
  24303. bool isMultiLine() const throw();
  24304. /** Changes the behaviour of the return key.
  24305. If set to true, the return key will insert a new-line into the text; if false
  24306. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24307. method. By default this is set to false, and when true it will only insert
  24308. new-lines when in multi-line mode (see setMultiLine()).
  24309. */
  24310. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24311. /** Returns the value set by setReturnKeyStartsNewLine().
  24312. See setReturnKeyStartsNewLine() for more info.
  24313. */
  24314. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24315. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24316. or whether it gets ignored.
  24317. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24318. between components.
  24319. */
  24320. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24321. /** Returns true if the tab key is being used for input.
  24322. @see setTabKeyUsedAsCharacter
  24323. */
  24324. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24325. /** Changes the editor to read-only mode.
  24326. By default, the text editor is not read-only. If you're making it read-only, you
  24327. might also want to call setCaretVisible (false) to get rid of the caret.
  24328. The text can still be highlighted and copied when in read-only mode.
  24329. @see isReadOnly, setCaretVisible
  24330. */
  24331. void setReadOnly (const bool shouldBeReadOnly);
  24332. /** Returns true if the editor is in read-only mode.
  24333. */
  24334. bool isReadOnly() const throw();
  24335. /** Makes the caret visible or invisible.
  24336. By default the caret is visible.
  24337. @see setCaretColour, setCaretPosition
  24338. */
  24339. void setCaretVisible (const bool shouldBeVisible) throw();
  24340. /** Returns true if the caret is enabled.
  24341. @see setCaretVisible
  24342. */
  24343. bool isCaretVisible() const throw() { return caretVisible; }
  24344. /** Enables/disables a vertical scrollbar.
  24345. (This only applies when in multi-line mode). When the text gets too long to fit
  24346. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24347. this is enabled, the scrollbar will be hidden unless it's needed.
  24348. By default the scrollbar is enabled.
  24349. */
  24350. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24351. /** Returns true if scrollbars are enabled.
  24352. @see setScrollbarsShown
  24353. */
  24354. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24355. /** Changes the password character used to disguise the text.
  24356. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24357. for all characters that are drawn on screen - e.g. to create
  24358. a password-style textbox containing circular blobs instead of text,
  24359. you could set this value to 0x25cf, which is the unicode character
  24360. for a black splodge (not all fonts include this, though), or 0x2022,
  24361. which is a bullet (probably the best choice for linux).
  24362. */
  24363. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24364. /** Returns the current password character.
  24365. @see setPasswordCharacter
  24366. l */
  24367. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24368. /** Allows a right-click menu to appear for the editor.
  24369. (This defaults to being enabled).
  24370. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24371. of options such as cut/copy/paste, undo/redo, etc.
  24372. */
  24373. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24374. /** Returns true if the right-click menu is enabled.
  24375. @see setPopupMenuEnabled
  24376. */
  24377. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24378. /** Returns true if a popup-menu is currently being displayed.
  24379. */
  24380. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24381. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24382. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24383. methods.
  24384. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24385. */
  24386. enum ColourIds
  24387. {
  24388. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24389. transparent if necessary. */
  24390. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24391. that because the editor can contain multiple colours, calling this
  24392. method won't change the colour of existing text - to do that, call
  24393. applyFontToAllText() after calling this method.*/
  24394. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24395. the text - this can be transparent if you don't want to show any
  24396. highlighting.*/
  24397. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24398. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24399. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24400. the edge of the component. */
  24401. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24402. the edge of the component when it has focus. */
  24403. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24404. around the edge of the editor. */
  24405. };
  24406. /** Sets the font to use for newly added text.
  24407. This will change the font that will be used next time any text is added or entered
  24408. into the editor. It won't change the font of any existing text - to do that, use
  24409. applyFontToAllText() instead.
  24410. @see applyFontToAllText
  24411. */
  24412. void setFont (const Font& newFont) throw();
  24413. /** Applies a font to all the text in the editor.
  24414. This will also set the current font to use for any new text that's added.
  24415. @see setFont
  24416. */
  24417. void applyFontToAllText (const Font& newFont);
  24418. /** Returns the font that's currently being used for new text.
  24419. @see setFont
  24420. */
  24421. const Font getFont() const throw();
  24422. /** If set to true, focusing on the editor will highlight all its text.
  24423. (Set to false by default).
  24424. This is useful for boxes where you expect the user to re-enter all the
  24425. text when they focus on the component, rather than editing what's already there.
  24426. */
  24427. void setSelectAllWhenFocused (const bool b) throw();
  24428. /** Sets limits on the characters that can be entered.
  24429. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24430. limit is set
  24431. @param allowedCharacters if this is non-empty, then only characters that occur in
  24432. this string are allowed to be entered into the editor.
  24433. */
  24434. void setInputRestrictions (const int maxTextLength,
  24435. const String& allowedCharacters = String::empty) throw();
  24436. /** When the text editor is empty, it can be set to display a message.
  24437. This is handy for things like telling the user what to type in the box - the
  24438. string is only displayed, it's not taken to actually be the contents of
  24439. the editor.
  24440. */
  24441. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24442. /** Changes the size of the scrollbars that are used.
  24443. Handy if you need smaller scrollbars for a small text box.
  24444. */
  24445. void setScrollBarThickness (const int newThicknessPixels);
  24446. /** Shows or hides the buttons on any scrollbars that are used.
  24447. @see ScrollBar::setButtonVisibility
  24448. */
  24449. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24450. /** Registers a listener to be told when things happen to the text.
  24451. @see removeListener
  24452. */
  24453. void addListener (TextEditorListener* const newListener) throw();
  24454. /** Deregisters a listener.
  24455. @see addListener
  24456. */
  24457. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24458. /** Returns the entire contents of the editor. */
  24459. const String getText() const throw();
  24460. /** Returns a section of the contents of the editor. */
  24461. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24462. /** Returns true if there are no characters in the editor.
  24463. This is more efficient than calling getText().isEmpty().
  24464. */
  24465. bool isEmpty() const throw();
  24466. /** Sets the entire content of the editor.
  24467. This will clear the editor and insert the given text (using the current text colour
  24468. and font). You can set the current text colour using
  24469. @code setColour (TextEditor::textColourId, ...);
  24470. @endcode
  24471. @param newText the text to add
  24472. @param sendTextChangeMessage if true, this will cause a change message to
  24473. be sent to all the listeners.
  24474. @see insertText
  24475. */
  24476. void setText (const String& newText,
  24477. const bool sendTextChangeMessage = true);
  24478. /** Inserts some text at the current cursor position.
  24479. If a section of the text is highlighted, it will be replaced by
  24480. this string, otherwise it will be inserted.
  24481. To delete a section of text, you can use setHighlightedRegion() to
  24482. highlight it, and call insertTextAtCursor (String::empty).
  24483. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24484. */
  24485. void insertTextAtCursor (String textToInsert);
  24486. /** Deletes all the text from the editor. */
  24487. void clear();
  24488. /** Deletes the currently selected region, and puts it on the clipboard.
  24489. @see copy, paste, SystemClipboard
  24490. */
  24491. void cut();
  24492. /** Copies any currently selected region to the clipboard.
  24493. @see cut, paste, SystemClipboard
  24494. */
  24495. void copy();
  24496. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24497. @see cut, copy, SystemClipboard
  24498. */
  24499. void paste();
  24500. /** Moves the caret to be in front of a given character.
  24501. @see getCaretPosition
  24502. */
  24503. void setCaretPosition (const int newIndex) throw();
  24504. /** Returns the current index of the caret.
  24505. @see setCaretPosition
  24506. */
  24507. int getCaretPosition() const throw();
  24508. /** Attempts to scroll the text editor so that the caret ends up at
  24509. a specified position.
  24510. This won't affect the caret's position within the text, it tries to scroll
  24511. the entire editor vertically and horizontally so that the caret is sitting
  24512. at the given position (relative to the top-left of this component).
  24513. Depending on the amount of text available, it might not be possible to
  24514. scroll far enough for the caret to reach this exact position, but it
  24515. will go as far as it can in that direction.
  24516. */
  24517. void scrollEditorToPositionCaret (const int desiredCaretX,
  24518. const int desiredCaretY) throw();
  24519. /** Get the graphical position of the caret.
  24520. The rectangle returned is relative to the component's top-left corner.
  24521. @see scrollEditorToPositionCaret
  24522. */
  24523. const Rectangle getCaretRectangle() throw();
  24524. /** Selects a section of the text.
  24525. */
  24526. void setHighlightedRegion (int startIndex,
  24527. int numberOfCharactersToHighlight) throw();
  24528. /** Returns the first character that is selected.
  24529. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24530. will return 0.
  24531. @see setHighlightedRegion, getHighlightedRegionLength
  24532. */
  24533. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24534. /** Returns the number of characters that are selected.
  24535. @see setHighlightedRegion, getHighlightedRegionStart
  24536. */
  24537. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24538. /** Returns the section of text that is currently selected. */
  24539. const String getHighlightedText() const throw();
  24540. /** Finds the index of the character at a given position.
  24541. The co-ordinates are relative to the component's top-left.
  24542. */
  24543. int getTextIndexAt (const int x, const int y) throw();
  24544. /** Returns the total width of the text, as it is currently laid-out.
  24545. This may be larger than the size of the TextEditor, and can change when
  24546. the TextEditor is resized or the text changes.
  24547. */
  24548. int getTextWidth() const throw();
  24549. /** Returns the maximum height of the text, as it is currently laid-out.
  24550. This may be larger than the size of the TextEditor, and can change when
  24551. the TextEditor is resized or the text changes.
  24552. */
  24553. int getTextHeight() const throw();
  24554. /** Changes the size of the gap at the top and left-edge of the editor.
  24555. By default there's a gap of 4 pixels.
  24556. */
  24557. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24558. /** Changes the size of border left around the edge of the component.
  24559. @see getBorder
  24560. */
  24561. void setBorder (const BorderSize& border) throw();
  24562. /** Returns the size of border around the edge of the component.
  24563. @see setBorder
  24564. */
  24565. const BorderSize getBorder() const throw();
  24566. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24567. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24568. set to false, it won't.
  24569. */
  24570. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24571. /** @internal */
  24572. void paint (Graphics& g);
  24573. /** @internal */
  24574. void paintOverChildren (Graphics& g);
  24575. /** @internal */
  24576. void mouseDown (const MouseEvent& e);
  24577. /** @internal */
  24578. void mouseUp (const MouseEvent& e);
  24579. /** @internal */
  24580. void mouseDrag (const MouseEvent& e);
  24581. /** @internal */
  24582. void mouseDoubleClick (const MouseEvent& e);
  24583. /** @internal */
  24584. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24585. /** @internal */
  24586. bool keyPressed (const KeyPress& key);
  24587. /** @internal */
  24588. bool keyStateChanged();
  24589. /** @internal */
  24590. void focusGained (FocusChangeType cause);
  24591. /** @internal */
  24592. void focusLost (FocusChangeType cause);
  24593. /** @internal */
  24594. void resized();
  24595. /** @internal */
  24596. void enablementChanged();
  24597. /** @internal */
  24598. void colourChanged();
  24599. juce_UseDebuggingNewOperator
  24600. protected:
  24601. /** This adds the items to the popup menu.
  24602. By default it adds the cut/copy/paste items, but you can override this if
  24603. you need to replace these with your own items.
  24604. If you want to add your own items to the existing ones, you can override this,
  24605. call the base class's addPopupMenuItems() method, then append your own items.
  24606. When the menu has been shown, performPopupMenuAction() will be called to
  24607. perform the item that the user has chosen.
  24608. The default menu items will be added using item IDs in the range
  24609. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24610. menu IDs.
  24611. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24612. a pointer to the info about it, or may be null if the menu is being triggered
  24613. by some other means.
  24614. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24615. */
  24616. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24617. const MouseEvent* mouseClickEvent);
  24618. /** This is called to perform one of the items that was shown on the popup menu.
  24619. If you've overridden addPopupMenuItems(), you should also override this
  24620. to perform the actions that you've added.
  24621. If you've overridden addPopupMenuItems() but have still left the default items
  24622. on the menu, remember to call the superclass's performPopupMenuAction()
  24623. so that it can perform the default actions if that's what the user clicked on.
  24624. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24625. */
  24626. virtual void performPopupMenuAction (const int menuItemID);
  24627. /** Scrolls the minimum distance needed to get the caret into view. */
  24628. void scrollToMakeSureCursorIsVisible() throw();
  24629. /** @internal */
  24630. void moveCaret (int newCaretPos) throw();
  24631. /** @internal */
  24632. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24633. /** Used internally to dispatch a text-change message. */
  24634. void textChanged() throw();
  24635. /** Counts the number of characters in the text.
  24636. This is quicker than getting the text as a string if you just need to know
  24637. the length.
  24638. */
  24639. int getTotalNumChars() throw();
  24640. /** Begins a new transaction in the UndoManager.
  24641. */
  24642. void newTransaction() throw();
  24643. /** Used internally to trigger an undo or redo. */
  24644. void doUndoRedo (const bool isRedo);
  24645. /** Can be overridden to intercept return key presses directly */
  24646. virtual void returnPressed();
  24647. /** Can be overridden to intercept escape key presses directly */
  24648. virtual void escapePressed();
  24649. /** @internal */
  24650. void handleCommandMessage (int commandId);
  24651. private:
  24652. Viewport* viewport;
  24653. TextHolderComponent* textHolder;
  24654. BorderSize borderSize;
  24655. bool readOnly : 1;
  24656. bool multiline : 1;
  24657. bool wordWrap : 1;
  24658. bool returnKeyStartsNewLine : 1;
  24659. bool caretVisible : 1;
  24660. bool popupMenuEnabled : 1;
  24661. bool selectAllTextWhenFocused : 1;
  24662. bool scrollbarVisible : 1;
  24663. bool wasFocused : 1;
  24664. bool caretFlashState : 1;
  24665. bool keepCursorOnScreen : 1;
  24666. bool tabKeyUsed : 1;
  24667. bool menuActive : 1;
  24668. UndoManager undoManager;
  24669. float cursorX, cursorY, cursorHeight;
  24670. int maxTextLength;
  24671. int selectionStart, selectionEnd;
  24672. int leftIndent, topIndent;
  24673. unsigned int lastTransactionTime;
  24674. Font currentFont;
  24675. int totalNumChars, caretPosition;
  24676. VoidArray sections;
  24677. String textToShowWhenEmpty;
  24678. Colour colourForTextWhenEmpty;
  24679. tchar passwordCharacter;
  24680. enum
  24681. {
  24682. notDragging,
  24683. draggingSelectionStart,
  24684. draggingSelectionEnd
  24685. } dragType;
  24686. String allowedCharacters;
  24687. SortedSet <void*> listeners;
  24688. friend class TextEditorInsertAction;
  24689. friend class TextEditorRemoveAction;
  24690. void coalesceSimilarSections() throw();
  24691. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24692. void clearInternal (UndoManager* const um) throw();
  24693. void insert (const String& text,
  24694. const int insertIndex,
  24695. const Font& font,
  24696. const Colour& colour,
  24697. UndoManager* const um,
  24698. const int caretPositionToMoveTo) throw();
  24699. void reinsert (const int insertIndex,
  24700. const VoidArray& sections) throw();
  24701. void remove (const int startIndex,
  24702. int endIndex,
  24703. UndoManager* const um,
  24704. const int caretPositionToMoveTo) throw();
  24705. void getCharPosition (const int index,
  24706. float& x, float& y,
  24707. float& lineHeight) const throw();
  24708. void updateCaretPosition() throw();
  24709. int indexAtPosition (const float x,
  24710. const float y) throw();
  24711. int findWordBreakAfter (const int position) const throw();
  24712. int findWordBreakBefore (const int position) const throw();
  24713. friend class TextHolderComponent;
  24714. friend class TextEditorViewport;
  24715. void drawContent (Graphics& g);
  24716. void updateTextHolderSize() throw();
  24717. float getWordWrapWidth() const throw();
  24718. void timerCallbackInt();
  24719. void repaintCaret();
  24720. void repaintText (int textStartIndex, int textEndIndex);
  24721. TextEditor (const TextEditor&);
  24722. const TextEditor& operator= (const TextEditor&);
  24723. };
  24724. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24725. /********* End of inlined file: juce_TextEditor.h *********/
  24726. class Label;
  24727. /**
  24728. A class for receiving events from a Label.
  24729. You can register a LabelListener with a Label using the Label::addListener()
  24730. method, and it will be called when the text of the label changes, either because
  24731. of a call to Label::setText() or by the user editing the text (if the label is
  24732. editable).
  24733. @see Label::addListener, Label::removeListener
  24734. */
  24735. class JUCE_API LabelListener
  24736. {
  24737. public:
  24738. /** Destructor. */
  24739. virtual ~LabelListener() {}
  24740. /** Called when a Label's text has changed.
  24741. */
  24742. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24743. };
  24744. /**
  24745. A component that displays a text string, and can optionally become a text
  24746. editor when clicked.
  24747. */
  24748. class JUCE_API Label : public Component,
  24749. public SettableTooltipClient,
  24750. protected TextEditorListener,
  24751. private ComponentListener
  24752. {
  24753. public:
  24754. /** Creates a Label.
  24755. @param componentName the name to give the component
  24756. @param labelText the text to show in the label
  24757. */
  24758. Label (const String& componentName,
  24759. const String& labelText);
  24760. /** Destructor. */
  24761. ~Label();
  24762. /** Changes the label text.
  24763. If broadcastChangeMessage is true and the new text is different to the current
  24764. text, then the class will broadcast a change message to any LabelListeners that
  24765. are registered.
  24766. */
  24767. void setText (const String& newText,
  24768. const bool broadcastChangeMessage);
  24769. /** Returns the label's current text.
  24770. @param returnActiveEditorContents if this is true and the label is currently
  24771. being edited, then this method will return the
  24772. text as it's being shown in the editor. If false,
  24773. then the value returned here won't be updated until
  24774. the user has finished typing and pressed the return
  24775. key.
  24776. */
  24777. const String getText (const bool returnActiveEditorContents = false) const throw();
  24778. /** Changes the font to use to draw the text.
  24779. @see getFont
  24780. */
  24781. void setFont (const Font& newFont) throw();
  24782. /** Returns the font currently being used.
  24783. @see setFont
  24784. */
  24785. const Font& getFont() const throw();
  24786. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24787. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24788. methods.
  24789. Note that you can also use the constants from TextEditor::ColourIds to change the
  24790. colour of the text editor that is opened when a label is editable.
  24791. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24792. */
  24793. enum ColourIds
  24794. {
  24795. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  24796. textColourId = 0x1000281, /**< The colour for the text. */
  24797. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  24798. Leave this transparent to not have an outline. */
  24799. };
  24800. /** Sets the style of justification to be used for positioning the text.
  24801. (The default is Justification::centredLeft)
  24802. */
  24803. void setJustificationType (const Justification& justification) throw();
  24804. /** Returns the type of justification, as set in setJustificationType(). */
  24805. const Justification getJustificationType() const throw() { return justification; }
  24806. /** Changes the gap that is left between the edge of the component and the text.
  24807. By default there's a small gap left at the sides of the component to allow for
  24808. the drawing of the border, but you can change this if necessary.
  24809. */
  24810. void setBorderSize (int horizontalBorder, int verticalBorder);
  24811. /** Returns the size of the horizontal gap being left around the text.
  24812. */
  24813. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  24814. /** Returns the size of the vertical gap being left around the text.
  24815. */
  24816. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  24817. /** Makes this label "stick to" another component.
  24818. This will cause the label to follow another component around, staying
  24819. either to its left or above it.
  24820. @param owner the component to follow
  24821. @param onLeft if true, the label will stay on the left of its component; if
  24822. false, it will stay above it.
  24823. */
  24824. void attachToComponent (Component* owner,
  24825. const bool onLeft);
  24826. /** If this label has been attached to another component using attachToComponent, this
  24827. returns the other component.
  24828. Returns 0 if the label is not attached.
  24829. */
  24830. Component* getAttachedComponent() const throw() { return ownerComponent; }
  24831. /** If the label is attached to the left of another component, this returns true.
  24832. Returns false if the label is above the other component. This is only relevent if
  24833. attachToComponent() has been called.
  24834. */
  24835. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  24836. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  24837. using ellipsis.
  24838. @see Graphics::drawFittedText
  24839. */
  24840. void setMinimumHorizontalScale (const float newScale);
  24841. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  24842. /** Registers a listener that will be called when the label's text changes. */
  24843. void addListener (LabelListener* const listener) throw();
  24844. /** Deregisters a previously-registered listener. */
  24845. void removeListener (LabelListener* const listener) throw();
  24846. /** Makes the label turn into a TextEditor when clicked.
  24847. By default this is turned off.
  24848. If turned on, then single- or double-clicking will turn the label into
  24849. an editor. If the user then changes the text, then the ChangeBroadcaster
  24850. base class will be used to send change messages to any listeners that
  24851. have registered.
  24852. If the user changes the text, the textWasEdited() method will be called
  24853. afterwards, and subclasses can override this if they need to do anything
  24854. special.
  24855. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  24856. @param editOnDoubleClick if true, a double-click is needed to start editing
  24857. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  24858. edited will discard any changes; if false, then this will
  24859. commit the changes.
  24860. @see showEditor, setEditorColours, TextEditor
  24861. */
  24862. void setEditable (const bool editOnSingleClick,
  24863. const bool editOnDoubleClick = false,
  24864. const bool lossOfFocusDiscardsChanges = false) throw();
  24865. /** Returns true if this option was set using setEditable(). */
  24866. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  24867. /** Returns true if this option was set using setEditable(). */
  24868. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  24869. /** Returns true if this option has been set in a call to setEditable(). */
  24870. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  24871. /** Returns true if the user can edit this label's text. */
  24872. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  24873. /** Makes the editor appear as if the label had been clicked by the user.
  24874. @see textWasEdited, setEditable
  24875. */
  24876. void showEditor();
  24877. /** Hides the editor if it was being shown.
  24878. @param discardCurrentEditorContents if true, the label's text will be
  24879. reset to whatever it was before the editor
  24880. was shown; if false, the current contents of the
  24881. editor will be used to set the label's text
  24882. before it is hidden.
  24883. */
  24884. void hideEditor (const bool discardCurrentEditorContents);
  24885. /** Returns true if the editor is currently focused and active. */
  24886. bool isBeingEdited() const throw();
  24887. juce_UseDebuggingNewOperator
  24888. protected:
  24889. /** @internal */
  24890. void paint (Graphics& g);
  24891. /** @internal */
  24892. void resized();
  24893. /** @internal */
  24894. void mouseUp (const MouseEvent& e);
  24895. /** @internal */
  24896. void mouseDoubleClick (const MouseEvent& e);
  24897. /** @internal */
  24898. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24899. /** @internal */
  24900. void componentParentHierarchyChanged (Component& component);
  24901. /** @internal */
  24902. void componentVisibilityChanged (Component& component);
  24903. /** @internal */
  24904. void inputAttemptWhenModal();
  24905. /** @internal */
  24906. void focusGained (FocusChangeType);
  24907. /** @internal */
  24908. void enablementChanged();
  24909. /** @internal */
  24910. KeyboardFocusTraverser* createFocusTraverser();
  24911. /** @internal */
  24912. void textEditorTextChanged (TextEditor& editor);
  24913. /** @internal */
  24914. void textEditorReturnKeyPressed (TextEditor& editor);
  24915. /** @internal */
  24916. void textEditorEscapeKeyPressed (TextEditor& editor);
  24917. /** @internal */
  24918. void textEditorFocusLost (TextEditor& editor);
  24919. /** @internal */
  24920. void colourChanged();
  24921. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  24922. Subclasses can override this if they need to customise this component in some way.
  24923. */
  24924. virtual TextEditor* createEditorComponent();
  24925. /** Called after the user changes the text.
  24926. */
  24927. virtual void textWasEdited();
  24928. /** Called when the text has been altered.
  24929. */
  24930. virtual void textWasChanged();
  24931. private:
  24932. String text;
  24933. Font font;
  24934. Justification justification;
  24935. TextEditor* editor;
  24936. SortedSet <void*> listeners;
  24937. Component* ownerComponent;
  24938. ComponentDeletionWatcher* deletionWatcher;
  24939. int horizontalBorderSize, verticalBorderSize;
  24940. float minimumHorizontalScale;
  24941. bool editSingleClick : 1;
  24942. bool editDoubleClick : 1;
  24943. bool lossOfFocusDiscardsChanges : 1;
  24944. bool leftOfOwnerComp : 1;
  24945. bool updateFromTextEditorContents();
  24946. void callChangeListeners();
  24947. Label (const Label&);
  24948. const Label& operator= (const Label&);
  24949. };
  24950. #endif // __JUCE_LABEL_JUCEHEADER__
  24951. /********* End of inlined file: juce_Label.h *********/
  24952. class ComboBox;
  24953. /**
  24954. A class for receiving events from a ComboBox.
  24955. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  24956. method, and it will be called when the selected item in the box changes.
  24957. @see ComboBox::addListener, ComboBox::removeListener
  24958. */
  24959. class JUCE_API ComboBoxListener
  24960. {
  24961. public:
  24962. /** Destructor. */
  24963. virtual ~ComboBoxListener() {}
  24964. /** Called when a ComboBox has its selected item changed.
  24965. */
  24966. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  24967. };
  24968. /**
  24969. A component that lets the user choose from a drop-down list of choices.
  24970. The combo-box has a list of text strings, each with an associated id number,
  24971. that will be shown in the drop-down list when the user clicks on the component.
  24972. The currently selected choice is displayed in the combo-box, and this can
  24973. either be read-only text, or editable.
  24974. To find out when the user selects a different item or edits the text, you
  24975. can register a ComboBoxListener to receive callbacks.
  24976. @see ComboBoxListener
  24977. */
  24978. class JUCE_API ComboBox : public Component,
  24979. public SettableTooltipClient,
  24980. private LabelListener,
  24981. private AsyncUpdater
  24982. {
  24983. public:
  24984. /** Creates a combo-box.
  24985. On construction, the text field will be empty, so you should call the
  24986. setSelectedId() or setText() method to choose the initial value before
  24987. displaying it.
  24988. @param componentName the name to set for the component (see Component::setName())
  24989. */
  24990. ComboBox (const String& componentName);
  24991. /** Destructor. */
  24992. ~ComboBox();
  24993. /** Sets whether the test in the combo-box is editable.
  24994. The default state for a new ComboBox is non-editable, and can only be changed
  24995. by choosing from the drop-down list.
  24996. */
  24997. void setEditableText (const bool isEditable);
  24998. /** Returns true if the text is directly editable.
  24999. @see setEditableText
  25000. */
  25001. bool isTextEditable() const throw();
  25002. /** Sets the style of justification to be used for positioning the text.
  25003. The default is Justification::centredLeft. The text is displayed using a
  25004. Label component inside the ComboBox.
  25005. */
  25006. void setJustificationType (const Justification& justification) throw();
  25007. /** Returns the current justification for the text box.
  25008. @see setJustificationType
  25009. */
  25010. const Justification getJustificationType() const throw();
  25011. /** Adds an item to be shown in the drop-down list.
  25012. @param newItemText the text of the item to show in the list
  25013. @param newItemId an associated ID number that can be set or retrieved - see
  25014. getSelectedId() and setSelectedId()
  25015. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25016. */
  25017. void addItem (const String& newItemText,
  25018. const int newItemId) throw();
  25019. /** Adds a separator line to the drop-down list.
  25020. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25021. */
  25022. void addSeparator() throw();
  25023. /** Adds a heading to the drop-down list, so that you can group the items into
  25024. different sections.
  25025. The headings are indented slightly differently to set them apart from the
  25026. items on the list, and obviously can't be selected. You might want to add
  25027. separators between your sections too.
  25028. @see addItem, addSeparator
  25029. */
  25030. void addSectionHeading (const String& headingName) throw();
  25031. /** This allows items in the drop-down list to be selectively disabled.
  25032. When you add an item, it's enabled by default, but you can call this
  25033. method to change its status.
  25034. If you disable an item which is already selected, this won't change the
  25035. current selection - it just stops the user choosing that item from the list.
  25036. */
  25037. void setItemEnabled (const int itemId,
  25038. const bool isEnabled) throw();
  25039. /** Changes the text for an existing item.
  25040. */
  25041. void changeItemText (const int itemId,
  25042. const String& newText) throw();
  25043. /** Removes all the items from the drop-down list.
  25044. If this call causes the content to be cleared, then a change-message
  25045. will be broadcast unless dontSendChangeMessage is true.
  25046. @see addItem, removeItem, getNumItems
  25047. */
  25048. void clear (const bool dontSendChangeMessage = false);
  25049. /** Returns the number of items that have been added to the list.
  25050. Note that this doesn't include headers or separators.
  25051. */
  25052. int getNumItems() const throw();
  25053. /** Returns the text for one of the items in the list.
  25054. Note that this doesn't include headers or separators.
  25055. @param index the item's index from 0 to (getNumItems() - 1)
  25056. */
  25057. const String getItemText (const int index) const throw();
  25058. /** Returns the ID for one of the items in the list.
  25059. Note that this doesn't include headers or separators.
  25060. @param index the item's index from 0 to (getNumItems() - 1)
  25061. */
  25062. int getItemId (const int index) const throw();
  25063. /** Returns the ID of the item that's currently shown in the box.
  25064. If no item is selected, or if the text is editable and the user
  25065. has entered something which isn't one of the items in the list, then
  25066. this will return 0.
  25067. @see setSelectedId, getSelectedItemIndex, getText
  25068. */
  25069. int getSelectedId() const throw();
  25070. /** Sets one of the items to be the current selection.
  25071. This will set the ComboBox's text to that of the item that matches
  25072. this ID.
  25073. @param newItemId the new item to select
  25074. @param dontSendChangeMessage if set to true, this method won't trigger a
  25075. change notification
  25076. @see getSelectedId, setSelectedItemIndex, setText
  25077. */
  25078. void setSelectedId (const int newItemId,
  25079. const bool dontSendChangeMessage = false) throw();
  25080. /** Returns the index of the item that's currently shown in the box.
  25081. If no item is selected, or if the text is editable and the user
  25082. has entered something which isn't one of the items in the list, then
  25083. this will return -1.
  25084. @see setSelectedItemIndex, getSelectedId, getText
  25085. */
  25086. int getSelectedItemIndex() const throw();
  25087. /** Sets one of the items to be the current selection.
  25088. This will set the ComboBox's text to that of the item at the given
  25089. index in the list.
  25090. @param newItemIndex the new item to select
  25091. @param dontSendChangeMessage if set to true, this method won't trigger a
  25092. change notification
  25093. @see getSelectedItemIndex, setSelectedId, setText
  25094. */
  25095. void setSelectedItemIndex (const int newItemIndex,
  25096. const bool dontSendChangeMessage = false) throw();
  25097. /** Returns the text that is currently shown in the combo-box's text field.
  25098. If the ComboBox has editable text, then this text may have been edited
  25099. by the user; otherwise it will be one of the items from the list, or
  25100. possibly an empty string if nothing was selected.
  25101. @see setText, getSelectedId, getSelectedItemIndex
  25102. */
  25103. const String getText() const throw();
  25104. /** Sets the contents of the combo-box's text field.
  25105. The text passed-in will be set as the current text regardless of whether
  25106. it is one of the items in the list. If the current text isn't one of the
  25107. items, then getSelectedId() will return -1, otherwise it wil return
  25108. the approriate ID.
  25109. @param newText the text to select
  25110. @param dontSendChangeMessage if set to true, this method won't trigger a
  25111. change notification
  25112. @see getText
  25113. */
  25114. void setText (const String& newText,
  25115. const bool dontSendChangeMessage = false) throw();
  25116. /** Programmatically opens the text editor to allow the user to edit the current item.
  25117. This is the same effect as when the box is clicked-on.
  25118. @see Label::showEditor();
  25119. */
  25120. void showEditor();
  25121. /** Registers a listener that will be called when the box's content changes. */
  25122. void addListener (ComboBoxListener* const listener) throw();
  25123. /** Deregisters a previously-registered listener. */
  25124. void removeListener (ComboBoxListener* const listener) throw();
  25125. /** Sets a message to display when there is no item currently selected.
  25126. @see getTextWhenNothingSelected
  25127. */
  25128. void setTextWhenNothingSelected (const String& newMessage) throw();
  25129. /** Returns the text that is shown when no item is selected.
  25130. @see setTextWhenNothingSelected
  25131. */
  25132. const String getTextWhenNothingSelected() const throw();
  25133. /** Sets the message to show when there are no items in the list, and the user clicks
  25134. on the drop-down box.
  25135. By default it just says "no choices", but this lets you change it to something more
  25136. meaningful.
  25137. */
  25138. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25139. /** Returns the text shown when no items have been added to the list.
  25140. @see setTextWhenNoChoicesAvailable
  25141. */
  25142. const String getTextWhenNoChoicesAvailable() const throw();
  25143. /** Gives the ComboBox a tooltip. */
  25144. void setTooltip (const String& newTooltip);
  25145. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25146. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25147. methods.
  25148. To change the colours of the menu that pops up
  25149. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25150. */
  25151. enum ColourIds
  25152. {
  25153. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25154. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25155. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25156. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25157. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25158. };
  25159. /** @internal */
  25160. void labelTextChanged (Label*);
  25161. /** @internal */
  25162. void enablementChanged();
  25163. /** @internal */
  25164. void colourChanged();
  25165. /** @internal */
  25166. void focusGained (Component::FocusChangeType cause);
  25167. /** @internal */
  25168. void focusLost (Component::FocusChangeType cause);
  25169. /** @internal */
  25170. void handleAsyncUpdate();
  25171. /** @internal */
  25172. const String getTooltip() { return label->getTooltip(); }
  25173. /** @internal */
  25174. void mouseDown (const MouseEvent&);
  25175. /** @internal */
  25176. void mouseDrag (const MouseEvent&);
  25177. /** @internal */
  25178. void mouseUp (const MouseEvent&);
  25179. /** @internal */
  25180. void lookAndFeelChanged();
  25181. /** @internal */
  25182. void paint (Graphics&);
  25183. /** @internal */
  25184. void resized();
  25185. /** @internal */
  25186. bool keyStateChanged();
  25187. /** @internal */
  25188. bool keyPressed (const KeyPress&);
  25189. juce_UseDebuggingNewOperator
  25190. private:
  25191. struct ItemInfo
  25192. {
  25193. String name;
  25194. int itemId;
  25195. bool isEnabled : 1, isHeading : 1;
  25196. bool isSeparator() const throw();
  25197. bool isRealItem() const throw();
  25198. };
  25199. OwnedArray <ItemInfo> items;
  25200. int currentIndex;
  25201. bool isButtonDown;
  25202. bool separatorPending;
  25203. bool menuActive;
  25204. SortedSet <void*> listeners;
  25205. Label* label;
  25206. String textWhenNothingSelected, noChoicesMessage;
  25207. void showPopup();
  25208. ItemInfo* getItemForId (const int itemId) const throw();
  25209. ItemInfo* getItemForIndex (const int index) const throw();
  25210. ComboBox (const ComboBox&);
  25211. const ComboBox& operator= (const ComboBox&);
  25212. };
  25213. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25214. /********* End of inlined file: juce_ComboBox.h *********/
  25215. /**
  25216. Manages the state of some audio and midi i/o devices.
  25217. This class keeps tracks of a currently-selected audio device, through
  25218. with which it continuously streams data from an audio callback, as well as
  25219. one or more midi inputs.
  25220. The idea is that your application will create one global instance of this object,
  25221. and let it take care of creating and deleting specific types of audio devices
  25222. internally. So when the device is changed, your callbacks will just keep running
  25223. without having to worry about this.
  25224. The manager can save and reload all of its device settings as XML, which
  25225. makes it very easy for you to save and reload the audio setup of your
  25226. application.
  25227. And to make it easy to let the user change its settings, there's a component
  25228. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25229. device selection/sample-rate/latency controls.
  25230. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25231. call setAudioCallback() to register your audio callback with it, and use that to process
  25232. your audio data.
  25233. The manager also acts as a handy hub for incoming midi messages, allowing a
  25234. listener to register for messages from either a specific midi device, or from whatever
  25235. the current default midi input device is. The listener then doesn't have to worry about
  25236. re-registering with different midi devices if they are changed or deleted.
  25237. And yet another neat trick is that amount of CPU time being used is measured and
  25238. available with the getCpuUsage() method.
  25239. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25240. listeners whenever one of its settings is changed.
  25241. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25242. */
  25243. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25244. {
  25245. public:
  25246. /** Creates a default AudioDeviceManager.
  25247. Initially no audio device will be selected. You should call the initialise() method
  25248. and register an audio callback with setAudioCallback() before it'll be able to
  25249. actually make any noise.
  25250. */
  25251. AudioDeviceManager();
  25252. /** Destructor. */
  25253. ~AudioDeviceManager();
  25254. /** Opens a set of audio devices ready for use.
  25255. This will attempt to open either a default audio device, or one that was
  25256. previously saved as XML.
  25257. @param numInputChannelsNeeded a minimum number of input channels needed
  25258. by your app.
  25259. @param numOutputChannelsNeeded a minimum number of output channels to open
  25260. @param savedState either a previously-saved state that was produced
  25261. by createStateXml(), or 0 if you want the manager
  25262. to choose the best device to open.
  25263. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25264. fails to open, then a default device will be used
  25265. instead. If false, then on failure, no device is
  25266. opened.
  25267. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25268. name, then that will be used as the default device
  25269. (assuming that there wasn't one specified in the XML).
  25270. The string can actually be a simple wildcard, containing "*"
  25271. and "?" characters
  25272. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25273. */
  25274. const String initialise (const int numInputChannelsNeeded,
  25275. const int numOutputChannelsNeeded,
  25276. const XmlElement* const savedState,
  25277. const bool selectDefaultDeviceOnFailure,
  25278. const String& preferredDefaultDeviceName = String::empty);
  25279. /** Returns some XML representing the current state of the manager.
  25280. This stores the current device, its samplerate, block size, etc, and
  25281. can be restored later with initialise().
  25282. */
  25283. XmlElement* createStateXml() const;
  25284. /**
  25285. */
  25286. struct AudioDeviceSetup
  25287. {
  25288. AudioDeviceSetup();
  25289. bool operator== (const AudioDeviceSetup& other) const;
  25290. /**
  25291. */
  25292. String outputDeviceName;
  25293. /**
  25294. */
  25295. String inputDeviceName;
  25296. /**
  25297. */
  25298. double sampleRate;
  25299. /**
  25300. */
  25301. int bufferSize;
  25302. /**
  25303. */
  25304. BitArray inputChannels;
  25305. bool useDefaultInputChannels;
  25306. /**
  25307. */
  25308. BitArray outputChannels;
  25309. bool useDefaultOutputChannels;
  25310. };
  25311. /**
  25312. */
  25313. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25314. /**
  25315. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25316. settings will be taken as having been explicitly chosen by the
  25317. user, and the next time createStateXml() is called, these settings
  25318. will be returned. If it's false, then the device is treated as a
  25319. temporary or default device, and a call to createStateXml() will
  25320. return either the last settings that were made with treatAsChosenDevice
  25321. as true, or the last XML settings that were passed into initialise().
  25322. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25323. */
  25324. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25325. const bool treatAsChosenDevice);
  25326. /** Returns the currently-active audio device. */
  25327. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25328. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25329. void setCurrentAudioDeviceType (const String& type,
  25330. const bool treatAsChosenDevice);
  25331. /** Closes the currently-open device.
  25332. You can call restartLastAudioDevice() later to reopen it in the same state
  25333. that it was just in.
  25334. */
  25335. void closeAudioDevice();
  25336. /** Tries to reload the last audio device that was running.
  25337. Note that this only reloads the last device that was running before
  25338. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25339. and can only be called after a device has been opened with SetAudioDevice().
  25340. If a device is already open, this call will do nothing.
  25341. */
  25342. void restartLastAudioDevice();
  25343. /** Gives the manager an audio callback to use.
  25344. The manager will redirect callbacks from whatever audio device is currently
  25345. in use to this callback object.
  25346. You can pass 0 in here to stop callbacks being made.
  25347. */
  25348. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25349. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25350. Returns a value between 0 and 1.0
  25351. */
  25352. double getCpuUsage() const;
  25353. /** Enables or disables a midi input device.
  25354. The list of devices can be obtained with the MidiInput::getDevices() method.
  25355. Any incoming messages from enabled input devices will be forwarded on to all the
  25356. listeners that have been registered with the addMidiInputCallback() method. They
  25357. can either register for messages from a particular device, or from just the
  25358. "default" midi input.
  25359. Routing the midi input via an AudioDeviceManager means that when a listener
  25360. registers for the default midi input, this default device can be changed by the
  25361. manager without the listeners having to know about it or re-register.
  25362. It also means that a listener can stay registered for a midi input that is disabled
  25363. or not present, so that when the input is re-enabled, the listener will start
  25364. receiving messages again.
  25365. @see addMidiInputCallback, isMidiInputEnabled
  25366. */
  25367. void setMidiInputEnabled (const String& midiInputDeviceName,
  25368. const bool enabled);
  25369. /** Returns true if a given midi input device is being used.
  25370. @see setMidiInputEnabled
  25371. */
  25372. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25373. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25374. The device name can be empty to indicate that it wants events from whatever the
  25375. current "default" device is. Or it can be the name of one of the midi input devices
  25376. (see MidiInput::getDevices() for the names).
  25377. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25378. events forwarded on to listeners.
  25379. */
  25380. void addMidiInputCallback (const String& midiInputDeviceName,
  25381. MidiInputCallback* callback);
  25382. /** Removes a listener that was previously registered with addMidiInputCallback().
  25383. */
  25384. void removeMidiInputCallback (const String& midiInputDeviceName,
  25385. MidiInputCallback* callback);
  25386. /** Sets a midi output device to use as the default.
  25387. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25388. The specified device will be opened automatically and can be retrieved with the
  25389. getDefaultMidiOutput() method.
  25390. Pass in an empty string to deselect all devices. For the default device, you
  25391. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25392. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25393. */
  25394. void setDefaultMidiOutput (const String& deviceName);
  25395. /** Returns the name of the default midi output.
  25396. @see setDefaultMidiOutput, getDefaultMidiOutput
  25397. */
  25398. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25399. /** Returns the current default midi output device.
  25400. If no device has been selected, or the device can't be opened, this will
  25401. return 0.
  25402. @see getDefaultMidiOutputName
  25403. */
  25404. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25405. /**
  25406. */
  25407. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25408. /** Creates a list of available types.
  25409. This will add a set of new AudioIODeviceType objects to the specified list, to
  25410. represent each available types of device.
  25411. You can override this if your app needs to do something specific, like avoid
  25412. using DirectSound devices, etc.
  25413. */
  25414. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25415. /** Plays a beep through the current audio device.
  25416. This is here to allow the audio setup UI panels to easily include a "test"
  25417. button so that the user can check where the audio is coming from.
  25418. */
  25419. void playTestSound();
  25420. /** Turns on level-measuring.
  25421. When enabled, the device manager will measure the peak input level
  25422. across all channels, and you can get this level by calling getCurrentInputLevel().
  25423. This is mainly intended for audio setup UI panels to use to create a mic
  25424. level display, so that the user can check that they've selected the right
  25425. device.
  25426. A simple filter is used to make the level decay smoothly, but this is
  25427. only intended for giving rough feedback, and not for any kind of accurate
  25428. measurement.
  25429. */
  25430. void enableInputLevelMeasurement (const bool enableMeasurement);
  25431. /** Returns the current input level.
  25432. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25433. See enableInputLevelMeasurement() for more info.
  25434. */
  25435. double getCurrentInputLevel() const;
  25436. juce_UseDebuggingNewOperator
  25437. private:
  25438. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25439. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25440. AudioDeviceSetup currentSetup;
  25441. AudioIODevice* currentAudioDevice;
  25442. AudioIODeviceCallback* currentCallback;
  25443. int numInputChansNeeded, numOutputChansNeeded;
  25444. String currentDeviceType;
  25445. BitArray inputChannels, outputChannels;
  25446. XmlElement* lastExplicitSettings;
  25447. mutable bool listNeedsScanning;
  25448. bool useInputNames, inputLevelMeasurementEnabled;
  25449. double inputLevel;
  25450. AudioSampleBuffer* testSound;
  25451. int testSoundPosition;
  25452. StringArray midiInsFromXml;
  25453. OwnedArray <MidiInput> enabledMidiInputs;
  25454. Array <MidiInputCallback*> midiCallbacks;
  25455. Array <MidiInput*> midiCallbackDevices;
  25456. String defaultMidiOutputName;
  25457. MidiOutput* defaultMidiOutput;
  25458. CriticalSection audioCallbackLock, midiCallbackLock;
  25459. double cpuUsageMs, timeToCpuScale;
  25460. class CallbackHandler : public AudioIODeviceCallback,
  25461. public MidiInputCallback
  25462. {
  25463. public:
  25464. AudioDeviceManager* owner;
  25465. void audioDeviceIOCallback (const float** inputChannelData,
  25466. int totalNumInputChannels,
  25467. float** outputChannelData,
  25468. int totalNumOutputChannels,
  25469. int numSamples);
  25470. void audioDeviceAboutToStart (AudioIODevice*);
  25471. void audioDeviceStopped();
  25472. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25473. };
  25474. CallbackHandler callbackHandler;
  25475. friend class CallbackHandler;
  25476. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25477. int totalNumInputChannels,
  25478. float** outputChannelData,
  25479. int totalNumOutputChannels,
  25480. int numSamples);
  25481. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25482. void audioDeviceStoppedInt();
  25483. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25484. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25485. const BitArray& ins, const BitArray& outs);
  25486. void stopDevice();
  25487. void updateXml();
  25488. void createDeviceTypesIfNeeded();
  25489. void scanDevicesIfNeeded();
  25490. void deleteCurrentDevice();
  25491. double chooseBestSampleRate (double preferred) const;
  25492. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25493. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25494. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25495. AudioDeviceManager (const AudioDeviceManager&);
  25496. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25497. };
  25498. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25499. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25500. #endif
  25501. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25502. #endif
  25503. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25504. #endif
  25505. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25506. #endif
  25507. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25508. #endif
  25509. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25510. /********* Start of inlined file: juce_Sampler.h *********/
  25511. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25512. #define __JUCE_SAMPLER_JUCEHEADER__
  25513. /********* Start of inlined file: juce_Synthesiser.h *********/
  25514. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25515. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25516. /**
  25517. Describes one of the sounds that a Synthesiser can play.
  25518. A synthesiser can contain one or more sounds, and a sound can choose which
  25519. midi notes and channels can trigger it.
  25520. The SynthesiserSound is a passive class that just describes what the sound is -
  25521. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25522. more than one SynthesiserVoice to play the same sound at the same time.
  25523. @see Synthesiser, SynthesiserVoice
  25524. */
  25525. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25526. {
  25527. protected:
  25528. SynthesiserSound();
  25529. public:
  25530. /** Destructor. */
  25531. virtual ~SynthesiserSound();
  25532. /** Returns true if this sound should be played when a given midi note is pressed.
  25533. The Synthesiser will use this information when deciding which sounds to trigger
  25534. for a given note.
  25535. */
  25536. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25537. /** Returns true if the sound should be triggered by midi events on a given channel.
  25538. The Synthesiser will use this information when deciding which sounds to trigger
  25539. for a given note.
  25540. */
  25541. virtual bool appliesToChannel (const int midiChannel) = 0;
  25542. /**
  25543. */
  25544. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25545. juce_UseDebuggingNewOperator
  25546. };
  25547. /**
  25548. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25549. A voice plays a single sound at a time, and a synthesiser holds an array of
  25550. voices so that it can play polyphonically.
  25551. @see Synthesiser, SynthesiserSound
  25552. */
  25553. class JUCE_API SynthesiserVoice
  25554. {
  25555. public:
  25556. /** Creates a voice. */
  25557. SynthesiserVoice();
  25558. /** Destructor. */
  25559. virtual ~SynthesiserVoice();
  25560. /** Returns the midi note that this voice is currently playing.
  25561. Returns a value less than 0 if no note is playing.
  25562. */
  25563. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25564. /** Returns the sound that this voice is currently playing.
  25565. Returns 0 if it's not playing.
  25566. */
  25567. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25568. /** Must return true if this voice object is capable of playing the given sound.
  25569. If there are different classes of sound, and different classes of voice, a voice can
  25570. choose which ones it wants to take on.
  25571. A typical implementation of this method may just return true if there's only one type
  25572. of voice and sound, or it might check the type of the sound object passed-in and
  25573. see if it's one that it understands.
  25574. */
  25575. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25576. /** Called to start a new note.
  25577. This will be called during the rendering callback, so must be fast and thread-safe.
  25578. */
  25579. virtual void startNote (const int midiNoteNumber,
  25580. const float velocity,
  25581. SynthesiserSound* sound,
  25582. const int currentPitchWheelPosition) = 0;
  25583. /** Called to stop a note.
  25584. This will be called during the rendering callback, so must be fast and thread-safe.
  25585. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25586. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25587. and allow the synth to reassign it another sound.
  25588. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25589. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25590. finishes playing (during the rendering callback), it must make sure that it calls
  25591. clearCurrentNote().
  25592. */
  25593. virtual void stopNote (const bool allowTailOff) = 0;
  25594. /** Called to let the voice know that the pitch wheel has been moved.
  25595. This will be called during the rendering callback, so must be fast and thread-safe.
  25596. */
  25597. virtual void pitchWheelMoved (const int newValue) = 0;
  25598. /** Called to let the voice know that a midi controller has been moved.
  25599. This will be called during the rendering callback, so must be fast and thread-safe.
  25600. */
  25601. virtual void controllerMoved (const int controllerNumber,
  25602. const int newValue) = 0;
  25603. /** Renders the next block of data for this voice.
  25604. The output audio data must be added to the current contents of the buffer provided.
  25605. Only the region of the buffer between startSample and (startSample + numSamples)
  25606. should be altered by this method.
  25607. If the voice is currently silent, it should just return without doing anything.
  25608. If the sound that the voice is playing finishes during the course of this rendered
  25609. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25610. The size of the blocks that are rendered can change each time it is called, and may
  25611. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25612. the voice's methods will be called to tell it about note and controller events.
  25613. */
  25614. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25615. int startSample,
  25616. int numSamples) = 0;
  25617. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25618. midi channel.
  25619. If it's not currently playing, this will return false.
  25620. */
  25621. bool isPlayingChannel (const int midiChannel) const;
  25622. /** Changes the voice's reference sample rate.
  25623. The rate is set so that subclasses know the output rate and can set their pitch
  25624. accordingly.
  25625. This method is called by the synth, and subclasses can access the current rate with
  25626. the currentSampleRate member.
  25627. */
  25628. void setCurrentPlaybackSampleRate (const double newRate);
  25629. juce_UseDebuggingNewOperator
  25630. protected:
  25631. /** Returns the current target sample rate at which rendering is being done.
  25632. This is available for subclasses so they can pitch things correctly.
  25633. */
  25634. double getSampleRate() const throw() { return currentSampleRate; }
  25635. /** Resets the state of this voice after a sound has finished playing.
  25636. The subclass must call this when it finishes playing a note and becomes available
  25637. to play new ones.
  25638. It must either call it in the stopNote() method, or if the voice is tailing off,
  25639. then it should call it later during the renderNextBlock method, as soon as it
  25640. finishes its tail-off.
  25641. It can also be called at any time during the render callback if the sound happens
  25642. to have finished, e.g. if it's playing a sample and the sample finishes.
  25643. */
  25644. void clearCurrentNote();
  25645. private:
  25646. friend class Synthesiser;
  25647. double currentSampleRate;
  25648. int currentlyPlayingNote;
  25649. uint32 noteOnTime;
  25650. SynthesiserSound::Ptr currentlyPlayingSound;
  25651. };
  25652. /**
  25653. Base class for a musical device that can play sounds.
  25654. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25655. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25656. which can play back one of these sounds.
  25657. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25658. set of sounds, and a set of voices it can use to play them. If you only give it
  25659. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25660. have available.
  25661. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25662. events that go in will be scanned for note on/off messages, and these are used to
  25663. start and stop the voices playing the appropriate sounds.
  25664. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25665. noteOff() and other controller methods.
  25666. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25667. what the target playback rate is. This value is passed on to the voices so that
  25668. they can pitch their output correctly.
  25669. */
  25670. class JUCE_API Synthesiser
  25671. {
  25672. public:
  25673. /** Creates a new synthesiser.
  25674. You'll need to add some sounds and voices before it'll make any sound..
  25675. */
  25676. Synthesiser();
  25677. /** Destructor. */
  25678. virtual ~Synthesiser();
  25679. /** Deletes all voices. */
  25680. void clearVoices();
  25681. /** Returns the number of voices that have been added. */
  25682. int getNumVoices() const throw() { return voices.size(); }
  25683. /** Returns one of the voices that have been added. */
  25684. SynthesiserVoice* getVoice (const int index) const throw();
  25685. /** Adds a new voice to the synth.
  25686. All the voices should be the same class of object and are treated equally.
  25687. The object passed in will be managed by the synthesiser, which will delete
  25688. it later on when no longer needed. The caller should not retain a pointer to the
  25689. voice.
  25690. */
  25691. void addVoice (SynthesiserVoice* const newVoice);
  25692. /** Deletes one of the voices. */
  25693. void removeVoice (const int index);
  25694. /** Deletes all sounds. */
  25695. void clearSounds();
  25696. /** Returns the number of sounds that have been added to the synth. */
  25697. int getNumSounds() const throw() { return sounds.size(); }
  25698. /** Returns one of the sounds. */
  25699. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25700. /** Adds a new sound to the synthesiser.
  25701. The object passed in is reference counted, so will be deleted when it is removed
  25702. from the synthesiser, and when no voices are still using it.
  25703. */
  25704. void addSound (const SynthesiserSound::Ptr& newSound);
  25705. /** Removes and deletes one of the sounds. */
  25706. void removeSound (const int index);
  25707. /** If set to true, then the synth will try to take over an existing voice if
  25708. it runs out and needs to play another note.
  25709. The value of this boolean is passed into findFreeVoice(), so the result will
  25710. depend on the implementation of this method.
  25711. */
  25712. void setNoteStealingEnabled (const bool shouldStealNotes);
  25713. /** Returns true if note-stealing is enabled.
  25714. @see setNoteStealingEnabled
  25715. */
  25716. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25717. /** Triggers a note-on event.
  25718. The default method here will find all the sounds that want to be triggered by
  25719. this note/channel. For each sound, it'll try to find a free voice, and use the
  25720. voice to start playing the sound.
  25721. Subclasses might want to override this if they need a more complex algorithm.
  25722. This method will be called automatically according to the midi data passed into
  25723. renderNextBlock(), but may be called explicitly too.
  25724. */
  25725. virtual void noteOn (const int midiChannel,
  25726. const int midiNoteNumber,
  25727. const float velocity);
  25728. /** Triggers a note-off event.
  25729. This will turn off any voices that are playing a sound for the given note/channel.
  25730. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25731. (if they can do). If this is false, the notes will all be cut off immediately.
  25732. This method will be called automatically according to the midi data passed into
  25733. renderNextBlock(), but may be called explicitly too.
  25734. */
  25735. virtual void noteOff (const int midiChannel,
  25736. const int midiNoteNumber,
  25737. const bool allowTailOff);
  25738. /** Turns off all notes.
  25739. This will turn off any voices that are playing a sound on the given midi channel.
  25740. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25741. which channel they're playing.
  25742. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25743. (if they can do). If this is false, the notes will all be cut off immediately.
  25744. This method will be called automatically according to the midi data passed into
  25745. renderNextBlock(), but may be called explicitly too.
  25746. */
  25747. virtual void allNotesOff (const int midiChannel,
  25748. const bool allowTailOff);
  25749. /** Sends a pitch-wheel message.
  25750. This will send a pitch-wheel message to any voices that are playing sounds on
  25751. the given midi channel.
  25752. This method will be called automatically according to the midi data passed into
  25753. renderNextBlock(), but may be called explicitly too.
  25754. @param midiChannel the midi channel for the event
  25755. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25756. */
  25757. virtual void handlePitchWheel (const int midiChannel,
  25758. const int wheelValue);
  25759. /** Sends a midi controller message.
  25760. This will send a midi controller message to any voices that are playing sounds on
  25761. the given midi channel.
  25762. This method will be called automatically according to the midi data passed into
  25763. renderNextBlock(), but may be called explicitly too.
  25764. @param midiChannel the midi channel for the event
  25765. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  25766. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  25767. */
  25768. virtual void handleController (const int midiChannel,
  25769. const int controllerNumber,
  25770. const int controllerValue);
  25771. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  25772. render.
  25773. This value is propagated to the voices so that they can use it to render the correct
  25774. pitches.
  25775. */
  25776. void setCurrentPlaybackSampleRate (const double sampleRate);
  25777. /** Creates the next block of audio output.
  25778. This will process the next numSamples of data from all the voices, and add that output
  25779. to the audio block supplied, starting from the offset specified. Note that the
  25780. data will be added to the current contents of the buffer, so you should clear it
  25781. before calling this method if necessary.
  25782. The midi events in the inputMidi buffer are parsed for note and controller events,
  25783. and these are used to trigger the voices. Note that the startSample offset applies
  25784. both to the audio output buffer and the midi input buffer, so any midi events
  25785. with timestamps outside the specified region will be ignored.
  25786. */
  25787. void renderNextBlock (AudioSampleBuffer& outputAudio,
  25788. const MidiBuffer& inputMidi,
  25789. int startSample,
  25790. int numSamples);
  25791. juce_UseDebuggingNewOperator
  25792. protected:
  25793. /** This is used to control access to the rendering callback and the note trigger methods. */
  25794. CriticalSection lock;
  25795. OwnedArray <SynthesiserVoice> voices;
  25796. ReferenceCountedArray <SynthesiserSound> sounds;
  25797. /** The last pitch-wheel values for each midi channel. */
  25798. int lastPitchWheelValues [16];
  25799. /** Searches through the voices to find one that's not currently playing, and which
  25800. can play the given sound.
  25801. Returns 0 if all voices are busy and stealing isn't enabled.
  25802. This can be overridden to implement custom voice-stealing algorithms.
  25803. */
  25804. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  25805. const bool stealIfNoneAvailable) const;
  25806. /** Starts a specified voice playing a particular sound.
  25807. You'll probably never need to call this, it's used internally by noteOn(), but
  25808. may be needed by subclasses for custom behaviours.
  25809. */
  25810. void startVoice (SynthesiserVoice* const voice,
  25811. SynthesiserSound* const sound,
  25812. const int midiChannel,
  25813. const int midiNoteNumber,
  25814. const float velocity);
  25815. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  25816. int findFreeVoice (const bool) const { return 0; }
  25817. private:
  25818. double sampleRate;
  25819. uint32 lastNoteOnCounter;
  25820. bool shouldStealNotes;
  25821. Synthesiser (const Synthesiser&);
  25822. const Synthesiser& operator= (const Synthesiser&);
  25823. };
  25824. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  25825. /********* End of inlined file: juce_Synthesiser.h *********/
  25826. /**
  25827. A subclass of SynthesiserSound that represents a sampled audio clip.
  25828. This is a pretty basic sampler, and just attempts to load the whole audio stream
  25829. into memory.
  25830. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25831. give it some SampledSound objects to play.
  25832. @see SamplerVoice, Synthesiser, SynthesiserSound
  25833. */
  25834. class JUCE_API SamplerSound : public SynthesiserSound
  25835. {
  25836. public:
  25837. /** Creates a sampled sound from an audio reader.
  25838. This will attempt to load the audio from the source into memory and store
  25839. it in this object.
  25840. @param name a name for the sample
  25841. @param source the audio to load. This object can be safely deleted by the
  25842. caller after this constructor returns
  25843. @param midiNotes the set of midi keys that this sound should be played on. This
  25844. is used by the SynthesiserSound::appliesToNote() method
  25845. @param midiNoteForNormalPitch the midi note at which the sample should be played
  25846. with its natural rate. All other notes will be pitched
  25847. up or down relative to this one
  25848. @param attackTimeSecs the attack (fade-in) time, in seconds
  25849. @param releaseTimeSecs the decay (fade-out) time, in seconds
  25850. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  25851. source, in seconds
  25852. */
  25853. SamplerSound (const String& name,
  25854. AudioFormatReader& source,
  25855. const BitArray& midiNotes,
  25856. const int midiNoteForNormalPitch,
  25857. const double attackTimeSecs,
  25858. const double releaseTimeSecs,
  25859. const double maxSampleLengthSeconds);
  25860. /** Destructor. */
  25861. ~SamplerSound();
  25862. /** Returns the sample's name */
  25863. const String& getName() const throw() { return name; }
  25864. /** Returns the audio sample data.
  25865. This could be 0 if there was a problem loading it.
  25866. */
  25867. AudioSampleBuffer* getAudioData() const throw() { return data; }
  25868. bool appliesToNote (const int midiNoteNumber);
  25869. bool appliesToChannel (const int midiChannel);
  25870. juce_UseDebuggingNewOperator
  25871. private:
  25872. friend class SamplerVoice;
  25873. String name;
  25874. AudioSampleBuffer* data;
  25875. double sourceSampleRate;
  25876. BitArray midiNotes;
  25877. int length, attackSamples, releaseSamples;
  25878. int midiRootNote;
  25879. };
  25880. /**
  25881. A subclass of SynthesiserVoice that can play a SamplerSound.
  25882. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25883. give it some SampledSound objects to play.
  25884. @see SamplerSound, Synthesiser, SynthesiserVoice
  25885. */
  25886. class JUCE_API SamplerVoice : public SynthesiserVoice
  25887. {
  25888. public:
  25889. /** Creates a SamplerVoice.
  25890. */
  25891. SamplerVoice();
  25892. /** Destructor. */
  25893. ~SamplerVoice();
  25894. bool canPlaySound (SynthesiserSound* sound);
  25895. void startNote (const int midiNoteNumber,
  25896. const float velocity,
  25897. SynthesiserSound* sound,
  25898. const int currentPitchWheelPosition);
  25899. void stopNote (const bool allowTailOff);
  25900. void pitchWheelMoved (const int newValue);
  25901. void controllerMoved (const int controllerNumber,
  25902. const int newValue);
  25903. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  25904. juce_UseDebuggingNewOperator
  25905. private:
  25906. double pitchRatio;
  25907. double sourceSamplePosition;
  25908. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  25909. bool isInAttack, isInRelease;
  25910. };
  25911. #endif // __JUCE_SAMPLER_JUCEHEADER__
  25912. /********* End of inlined file: juce_Sampler.h *********/
  25913. #endif
  25914. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25915. #endif
  25916. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25917. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  25918. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25919. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25920. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  25921. /**
  25922. Implements a plugin format manager for AudioUnits.
  25923. */
  25924. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  25925. {
  25926. public:
  25927. AudioUnitPluginFormat();
  25928. ~AudioUnitPluginFormat();
  25929. const String getName() const { return "AudioUnit"; }
  25930. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  25931. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25932. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  25933. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  25934. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  25935. bool doesPluginStillExist (const PluginDescription& desc);
  25936. const FileSearchPath getDefaultLocationsToSearch();
  25937. juce_UseDebuggingNewOperator
  25938. private:
  25939. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  25940. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  25941. };
  25942. #endif
  25943. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25944. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  25945. #endif
  25946. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25947. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  25948. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25949. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25950. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  25951. // Sorry, this file is just a placeholder at the moment!...
  25952. /**
  25953. Implements a plugin format manager for DirectX plugins.
  25954. */
  25955. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  25956. {
  25957. public:
  25958. DirectXPluginFormat();
  25959. ~DirectXPluginFormat();
  25960. const String getName() const { return "DirectX"; }
  25961. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  25962. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25963. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  25964. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  25965. const FileSearchPath getDefaultLocationsToSearch();
  25966. juce_UseDebuggingNewOperator
  25967. private:
  25968. DirectXPluginFormat (const DirectXPluginFormat&);
  25969. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  25970. };
  25971. #endif
  25972. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25973. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  25974. #endif
  25975. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25976. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  25977. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25978. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25979. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  25980. // Sorry, this file is just a placeholder at the moment!...
  25981. /**
  25982. Implements a plugin format manager for DirectX plugins.
  25983. */
  25984. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  25985. {
  25986. public:
  25987. LADSPAPluginFormat();
  25988. ~LADSPAPluginFormat();
  25989. const String getName() const { return "LADSPA"; }
  25990. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  25991. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25992. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  25993. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  25994. const FileSearchPath getDefaultLocationsToSearch();
  25995. juce_UseDebuggingNewOperator
  25996. private:
  25997. LADSPAPluginFormat (const LADSPAPluginFormat&);
  25998. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  25999. };
  26000. #endif
  26001. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26002. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26003. #endif
  26004. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26005. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26006. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26007. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26008. #if JUCE_PLUGINHOST_VST
  26009. /**
  26010. Implements a plugin format manager for VSTs.
  26011. */
  26012. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26013. {
  26014. public:
  26015. VSTPluginFormat();
  26016. ~VSTPluginFormat();
  26017. const String getName() const { return "VST"; }
  26018. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26019. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26020. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26021. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26022. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26023. bool doesPluginStillExist (const PluginDescription& desc);
  26024. const FileSearchPath getDefaultLocationsToSearch();
  26025. juce_UseDebuggingNewOperator
  26026. private:
  26027. VSTPluginFormat (const VSTPluginFormat&);
  26028. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26029. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26030. };
  26031. #endif
  26032. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26033. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26034. #endif
  26035. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26036. #endif
  26037. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26038. #endif
  26039. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26040. #endif
  26041. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26042. #endif
  26043. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26044. #endif
  26045. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26046. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26047. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26048. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26049. /**
  26050. Scans a directory for plugins, and adds them to a KnownPluginList.
  26051. To use one of these, create it and call scanNextFile() repeatedly, until
  26052. it returns false.
  26053. */
  26054. class JUCE_API PluginDirectoryScanner
  26055. {
  26056. public:
  26057. /**
  26058. Creates a scanner.
  26059. @param listToAddResultsTo this will get the new types added to it.
  26060. @param formatToLookFor this is the type of format that you want to look for
  26061. @param directoriesToSearch the path to search
  26062. @param searchRecursively true to search recursively
  26063. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26064. be used as a file to store the names of any plugins
  26065. that crash during initialisation. If there are
  26066. any plugins listed in it, then these will always
  26067. be scanned after all other possible files have
  26068. been tried - in this way, even if there's a few
  26069. dodgy plugins in your path, then a couple of rescans
  26070. will still manage to find all the proper plugins.
  26071. It's probably best to choose a file in the user's
  26072. application data directory (alongside your app's
  26073. settings file) for this. The file format it uses
  26074. is just a list of filenames of the modules that
  26075. failed.
  26076. */
  26077. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26078. AudioPluginFormat& formatToLookFor,
  26079. FileSearchPath directoriesToSearch,
  26080. const bool searchRecursively,
  26081. const File& deadMansPedalFile);
  26082. /** Destructor. */
  26083. ~PluginDirectoryScanner();
  26084. /** Tries the next likely-looking file.
  26085. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26086. re-tested if it's not already in the list, or if the file's modification
  26087. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26088. false, the file will always be reloaded and tested.
  26089. Returns false when there are no more files to try.
  26090. */
  26091. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26092. /** Returns the description of the plugin that will be scanned during the next
  26093. call to scanNextFile().
  26094. This is handy if you want to show the user which file is currently getting
  26095. scanned.
  26096. */
  26097. const String getNextPluginFileThatWillBeScanned() const throw();
  26098. /** Returns the estimated progress, between 0 and 1.
  26099. */
  26100. float getProgress() const { return progress; }
  26101. /** This returns a list of all the filenames of things that looked like being
  26102. a plugin file, but which failed to open for some reason.
  26103. */
  26104. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26105. juce_UseDebuggingNewOperator
  26106. private:
  26107. KnownPluginList& list;
  26108. AudioPluginFormat& format;
  26109. StringArray filesOrIdentifiersToScan;
  26110. File deadMansPedalFile;
  26111. StringArray failedFiles;
  26112. int nextIndex;
  26113. float progress;
  26114. const StringArray getDeadMansPedalFile() throw();
  26115. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26116. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26117. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26118. };
  26119. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26120. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26121. #endif
  26122. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26123. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26124. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26125. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26126. /********* Start of inlined file: juce_ListBox.h *********/
  26127. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26128. #define __JUCE_LISTBOX_JUCEHEADER__
  26129. class ListViewport;
  26130. /**
  26131. A subclass of this is used to drive a ListBox.
  26132. @see ListBox
  26133. */
  26134. class JUCE_API ListBoxModel
  26135. {
  26136. public:
  26137. /** Destructor. */
  26138. virtual ~ListBoxModel() {}
  26139. /** This has to return the number of items in the list.
  26140. @see ListBox::getNumRows()
  26141. */
  26142. virtual int getNumRows() = 0;
  26143. /** This method must be implemented to draw a row of the list.
  26144. */
  26145. virtual void paintListBoxItem (int rowNumber,
  26146. Graphics& g,
  26147. int width, int height,
  26148. bool rowIsSelected) = 0;
  26149. /** This is used to create or update a custom component to go in a row of the list.
  26150. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26151. and handle mouse clicks with listBoxItemClicked().
  26152. This method will be called whenever a custom component might need to be updated - e.g.
  26153. when the table is changed, or TableListBox::updateContent() is called.
  26154. If you don't need a custom component for the specified row, then return 0.
  26155. If you do want a custom component, and the existingComponentToUpdate is null, then
  26156. this method must create a suitable new component and return it.
  26157. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26158. by this method. In this case, the method must either update it to make sure it's correctly representing
  26159. the given row (which may be different from the one that the component was created for), or it can
  26160. delete this component and return a new one.
  26161. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26162. */
  26163. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26164. Component* existingComponentToUpdate);
  26165. /** This can be overridden to react to the user clicking on a row.
  26166. @see listBoxItemDoubleClicked
  26167. */
  26168. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26169. /** This can be overridden to react to the user double-clicking on a row.
  26170. @see listBoxItemClicked
  26171. */
  26172. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26173. /** This can be overridden to react to the user double-clicking on a part of the list where
  26174. there are no rows.
  26175. @see listBoxItemClicked
  26176. */
  26177. virtual void backgroundClicked();
  26178. /** Override this to be informed when rows are selected or deselected.
  26179. This will be called whenever a row is selected or deselected. If a range of
  26180. rows is selected all at once, this will just be called once for that event.
  26181. @param lastRowSelected the last row that the user selected. If no
  26182. rows are currently selected, this may be -1.
  26183. */
  26184. virtual void selectedRowsChanged (int lastRowSelected);
  26185. /** Override this to be informed when the delete key is pressed.
  26186. If no rows are selected when they press the key, this won't be called.
  26187. @param lastRowSelected the last row that had been selected when they pressed the
  26188. key - if there are multiple selections, this might not be
  26189. very useful
  26190. */
  26191. virtual void deleteKeyPressed (int lastRowSelected);
  26192. /** Override this to be informed when the return key is pressed.
  26193. If no rows are selected when they press the key, this won't be called.
  26194. @param lastRowSelected the last row that had been selected when they pressed the
  26195. key - if there are multiple selections, this might not be
  26196. very useful
  26197. */
  26198. virtual void returnKeyPressed (int lastRowSelected);
  26199. /** Override this to be informed when the list is scrolled.
  26200. This might be caused by the user moving the scrollbar, or by programmatic changes
  26201. to the list position.
  26202. */
  26203. virtual void listWasScrolled();
  26204. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26205. If this returns a non-empty name then when the user drags a row, the listbox will
  26206. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26207. a drag-and-drop operation, using this string as the source description, with the listbox
  26208. itself as the source component.
  26209. @see DragAndDropContainer::startDragging
  26210. */
  26211. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26212. };
  26213. /**
  26214. A list of items that can be scrolled vertically.
  26215. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26216. either paint each row of the list and respond to events via callbacks, or for
  26217. more specialised tasks, it can supply a custom component to fill each row.
  26218. @see ComboBox, TableListBox
  26219. */
  26220. class JUCE_API ListBox : public Component,
  26221. public SettableTooltipClient
  26222. {
  26223. public:
  26224. /** Creates a ListBox.
  26225. The model pointer passed-in can be null, in which case you can set it later
  26226. with setModel().
  26227. */
  26228. ListBox (const String& componentName,
  26229. ListBoxModel* const model);
  26230. /** Destructor. */
  26231. ~ListBox();
  26232. /** Changes the current data model to display. */
  26233. void setModel (ListBoxModel* const newModel);
  26234. /** Returns the current list model. */
  26235. ListBoxModel* getModel() const throw() { return model; }
  26236. /** Causes the list to refresh its content.
  26237. Call this when the number of rows in the list changes, or if you want it
  26238. to call refreshComponentForRow() on all the row components.
  26239. Be careful not to call it from a different thread, though, as it's not
  26240. thread-safe.
  26241. */
  26242. void updateContent();
  26243. /** Turns on multiple-selection of rows.
  26244. By default this is disabled.
  26245. When your row component gets clicked you'll need to call the
  26246. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26247. clicked and to get it to do the appropriate selection based on whether
  26248. the ctrl/shift keys are held down.
  26249. */
  26250. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26251. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26252. This function is here primarily for the ComboBox class to use, but might be
  26253. useful for some other purpose too.
  26254. */
  26255. void setMouseMoveSelectsRows (bool shouldSelect);
  26256. /** Selects a row.
  26257. If the row is already selected, this won't do anything.
  26258. @param rowNumber the row to select
  26259. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26260. the selected row is off-screen, it'll scroll to make
  26261. sure that row is on-screen
  26262. @param deselectOthersFirst if true and there are multiple selections, these will
  26263. first be deselected before this item is selected
  26264. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26265. deselectAllRows, selectRangeOfRows
  26266. */
  26267. void selectRow (const int rowNumber,
  26268. bool dontScrollToShowThisRow = false,
  26269. bool deselectOthersFirst = true);
  26270. /** Selects a set of rows.
  26271. This will add these rows to the current selection, so you might need to
  26272. clear the current selection first with deselectAllRows()
  26273. @param firstRow the first row to select (inclusive)
  26274. @param lastRow the last row to select (inclusive)
  26275. */
  26276. void selectRangeOfRows (int firstRow,
  26277. int lastRow);
  26278. /** Deselects a row.
  26279. If it's not currently selected, this will do nothing.
  26280. @see selectRow, deselectAllRows
  26281. */
  26282. void deselectRow (const int rowNumber);
  26283. /** Deselects any currently selected rows.
  26284. @see deselectRow
  26285. */
  26286. void deselectAllRows();
  26287. /** Selects or deselects a row.
  26288. If the row's currently selected, this deselects it, and vice-versa.
  26289. */
  26290. void flipRowSelection (const int rowNumber);
  26291. /** Returns a sparse set indicating the rows that are currently selected.
  26292. @see setSelectedRows
  26293. */
  26294. const SparseSet<int> getSelectedRows() const;
  26295. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26296. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26297. method will be called. If it's false, no notification will be sent to the model.
  26298. @see getSelectedRows
  26299. */
  26300. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26301. const bool sendNotificationEventToModel = true);
  26302. /** Checks whether a row is selected.
  26303. */
  26304. bool isRowSelected (const int rowNumber) const;
  26305. /** Returns the number of rows that are currently selected.
  26306. @see getSelectedRow, isRowSelected, getLastRowSelected
  26307. */
  26308. int getNumSelectedRows() const;
  26309. /** Returns the row number of a selected row.
  26310. This will return the row number of the Nth selected row. The row numbers returned will
  26311. be sorted in order from low to high.
  26312. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26313. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26314. selected
  26315. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26316. */
  26317. int getSelectedRow (const int index = 0) const;
  26318. /** Returns the last row that the user selected.
  26319. This isn't the same as the highest row number that is currently selected - if the user
  26320. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26321. If nothing is selected, it will return -1.
  26322. */
  26323. int getLastRowSelected() const;
  26324. /** Multiply-selects rows based on the modifier keys.
  26325. If no modifier keys are down, this will select the given row and
  26326. deselect any others.
  26327. If the ctrl (or command on the Mac) key is down, it'll flip the
  26328. state of the selected row.
  26329. If the shift key is down, it'll select up to the given row from the
  26330. last row selected.
  26331. @see selectRow
  26332. */
  26333. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26334. const ModifierKeys& modifiers);
  26335. /** Scrolls the list to a particular position.
  26336. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26337. 1.0 scrolls to the bottom.
  26338. If the total number of rows all fit onto the screen at once, then this
  26339. method won't do anything.
  26340. @see getVerticalPosition
  26341. */
  26342. void setVerticalPosition (const double newProportion);
  26343. /** Returns the current vertical position as a proportion of the total.
  26344. This can be used in conjunction with setVerticalPosition() to save and restore
  26345. the list's position. It returns a value in the range 0 to 1.
  26346. @see setVerticalPosition
  26347. */
  26348. double getVerticalPosition() const;
  26349. /** Scrolls if necessary to make sure that a particular row is visible.
  26350. */
  26351. void scrollToEnsureRowIsOnscreen (const int row);
  26352. /** Returns a pointer to the scrollbar.
  26353. (Unlikely to be useful for most people).
  26354. */
  26355. ScrollBar* getVerticalScrollBar() const throw();
  26356. /** Returns a pointer to the scrollbar.
  26357. (Unlikely to be useful for most people).
  26358. */
  26359. ScrollBar* getHorizontalScrollBar() const throw();
  26360. /** Finds the row index that contains a given x,y position.
  26361. The position is relative to the ListBox's top-left.
  26362. If no row exists at this position, the method will return -1.
  26363. @see getComponentForRowNumber
  26364. */
  26365. int getRowContainingPosition (const int x, const int y) const throw();
  26366. /** Finds a row index that would be the most suitable place to insert a new
  26367. item for a given position.
  26368. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26369. because it lets you easily choose the best position to insert the item that
  26370. they drop, based on where they drop it.
  26371. If the position is out of range, this will return -1. If the position is
  26372. beyond the end of the list, it will return getNumRows() to indicate the end
  26373. of the list.
  26374. @see getComponentForRowNumber
  26375. */
  26376. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26377. /** Returns the position of one of the rows, relative to the top-left of
  26378. the listbox.
  26379. This may be off-screen, and the range of the row number that is passed-in is
  26380. not checked to see if it's a valid row.
  26381. */
  26382. const Rectangle getRowPosition (const int rowNumber,
  26383. const bool relativeToComponentTopLeft) const throw();
  26384. /** Finds the row component for a given row in the list.
  26385. The component returned will have been created using createRowComponent().
  26386. If the component for this row is off-screen or if the row is out-of-range,
  26387. this will return 0.
  26388. @see getRowContainingPosition
  26389. */
  26390. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26391. /** Returns the row number that the given component represents.
  26392. If the component isn't one of the list's rows, this will return -1.
  26393. */
  26394. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26395. /** Returns the width of a row (which may be less than the width of this component
  26396. if there's a scrollbar).
  26397. */
  26398. int getVisibleRowWidth() const throw();
  26399. /** Sets the height of each row in the list.
  26400. The default height is 22 pixels.
  26401. @see getRowHeight
  26402. */
  26403. void setRowHeight (const int newHeight);
  26404. /** Returns the height of a row in the list.
  26405. @see setRowHeight
  26406. */
  26407. int getRowHeight() const throw() { return rowHeight; }
  26408. /** Returns the number of rows actually visible.
  26409. This is the number of whole rows which will fit on-screen, so the value might
  26410. be more than the actual number of rows in the list.
  26411. */
  26412. int getNumRowsOnScreen() const throw();
  26413. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26414. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26415. methods.
  26416. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26417. */
  26418. enum ColourIds
  26419. {
  26420. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26421. Make this transparent if you don't want the background to be filled. */
  26422. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26423. Make this transparent to not have an outline. */
  26424. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26425. };
  26426. /** Sets the thickness of a border that will be drawn around the box.
  26427. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26428. @see outlineColourId
  26429. */
  26430. void setOutlineThickness (const int outlineThickness);
  26431. /** Returns the thickness of outline that will be drawn around the listbox.
  26432. @see setOutlineColour
  26433. */
  26434. int getOutlineThickness() const throw() { return outlineThickness; }
  26435. /** Sets a component that the list should use as a header.
  26436. This will position the given component at the top of the list, maintaining the
  26437. height of the component passed-in, but rescaling it horizontally to match the
  26438. width of the items in the listbox.
  26439. The component will be deleted when setHeaderComponent() is called with a
  26440. different component, or when the listbox is deleted.
  26441. */
  26442. void setHeaderComponent (Component* const newHeaderComponent);
  26443. /** Changes the width of the rows in the list.
  26444. This can be used to make the list's row components wider than the list itself - the
  26445. width of the rows will be either the width of the list or this value, whichever is
  26446. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26447. appear.
  26448. The default value for this is 0, which means that the rows will always
  26449. be the same width as the list.
  26450. */
  26451. void setMinimumContentWidth (const int newMinimumWidth);
  26452. /** Returns the space currently available for the row items, taking into account
  26453. borders, scrollbars, etc.
  26454. */
  26455. int getVisibleContentWidth() const throw();
  26456. /** Repaints one of the rows.
  26457. This is a lightweight alternative to calling updateContent, and just causes a
  26458. repaint of the row's area.
  26459. */
  26460. void repaintRow (const int rowNumber) throw();
  26461. /** This fairly obscure method creates an image that just shows the currently
  26462. selected row components.
  26463. It's a handy method for doing drag-and-drop, as it can be passed to the
  26464. DragAndDropContainer for use as the drag image.
  26465. Note that it will make the row components temporarily invisible, so if you're
  26466. using custom components this could affect them if they're sensitive to that
  26467. sort of thing.
  26468. @see Component::createComponentSnapshot
  26469. */
  26470. Image* createSnapshotOfSelectedRows();
  26471. /** Returns the viewport that this ListBox uses.
  26472. You may need to use this to change parameters such as whether scrollbars
  26473. are shown, etc.
  26474. */
  26475. Viewport* getViewport() const throw();
  26476. /** @internal */
  26477. bool keyPressed (const KeyPress& key);
  26478. /** @internal */
  26479. bool keyStateChanged();
  26480. /** @internal */
  26481. void paint (Graphics& g);
  26482. /** @internal */
  26483. void paintOverChildren (Graphics& g);
  26484. /** @internal */
  26485. void resized();
  26486. /** @internal */
  26487. void visibilityChanged();
  26488. /** @internal */
  26489. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26490. /** @internal */
  26491. void mouseMove (const MouseEvent&);
  26492. /** @internal */
  26493. void mouseExit (const MouseEvent&);
  26494. /** @internal */
  26495. void mouseUp (const MouseEvent&);
  26496. /** @internal */
  26497. void colourChanged();
  26498. juce_UseDebuggingNewOperator
  26499. private:
  26500. friend class ListViewport;
  26501. friend class TableListBox;
  26502. ListBoxModel* model;
  26503. ListViewport* viewport;
  26504. Component* headerComponent;
  26505. int totalItems, rowHeight, minimumRowWidth;
  26506. int outlineThickness;
  26507. int lastMouseX, lastMouseY, lastRowSelected;
  26508. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26509. SparseSet <int> selected;
  26510. void selectRowInternal (const int rowNumber,
  26511. bool dontScrollToShowThisRow,
  26512. bool deselectOthersFirst,
  26513. bool isMouseClick);
  26514. ListBox (const ListBox&);
  26515. const ListBox& operator= (const ListBox&);
  26516. };
  26517. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26518. /********* End of inlined file: juce_ListBox.h *********/
  26519. /********* Start of inlined file: juce_TextButton.h *********/
  26520. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26521. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26522. /**
  26523. A button that uses the standard lozenge-shaped background with a line of
  26524. text on it.
  26525. @see Button, DrawableButton
  26526. */
  26527. class JUCE_API TextButton : public Button
  26528. {
  26529. public:
  26530. /** Creates a TextButton.
  26531. @param buttonName the text to put in the button (the component's name is also
  26532. initially set to this string, but these can be changed later
  26533. using the setName() and setButtonText() methods)
  26534. @param toolTip an optional string to use as a toolip
  26535. @see Button
  26536. */
  26537. TextButton (const String& buttonName,
  26538. const String& toolTip = String::empty);
  26539. /** Destructor. */
  26540. ~TextButton();
  26541. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26542. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26543. methods.
  26544. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26545. */
  26546. enum ColourIds
  26547. {
  26548. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26549. 'off'). The look-and-feel class might re-interpret this to add
  26550. effects, etc. */
  26551. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26552. 'on'). The look-and-feel class might re-interpret this to add
  26553. effects, etc. */
  26554. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26555. };
  26556. /** Resizes the button to fit neatly around its current text.
  26557. If newHeight is >= 0, the button's height will be changed to this
  26558. value. If it's less than zero, its height will be unaffected.
  26559. */
  26560. void changeWidthToFitText (const int newHeight = -1);
  26561. /** This can be overridden to use different fonts than the default one.
  26562. Note that you'll need to set the font's size appropriately, too.
  26563. */
  26564. virtual const Font getFont();
  26565. juce_UseDebuggingNewOperator
  26566. protected:
  26567. /** @internal */
  26568. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26569. /** @internal */
  26570. void colourChanged();
  26571. private:
  26572. TextButton (const TextButton&);
  26573. const TextButton& operator= (const TextButton&);
  26574. };
  26575. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26576. /********* End of inlined file: juce_TextButton.h *********/
  26577. /**
  26578. A component displaying a list of plugins, with options to scan for them,
  26579. add, remove and sort them.
  26580. */
  26581. class JUCE_API PluginListComponent : public Component,
  26582. public ListBoxModel,
  26583. public ChangeListener,
  26584. public ButtonListener,
  26585. public Timer
  26586. {
  26587. public:
  26588. /**
  26589. Creates the list component.
  26590. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26591. The properties file, if supplied, is used to store the user's last search paths.
  26592. */
  26593. PluginListComponent (KnownPluginList& listToRepresent,
  26594. const File& deadMansPedalFile,
  26595. PropertiesFile* const propertiesToUse);
  26596. /** Destructor. */
  26597. ~PluginListComponent();
  26598. /** @internal */
  26599. void resized();
  26600. /** @internal */
  26601. bool isInterestedInFileDrag (const StringArray& files);
  26602. /** @internal */
  26603. void filesDropped (const StringArray& files, int, int);
  26604. /** @internal */
  26605. int getNumRows();
  26606. /** @internal */
  26607. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26608. /** @internal */
  26609. void deleteKeyPressed (int lastRowSelected);
  26610. /** @internal */
  26611. void buttonClicked (Button* b);
  26612. /** @internal */
  26613. void changeListenerCallback (void*);
  26614. /** @internal */
  26615. void timerCallback();
  26616. juce_UseDebuggingNewOperator
  26617. private:
  26618. KnownPluginList& list;
  26619. File deadMansPedalFile;
  26620. ListBox* listBox;
  26621. TextButton* optionsButton;
  26622. PropertiesFile* propertiesToUse;
  26623. int typeToScan;
  26624. void scanFor (AudioPluginFormat* format);
  26625. PluginListComponent (const PluginListComponent&);
  26626. const PluginListComponent& operator= (const PluginListComponent&);
  26627. };
  26628. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26629. /********* End of inlined file: juce_PluginListComponent.h *********/
  26630. #endif
  26631. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26632. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  26633. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26634. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26635. /********* Start of inlined file: juce_AudioFormat.h *********/
  26636. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26637. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26638. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  26639. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26640. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26641. /**
  26642. Writes samples to an audio file stream.
  26643. A subclass that writes a specific type of audio format will be created by
  26644. an AudioFormat object.
  26645. After creating one of these with the AudioFormat::createWriterFor() method
  26646. you can call its write() method to store the samples, and then delete it.
  26647. @see AudioFormat, AudioFormatReader
  26648. */
  26649. class JUCE_API AudioFormatWriter
  26650. {
  26651. protected:
  26652. /** Creates an AudioFormatWriter object.
  26653. @param destStream the stream to write to - this will be deleted
  26654. by this object when it is no longer needed
  26655. @param formatName the description that will be returned by the getFormatName()
  26656. method
  26657. @param sampleRate the sample rate to use - the base class just stores
  26658. this value, it doesn't do anything with it
  26659. @param numberOfChannels the number of channels to write - the base class just stores
  26660. this value, it doesn't do anything with it
  26661. @param bitsPerSample the bit depth of the stream - the base class just stores
  26662. this value, it doesn't do anything with it
  26663. */
  26664. AudioFormatWriter (OutputStream* const destStream,
  26665. const String& formatName,
  26666. const double sampleRate,
  26667. const unsigned int numberOfChannels,
  26668. const unsigned int bitsPerSample);
  26669. public:
  26670. /** Destructor. */
  26671. virtual ~AudioFormatWriter();
  26672. /** Returns a description of what type of format this is.
  26673. E.g. "AIFF file"
  26674. */
  26675. const String getFormatName() const throw() { return formatName; }
  26676. /** Writes a set of samples to the audio stream.
  26677. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  26678. can use AudioSampleBuffer::writeToAudioWriter().
  26679. @param samplesToWrite an array of arrays containing the sample data for
  26680. each channel to write. This is a zero-terminated
  26681. array of arrays, and can contain a different number
  26682. of channels than the actual stream uses, and the
  26683. writer should do its best to cope with this.
  26684. If the format is fixed-point, each channel will be formatted
  26685. as an array of signed integers using the full 32-bit
  26686. range -0x80000000 to 0x7fffffff, regardless of the source's
  26687. bit-depth. If it is a floating-point format, you should treat
  26688. the arrays as arrays of floats, and just cast it to an (int**)
  26689. to pass it into the method.
  26690. @param numSamples the number of samples to write
  26691. */
  26692. virtual bool write (const int** samplesToWrite,
  26693. int numSamples) = 0;
  26694. /** Reads a section of samples from an AudioFormatReader, and writes these to
  26695. the output.
  26696. This will take care of any floating-point conversion that's required to convert
  26697. between the two formats. It won't deal with sample-rate conversion, though.
  26698. @returns false if it can't read or write properly during the operation
  26699. */
  26700. bool writeFromAudioReader (AudioFormatReader& reader,
  26701. int64 startSample,
  26702. int numSamplesToRead);
  26703. /** Reads some samples from an AudioSource, and writes these to the output.
  26704. The source must already have been initialised with the AudioSource::prepareToPlay() method
  26705. @param source the source to read from
  26706. @param numSamplesToRead total number of samples to read and write
  26707. @param samplesPerBlock the maximum number of samples to fetch from the source
  26708. @returns false if it can't read or write properly during the operation
  26709. */
  26710. bool writeFromAudioSource (AudioSource& source,
  26711. int numSamplesToRead,
  26712. const int samplesPerBlock = 2048);
  26713. /** Returns the sample rate being used. */
  26714. double getSampleRate() const throw() { return sampleRate; }
  26715. /** Returns the number of channels being written. */
  26716. int getNumChannels() const throw() { return numChannels; }
  26717. /** Returns the bit-depth of the data being written. */
  26718. int getBitsPerSample() const throw() { return bitsPerSample; }
  26719. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  26720. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  26721. juce_UseDebuggingNewOperator
  26722. protected:
  26723. /** The sample rate of the stream. */
  26724. double sampleRate;
  26725. /** The number of channels being written to the stream. */
  26726. unsigned int numChannels;
  26727. /** The bit depth of the file. */
  26728. unsigned int bitsPerSample;
  26729. /** True if it's a floating-point format, false if it's fixed-point. */
  26730. bool usesFloatingPointData;
  26731. /** The output stream for Use by subclasses. */
  26732. OutputStream* output;
  26733. private:
  26734. String formatName;
  26735. };
  26736. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26737. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  26738. /**
  26739. Subclasses of AudioFormat are used to read and write different audio
  26740. file formats.
  26741. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  26742. */
  26743. class JUCE_API AudioFormat
  26744. {
  26745. public:
  26746. /** Destructor. */
  26747. virtual ~AudioFormat();
  26748. /** Returns the name of this format.
  26749. e.g. "WAV file" or "AIFF file"
  26750. */
  26751. const String& getFormatName() const;
  26752. /** Returns all the file extensions that might apply to a file of this format.
  26753. The first item will be the one that's preferred when creating a new file.
  26754. So for a wav file this might just return ".wav"; for an AIFF file it might
  26755. return two items, ".aif" and ".aiff"
  26756. */
  26757. const StringArray& getFileExtensions() const;
  26758. /** Returns true if this the given file can be read by this format.
  26759. Subclasses shouldn't do too much work here, just check the extension or
  26760. file type. The base class implementation just checks the file's extension
  26761. against one of the ones that was registered in the constructor.
  26762. */
  26763. virtual bool canHandleFile (const File& fileToTest);
  26764. /** Returns a set of sample rates that the format can read and write. */
  26765. virtual const Array <int> getPossibleSampleRates() = 0;
  26766. /** Returns a set of bit depths that the format can read and write. */
  26767. virtual const Array <int> getPossibleBitDepths() = 0;
  26768. /** Returns true if the format can do 2-channel audio. */
  26769. virtual bool canDoStereo() = 0;
  26770. /** Returns true if the format can do 1-channel audio. */
  26771. virtual bool canDoMono() = 0;
  26772. /** Returns true if the format uses compressed data. */
  26773. virtual bool isCompressed();
  26774. /** Returns a list of different qualities that can be used when writing.
  26775. Non-compressed formats will just return an empty array, but for something
  26776. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  26777. When calling createWriterFor(), an index from this array is passed in to
  26778. tell the format which option is required.
  26779. */
  26780. virtual const StringArray getQualityOptions();
  26781. /** Tries to create an object that can read from a stream containing audio
  26782. data in this format.
  26783. The reader object that is returned can be used to read from the stream, and
  26784. should then be deleted by the caller.
  26785. @param sourceStream the stream to read from - the AudioFormatReader object
  26786. that is returned will delete this stream when it no longer
  26787. needs it.
  26788. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  26789. should delete the stream object that was passed-in. (If a valid
  26790. reader is returned, it will always be in charge of deleting the
  26791. stream, so this parameter is ignored)
  26792. @see AudioFormatReader
  26793. */
  26794. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26795. const bool deleteStreamIfOpeningFails) = 0;
  26796. /** Tries to create an object that can write to a stream with this audio format.
  26797. The writer object that is returned can be used to write to the stream, and
  26798. should then be deleted by the caller.
  26799. If the stream can't be created for some reason (e.g. the parameters passed in
  26800. here aren't suitable), this will return 0.
  26801. @param streamToWriteTo the stream that the data will go to - this will be
  26802. deleted by the AudioFormatWriter object when it's no longer
  26803. needed. If no AudioFormatWriter can be created by this method,
  26804. the stream will NOT be deleted, so that the caller can re-use it
  26805. to try to open a different format, etc
  26806. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  26807. returned by getPossibleSampleRates()
  26808. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  26809. the choice will depend on the results of canDoMono() and
  26810. canDoStereo()
  26811. @param bitsPerSample the bits per sample to use - this must be one of the values
  26812. returned by getPossibleBitDepths()
  26813. @param metadataValues a set of metadata values that the writer should try to write
  26814. to the stream. Exactly what these are depends on the format,
  26815. and the subclass doesn't actually have to do anything with
  26816. them if it doesn't want to. Have a look at the specific format
  26817. implementation classes to see possible values that can be
  26818. used
  26819. @param qualityOptionIndex the index of one of compression qualities returned by the
  26820. getQualityOptions() method. If there aren't any quality options
  26821. for this format, just pass 0 in this parameter, as it'll be
  26822. ignored
  26823. @see AudioFormatWriter
  26824. */
  26825. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26826. double sampleRateToUse,
  26827. unsigned int numberOfChannels,
  26828. int bitsPerSample,
  26829. const StringPairArray& metadataValues,
  26830. int qualityOptionIndex) = 0;
  26831. protected:
  26832. /** Creates an AudioFormat object.
  26833. @param formatName this sets the value that will be returned by getFormatName()
  26834. @param fileExtensions a zero-terminated list of file extensions - this is what will
  26835. be returned by getFileExtension()
  26836. */
  26837. AudioFormat (const String& formatName,
  26838. const tchar** const fileExtensions);
  26839. private:
  26840. String formatName;
  26841. StringArray fileExtensions;
  26842. };
  26843. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  26844. /********* End of inlined file: juce_AudioFormat.h *********/
  26845. /**
  26846. Reads and Writes AIFF format audio files.
  26847. @see AudioFormat
  26848. */
  26849. class JUCE_API AiffAudioFormat : public AudioFormat
  26850. {
  26851. public:
  26852. /** Creates an format object. */
  26853. AiffAudioFormat();
  26854. /** Destructor. */
  26855. ~AiffAudioFormat();
  26856. const Array <int> getPossibleSampleRates();
  26857. const Array <int> getPossibleBitDepths();
  26858. bool canDoStereo();
  26859. bool canDoMono();
  26860. #if JUCE_MAC
  26861. bool canHandleFile (const File& fileToTest);
  26862. #endif
  26863. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26864. const bool deleteStreamIfOpeningFails);
  26865. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26866. double sampleRateToUse,
  26867. unsigned int numberOfChannels,
  26868. int bitsPerSample,
  26869. const StringPairArray& metadataValues,
  26870. int qualityOptionIndex);
  26871. juce_UseDebuggingNewOperator
  26872. };
  26873. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26874. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  26875. #endif
  26876. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26877. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  26878. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26879. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26880. /**
  26881. */
  26882. class AudioCDBurner
  26883. {
  26884. public:
  26885. /** Returns a list of available optical drives.
  26886. Use openDevice() to open one of the items from this list.
  26887. */
  26888. static const StringArray findAvailableDevices();
  26889. /** Tries to open one of the optical drives.
  26890. The deviceIndex is an index into the array returned by findAvailableDevices().
  26891. */
  26892. static AudioCDBurner* openDevice (const int deviceIndex);
  26893. /** Destructor. */
  26894. ~AudioCDBurner();
  26895. /** Returns true if there's a writable disk in the drive.
  26896. */
  26897. bool isDiskPresent() const;
  26898. /** Returns the number of free blocks on the disk.
  26899. There are 75 blocks per second, at 44100Hz.
  26900. */
  26901. int getNumAvailableAudioBlocks() const;
  26902. /** Adds a track to be written.
  26903. The source passed-in here will be kept by this object, and it will
  26904. be used and deleted at some point in the future, either during the
  26905. burn() method or when this AudioCDBurner object is deleted. Your caller
  26906. method shouldn't keep a reference to it or use it again after passing
  26907. it in here.
  26908. */
  26909. bool addAudioTrack (AudioSource* source, int numSamples);
  26910. /**
  26911. Return true to cancel the current burn operation
  26912. */
  26913. class BurnProgressListener
  26914. {
  26915. public:
  26916. BurnProgressListener() throw() {}
  26917. virtual ~BurnProgressListener() {}
  26918. /** Called at intervals to report on the progress of the AudioCDBurner.
  26919. To cancel the burn, return true from this.
  26920. */
  26921. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  26922. };
  26923. const String burn (BurnProgressListener* listener,
  26924. const bool ejectDiscAfterwards,
  26925. const bool peformFakeBurnForTesting);
  26926. juce_UseDebuggingNewOperator
  26927. private:
  26928. AudioCDBurner (const int deviceIndex);
  26929. void* internal;
  26930. };
  26931. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26932. /********* End of inlined file: juce_AudioCDBurner.h *********/
  26933. #endif
  26934. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26935. /********* Start of inlined file: juce_AudioCDReader.h *********/
  26936. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26937. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  26938. #if JUCE_MAC
  26939. #endif
  26940. /**
  26941. A type of AudioFormatReader that reads from an audio CD.
  26942. One of these can be used to read a CD as if it's one big audio stream. Use the
  26943. getPositionOfTrackStart() method to find where the individual tracks are
  26944. within the stream.
  26945. @see AudioFormatReader
  26946. */
  26947. class JUCE_API AudioCDReader : public AudioFormatReader
  26948. {
  26949. public:
  26950. /** Returns a list of names of Audio CDs currently available for reading.
  26951. If there's a CD drive but no CD in it, this might return an empty list, or
  26952. possibly a device that can be opened but which has no tracks, depending
  26953. on the platform.
  26954. @see createReaderForCD
  26955. */
  26956. static const StringArray getAvailableCDNames();
  26957. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  26958. @param index the index of one of the available CDs - use getAvailableCDNames()
  26959. to find out how many there are.
  26960. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  26961. caller will be responsible for deleting the object returned.
  26962. */
  26963. static AudioCDReader* createReaderForCD (const int index);
  26964. /** Destructor. */
  26965. ~AudioCDReader();
  26966. /** Implementation of the AudioFormatReader method. */
  26967. bool read (int** destSamples,
  26968. int64 startSampleInFile,
  26969. int numSamples);
  26970. /** Checks whether the CD has been removed from the drive.
  26971. */
  26972. bool isCDStillPresent() const;
  26973. /** Returns the total number of tracks (audio + data).
  26974. */
  26975. int getNumTracks() const;
  26976. /** Finds the sample offset of the start of a track.
  26977. @param trackNum the track number, where 0 is the first track.
  26978. */
  26979. int getPositionOfTrackStart (int trackNum) const;
  26980. /** Returns true if a given track is an audio track.
  26981. @param trackNum the track number, where 0 is the first track.
  26982. */
  26983. bool isTrackAudio (int trackNum) const;
  26984. /** Refreshes the object's table of contents.
  26985. If the disc has been ejected and a different one put in since this
  26986. object was created, this will cause it to update its idea of how many tracks
  26987. there are, etc.
  26988. */
  26989. void refreshTrackLengths();
  26990. /** Enables scanning for indexes within tracks.
  26991. @see getLastIndex
  26992. */
  26993. void enableIndexScanning (bool enabled);
  26994. /** Returns the index number found during the last read() call.
  26995. Index scanning is turned off by default - turn it on with enableIndexScanning().
  26996. Then when the read() method is called, if it comes across an index within that
  26997. block, the index number is stored and returned by this method.
  26998. Some devices might not support indexes, of course.
  26999. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27000. @see enableIndexScanning
  27001. */
  27002. int getLastIndex() const;
  27003. /** Scans a track to find the position of any indexes within it.
  27004. @param trackNumber the track to look in, where 0 is the first track on the disc
  27005. @returns an array of sample positions of any index points found (not including
  27006. the index that marks the start of the track)
  27007. */
  27008. const Array <int> findIndexesInTrack (const int trackNumber);
  27009. /** Returns the CDDB id number for the CD.
  27010. It's not a great way of identifying a disc, but it's traditional.
  27011. */
  27012. int getCDDBId();
  27013. /** Tries to eject the disk.
  27014. Of course this might not be possible, if some other process is using it.
  27015. */
  27016. void ejectDisk();
  27017. juce_UseDebuggingNewOperator
  27018. private:
  27019. #if JUCE_MAC
  27020. File volumeDir;
  27021. OwnedArray<File> tracks;
  27022. Array <int> trackStartSamples;
  27023. int currentReaderTrack;
  27024. AudioFormatReader* reader;
  27025. AudioCDReader (const File& volume);
  27026. public:
  27027. static int compareElements (const File* const, const File* const) throw();
  27028. private:
  27029. #elif JUCE_WIN32
  27030. int numTracks;
  27031. int trackStarts[100];
  27032. bool audioTracks [100];
  27033. void* handle;
  27034. bool indexingEnabled;
  27035. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27036. MemoryBlock buffer;
  27037. AudioCDReader (void* handle);
  27038. int getIndexAt (int samplePos);
  27039. #elif JUCE_LINUX
  27040. AudioCDReader();
  27041. #endif
  27042. AudioCDReader (const AudioCDReader&);
  27043. const AudioCDReader& operator= (const AudioCDReader&);
  27044. };
  27045. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27046. /********* End of inlined file: juce_AudioCDReader.h *********/
  27047. #endif
  27048. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27049. #endif
  27050. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27051. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27052. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27053. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27054. /**
  27055. A class for keeping a list of available audio formats, and for deciding which
  27056. one to use to open a given file.
  27057. You can either use this class as a singleton object, or create instances of it
  27058. yourself. Once created, use its registerFormat() method to tell it which
  27059. formats it should use.
  27060. @see AudioFormat
  27061. */
  27062. class JUCE_API AudioFormatManager
  27063. {
  27064. public:
  27065. /** Creates an empty format manager.
  27066. Before it'll be any use, you'll need to call registerFormat() with all the
  27067. formats you want it to be able to recognise.
  27068. */
  27069. AudioFormatManager();
  27070. /** Destructor. */
  27071. ~AudioFormatManager();
  27072. juce_DeclareSingleton (AudioFormatManager, false);
  27073. /** Adds a format to the manager's list of available file types.
  27074. The object passed-in will be deleted by this object, so don't keep a pointer
  27075. to it!
  27076. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27077. return this one when called.
  27078. */
  27079. void registerFormat (AudioFormat* newFormat,
  27080. const bool makeThisTheDefaultFormat);
  27081. /** Handy method to make it easy to register the formats that come with Juce.
  27082. Currently, this will add WAV and AIFF to the list.
  27083. */
  27084. void registerBasicFormats();
  27085. /** Clears the list of known formats. */
  27086. void clearFormats();
  27087. /** Returns the number of currently registered file formats. */
  27088. int getNumKnownFormats() const;
  27089. /** Returns one of the registered file formats. */
  27090. AudioFormat* getKnownFormat (const int index) const;
  27091. /** Looks for which of the known formats is listed as being for a given file
  27092. extension.
  27093. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27094. */
  27095. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27096. /** Returns the format which has been set as the default one.
  27097. You can set a format as being the default when it is registered. It's useful
  27098. when you want to write to a file, because the best format may change between
  27099. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27100. If none has been set as the default, this method will just return the first
  27101. one in the list.
  27102. */
  27103. AudioFormat* getDefaultFormat() const;
  27104. /** Returns a set of wildcards for file-matching that contains the extensions for
  27105. all known formats.
  27106. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27107. */
  27108. const String getWildcardForAllFormats() const;
  27109. /** Searches through the known formats to try to create a suitable reader for
  27110. this file.
  27111. If none of the registered formats can open the file, it'll return 0. If it
  27112. returns a reader, it's the caller's responsibility to delete the reader.
  27113. */
  27114. AudioFormatReader* createReaderFor (const File& audioFile);
  27115. /** Searches through the known formats to try to create a suitable reader for
  27116. this stream.
  27117. The stream object that is passed-in will be deleted by this method or by the
  27118. reader that is returned, so the caller should not keep any references to it.
  27119. The stream that is passed-in must be capable of being repositioned so
  27120. that all the formats can have a go at opening it.
  27121. If none of the registered formats can open the stream, it'll return 0. If it
  27122. returns a reader, it's the caller's responsibility to delete the reader.
  27123. */
  27124. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27125. juce_UseDebuggingNewOperator
  27126. private:
  27127. VoidArray knownFormats;
  27128. int defaultFormatIndex;
  27129. };
  27130. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27131. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27132. #endif
  27133. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27134. #endif
  27135. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27136. #endif
  27137. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27138. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27139. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27140. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27141. /**
  27142. This class is used to wrap an AudioFormatReader and only read from a
  27143. subsection of the file.
  27144. So if you have a reader which can read a 1000 sample file, you could wrap it
  27145. in one of these to only access, e.g. samples 100 to 200, and any samples
  27146. outside that will come back as 0. Accessing sample 0 from this reader will
  27147. actually read the first sample from the other's subsection, which might
  27148. be at a non-zero position.
  27149. @see AudioFormatReader
  27150. */
  27151. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27152. {
  27153. public:
  27154. /** Creates a AudioSubsectionReader for a given data source.
  27155. @param sourceReader the source reader from which we'll be taking data
  27156. @param subsectionStartSample the sample within the source reader which will be
  27157. mapped onto sample 0 for this reader.
  27158. @param subsectionLength the number of samples from the source that will
  27159. make up the subsection. If this reader is asked for
  27160. any samples beyond this region, it will return zero.
  27161. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27162. this object is deleted.
  27163. */
  27164. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27165. const int64 subsectionStartSample,
  27166. const int64 subsectionLength,
  27167. const bool deleteSourceWhenDeleted);
  27168. /** Destructor. */
  27169. ~AudioSubsectionReader();
  27170. bool read (int** destSamples,
  27171. int64 startSample,
  27172. int numSamples);
  27173. void readMaxLevels (int64 startSample,
  27174. int64 numSamples,
  27175. float& lowestLeft,
  27176. float& highestLeft,
  27177. float& lowestRight,
  27178. float& highestRight);
  27179. juce_UseDebuggingNewOperator
  27180. private:
  27181. AudioFormatReader* const source;
  27182. int64 startSample, length;
  27183. const bool deleteSourceWhenDeleted;
  27184. AudioSubsectionReader (const AudioSubsectionReader&);
  27185. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27186. };
  27187. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27188. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27189. #endif
  27190. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27191. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27192. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27193. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27194. class AudioThumbnailCache;
  27195. /**
  27196. Makes it easy to quickly draw scaled views of the waveform shape of an
  27197. audio file.
  27198. To use this class, just create an AudioThumbNail class for the file you want
  27199. to draw, call setSource to tell it which file or resource to use, then call
  27200. drawChannel() to draw it.
  27201. The class will asynchronously scan the wavefile to create its scaled-down view,
  27202. so you should make your UI repaint itself as this data comes in. To do this, the
  27203. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27204. listeners should repaint themselves.
  27205. The thumbnail stores an internal low-res version of the wave data, and this can
  27206. be loaded and saved to avoid having to scan the file again.
  27207. @see AudioThumbnailCache
  27208. */
  27209. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27210. public TimeSliceClient,
  27211. private Timer
  27212. {
  27213. public:
  27214. /** Creates an audio thumbnail.
  27215. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27216. of the audio data, this is the scale at which it should be done
  27217. @param formatManagerToUse the audio format manager that is used to open the file
  27218. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27219. thread and storage that is used to by the thumbnail, and the cache
  27220. object can be shared between multiple thumbnails
  27221. */
  27222. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27223. AudioFormatManager& formatManagerToUse,
  27224. AudioThumbnailCache& cacheToUse);
  27225. /** Destructor. */
  27226. ~AudioThumbnail();
  27227. /** Specifies the file or stream that contains the audio file.
  27228. For a file, just call
  27229. @code
  27230. setSource (new FileInputSource (file))
  27231. @endcode
  27232. You can pass a zero in here to clear the thumbnail.
  27233. The source that is passed in will be deleted by this object when it is no
  27234. longer needed
  27235. */
  27236. void setSource (InputSource* const newSource);
  27237. /** Reloads the low res thumbnail data from an input stream.
  27238. The thumb will automatically attempt to reload itself from its
  27239. AudioThumbnailCache.
  27240. */
  27241. void loadFrom (InputStream& input);
  27242. /** Saves the low res thumbnail data to an output stream.
  27243. The thumb will automatically attempt to save itself to its
  27244. AudioThumbnailCache after it finishes scanning the wave file.
  27245. */
  27246. void saveTo (OutputStream& output) const;
  27247. /** Returns the number of channels in the file.
  27248. */
  27249. int getNumChannels() const throw();
  27250. /** Returns the length of the audio file.
  27251. */
  27252. double getTotalLength() const throw();
  27253. /** Renders the waveform shape for a channel.
  27254. The waveform will be drawn within the specified rectangle, where startTime
  27255. and endTime specify the times within the audio file that should be positioned
  27256. at the left and right edges of the rectangle.
  27257. The waveform will be scaled vertically so that a full-volume sample will fill
  27258. the rectangle vertically, but you can also specify an extra vertical scale factor
  27259. with the verticalZoomFactor parameter.
  27260. */
  27261. void drawChannel (Graphics& g,
  27262. int x, int y, int w, int h,
  27263. double startTime,
  27264. double endTime,
  27265. int channelNum,
  27266. const float verticalZoomFactor);
  27267. /** Returns true if the low res preview is fully generated.
  27268. */
  27269. bool isFullyLoaded() const throw();
  27270. /** @internal */
  27271. bool useTimeSlice();
  27272. /** @internal */
  27273. void timerCallback();
  27274. juce_UseDebuggingNewOperator
  27275. private:
  27276. AudioFormatManager& formatManagerToUse;
  27277. AudioThumbnailCache& cache;
  27278. InputSource* source;
  27279. CriticalSection readerLock;
  27280. AudioFormatReader* reader;
  27281. MemoryBlock data, cachedLevels;
  27282. int orginalSamplesPerThumbnailSample;
  27283. int numChannelsCached, numSamplesCached;
  27284. double cachedStart, cachedTimePerPixel;
  27285. bool cacheNeedsRefilling;
  27286. void clear();
  27287. AudioFormatReader* createReader() const;
  27288. void generateSection (AudioFormatReader& reader,
  27289. int64 startSample,
  27290. int numSamples);
  27291. char* getChannelData (int channel) const;
  27292. void refillCache (const int numSamples,
  27293. double startTime,
  27294. const double timePerPixel);
  27295. friend class AudioThumbnailCache;
  27296. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27297. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27298. // returns true if more needs to be read
  27299. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27300. };
  27301. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27302. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27303. #endif
  27304. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27305. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27306. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27307. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27308. struct ThumbnailCacheEntry;
  27309. /**
  27310. An instance of this class is used to manage multiple AudioThumbnail objects.
  27311. The cache runs a single background thread that is shared by all the thumbnails
  27312. that need it, and it maintains a set of low-res previews in memory, to avoid
  27313. having to re-scan audio files too often.
  27314. @see AudioThumbnail
  27315. */
  27316. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27317. {
  27318. public:
  27319. /** Creates a cache object.
  27320. The maxNumThumbsToStore parameter lets you specify how many previews should
  27321. be kept in memory at once.
  27322. */
  27323. AudioThumbnailCache (const int maxNumThumbsToStore);
  27324. /** Destructor. */
  27325. ~AudioThumbnailCache();
  27326. /** Clears out any stored thumbnails.
  27327. */
  27328. void clear();
  27329. /** Reloads the specified thumb if this cache contains the appropriate stored
  27330. data.
  27331. This is called automatically by the AudioThumbnail class, so you shouldn't
  27332. normally need to call it directly.
  27333. */
  27334. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27335. /** Stores the cachable data from the specified thumb in this cache.
  27336. This is called automatically by the AudioThumbnail class, so you shouldn't
  27337. normally need to call it directly.
  27338. */
  27339. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27340. juce_UseDebuggingNewOperator
  27341. private:
  27342. OwnedArray <ThumbnailCacheEntry> thumbs;
  27343. int maxNumThumbsToStore;
  27344. friend class AudioThumbnail;
  27345. void addThumbnail (AudioThumbnail* const thumb);
  27346. void removeThumbnail (AudioThumbnail* const thumb);
  27347. };
  27348. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27349. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27350. #endif
  27351. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27352. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27353. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27354. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27355. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27356. /**
  27357. Reads and writes the lossless-compression FLAC audio format.
  27358. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27359. and make sure your include search path and library search path are set up to find
  27360. the FLAC header files and static libraries.
  27361. @see AudioFormat
  27362. */
  27363. class JUCE_API FlacAudioFormat : public AudioFormat
  27364. {
  27365. public:
  27366. FlacAudioFormat();
  27367. ~FlacAudioFormat();
  27368. const Array <int> getPossibleSampleRates();
  27369. const Array <int> getPossibleBitDepths();
  27370. bool canDoStereo();
  27371. bool canDoMono();
  27372. bool isCompressed();
  27373. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27374. const bool deleteStreamIfOpeningFails);
  27375. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27376. double sampleRateToUse,
  27377. unsigned int numberOfChannels,
  27378. int bitsPerSample,
  27379. const StringPairArray& metadataValues,
  27380. int qualityOptionIndex);
  27381. juce_UseDebuggingNewOperator
  27382. };
  27383. #endif
  27384. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27385. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27386. #endif
  27387. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27388. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27389. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27390. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27391. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27392. /**
  27393. Reads and writes the Ogg-Vorbis audio format.
  27394. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27395. and make sure your include search path and library search path are set up to find
  27396. the Vorbis and Ogg header files and static libraries.
  27397. @see AudioFormat,
  27398. */
  27399. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27400. {
  27401. public:
  27402. OggVorbisAudioFormat();
  27403. ~OggVorbisAudioFormat();
  27404. const Array <int> getPossibleSampleRates();
  27405. const Array <int> getPossibleBitDepths();
  27406. bool canDoStereo();
  27407. bool canDoMono();
  27408. bool isCompressed();
  27409. const StringArray getQualityOptions();
  27410. /** Tries to estimate the quality level of an ogg file based on its size.
  27411. If it can't read the file for some reason, this will just return 1 (medium quality),
  27412. otherwise it will return the approximate quality setting that would have been used
  27413. to create the file.
  27414. @see getQualityOptions
  27415. */
  27416. int estimateOggFileQuality (const File& source);
  27417. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27418. const bool deleteStreamIfOpeningFails);
  27419. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27420. double sampleRateToUse,
  27421. unsigned int numberOfChannels,
  27422. int bitsPerSample,
  27423. const StringPairArray& metadataValues,
  27424. int qualityOptionIndex);
  27425. juce_UseDebuggingNewOperator
  27426. };
  27427. #endif
  27428. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27429. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27430. #endif
  27431. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27432. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27433. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27434. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27435. #if JUCE_QUICKTIME
  27436. /**
  27437. Uses QuickTime to read the audio track a movie or media file.
  27438. As well as QuickTime movies, this should also manage to open other audio
  27439. files that quicktime can understand, like mp3, m4a, etc.
  27440. @see AudioFormat
  27441. */
  27442. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27443. {
  27444. public:
  27445. /** Creates a format object. */
  27446. QuickTimeAudioFormat();
  27447. /** Destructor. */
  27448. ~QuickTimeAudioFormat();
  27449. const Array <int> getPossibleSampleRates();
  27450. const Array <int> getPossibleBitDepths();
  27451. bool canDoStereo();
  27452. bool canDoMono();
  27453. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27454. const bool deleteStreamIfOpeningFails);
  27455. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27456. double sampleRateToUse,
  27457. unsigned int numberOfChannels,
  27458. int bitsPerSample,
  27459. const StringPairArray& metadataValues,
  27460. int qualityOptionIndex);
  27461. juce_UseDebuggingNewOperator
  27462. };
  27463. #endif
  27464. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27465. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27466. #endif
  27467. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27468. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27469. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27470. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27471. /**
  27472. Reads and Writes WAV format audio files.
  27473. @see AudioFormat
  27474. */
  27475. class JUCE_API WavAudioFormat : public AudioFormat
  27476. {
  27477. public:
  27478. /** Creates a format object. */
  27479. WavAudioFormat();
  27480. /** Destructor. */
  27481. ~WavAudioFormat();
  27482. /** Metadata property name used by wav readers and writers for adding
  27483. a BWAV chunk to the file.
  27484. @see AudioFormatReader::metadataValues, createWriterFor
  27485. */
  27486. static const tchar* const bwavDescription;
  27487. /** Metadata property name used by wav readers and writers for adding
  27488. a BWAV chunk to the file.
  27489. @see AudioFormatReader::metadataValues, createWriterFor
  27490. */
  27491. static const tchar* const bwavOriginator;
  27492. /** Metadata property name used by wav readers and writers for adding
  27493. a BWAV chunk to the file.
  27494. @see AudioFormatReader::metadataValues, createWriterFor
  27495. */
  27496. static const tchar* const bwavOriginatorRef;
  27497. /** Metadata property name used by wav readers and writers for adding
  27498. a BWAV chunk to the file.
  27499. Date format is: yyyy-mm-dd
  27500. @see AudioFormatReader::metadataValues, createWriterFor
  27501. */
  27502. static const tchar* const bwavOriginationDate;
  27503. /** Metadata property name used by wav readers and writers for adding
  27504. a BWAV chunk to the file.
  27505. Time format is: hh-mm-ss
  27506. @see AudioFormatReader::metadataValues, createWriterFor
  27507. */
  27508. static const tchar* const bwavOriginationTime;
  27509. /** Metadata property name used by wav readers and writers for adding
  27510. a BWAV chunk to the file.
  27511. This is the number of samples from the start of an edit that the
  27512. file is supposed to begin at. Seems like an obvious mistake to
  27513. only allow a file to occur in an edit once, but that's the way
  27514. it is..
  27515. @see AudioFormatReader::metadataValues, createWriterFor
  27516. */
  27517. static const tchar* const bwavTimeReference;
  27518. /** Metadata property name used by wav readers and writers for adding
  27519. a BWAV chunk to the file.
  27520. This is a
  27521. @see AudioFormatReader::metadataValues, createWriterFor
  27522. */
  27523. static const tchar* const bwavCodingHistory;
  27524. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27525. This just makes it easier than using the property names directly, and it
  27526. fills out the time and date in the right format.
  27527. */
  27528. static const StringPairArray createBWAVMetadata (const String& description,
  27529. const String& originator,
  27530. const String& originatorRef,
  27531. const Time& dateAndTime,
  27532. const int64 timeReferenceSamples,
  27533. const String& codingHistory);
  27534. const Array <int> getPossibleSampleRates();
  27535. const Array <int> getPossibleBitDepths();
  27536. bool canDoStereo();
  27537. bool canDoMono();
  27538. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27539. const bool deleteStreamIfOpeningFails);
  27540. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27541. double sampleRateToUse,
  27542. unsigned int numberOfChannels,
  27543. int bitsPerSample,
  27544. const StringPairArray& metadataValues,
  27545. int qualityOptionIndex);
  27546. juce_UseDebuggingNewOperator
  27547. };
  27548. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27549. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27550. #endif
  27551. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27552. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  27553. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27554. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27555. /********* Start of inlined file: juce_ActionListenerList.h *********/
  27556. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27557. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27558. /**
  27559. A set of ActionListeners.
  27560. Listeners can be added and removed from the list, and messages can be
  27561. broadcast to all the listeners.
  27562. @see ActionListener, ActionBroadcaster
  27563. */
  27564. class JUCE_API ActionListenerList : public MessageListener
  27565. {
  27566. public:
  27567. /** Creates an empty list. */
  27568. ActionListenerList() throw();
  27569. /** Destructor. */
  27570. ~ActionListenerList() throw();
  27571. /** Adds a listener to the list.
  27572. (Trying to add a listener that's already on the list will have no effect).
  27573. */
  27574. void addActionListener (ActionListener* const listener) throw();
  27575. /** Removes a listener from the list.
  27576. If the listener isn't on the list, this won't have any effect.
  27577. */
  27578. void removeActionListener (ActionListener* const listener) throw();
  27579. /** Removes all listeners from the list. */
  27580. void removeAllActionListeners() throw();
  27581. /** Broadcasts a message to all the registered listeners.
  27582. This sends the message asynchronously.
  27583. If a listener is on the list when this method is called but is removed from
  27584. the list before the message arrives, it won't receive the message. Similarly
  27585. listeners that are added to the list after the message is sent but before it
  27586. arrives won't get the message either.
  27587. */
  27588. void sendActionMessage (const String& message) const;
  27589. /** @internal */
  27590. void handleMessage (const Message&);
  27591. juce_UseDebuggingNewOperator
  27592. private:
  27593. SortedSet <void*> actionListeners_;
  27594. CriticalSection actionListenerLock_;
  27595. ActionListenerList (const ActionListenerList&);
  27596. const ActionListenerList& operator= (const ActionListenerList&);
  27597. };
  27598. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27599. /********* End of inlined file: juce_ActionListenerList.h *********/
  27600. /** Manages a list of ActionListeners, and can send them messages.
  27601. To quickly add methods to your class that can add/remove action
  27602. listeners and broadcast to them, you can derive from this.
  27603. @see ActionListenerList, ActionListener
  27604. */
  27605. class JUCE_API ActionBroadcaster
  27606. {
  27607. public:
  27608. /** Creates an ActionBroadcaster. */
  27609. ActionBroadcaster() throw();
  27610. /** Destructor. */
  27611. virtual ~ActionBroadcaster();
  27612. /** Adds a listener to the list.
  27613. (Trying to add a listener that's already on the list will have no effect).
  27614. */
  27615. void addActionListener (ActionListener* const listener);
  27616. /** Removes a listener from the list.
  27617. If the listener isn't on the list, this won't have any effect.
  27618. */
  27619. void removeActionListener (ActionListener* const listener);
  27620. /** Removes all listeners from the list. */
  27621. void removeAllActionListeners();
  27622. /** Broadcasts a message to all the registered listeners.
  27623. @see ActionListenerList::sendActionMessage
  27624. */
  27625. void sendActionMessage (const String& message) const;
  27626. private:
  27627. ActionListenerList actionListenerList;
  27628. ActionBroadcaster (const ActionBroadcaster&);
  27629. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  27630. };
  27631. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27632. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  27633. #endif
  27634. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  27635. #endif
  27636. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27637. #endif
  27638. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  27639. #endif
  27640. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  27641. #endif
  27642. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  27643. #endif
  27644. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  27645. #endif
  27646. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27647. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  27648. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27649. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27650. class InterprocessConnectionServer;
  27651. /**
  27652. Manages a simple two-way messaging connection to another process, using either
  27653. a socket or a named pipe as the transport medium.
  27654. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  27655. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27656. and incoming messages will result in a callback via the messageReceived()
  27657. method.
  27658. To open a pipe and wait for another client to connect to it, use the createPipe()
  27659. method.
  27660. To act as a socket server and create connections for one or more client, see the
  27661. InterprocessConnectionServer class.
  27662. @see InterprocessConnectionServer, Socket, NamedPipe
  27663. */
  27664. class JUCE_API InterprocessConnection : public Thread,
  27665. private MessageListener
  27666. {
  27667. public:
  27668. /** Creates a connection.
  27669. Connections are created manually, connecting them with the connectToSocket()
  27670. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  27671. when a client wants to connect.
  27672. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  27673. connectionLost() and messageReceived() methods will
  27674. always be made using the message thread; if false,
  27675. these will be called immediately on the connection's
  27676. own thread.
  27677. @param magicMessageHeaderNumber a magic number to use in the header to check the
  27678. validity of the data blocks being sent and received. This
  27679. can be any number, but the sender and receiver must obviously
  27680. use matching values or they won't recognise each other.
  27681. */
  27682. InterprocessConnection (const bool callbacksOnMessageThread = true,
  27683. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  27684. /** Destructor. */
  27685. ~InterprocessConnection();
  27686. /** Tries to connect this object to a socket.
  27687. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  27688. object waiting to receive client connections on this port number.
  27689. @param hostName the host computer, either a network address or name
  27690. @param portNumber the socket port number to try to connect to
  27691. @param timeOutMillisecs how long to keep trying before giving up
  27692. @returns true if the connection is established successfully
  27693. @see Socket
  27694. */
  27695. bool connectToSocket (const String& hostName,
  27696. const int portNumber,
  27697. const int timeOutMillisecs);
  27698. /** Tries to connect the object to an existing named pipe.
  27699. For this to work, another process on the same computer must already have opened
  27700. an InterprocessConnection object and used createPipe() to create a pipe for this
  27701. to connect to.
  27702. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27703. @returns true if it connects successfully.
  27704. @see createPipe, NamedPipe
  27705. */
  27706. bool connectToPipe (const String& pipeName,
  27707. const int pipeReceiveMessageTimeoutMs = -1);
  27708. /** Tries to create a new pipe for other processes to connect to.
  27709. This creates a pipe with the given name, so that other processes can use
  27710. connectToPipe() to connect to the other end.
  27711. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27712. If another process is already using this pipe, this will fail and return false.
  27713. */
  27714. bool createPipe (const String& pipeName,
  27715. const int pipeReceiveMessageTimeoutMs = -1);
  27716. /** Disconnects and closes any currently-open sockets or pipes. */
  27717. void disconnect();
  27718. /** True if a socket or pipe is currently active. */
  27719. bool isConnected() const;
  27720. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  27721. StreamingSocket* getSocket() const throw() { return socket; }
  27722. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  27723. NamedPipe* getPipe() const throw() { return pipe; }
  27724. /** Returns the name of the machine at the other end of this connection.
  27725. This will return an empty string if the other machine isn't known for
  27726. some reason.
  27727. */
  27728. const String getConnectedHostName() const;
  27729. /** Tries to send a message to the other end of this connection.
  27730. This will fail if it's not connected, or if there's some kind of write error. If
  27731. it succeeds, the connection object at the other end will receive the message by
  27732. a callback to its messageReceived() method.
  27733. @see messageReceived
  27734. */
  27735. bool sendMessage (const MemoryBlock& message);
  27736. /** Called when the connection is first connected.
  27737. If the connection was created with the callbacksOnMessageThread flag set, then
  27738. this will be called on the message thread; otherwise it will be called on a server
  27739. thread.
  27740. */
  27741. virtual void connectionMade() = 0;
  27742. /** Called when the connection is broken.
  27743. If the connection was created with the callbacksOnMessageThread flag set, then
  27744. this will be called on the message thread; otherwise it will be called on a server
  27745. thread.
  27746. */
  27747. virtual void connectionLost() = 0;
  27748. /** Called when a message arrives.
  27749. When the object at the other end of this connection sends us a message with sendMessage(),
  27750. this callback is used to deliver it to us.
  27751. If the connection was created with the callbacksOnMessageThread flag set, then
  27752. this will be called on the message thread; otherwise it will be called on a server
  27753. thread.
  27754. @see sendMessage
  27755. */
  27756. virtual void messageReceived (const MemoryBlock& message) = 0;
  27757. juce_UseDebuggingNewOperator
  27758. private:
  27759. CriticalSection pipeAndSocketLock;
  27760. StreamingSocket* socket;
  27761. NamedPipe* pipe;
  27762. bool callbackConnectionState;
  27763. const bool useMessageThread;
  27764. const uint32 magicMessageHeader;
  27765. int pipeReceiveMessageTimeout;
  27766. friend class InterprocessConnectionServer;
  27767. void initialiseWithSocket (StreamingSocket* const socket_);
  27768. void initialiseWithPipe (NamedPipe* const pipe_);
  27769. void handleMessage (const Message& message);
  27770. void connectionMadeInt();
  27771. void connectionLostInt();
  27772. void deliverDataInt (const MemoryBlock& data);
  27773. bool readNextMessageInt();
  27774. void run();
  27775. InterprocessConnection (const InterprocessConnection&);
  27776. const InterprocessConnection& operator= (const InterprocessConnection&);
  27777. };
  27778. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27779. /********* End of inlined file: juce_InterprocessConnection.h *********/
  27780. #endif
  27781. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27782. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  27783. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27784. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27785. /**
  27786. An object that waits for client sockets to connect to a port on this host, and
  27787. creates InterprocessConnection objects for each one.
  27788. To use this, create a class derived from it which implements the createConnectionObject()
  27789. method, so that it creates suitable connection objects for each client that tries
  27790. to connect.
  27791. @see InterprocessConnection
  27792. */
  27793. class JUCE_API InterprocessConnectionServer : private Thread
  27794. {
  27795. public:
  27796. /** Creates an uninitialised server object.
  27797. */
  27798. InterprocessConnectionServer();
  27799. /** Destructor. */
  27800. ~InterprocessConnectionServer();
  27801. /** Starts an internal thread which listens on the given port number.
  27802. While this is running, in another process tries to connect with the
  27803. InterprocessConnection::connectToSocket() method, this object will call
  27804. createConnectionObject() to create a connection to that client.
  27805. Use stop() to stop the thread running.
  27806. @see createConnectionObject, stop
  27807. */
  27808. bool beginWaitingForSocket (const int portNumber);
  27809. /** Terminates the listener thread, if it's active.
  27810. @see beginWaitingForSocket
  27811. */
  27812. void stop();
  27813. protected:
  27814. /** Creates a suitable connection object for a client process that wants to
  27815. connect to this one.
  27816. This will be called by the listener thread when a client process tries
  27817. to connect, and must return a new InterprocessConnection object that will
  27818. then run as this end of the connection.
  27819. @see InterprocessConnection
  27820. */
  27821. virtual InterprocessConnection* createConnectionObject() = 0;
  27822. public:
  27823. juce_UseDebuggingNewOperator
  27824. private:
  27825. StreamingSocket* volatile socket;
  27826. void run();
  27827. InterprocessConnectionServer (const InterprocessConnectionServer&);
  27828. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  27829. };
  27830. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27831. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  27832. #endif
  27833. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  27834. #endif
  27835. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  27836. #endif
  27837. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27838. /********* Start of inlined file: juce_MessageManager.h *********/
  27839. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27840. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27841. class Component;
  27842. class MessageManagerLock;
  27843. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  27844. */
  27845. typedef void* (MessageCallbackFunction) (void* userData);
  27846. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  27847. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  27848. */
  27849. class JUCE_API MessageManager : private DeletedAtShutdown
  27850. {
  27851. public:
  27852. /** Returns the global instance of the MessageManager. */
  27853. static MessageManager* getInstance() throw();
  27854. /** Runs the event dispatch loop until a stop message is posted.
  27855. This method is only intended to be run by the application's startup routine,
  27856. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  27857. @see stopDispatchLoop
  27858. */
  27859. void runDispatchLoop();
  27860. /** Sends a signal that the dispatch loop should terminate.
  27861. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  27862. will be interrupted and will return.
  27863. @see runDispatchLoop
  27864. */
  27865. void stopDispatchLoop();
  27866. /** Returns true if the stopDispatchLoop() method has been called.
  27867. */
  27868. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  27869. /** Synchronously dispatches messages until a given time has elapsed.
  27870. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  27871. otherwise returns true.
  27872. */
  27873. bool runDispatchLoopUntil (int millisecondsToRunFor);
  27874. /** Calls a function using the message-thread.
  27875. This can be used by any thread to cause this function to be called-back
  27876. by the message thread. If it's the message-thread that's calling this method,
  27877. then the function will just be called; if another thread is calling, a message
  27878. will be posted to the queue, and this method will block until that message
  27879. is delivered, the function is called, and the result is returned.
  27880. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  27881. thread has a critical section locked, which an unrelated message callback then tries to lock
  27882. before the message thread gets round to processing this callback.
  27883. @param callback the function to call - its signature must be @code
  27884. void* myCallbackFunction (void*) @endcode
  27885. @param userData a user-defined pointer that will be passed to the function that gets called
  27886. @returns the value that the callback function returns.
  27887. @see MessageManagerLock
  27888. */
  27889. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  27890. void* userData);
  27891. /** Returns true if the caller-thread is the message thread. */
  27892. bool isThisTheMessageThread() const throw();
  27893. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  27894. (Best to ignore this method unless you really know what you're doing..)
  27895. @see getCurrentMessageThread
  27896. */
  27897. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  27898. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  27899. (Best to ignore this method unless you really know what you're doing..)
  27900. @see setCurrentMessageThread
  27901. */
  27902. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  27903. /** Returns true if the caller thread has currenltly got the message manager locked.
  27904. see the MessageManagerLock class for more info about this.
  27905. This will be true if the caller is the message thread, because that automatically
  27906. gains a lock while a message is being dispatched.
  27907. */
  27908. bool currentThreadHasLockedMessageManager() const throw();
  27909. /** Sends a message to all other JUCE applications that are running.
  27910. @param messageText the string that will be passed to the actionListenerCallback()
  27911. method of the broadcast listeners in the other app.
  27912. @see registerBroadcastListener, ActionListener
  27913. */
  27914. static void broadcastMessage (const String& messageText) throw();
  27915. /** Registers a listener to get told about broadcast messages.
  27916. The actionListenerCallback() callback's string parameter
  27917. is the message passed into broadcastMessage().
  27918. @see broadcastMessage
  27919. */
  27920. void registerBroadcastListener (ActionListener* listener) throw();
  27921. /** Deregisters a broadcast listener. */
  27922. void deregisterBroadcastListener (ActionListener* listener) throw();
  27923. /** @internal */
  27924. void deliverMessage (void*);
  27925. /** @internal */
  27926. void deliverBroadcastMessage (const String&);
  27927. juce_UseDebuggingNewOperator
  27928. private:
  27929. MessageManager() throw();
  27930. ~MessageManager() throw();
  27931. friend class MessageListener;
  27932. friend class ChangeBroadcaster;
  27933. friend class ActionBroadcaster;
  27934. static MessageManager* instance;
  27935. SortedSet<const MessageListener*> messageListeners;
  27936. ActionListenerList* broadcastListeners;
  27937. friend class JUCEApplication;
  27938. bool quitMessagePosted, quitMessageReceived;
  27939. Thread::ThreadID messageThreadId;
  27940. VoidArray modalComponents;
  27941. static void* exitModalLoopCallback (void*);
  27942. void postMessageToQueue (Message* const message);
  27943. static void doPlatformSpecificInitialisation();
  27944. static void doPlatformSpecificShutdown();
  27945. friend class MessageManagerLock;
  27946. CriticalSection messageDispatchLock;
  27947. Thread::ThreadID currentLockingThreadId;
  27948. MessageManager (const MessageManager&);
  27949. const MessageManager& operator= (const MessageManager&);
  27950. };
  27951. /** Used to make sure that the calling thread has exclusive access to the message loop.
  27952. Because it's not thread-safe to call any of the Component or other UI classes
  27953. from threads other than the message thread, one of these objects can be used to
  27954. lock the message loop and allow this to be done. The message thread will be
  27955. suspended for the lifetime of the MessageManagerLock object, so create one on
  27956. the stack like this: @code
  27957. void MyThread::run()
  27958. {
  27959. someData = 1234;
  27960. const MessageManagerLock mmLock;
  27961. // the event loop will now be locked so it's safe to make a few calls..
  27962. myComponent->setBounds (newBounds);
  27963. myComponent->repaint();
  27964. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  27965. }
  27966. @endcode
  27967. Obviously be careful not to create one of these and leave it lying around, or
  27968. your app will grind to a halt!
  27969. Another caveat is that using this in conjunction with other CriticalSections
  27970. can create lots of interesting ways of producing a deadlock! In particular, if
  27971. your message thread calls stopThread() for a thread that uses these locks,
  27972. you'll get an (occasional) deadlock..
  27973. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  27974. */
  27975. class JUCE_API MessageManagerLock
  27976. {
  27977. public:
  27978. /** Tries to acquire a lock on the message manager.
  27979. If this constructor
  27980. When this constructor returns, the message manager will have finished processing the
  27981. last message and will not send another message until this MessageManagerLock is
  27982. deleted.
  27983. If the current thread already has the lock, nothing will be done, so it's perfectly
  27984. safe to create these locks recursively.
  27985. */
  27986. MessageManagerLock() throw();
  27987. /** Releases the current thread's lock on the message manager.
  27988. Make sure this object is created and deleted by the same thread,
  27989. otherwise there are no guarantees what will happen!
  27990. */
  27991. ~MessageManagerLock() throw();
  27992. /** Tries to acquire a lock on the message manager.
  27993. This does the same thing as the normal constructor, but while it's waiting to get
  27994. the lock, it checks the specified thread to see if it has been given the
  27995. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  27996. without gaining the lock.
  27997. To find out whether the lock was successful, call lockWasGained(). If this is
  27998. false, your thread is being told to die, so you'd better get out of there.
  27999. If the current thread already has the lock, nothing will be done, so it's perfectly
  28000. safe to create these locks recursively.
  28001. E.g.
  28002. @code
  28003. void run()
  28004. {
  28005. ...
  28006. while (! threadShouldExit())
  28007. {
  28008. MessageManagerLock mml (Thread::getCurrentThread());
  28009. if (! mml.lockWasGained)
  28010. return; // another thread is trying to kill us!
  28011. ..do some locked stuff here..
  28012. }
  28013. ..and now the MM is now unlocked..
  28014. }
  28015. @endcode
  28016. */
  28017. MessageManagerLock (Thread* const threadToCheckForExitSignal) throw();
  28018. /** Returns true if the lock was successfully acquired.
  28019. (See the constructor that takes a Thread for more info).
  28020. */
  28021. bool lockWasGained() const throw() { return locked; }
  28022. private:
  28023. Thread::ThreadID lastLockingThreadId;
  28024. bool locked;
  28025. };
  28026. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28027. /********* End of inlined file: juce_MessageManager.h *********/
  28028. #endif
  28029. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28030. /********* Start of inlined file: juce_MultiTimer.h *********/
  28031. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28032. #define __JUCE_MULTITIMER_JUCEHEADER__
  28033. /**
  28034. A type of timer class that can run multiple timers with different frequencies,
  28035. all of which share a single callback.
  28036. This class is very similar to the Timer class, but allows you run multiple
  28037. separate timers, where each one has a unique ID number. The methods in this
  28038. class are exactly equivalent to those in Timer, but with the addition of
  28039. this ID number.
  28040. To use it, you need to create a subclass of MultiTimer, implementing the
  28041. timerCallback() method. Then you can start timers with startTimer(), and
  28042. each time the callback is triggered, it passes in the ID of the timer that
  28043. caused it.
  28044. @see Timer
  28045. */
  28046. class JUCE_API MultiTimer
  28047. {
  28048. protected:
  28049. /** Creates a MultiTimer.
  28050. When created, no timers are running, so use startTimer() to start things off.
  28051. */
  28052. MultiTimer() throw();
  28053. /** Creates a copy of another timer.
  28054. Note that this timer will not contain any running timers, even if the one you're
  28055. copying from was running.
  28056. */
  28057. MultiTimer (const MultiTimer& other) throw();
  28058. public:
  28059. /** Destructor. */
  28060. virtual ~MultiTimer();
  28061. /** The user-defined callback routine that actually gets called by each of the
  28062. timers that are running.
  28063. It's perfectly ok to call startTimer() or stopTimer() from within this
  28064. callback to change the subsequent intervals.
  28065. */
  28066. virtual void timerCallback (const int timerId) = 0;
  28067. /** Starts a timer and sets the length of interval required.
  28068. If the timer is already started, this will reset it, so the
  28069. time between calling this method and the next timer callback
  28070. will not be less than the interval length passed in.
  28071. @param timerId a unique Id number that identifies the timer to
  28072. start. This is the id that will be passed back
  28073. to the timerCallback() method when this timer is
  28074. triggered
  28075. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28076. rounded up to 1)
  28077. */
  28078. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28079. /** Stops a timer.
  28080. If a timer has been started with the given ID number, it will be cancelled.
  28081. No more callbacks will be made for the specified timer after this method returns.
  28082. If this is called from a different thread, any callbacks that may
  28083. be currently executing may be allowed to finish before the method
  28084. returns.
  28085. */
  28086. void stopTimer (const int timerId) throw();
  28087. /** Checks whether a timer has been started for a specified ID.
  28088. @returns true if a timer with the given ID is running.
  28089. */
  28090. bool isTimerRunning (const int timerId) const throw();
  28091. /** Returns the interval for a specified timer ID.
  28092. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28093. is running for the ID number specified.
  28094. */
  28095. int getTimerInterval (const int timerId) const throw();
  28096. private:
  28097. CriticalSection timerListLock;
  28098. VoidArray timers;
  28099. const MultiTimer& operator= (const MultiTimer&);
  28100. };
  28101. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28102. /********* End of inlined file: juce_MultiTimer.h *********/
  28103. #endif
  28104. #ifndef __JUCE_TIMER_JUCEHEADER__
  28105. #endif
  28106. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28107. #endif
  28108. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28109. /********* Start of inlined file: juce_GradientBrush.h *********/
  28110. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28111. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28112. /********* Start of inlined file: juce_ColourGradient.h *********/
  28113. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28114. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28115. /**
  28116. Structure used to define a colour gradient for painting areas.
  28117. @see GradientBrush
  28118. */
  28119. class JUCE_API ColourGradient
  28120. {
  28121. public:
  28122. /** Creates a gradient object.
  28123. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28124. colour2 should be. In between them there's a gradient.
  28125. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28126. its centre.
  28127. The alpha transparencies of the colours are used, so note that
  28128. if you blend from transparent to a solid colour, the RGB of the transparent
  28129. colour will become visible in parts of the gradient. e.g. blending
  28130. from Colour::transparentBlack to Colours::white will produce a
  28131. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28132. will be white all the way across.
  28133. @see ColourGradient
  28134. */
  28135. ColourGradient (const Colour& colour1,
  28136. const float x1,
  28137. const float y1,
  28138. const Colour& colour2,
  28139. const float x2,
  28140. const float y2,
  28141. const bool isRadial) throw();
  28142. /** Creates an uninitialised gradient.
  28143. If you use this constructor instead of the other one, be sure to set all the
  28144. object's public member variables before using it!
  28145. */
  28146. ColourGradient() throw();
  28147. /** Destructor */
  28148. ~ColourGradient() throw();
  28149. /** Removes any colours that have been added.
  28150. This will also remove any start and end colours, so the gradient won't work. You'll
  28151. need to add more colours with addColour().
  28152. */
  28153. void clearColours() throw();
  28154. /** Adds a colour at a point along the length of the gradient.
  28155. This allows the gradient to go through a spectrum of colours, instead of just a
  28156. start and end colour.
  28157. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28158. of the distance along the line between the two points
  28159. at which the colour should occur.
  28160. @param colour the colour that should be used at this point
  28161. */
  28162. void addColour (const double proportionAlongGradient,
  28163. const Colour& colour) throw();
  28164. /** Multiplies the alpha value of all the colours by the given scale factor */
  28165. void multiplyOpacity (const float multiplier) throw();
  28166. /** Returns the number of colour-stops that have been added. */
  28167. int getNumColours() const throw();
  28168. /** Returns the position along the length of the gradient of the colour with this index.
  28169. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28170. */
  28171. double getColourPosition (const int index) const throw();
  28172. /** Returns the colour that was added with a given index.
  28173. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28174. */
  28175. const Colour getColour (const int index) const throw();
  28176. /** Creates a set of interpolated premultiplied ARGB values.
  28177. The caller must delete the array that is returned using juce_free().
  28178. */
  28179. PixelARGB* createLookupTable (int& numEntries) const throw();
  28180. /** Returns true if all colours are opaque. */
  28181. bool isOpaque() const throw();
  28182. /** Returns true if all colours are completely transparent. */
  28183. bool isInvisible() const throw();
  28184. float x1;
  28185. float y1;
  28186. float x2;
  28187. float y2;
  28188. /** If true, the gradient should be filled circularly, centred around
  28189. (x1, y1), with (x2, y2) defining a point on the circumference.
  28190. If false, the gradient is linear between the two points.
  28191. */
  28192. bool isRadial;
  28193. /** A transform to apply to the resultant gradient shape */
  28194. AffineTransform transform;
  28195. juce_UseDebuggingNewOperator
  28196. private:
  28197. Array <uint32> colours;
  28198. };
  28199. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28200. /********* End of inlined file: juce_ColourGradient.h *********/
  28201. /**
  28202. A Brush that fills areas with a colour gradient.
  28203. The gradient can either be linear or circular.
  28204. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28205. */
  28206. class JUCE_API GradientBrush : public Brush
  28207. {
  28208. public:
  28209. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28210. (x1, y1) is the location relative to the origin of the Graphics context,
  28211. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28212. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28213. its centre.
  28214. The alpha transparencies of the colours are used, so the brush
  28215. need not be completely opaque. Note that this means that if you
  28216. blend from transparent to a solid colour, the RGB of the transparent
  28217. colour will become visible in parts of the gradient. e.g. blending
  28218. from Colour::transparentBlack to Colours::white will produce a
  28219. grey colour, but Colour::transparentWhite to Colours::white will be
  28220. white all the way across.
  28221. @see ColourGradient
  28222. */
  28223. GradientBrush (const Colour& colour1,
  28224. const float x1,
  28225. const float y1,
  28226. const Colour& colour2,
  28227. const float x2,
  28228. const float y2,
  28229. const bool isRadial) throw();
  28230. /** Creates a gradient brush from a ColourGradient object.
  28231. */
  28232. GradientBrush (const ColourGradient& gradient) throw();
  28233. /** Destructor. */
  28234. ~GradientBrush() throw();
  28235. Brush* createCopy() const throw();
  28236. void applyTransform (const AffineTransform& transform) throw();
  28237. void multiplyOpacity (const float multiple) throw();
  28238. bool isInvisible() const throw();
  28239. void paintPath (LowLevelGraphicsContext& context,
  28240. const Path& path, const AffineTransform& transform) throw();
  28241. void paintRectangle (LowLevelGraphicsContext& context,
  28242. int x, int y, int w, int h) throw();
  28243. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28244. const Image& alphaChannelImage, int imageX, int imageY,
  28245. int x, int y, int w, int h) throw();
  28246. juce_UseDebuggingNewOperator
  28247. protected:
  28248. ColourGradient gradient;
  28249. private:
  28250. GradientBrush (const GradientBrush&);
  28251. const GradientBrush& operator= (const GradientBrush&);
  28252. };
  28253. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28254. /********* End of inlined file: juce_GradientBrush.h *********/
  28255. #endif
  28256. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28257. /********* Start of inlined file: juce_ImageBrush.h *********/
  28258. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28259. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28260. /********* Start of inlined file: juce_Image.h *********/
  28261. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28262. #define __JUCE_IMAGE_JUCEHEADER__
  28263. /**
  28264. Holds a fixed-size bitmap.
  28265. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28266. To draw into an image, create a Graphics object for it.
  28267. e.g. @code
  28268. // create a transparent 500x500 image..
  28269. Image myImage (Image::RGB, 500, 500, true);
  28270. Graphics g (myImage);
  28271. g.setColour (Colours::red);
  28272. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28273. @endcode
  28274. Other useful ways to create an image are with the ImageCache class, or the
  28275. ImageFileFormat, which provides a way to load common image files.
  28276. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28277. */
  28278. class JUCE_API Image
  28279. {
  28280. public:
  28281. enum PixelFormat
  28282. {
  28283. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28284. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28285. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28286. };
  28287. /** Creates an in-memory image with a specified size and format.
  28288. @param format the number of colour channels in the image
  28289. @param imageWidth the desired width of the image, in pixels - this value must be
  28290. greater than zero (otherwise a width of 1 will be used)
  28291. @param imageHeight the desired width of the image, in pixels - this value must be
  28292. greater than zero (otherwise a height of 1 will be used)
  28293. @param clearImage if true, the image will initially be cleared to black or transparent
  28294. black. If false, the image may contain random data, and the
  28295. user will have to deal with this
  28296. */
  28297. Image (const PixelFormat format,
  28298. const int imageWidth,
  28299. const int imageHeight,
  28300. const bool clearImage);
  28301. /** Creates a copy of another image.
  28302. @see createCopy
  28303. */
  28304. Image (const Image& other);
  28305. /** Destructor. */
  28306. virtual ~Image();
  28307. /** Returns the image's width (in pixels). */
  28308. int getWidth() const throw() { return imageWidth; }
  28309. /** Returns the image's height (in pixels). */
  28310. int getHeight() const throw() { return imageHeight; }
  28311. /** Returns the image's pixel format. */
  28312. PixelFormat getFormat() const throw() { return format; }
  28313. /** True if the image's format is ARGB. */
  28314. bool isARGB() const throw() { return format == ARGB; }
  28315. /** True if the image's format is RGB. */
  28316. bool isRGB() const throw() { return format == RGB; }
  28317. /** True if the image contains an alpha-channel. */
  28318. bool hasAlphaChannel() const throw() { return format != RGB; }
  28319. /** Clears a section of the image with a given colour.
  28320. This won't do any alpha-blending - it just sets all pixels in the image to
  28321. the given colour (which may be non-opaque if the image has an alpha channel).
  28322. */
  28323. virtual void clear (int x, int y, int w, int h,
  28324. const Colour& colourToClearTo = Colour (0x00000000));
  28325. /** Returns a new image that's a copy of this one.
  28326. A new size for the copied image can be specified, or values less than
  28327. zero can be passed-in to use the image's existing dimensions.
  28328. It's up to the caller to delete the image when no longer needed.
  28329. */
  28330. virtual Image* createCopy (int newWidth = -1,
  28331. int newHeight = -1,
  28332. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28333. /** Returns the colour of one of the pixels in the image.
  28334. If the co-ordinates given are beyond the image's boundaries, this will
  28335. return Colours::transparentBlack.
  28336. (0, 0) is the image's top-left corner.
  28337. @see getAlphaAt, setPixelAt, blendPixelAt
  28338. */
  28339. virtual const Colour getPixelAt (const int x, const int y) const;
  28340. /** Sets the colour of one of the image's pixels.
  28341. If the co-ordinates are beyond the image's boundaries, then nothing will
  28342. happen.
  28343. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28344. just replace the existing pixel with the given one. The colour's opacity
  28345. will be ignored if this image doesn't have an alpha-channel.
  28346. (0, 0) is the image's top-left corner.
  28347. @see blendPixelAt
  28348. */
  28349. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28350. /** Changes the opacity of a pixel.
  28351. This only has an effect if the image has an alpha channel and if the
  28352. given co-ordinates are inside the image's boundary.
  28353. The multiplier must be in the range 0 to 1.0, and the current alpha
  28354. at the given co-ordinates will be multiplied by this value.
  28355. @see getAlphaAt, setPixelAt
  28356. */
  28357. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28358. /** Changes the overall opacity of the image.
  28359. This will multiply the alpha value of each pixel in the image by the given
  28360. amount (limiting the resulting alpha values between 0 and 255). This allows
  28361. you to make an image more or less transparent.
  28362. If the image doesn't have an alpha channel, this won't have any effect.
  28363. */
  28364. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28365. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28366. */
  28367. virtual void desaturate();
  28368. /** Locks some of the pixels in the image so they can be read and written to.
  28369. This returns a pointer to some memory containing the pixels in the given
  28370. rectangle. It also returns values for the line and pixel stride used within
  28371. the data. The format of the pixel data is the same as that of this image.
  28372. When you've finished reading and changing the data, you must call
  28373. releasePixelDataReadWrite() to give the pixels back to the image.
  28374. For images that are stored in memory, this method may just return a direct
  28375. pointer to the image's data, but other types of image may be stored elsewhere,
  28376. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28377. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28378. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28379. instead.
  28380. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28381. */
  28382. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28383. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28384. */
  28385. virtual void releasePixelDataReadWrite (void* sourceData);
  28386. /** Locks some of the pixels in the image so they can be read.
  28387. This returns a pointer to some memory containing the pixels in the given
  28388. rectangle. It also returns values for the line and pixel stride used within
  28389. the data. The format of the pixel data is the same as that of this image.
  28390. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28391. to let the image free the memory if necessary.
  28392. For images that are stored in memory, this method may just return a direct
  28393. pointer to the image's data, but other types of image may be stored elsewhere,
  28394. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28395. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28396. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28397. instead.
  28398. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28399. */
  28400. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28401. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28402. */
  28403. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28404. /** Copies some pixel values to a rectangle of the image.
  28405. The format of the pixel data must match that of the image itself, and the
  28406. rectangle supplied must be within the image's bounds.
  28407. */
  28408. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28409. const uint8* sourcePixelData, int sourceLineStride);
  28410. /** Copies a section of the image to somewhere else within itself.
  28411. */
  28412. virtual void moveImageSection (int destX, int destY,
  28413. int sourceX, int sourceY,
  28414. int width, int height);
  28415. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28416. of the image.
  28417. @param result the list that will have the area added to it
  28418. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28419. above this level will be considered opaque
  28420. */
  28421. void createSolidAreaMask (RectangleList& result,
  28422. const float alphaThreshold = 0.5f) const;
  28423. juce_UseDebuggingNewOperator
  28424. /** Creates a context suitable for drawing onto this image.
  28425. Don't call this method directly! It's used internally by the Graphics class.
  28426. */
  28427. virtual LowLevelGraphicsContext* createLowLevelContext();
  28428. protected:
  28429. const PixelFormat format;
  28430. const int imageWidth, imageHeight;
  28431. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28432. Image (const PixelFormat format,
  28433. const int imageWidth,
  28434. const int imageHeight);
  28435. int pixelStride, lineStride;
  28436. uint8* imageData;
  28437. private:
  28438. const Image& operator= (const Image&);
  28439. };
  28440. #endif // __JUCE_IMAGE_JUCEHEADER__
  28441. /********* End of inlined file: juce_Image.h *********/
  28442. /**
  28443. A Brush that fills areas with tiled repetitions of an image.
  28444. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28445. */
  28446. class JUCE_API ImageBrush : public Brush
  28447. {
  28448. public:
  28449. /* Creates an image brush, ready for use in Graphics::setBrush().
  28450. (x, y) is an anchor point for the top-left of the image
  28451. A reference to the image passed in will be kept, so don't delete
  28452. it within the lifetime of this object
  28453. */
  28454. ImageBrush (Image* const image,
  28455. const int anchorX,
  28456. const int anchorY,
  28457. const float opacity) throw();
  28458. /** Destructor. */
  28459. ~ImageBrush() throw();
  28460. Brush* createCopy() const throw();
  28461. void applyTransform (const AffineTransform& transform) throw();
  28462. void multiplyOpacity (const float multiple) throw();
  28463. bool isInvisible() const throw();
  28464. void paintPath (LowLevelGraphicsContext& context,
  28465. const Path& path, const AffineTransform& transform) throw();
  28466. void paintRectangle (LowLevelGraphicsContext& context,
  28467. int x, int y, int w, int h) throw();
  28468. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28469. const Image& alphaChannelImage, int imageX, int imageY,
  28470. int x, int y, int w, int h) throw();
  28471. juce_UseDebuggingNewOperator
  28472. protected:
  28473. Image* image;
  28474. int anchorX, anchorY;
  28475. float opacity;
  28476. private:
  28477. ImageBrush (const ImageBrush&);
  28478. const ImageBrush& operator= (const ImageBrush&);
  28479. void getStartXY (int& x, int& y) const throw();
  28480. };
  28481. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28482. /********* End of inlined file: juce_ImageBrush.h *********/
  28483. #endif
  28484. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28485. #endif
  28486. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28487. #endif
  28488. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28489. #endif
  28490. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28491. #endif
  28492. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28493. #endif
  28494. #ifndef __JUCE_FONT_JUCEHEADER__
  28495. #endif
  28496. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28497. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28498. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28499. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28500. /**
  28501. An glyph from a particular font, with a particular size, style,
  28502. typeface and position.
  28503. @see GlyphArrangement, Font
  28504. */
  28505. class JUCE_API PositionedGlyph
  28506. {
  28507. public:
  28508. /** Returns the character the glyph represents. */
  28509. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28510. /** Checks whether the glyph is actually empty. */
  28511. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28512. /** Returns the position of the glyph's left-hand edge. */
  28513. float getLeft() const throw() { return x; }
  28514. /** Returns the position of the glyph's right-hand edge. */
  28515. float getRight() const throw() { return x + w; }
  28516. /** Returns the y position of the glyph's baseline. */
  28517. float getBaselineY() const throw() { return y; }
  28518. /** Returns the y position of the top of the glyph. */
  28519. float getTop() const throw() { return y - fontAscent; }
  28520. /** Returns the y position of the bottom of the glyph. */
  28521. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28522. /** Shifts the glyph's position by a relative amount. */
  28523. void moveBy (const float deltaX,
  28524. const float deltaY) throw();
  28525. /** Draws the glyph into a graphics context. */
  28526. void draw (const Graphics& g) const throw();
  28527. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28528. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28529. /** Returns the path for this glyph.
  28530. @param path the glyph's outline will be appended to this path
  28531. */
  28532. void createPath (Path& path) const throw();
  28533. /** Checks to see if a point lies within this glyph. */
  28534. bool hitTest (float x, float y) const throw();
  28535. juce_UseDebuggingNewOperator
  28536. private:
  28537. friend class GlyphArrangement;
  28538. float x, y, w;
  28539. float fontHeight, fontAscent, fontHorizontalScale;
  28540. bool isUnderlined;
  28541. const TypefaceGlyphInfo* glyphInfo;
  28542. PositionedGlyph() throw();
  28543. };
  28544. /**
  28545. A set of glyphs, each with a position.
  28546. You can create a GlyphArrangement, text to it and then draw it onto a
  28547. graphics context. It's used internally by the text methods in the
  28548. Graphics class, but can be used directly if more control is needed.
  28549. @see Font, PositionedGlyph
  28550. */
  28551. class JUCE_API GlyphArrangement
  28552. {
  28553. public:
  28554. /** Creates an empty arrangement. */
  28555. GlyphArrangement() throw();
  28556. /** Takes a copy of another arrangement. */
  28557. GlyphArrangement (const GlyphArrangement& other) throw();
  28558. /** Copies another arrangement onto this one.
  28559. To add another arrangement without clearing this one, use addGlyphArrangement().
  28560. */
  28561. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28562. /** Destructor. */
  28563. ~GlyphArrangement() throw();
  28564. /** Returns the total number of glyphs in the arrangement. */
  28565. int getNumGlyphs() const throw() { return numGlyphs; }
  28566. /** Returns one of the glyphs from the arrangement.
  28567. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28568. careful not to pass an out-of-range index here, as it
  28569. doesn't do any bounds-checking.
  28570. */
  28571. PositionedGlyph& getGlyph (const int index) const throw();
  28572. /** Clears all text from the arrangement and resets it.
  28573. */
  28574. void clear() throw();
  28575. /** Appends a line of text to the arrangement.
  28576. This will add the text as a single line, where x is the left-hand edge of the
  28577. first character, and y is the position for the text's baseline.
  28578. If the text contains new-lines or carriage-returns, this will ignore them - use
  28579. addJustifiedText() to add multi-line arrangements.
  28580. */
  28581. void addLineOfText (const Font& font,
  28582. const String& text,
  28583. const float x,
  28584. const float y) throw();
  28585. /** Adds a line of text, truncating it if it's wider than a specified size.
  28586. This is the same as addLineOfText(), but if the line's width exceeds the value
  28587. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  28588. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  28589. */
  28590. void addCurtailedLineOfText (const Font& font,
  28591. const String& text,
  28592. float x,
  28593. const float y,
  28594. const float maxWidthPixels,
  28595. const bool useEllipsis) throw();
  28596. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  28597. This will add text to the arrangement, breaking it into new lines either where there
  28598. is a new-line or carriage-return character in the text, or where a line's width
  28599. exceeds the value set in maxLineWidth.
  28600. Each line that is added will be laid out using the flags set in horizontalLayout, so
  28601. the lines can be left- or right-justified, or centred horizontally in the space
  28602. between x and (x + maxLineWidth).
  28603. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  28604. lines will be placed below it, separated by a distance of font.getHeight().
  28605. */
  28606. void addJustifiedText (const Font& font,
  28607. const String& text,
  28608. float x, float y,
  28609. const float maxLineWidth,
  28610. const Justification& horizontalLayout) throw();
  28611. /** Tries to fit some text withing a given space.
  28612. This does its best to make the given text readable within the specified rectangle,
  28613. so it useful for labelling things.
  28614. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  28615. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  28616. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  28617. it's been truncated.
  28618. A Justification parameter lets you specify how the text is laid out within the rectangle,
  28619. both horizontally and vertically.
  28620. @see Graphics::drawFittedText
  28621. */
  28622. void addFittedText (const Font& font,
  28623. const String& text,
  28624. float x, float y,
  28625. float width, float height,
  28626. const Justification& layout,
  28627. int maximumLinesToUse,
  28628. const float minimumHorizontalScale = 0.7f) throw();
  28629. /** Appends another glyph arrangement to this one. */
  28630. void addGlyphArrangement (const GlyphArrangement& other) throw();
  28631. /** Draws this glyph arrangement to a graphics context.
  28632. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  28633. method, which renders the glyphs as filled vectors.
  28634. */
  28635. void draw (const Graphics& g) const throw();
  28636. /** Draws this glyph arrangement to a graphics context.
  28637. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  28638. method for non-transformed arrangements.
  28639. */
  28640. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28641. /** Converts the set of glyphs into a path.
  28642. @param path the glyphs' outlines will be appended to this path
  28643. */
  28644. void createPath (Path& path) const throw();
  28645. /** Looks for a glyph that contains the given co-ordinate.
  28646. @returns the index of the glyph, or -1 if none were found.
  28647. */
  28648. int findGlyphIndexAt (float x, float y) const throw();
  28649. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  28650. @param startIndex the first glyph to test
  28651. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  28652. startIndex will be included
  28653. @param left on return, the leftmost co-ordinate of the rectangle
  28654. @param top on return, the top co-ordinate of the rectangle
  28655. @param right on return, the rightmost co-ordinate of the rectangle
  28656. @param bottom on return, the bottom co-ordinate of the rectangle
  28657. @param includeWhitespace if true, the extent of any whitespace characters will also
  28658. be taken into account
  28659. */
  28660. void getBoundingBox (int startIndex,
  28661. int numGlyphs,
  28662. float& left,
  28663. float& top,
  28664. float& right,
  28665. float& bottom,
  28666. const bool includeWhitespace) const throw();
  28667. /** Shifts a set of glyphs by a given amount.
  28668. @param startIndex the first glyph to transform
  28669. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  28670. startIndex will be used
  28671. @param deltaX the amount to add to their x-positions
  28672. @param deltaY the amount to add to their y-positions
  28673. */
  28674. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  28675. const float deltaX,
  28676. const float deltaY) throw();
  28677. /** Removes a set of glyphs from the arrangement.
  28678. @param startIndex the first glyph to remove
  28679. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  28680. startIndex will be deleted
  28681. */
  28682. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  28683. /** Expands or compresses a set of glyphs horizontally.
  28684. @param startIndex the first glyph to transform
  28685. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  28686. startIndex will be used
  28687. @param horizontalScaleFactor how much to scale their horizontal width by
  28688. */
  28689. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  28690. const float horizontalScaleFactor) throw();
  28691. /** Justifies a set of glyphs within a given space.
  28692. This moves the glyphs as a block so that the whole thing is located within the
  28693. given rectangle with the specified layout.
  28694. If the Justification::horizontallyJustified flag is specified, each line will
  28695. be stretched out to fill the specified width.
  28696. */
  28697. void justifyGlyphs (const int startIndex, const int numGlyphs,
  28698. const float x,
  28699. const float y,
  28700. const float width,
  28701. const float height,
  28702. const Justification& justification) throw();
  28703. juce_UseDebuggingNewOperator
  28704. private:
  28705. int numGlyphs, numAllocated;
  28706. PositionedGlyph* glyphs;
  28707. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  28708. void removeLast() throw();
  28709. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  28710. void incGlyphRefCount (const int index) const throw();
  28711. void decGlyphRefCount (const int index) const throw();
  28712. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  28713. };
  28714. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28715. /********* End of inlined file: juce_GlyphArrangement.h *********/
  28716. #endif
  28717. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28718. /********* Start of inlined file: juce_TextLayout.h *********/
  28719. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28720. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  28721. class Graphics;
  28722. /**
  28723. A laid-out arrangement of text.
  28724. You can add text in different fonts to a TextLayout object, then call its
  28725. layout() method to word-wrap it into lines. The layout can then be drawn
  28726. using a graphics context.
  28727. It's handy if you've got a message to display, because you can format it,
  28728. measure the extent of the layout, and then create a suitably-sized window
  28729. to show it in.
  28730. @see Font, Graphics::drawFittedText, GlyphArrangement
  28731. */
  28732. class JUCE_API TextLayout
  28733. {
  28734. public:
  28735. /** Creates an empty text layout.
  28736. Text can then be appended using the appendText() method.
  28737. */
  28738. TextLayout() throw();
  28739. /** Creates a copy of another layout object. */
  28740. TextLayout (const TextLayout& other) throw();
  28741. /** Creates a text layout from an initial string and font. */
  28742. TextLayout (const String& text, const Font& font) throw();
  28743. /** Destructor. */
  28744. ~TextLayout() throw();
  28745. /** Copies another layout onto this one. */
  28746. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  28747. /** Clears the layout, removing all its text. */
  28748. void clear() throw();
  28749. /** Adds a string to the end of the arrangement.
  28750. The string will be broken onto new lines wherever it contains
  28751. carriage-returns or linefeeds. After adding it, you can call layout()
  28752. to wrap long lines into a paragraph and justify it.
  28753. */
  28754. void appendText (const String& textToAppend,
  28755. const Font& fontToUse) throw();
  28756. /** Replaces all the text with a new string.
  28757. This is equivalent to calling clear() followed by appendText().
  28758. */
  28759. void setText (const String& newText,
  28760. const Font& fontToUse) throw();
  28761. /** Breaks the text up to form a paragraph with the given width.
  28762. @param maximumWidth any text wider than this will be split
  28763. across multiple lines
  28764. @param justification how the lines are to be laid-out horizontally
  28765. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  28766. width that keeps all the lines of text at a
  28767. similar length - this is good when you're displaying
  28768. a short message and don't want it to get split
  28769. onto two lines with only a couple of words on
  28770. the second line, which looks untidy.
  28771. */
  28772. void layout (int maximumWidth,
  28773. const Justification& justification,
  28774. const bool attemptToBalanceLineLengths) throw();
  28775. /** Returns the overall width of the entire text layout. */
  28776. int getWidth() const throw();
  28777. /** Returns the overall height of the entire text layout. */
  28778. int getHeight() const throw();
  28779. /** Returns the total number of lines of text. */
  28780. int getNumLines() const throw() { return totalLines; }
  28781. /** Returns the width of a particular line of text.
  28782. @param lineNumber the line, from 0 to (getNumLines() - 1)
  28783. */
  28784. int getLineWidth (const int lineNumber) const throw();
  28785. /** Renders the text at a specified position using a graphics context.
  28786. */
  28787. void draw (Graphics& g,
  28788. const int topLeftX,
  28789. const int topLeftY) const throw();
  28790. /** Renders the text within a specified rectangle using a graphics context.
  28791. The justification flags dictate how the block of text should be positioned
  28792. within the rectangle.
  28793. */
  28794. void drawWithin (Graphics& g,
  28795. int x, int y, int w, int h,
  28796. const Justification& layoutFlags) const throw();
  28797. juce_UseDebuggingNewOperator
  28798. private:
  28799. VoidArray tokens;
  28800. int totalLines;
  28801. };
  28802. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  28803. /********* End of inlined file: juce_TextLayout.h *********/
  28804. #endif
  28805. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  28806. #endif
  28807. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28808. /********* Start of inlined file: juce_EdgeTable.h *********/
  28809. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28810. #define __JUCE_EDGETABLE_JUCEHEADER__
  28811. class Path;
  28812. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  28813. /**
  28814. A table of horizontal scan-line segments - used for rasterising Paths.
  28815. @see Path, Graphics
  28816. */
  28817. class JUCE_API EdgeTable
  28818. {
  28819. public:
  28820. /** Indicates the quality at which the edge table should be generated.
  28821. Higher values will have better quality anti-aliasing, but will take
  28822. longer to generate the edge table and to render it.
  28823. */
  28824. enum OversamplingLevel
  28825. {
  28826. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  28827. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  28828. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  28829. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  28830. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  28831. normal user-interface use. */
  28832. };
  28833. /** Creates an empty edge table ready to have paths added.
  28834. A table is created with a fixed vertical size, and only sections of paths
  28835. which lie within their range will be added to the table.
  28836. @param topY the lowest y co-ordinate that the table can contain
  28837. @param height the number of horizontal lines it can contain
  28838. @param verticalOversampling the amount of oversampling used for anti-aliasing
  28839. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  28840. worth changing this except for very special purposes
  28841. */
  28842. EdgeTable (const int topY,
  28843. const int height,
  28844. const OversamplingLevel verticalOversampling = Oversampling_4times,
  28845. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  28846. /** Creates a copy of another edge table. */
  28847. EdgeTable (const EdgeTable& other) throw();
  28848. /** Copies from another edge table. */
  28849. const EdgeTable& operator= (const EdgeTable& other) throw();
  28850. /** Destructor. */
  28851. ~EdgeTable() throw();
  28852. /** Adds edges to the table for a path.
  28853. This will add horizontal lines to the edge table for any parts of the path
  28854. which lie within the vertical bounds for which this table was created.
  28855. @param path the path to add
  28856. @param transform an optional transform to apply to the path while it's
  28857. being added
  28858. */
  28859. void addPath (const Path& path,
  28860. const AffineTransform& transform) throw();
  28861. /** Reduces the amount of space the table has allocated.
  28862. This will shrink the table down to use as little memory as possible - useful for
  28863. read-only tables that get stored and re-used for rendering.
  28864. */
  28865. void optimiseTable() throw();
  28866. /** Iterates the lines in the table, for rendering.
  28867. This function will iterate each line in the table, and call a user-defined class
  28868. to render each pixel or continuous line of pixels that the table contains.
  28869. @param iterationCallback this templated class must contain the following methods:
  28870. @code
  28871. inline void setEdgeTableYPos (int y);
  28872. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  28873. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  28874. @endcode
  28875. (these don't necessarily have to be 'const', but it might help it go faster)
  28876. @param clipLeft the left-hand edge of the rectangle which should be iterated
  28877. @param clipTop the top edge of the rectangle which should be iterated
  28878. @param clipRight the right-hand edge of the rectangle which should be iterated
  28879. @param clipBottom the bottom edge of the rectangle which should be iterated
  28880. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  28881. */
  28882. template <class EdgeTableIterationCallback>
  28883. void iterate (EdgeTableIterationCallback& iterationCallback,
  28884. const int clipLeft,
  28885. int clipTop,
  28886. const int clipRight,
  28887. int clipBottom,
  28888. const int subPixelXOffset) const
  28889. {
  28890. if (clipTop < top)
  28891. clipTop = top;
  28892. if (clipBottom > top + height)
  28893. clipBottom = top + height;
  28894. const int* singleLine = table + lineStrideElements
  28895. * ((clipTop - top) << (int) oversampling);
  28896. int mergedLineAllocation = 128;
  28897. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  28898. int* mergedLine = (int*) temp.getData();
  28899. const int timesOverSampling = 1 << (int) oversampling;
  28900. for (int y = clipTop; y < clipBottom; ++y)
  28901. {
  28902. int numMergedPoints = 0;
  28903. // sort all the oversampled lines into a single merged line ready to draw..
  28904. for (int over = timesOverSampling; --over >= 0;)
  28905. {
  28906. const int* l = singleLine;
  28907. singleLine += lineStrideElements;
  28908. int num = *l;
  28909. jassert (num >= 0);
  28910. if (num > 0)
  28911. {
  28912. if (numMergedPoints + num >= mergedLineAllocation)
  28913. {
  28914. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  28915. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  28916. mergedLine = (int*) temp.getData();
  28917. }
  28918. while (--num >= 0)
  28919. {
  28920. const int x = *++l;
  28921. const int winding = *++l;
  28922. int n = numMergedPoints << 1;
  28923. while (n > 0)
  28924. {
  28925. const int cx = mergedLine [n - 2];
  28926. if (cx <= x)
  28927. break;
  28928. mergedLine [n] = cx;
  28929. --n;
  28930. mergedLine [n + 2] = mergedLine [n];
  28931. --n;
  28932. }
  28933. mergedLine [n] = x;
  28934. mergedLine [n + 1] = winding;
  28935. ++numMergedPoints;
  28936. }
  28937. }
  28938. }
  28939. if (--numMergedPoints > 0)
  28940. {
  28941. const int* line = mergedLine;
  28942. int x = subPixelXOffset + *line;
  28943. int level = *++line;
  28944. int levelAccumulator = 0;
  28945. iterationCallback.setEdgeTableYPos (y);
  28946. while (--numMergedPoints >= 0)
  28947. {
  28948. const int endX = subPixelXOffset + *++line;
  28949. jassert (endX >= x);
  28950. const int absLevel = abs (level);
  28951. int endOfRun = (endX >> 8);
  28952. if (endOfRun == (x >> 8))
  28953. {
  28954. // small segment within the same pixel, so just save it for the next
  28955. // time round..
  28956. levelAccumulator += (endX - x) * absLevel;
  28957. }
  28958. else
  28959. {
  28960. // plot the fist pixel of this segment, including any accumulated
  28961. // levels from smaller segments that haven't been drawn yet
  28962. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  28963. levelAccumulator >>= 8;
  28964. if (levelAccumulator > 0xff)
  28965. levelAccumulator = 0xff;
  28966. x >>= 8;
  28967. if (x >= clipRight)
  28968. {
  28969. levelAccumulator = 0;
  28970. break;
  28971. }
  28972. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  28973. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  28974. if (++x >= clipRight)
  28975. {
  28976. levelAccumulator = 0;
  28977. break;
  28978. }
  28979. // if there's a segment of solid pixels, do it all in one go..
  28980. if (absLevel > 0 && endOfRun > x)
  28981. {
  28982. if (x < clipLeft)
  28983. x = clipLeft;
  28984. if (endOfRun > clipRight)
  28985. endOfRun = clipRight;
  28986. const int numPix = endOfRun - x;
  28987. if (numPix > 0)
  28988. iterationCallback.handleEdgeTableLine (x, numPix,
  28989. jmin (absLevel, 0xff));
  28990. }
  28991. // save the bit at the end to be drawn next time round the loop.
  28992. levelAccumulator = (endX & 0xff) * absLevel;
  28993. }
  28994. level += *++line;
  28995. x = endX;
  28996. }
  28997. if (levelAccumulator > 0)
  28998. {
  28999. levelAccumulator >>= 8;
  29000. if (levelAccumulator > 0xff)
  29001. levelAccumulator = 0xff;
  29002. x >>= 8;
  29003. if (x >= clipLeft && x < clipRight)
  29004. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29005. }
  29006. }
  29007. }
  29008. }
  29009. juce_UseDebuggingNewOperator
  29010. private:
  29011. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29012. int* table;
  29013. int top, height, maxEdgesPerLine, lineStrideElements;
  29014. OversamplingLevel oversampling;
  29015. // this will assume that the y co-ord is within bounds, and will avoid checking
  29016. // this for speed.
  29017. void addEdgePoint (const int x, const int y, const int winding) throw();
  29018. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29019. };
  29020. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29021. /********* End of inlined file: juce_EdgeTable.h *********/
  29022. #endif
  29023. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29024. #endif
  29025. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29026. #endif
  29027. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29028. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29029. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29030. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29031. /**
  29032. Interface class for graphics context objects, used internally by the Graphics class.
  29033. Users are not supposed to create instances of this class directly - do your drawing
  29034. via the Graphics object instead.
  29035. It's a base class for different types of graphics context, that may perform software-based
  29036. or OS-accelerated rendering.
  29037. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29038. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29039. context.
  29040. */
  29041. class JUCE_API LowLevelGraphicsContext
  29042. {
  29043. protected:
  29044. LowLevelGraphicsContext();
  29045. public:
  29046. virtual ~LowLevelGraphicsContext();
  29047. /** Returns true if this device is vector-based, e.g. a printer. */
  29048. virtual bool isVectorDevice() const = 0;
  29049. /** Moves the origin to a new position.
  29050. The co-ords are relative to the current origin, and indicate the new position
  29051. of (0, 0).
  29052. */
  29053. virtual void setOrigin (int x, int y) = 0;
  29054. /** Cliping co-ords are relative to the origin. */
  29055. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29056. /** Cliping co-ords are relative to the origin. */
  29057. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29058. /** Cliping co-ords are relative to the origin. */
  29059. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29060. virtual void saveState() = 0;
  29061. virtual void restoreState() = 0;
  29062. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29063. virtual const Rectangle getClipBounds() const = 0;
  29064. virtual bool isClipEmpty() const = 0;
  29065. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29066. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29067. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29068. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29069. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29070. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29071. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29072. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29073. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29074. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29075. virtual void blendImage (const Image& sourceImage,
  29076. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29077. float alpha) = 0;
  29078. virtual void blendImageRescaling (const Image& sourceImage,
  29079. int destX, int destY, int destW, int destH,
  29080. int sourceX, int sourceY, int sourceW, int sourceH,
  29081. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29082. virtual void blendImageWarping (const Image& sourceImage,
  29083. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29084. const AffineTransform& transform,
  29085. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29086. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29087. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29088. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29089. };
  29090. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29091. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29092. #endif
  29093. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29094. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29095. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29096. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29097. /**
  29098. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29099. into a PostScript document.
  29100. */
  29101. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29102. {
  29103. public:
  29104. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29105. const String& documentTitle,
  29106. const int totalWidth,
  29107. const int totalHeight);
  29108. ~LowLevelGraphicsPostScriptRenderer();
  29109. bool isVectorDevice() const;
  29110. void setOrigin (int x, int y);
  29111. bool reduceClipRegion (int x, int y, int w, int h);
  29112. bool reduceClipRegion (const RectangleList& clipRegion);
  29113. void excludeClipRegion (int x, int y, int w, int h);
  29114. void saveState();
  29115. void restoreState();
  29116. bool clipRegionIntersects (int x, int y, int w, int h);
  29117. const Rectangle getClipBounds() const;
  29118. bool isClipEmpty() const;
  29119. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29120. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29121. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29122. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29123. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29124. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29125. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29126. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29127. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29128. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29129. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29130. int sourceX, int sourceY, float alpha);
  29131. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29132. int sourceX, int sourceY, int sourceW, int sourceH,
  29133. float alpha, const Graphics::ResamplingQuality quality);
  29134. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29135. const AffineTransform& transform,
  29136. float alpha, const Graphics::ResamplingQuality quality);
  29137. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29138. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29139. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29140. juce_UseDebuggingNewOperator
  29141. protected:
  29142. OutputStream& out;
  29143. RectangleList* clip;
  29144. int totalWidth, totalHeight, xOffset, yOffset;
  29145. bool needToClip;
  29146. Colour lastColour;
  29147. struct SavedState
  29148. {
  29149. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29150. ~SavedState();
  29151. RectangleList* clip;
  29152. const int xOffset, yOffset;
  29153. private:
  29154. SavedState (const SavedState&);
  29155. const SavedState& operator= (const SavedState&);
  29156. };
  29157. OwnedArray <SavedState> stateStack;
  29158. void writeClip();
  29159. void writeColour (const Colour& colour);
  29160. void writePath (const Path& path) const;
  29161. void writeXY (const float x, const float y) const;
  29162. void writeTransform (const AffineTransform& trans) const;
  29163. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29164. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29165. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29166. };
  29167. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29168. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29169. #endif
  29170. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29171. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29172. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29173. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29174. /**
  29175. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29176. its rendering in memory.
  29177. User code is not supposed to create instances of this class directly - do all your
  29178. rendering via the Graphics class instead.
  29179. */
  29180. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29181. {
  29182. public:
  29183. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29184. ~LowLevelGraphicsSoftwareRenderer();
  29185. bool isVectorDevice() const;
  29186. void setOrigin (int x, int y);
  29187. bool reduceClipRegion (int x, int y, int w, int h);
  29188. bool reduceClipRegion (const RectangleList& clipRegion);
  29189. void excludeClipRegion (int x, int y, int w, int h);
  29190. void saveState();
  29191. void restoreState();
  29192. bool clipRegionIntersects (int x, int y, int w, int h);
  29193. const Rectangle getClipBounds() const;
  29194. bool isClipEmpty() const;
  29195. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29196. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29197. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29198. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29199. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29200. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29201. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29202. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29203. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29204. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29205. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29206. int sourceX, int sourceY, float alpha);
  29207. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29208. int sourceX, int sourceY, int sourceW, int sourceH,
  29209. float alpha, const Graphics::ResamplingQuality quality);
  29210. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29211. const AffineTransform& transform,
  29212. float alpha, const Graphics::ResamplingQuality quality);
  29213. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29214. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29215. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29216. RectangleList* getRawClipRegion() throw() { return clip; }
  29217. juce_UseDebuggingNewOperator
  29218. protected:
  29219. Image& image;
  29220. RectangleList* clip;
  29221. int xOffset, yOffset;
  29222. struct SavedState
  29223. {
  29224. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29225. ~SavedState();
  29226. RectangleList* clip;
  29227. const int xOffset, yOffset;
  29228. private:
  29229. SavedState (const SavedState&);
  29230. const SavedState& operator= (const SavedState&);
  29231. };
  29232. OwnedArray <SavedState> stateStack;
  29233. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29234. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29235. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29236. const Path& path, const AffineTransform& transform,
  29237. int& x, int& y, int& w, int& h) const;
  29238. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29239. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29240. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29241. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29242. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29243. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29244. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29245. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29246. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29247. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29248. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29249. float alpha);
  29250. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29251. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29252. const AffineTransform& transform,
  29253. float alpha, const Graphics::ResamplingQuality quality);
  29254. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29255. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29256. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29257. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29258. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29259. };
  29260. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29261. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29262. #endif
  29263. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29264. #endif
  29265. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29266. #endif
  29267. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29268. #endif
  29269. #ifndef __JUCE_LINE_JUCEHEADER__
  29270. #endif
  29271. #ifndef __JUCE_PATH_JUCEHEADER__
  29272. #endif
  29273. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29274. /********* Start of inlined file: juce_PathIterator.h *********/
  29275. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29276. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29277. /**
  29278. Flattens a Path object into a series of straight-line sections.
  29279. Use one of these to iterate through a Path object, and it will convert
  29280. all the curves into line sections so it's easy to render or perform
  29281. geometric operations on.
  29282. @see Path
  29283. */
  29284. class JUCE_API PathFlatteningIterator
  29285. {
  29286. public:
  29287. /** Creates a PathFlatteningIterator.
  29288. After creation, use the next() method to initialise the fields in the
  29289. object with the first line's position.
  29290. @param path the path to iterate along
  29291. @param transform a transform to apply to each point in the path being iterated
  29292. @param tolerence the amount by which the curves are allowed to deviate from the
  29293. lines into which they are being broken down - a higher tolerence
  29294. is a bit faster, but less smooth.
  29295. */
  29296. PathFlatteningIterator (const Path& path,
  29297. const AffineTransform& transform = AffineTransform::identity,
  29298. float tolerence = 9.0f) throw();
  29299. /** Destructor. */
  29300. ~PathFlatteningIterator() throw();
  29301. /** Fetches the next line segment from the path.
  29302. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29303. so that they describe the new line segment.
  29304. @returns false when there are no more lines to fetch.
  29305. */
  29306. bool next() throw();
  29307. /** The x position of the start of the current line segment. */
  29308. float x1;
  29309. /** The y position of the start of the current line segment. */
  29310. float y1;
  29311. /** The x position of the end of the current line segment. */
  29312. float x2;
  29313. /** The y position of the end of the current line segment. */
  29314. float y2;
  29315. /** Indicates whether the current line segment is closing a sub-path.
  29316. If the current line is the one that connects the end of a sub-path
  29317. back to the start again, this will be true.
  29318. */
  29319. bool closesSubPath;
  29320. /** The index of the current line within the current sub-path.
  29321. E.g. you can use this to see whether the line is the first one in the
  29322. subpath by seeing if it's 0.
  29323. */
  29324. int subPathIndex;
  29325. /** Returns true if the current segment is the last in the current sub-path. */
  29326. bool isLastInSubpath() const throw() { return stackPos == stackBase; }
  29327. juce_UseDebuggingNewOperator
  29328. private:
  29329. const Path& path;
  29330. const AffineTransform transform;
  29331. float* points;
  29332. float tolerence, subPathCloseX, subPathCloseY;
  29333. bool isIdentityTransform;
  29334. float* stackBase;
  29335. float* stackPos;
  29336. int index, stackSize;
  29337. PathFlatteningIterator (const PathFlatteningIterator&);
  29338. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29339. };
  29340. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29341. /********* End of inlined file: juce_PathIterator.h *********/
  29342. #endif
  29343. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29344. #endif
  29345. #ifndef __JUCE_POINT_JUCEHEADER__
  29346. #endif
  29347. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29348. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29349. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29350. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29351. /**
  29352. A rectangle whose co-ordinates can be defined in terms of absolute or
  29353. proportional distances.
  29354. Designed mainly for storing component positions, this gives you a lot of
  29355. control over how each co-ordinate is stored, either as an absolute position,
  29356. or as a proportion of the size of a parent rectangle.
  29357. It also allows you to define the anchor points by which the rectangle is
  29358. positioned, so for example you could specify that the top right of the
  29359. rectangle should be an absolute distance from its parent's bottom-right corner.
  29360. This object can be stored as a string, which takes the form "x y w h", including
  29361. symbols like '%' and letters to indicate the anchor point. See its toString()
  29362. method for more info.
  29363. Example usage:
  29364. @code
  29365. class MyComponent
  29366. {
  29367. void resized()
  29368. {
  29369. // this will set the child component's x to be 20% of our width, its y
  29370. // to be 30, its width to be 150, and its height to be 50% of our
  29371. // height..
  29372. const PositionedRectangle pos1 ("20% 30 150 50%");
  29373. pos1.applyToComponent (*myChildComponent1);
  29374. // this will inset the child component with a gap of 10 pixels
  29375. // around each of its edges..
  29376. const PositionedRectangle pos2 ("10 10 20M 20M");
  29377. pos2.applyToComponent (*myChildComponent2);
  29378. }
  29379. };
  29380. @endcode
  29381. */
  29382. class JUCE_API PositionedRectangle
  29383. {
  29384. public:
  29385. /** Creates an empty rectangle with all co-ordinates set to zero.
  29386. The default anchor point is top-left; the default
  29387. */
  29388. PositionedRectangle() throw();
  29389. /** Initialises a PositionedRectangle from a saved string version.
  29390. The string must be in the format generated by toString().
  29391. */
  29392. PositionedRectangle (const String& stringVersion) throw();
  29393. /** Creates a copy of another PositionedRectangle. */
  29394. PositionedRectangle (const PositionedRectangle& other) throw();
  29395. /** Copies another PositionedRectangle. */
  29396. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29397. /** Destructor. */
  29398. ~PositionedRectangle() throw();
  29399. /** Returns a string version of this position, from which it can later be
  29400. re-generated.
  29401. The format is four co-ordinates, "x y w h".
  29402. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29403. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29404. as a percentage, e.g. "80%".
  29405. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29406. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29407. the parent's right-hand edge.
  29408. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29409. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29410. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29411. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29412. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29413. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29414. has "c" appended to it. So "-50Rc" would mean that this component's
  29415. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29416. this component's centre should be placed 40% across the parent's width.
  29417. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29418. the number has "M" appended to it.
  29419. To reload a stored string, use the constructor that takes a string parameter.
  29420. */
  29421. const String toString() const throw();
  29422. /** Calculates the absolute position, given the size of the space that
  29423. it should go in.
  29424. This will work out any proportional distances and sizes relative to the
  29425. target rectangle, and will return the absolute position.
  29426. @see applyToComponent
  29427. */
  29428. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29429. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29430. */
  29431. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29432. double& x,
  29433. double& y,
  29434. double& width,
  29435. double& height) const throw();
  29436. /** This sets the bounds of the given component to this position.
  29437. This is equivalent to writing:
  29438. @code
  29439. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29440. @endcode
  29441. @see getRectangle, updateFromComponent
  29442. */
  29443. void applyToComponent (Component& comp) const throw();
  29444. /** Updates this object's co-ordinates to match the given rectangle.
  29445. This will set all co-ordinates based on the given rectangle, re-calculating
  29446. any proportional distances, and using the current anchor points.
  29447. So for example if the x co-ordinate mode is currently proportional, this will
  29448. re-calculate x based on the rectangle's relative position within the target
  29449. rectangle's width.
  29450. If the target rectangle's width or height are zero then it may not be possible
  29451. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29452. will not be changed.
  29453. */
  29454. void updateFrom (const Rectangle& newPosition,
  29455. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29456. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29457. */
  29458. void updateFromDouble (const double x, const double y,
  29459. const double width, const double height,
  29460. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29461. /** Updates this object's co-ordinates to match the bounds of this component.
  29462. This is equivalent to calling updateFrom() with the component's bounds and
  29463. it parent size.
  29464. If the component doesn't currently have a parent, then proportional co-ordinates
  29465. might not be updated because it would need to know the parent's size to do the
  29466. maths for this.
  29467. */
  29468. void updateFromComponent (const Component& comp) throw();
  29469. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29470. enum AnchorPoint
  29471. {
  29472. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29473. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29474. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29475. };
  29476. /** Specifies how an x or y co-ordinate should be interpreted. */
  29477. enum PositionMode
  29478. {
  29479. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29480. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29481. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29482. 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. */
  29483. };
  29484. /** Specifies how the width or height should be interpreted. */
  29485. enum SizeMode
  29486. {
  29487. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29488. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29489. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29490. };
  29491. /** Sets all options for all co-ordinates.
  29492. This requires a reference rectangle to be specified, because if you're changing any
  29493. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29494. the co-ordinates, and will need to know the parent size so it can calculate this.
  29495. */
  29496. void setModes (const AnchorPoint xAnchorMode,
  29497. const PositionMode xPositionMode,
  29498. const AnchorPoint yAnchorMode,
  29499. const PositionMode yPositionMode,
  29500. const SizeMode widthMode,
  29501. const SizeMode heightMode,
  29502. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29503. /** Returns the anchoring mode for the x co-ordinate.
  29504. To change any of the modes, use setModes().
  29505. */
  29506. AnchorPoint getAnchorPointX() const throw();
  29507. /** Returns the positioning mode for the x co-ordinate.
  29508. To change any of the modes, use setModes().
  29509. */
  29510. PositionMode getPositionModeX() const throw();
  29511. /** Returns the raw x co-ordinate.
  29512. If the x position mode is absolute, then this will be the absolute value. If it's
  29513. proportional, then this will be a fractional proportion, where 1.0 means the full
  29514. width of the parent space.
  29515. */
  29516. double getX() const throw() { return x; }
  29517. /** Sets the raw value of the x co-ordinate.
  29518. See getX() for the meaning of this value.
  29519. */
  29520. void setX (const double newX) throw() { x = newX; }
  29521. /** Returns the anchoring mode for the y co-ordinate.
  29522. To change any of the modes, use setModes().
  29523. */
  29524. AnchorPoint getAnchorPointY() const throw();
  29525. /** Returns the positioning mode for the y co-ordinate.
  29526. To change any of the modes, use setModes().
  29527. */
  29528. PositionMode getPositionModeY() const throw();
  29529. /** Returns the raw y co-ordinate.
  29530. If the y position mode is absolute, then this will be the absolute value. If it's
  29531. proportional, then this will be a fractional proportion, where 1.0 means the full
  29532. height of the parent space.
  29533. */
  29534. double getY() const throw() { return y; }
  29535. /** Sets the raw value of the y co-ordinate.
  29536. See getY() for the meaning of this value.
  29537. */
  29538. void setY (const double newY) throw() { y = newY; }
  29539. /** Returns the mode used to calculate the width.
  29540. To change any of the modes, use setModes().
  29541. */
  29542. SizeMode getWidthMode() const throw();
  29543. /** Returns the raw width value.
  29544. If the width mode is absolute, then this will be the absolute value. If the mode is
  29545. proportional, then this will be a fractional proportion, where 1.0 means the full
  29546. width of the parent space.
  29547. */
  29548. double getWidth() const throw() { return w; }
  29549. /** Sets the raw width value.
  29550. See getWidth() for the details about what this value means.
  29551. */
  29552. void setWidth (const double newWidth) throw() { w = newWidth; }
  29553. /** Returns the mode used to calculate the height.
  29554. To change any of the modes, use setModes().
  29555. */
  29556. SizeMode getHeightMode() const throw();
  29557. /** Returns the raw height value.
  29558. If the height mode is absolute, then this will be the absolute value. If the mode is
  29559. proportional, then this will be a fractional proportion, where 1.0 means the full
  29560. height of the parent space.
  29561. */
  29562. double getHeight() const throw() { return h; }
  29563. /** Sets the raw height value.
  29564. See getHeight() for the details about what this value means.
  29565. */
  29566. void setHeight (const double newHeight) throw() { h = newHeight; }
  29567. /** If the size and position are constance, and wouldn't be affected by changes
  29568. in the parent's size, then this will return true.
  29569. */
  29570. bool isPositionAbsolute() const throw();
  29571. /** Compares two objects. */
  29572. const bool operator== (const PositionedRectangle& other) const throw();
  29573. /** Compares two objects. */
  29574. const bool operator!= (const PositionedRectangle& other) const throw();
  29575. juce_UseDebuggingNewOperator
  29576. private:
  29577. double x, y, w, h;
  29578. uint8 xMode, yMode, wMode, hMode;
  29579. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  29580. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  29581. void decodePosString (const String& s, uint8& mode, double& value) throw();
  29582. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  29583. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  29584. const uint8 xMode, const uint8 wMode,
  29585. const int parentPos, const int parentSize) const throw();
  29586. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  29587. const uint8 xMode, const uint8 wMode,
  29588. const int parentPos, const int parentSize) const throw();
  29589. };
  29590. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29591. /********* End of inlined file: juce_PositionedRectangle.h *********/
  29592. #endif
  29593. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29594. #endif
  29595. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  29596. #endif
  29597. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29598. #endif
  29599. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29600. /********* Start of inlined file: juce_ImageCache.h *********/
  29601. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29602. #define __JUCE_IMAGECACHE_JUCEHEADER__
  29603. /**
  29604. A global cache of images that have been loaded from files or memory.
  29605. If you're loading an image and may need to use the image in more than one
  29606. place, this is used to allow the same image to be shared rather than loading
  29607. multiple copies into memory.
  29608. Another advantage is that after images are released, they will be kept in
  29609. memory for a few seconds before it is actually deleted, so if you're repeatedly
  29610. loading/deleting the same image, it'll reduce the chances of having to reload it
  29611. each time.
  29612. @see Image, ImageFileFormat
  29613. */
  29614. class JUCE_API ImageCache : private DeletedAtShutdown,
  29615. private Timer
  29616. {
  29617. public:
  29618. /** Loads an image from a file, (or just returns the image if it's already cached).
  29619. If the cache already contains an image that was loaded from this file,
  29620. that image will be returned. Otherwise, this method will try to load the
  29621. file, add it to the cache, and return it.
  29622. It's very important not to delete the image that is returned - instead use
  29623. the ImageCache::release() method.
  29624. Also, remember that the image returned is shared, so drawing into it might
  29625. affect other things that are using it!
  29626. @param file the file to try to load
  29627. @returns the image, or null if it there was an error loading it
  29628. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29629. */
  29630. static Image* getFromFile (const File& file);
  29631. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  29632. If the cache already contains an image that was loaded from this block of memory,
  29633. that image will be returned. Otherwise, this method will try to load the
  29634. file, add it to the cache, and return it.
  29635. It's very important not to delete the image that is returned - instead use
  29636. the ImageCache::release() method.
  29637. Also, remember that the image returned is shared, so drawing into it might
  29638. affect other things that are using it!
  29639. @param imageData the block of memory containing the image data
  29640. @param dataSize the data size in bytes
  29641. @returns the image, or null if it there was an error loading it
  29642. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29643. */
  29644. static Image* getFromMemory (const void* imageData,
  29645. const int dataSize);
  29646. /** Releases an image that was previously created by the ImageCache.
  29647. If an image has been returned by the getFromFile() or getFromMemory() methods,
  29648. it mustn't be deleted directly, but should be released with this method
  29649. instead.
  29650. @see getFromFile, getFromMemory
  29651. */
  29652. static void release (Image* const imageToRelease);
  29653. /** Checks whether an image is in the cache or not.
  29654. @returns true if the image is currently in the cache
  29655. */
  29656. static bool isImageInCache (Image* const imageToLookFor);
  29657. /** Increments the reference-count for a cached image.
  29658. If the image isn't in the cache, this method won't do anything.
  29659. */
  29660. static void incReferenceCount (Image* const image);
  29661. /** Checks the cache for an image with a particular hashcode.
  29662. If there's an image in the cache with this hashcode, it will be returned,
  29663. otherwise it will return zero.
  29664. If an image is returned, it must be released with the release() method
  29665. when no longer needed, to maintain the correct reference counts.
  29666. @param hashCode the hash code that would have been associated with the
  29667. image by addImageToCache()
  29668. @see addImageToCache
  29669. */
  29670. static Image* getFromHashCode (const int64 hashCode);
  29671. /** Adds an image to the cache with a user-defined hash-code.
  29672. After calling this, responsibilty for deleting the image will be taken
  29673. by the ImageCache.
  29674. The image will be initially be given a reference count of 1, so call
  29675. the release() method to delete it.
  29676. @param image the image to add
  29677. @param hashCode the hash-code to associate with it
  29678. @see getFromHashCode
  29679. */
  29680. static void addImageToCache (Image* const image,
  29681. const int64 hashCode);
  29682. /** Changes the amount of time before an unused image will be removed from the cache.
  29683. By default this is about 5 seconds.
  29684. */
  29685. static void setCacheTimeout (const int millisecs);
  29686. juce_UseDebuggingNewOperator
  29687. private:
  29688. CriticalSection lock;
  29689. VoidArray images;
  29690. ImageCache() throw();
  29691. ImageCache (const ImageCache&);
  29692. const ImageCache& operator= (const ImageCache&);
  29693. ~ImageCache();
  29694. void timerCallback();
  29695. };
  29696. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  29697. /********* End of inlined file: juce_ImageCache.h *********/
  29698. #endif
  29699. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29700. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  29701. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29702. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29703. /**
  29704. Represents a filter kernel to use in convoluting an image.
  29705. @see Image::applyConvolution
  29706. */
  29707. class JUCE_API ImageConvolutionKernel
  29708. {
  29709. public:
  29710. /** Creates an empty convulution kernel.
  29711. @param size the length of each dimension of the kernel, so e.g. if the size
  29712. is 5, it will create a 5x5 kernel
  29713. */
  29714. ImageConvolutionKernel (const int size) throw();
  29715. /** Destructor. */
  29716. ~ImageConvolutionKernel() throw();
  29717. /** Resets all values in the kernel to zero.
  29718. */
  29719. void clear() throw();
  29720. /** Sets the value of a specific cell in the kernel.
  29721. The x and y parameters must be in the range 0 < x < getKernelSize().
  29722. @see setOverallSum
  29723. */
  29724. void setKernelValue (const int x,
  29725. const int y,
  29726. const float value) throw();
  29727. /** Rescales all values in the kernel to make the total add up to a fixed value.
  29728. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  29729. */
  29730. void setOverallSum (const float desiredTotalSum) throw();
  29731. /** Multiplies all values in the kernel by a value. */
  29732. void rescaleAllValues (const float multiplier) throw();
  29733. /** Intialises the kernel for a gaussian blur.
  29734. @param blurRadius this may be larger or smaller than the kernel's actual
  29735. size but this will obviously be wasteful or clip at the
  29736. edges. Ideally the kernel should be just larger than
  29737. (blurRadius * 2).
  29738. */
  29739. void createGaussianBlur (const float blurRadius) throw();
  29740. /** Returns the size of the kernel.
  29741. E.g. if it's a 3x3 kernel, this returns 3.
  29742. */
  29743. int getKernelSize() const throw() { return size; }
  29744. /** Returns a 2-dimensional array of the kernel's values.
  29745. The size of each dimension of the array will be getKernelSize().
  29746. */
  29747. float** getValues() const throw() { return values; }
  29748. /** Applies the kernel to an image.
  29749. @param destImage the image that will receive the resultant convoluted pixels.
  29750. @param sourceImage an optional source image to read from - if this is 0, then the
  29751. destination image will be used as the source. If an image is
  29752. specified, it must be exactly the same size and type as the destination
  29753. image.
  29754. @param x the region of the image to apply the filter to
  29755. @param y the region of the image to apply the filter to
  29756. @param width the region of the image to apply the filter to
  29757. @param height the region of the image to apply the filter to
  29758. */
  29759. void applyToImage (Image& destImage,
  29760. const Image* sourceImage,
  29761. int x,
  29762. int y,
  29763. int width,
  29764. int height) const;
  29765. juce_UseDebuggingNewOperator
  29766. private:
  29767. float** values;
  29768. int size;
  29769. // no reason not to implement these one day..
  29770. ImageConvolutionKernel (const ImageConvolutionKernel&);
  29771. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  29772. };
  29773. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29774. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  29775. #endif
  29776. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29777. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  29778. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29779. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29780. /**
  29781. Base-class for codecs that can read and write image file formats such
  29782. as PNG, JPEG, etc.
  29783. This class also contains static methods to make it easy to load images
  29784. from files, streams or from memory.
  29785. @see Image, ImageCache
  29786. */
  29787. class JUCE_API ImageFileFormat
  29788. {
  29789. protected:
  29790. /** Creates an ImageFormat. */
  29791. ImageFileFormat() throw() {}
  29792. public:
  29793. /** Destructor. */
  29794. virtual ~ImageFileFormat() throw() {}
  29795. /** Returns a description of this file format.
  29796. E.g. "JPEG", "PNG"
  29797. */
  29798. virtual const String getFormatName() = 0;
  29799. /** Returns true if the given stream seems to contain data that this format
  29800. understands.
  29801. The format class should only read the first few bytes of the stream and sniff
  29802. for header bytes that it understands.
  29803. @see decodeImage
  29804. */
  29805. virtual bool canUnderstand (InputStream& input) = 0;
  29806. /** Tries to decode and return an image from the given stream.
  29807. This will be called for an image format after calling its canUnderStand() method
  29808. to see if it can handle the stream.
  29809. @param input the stream to read the data from. The stream will be positioned
  29810. at the start of the image data (but this may not necessarily
  29811. be position 0)
  29812. @returns the image that was decoded, or 0 if it fails. It's the
  29813. caller's responsibility to delete this image when no longer needed.
  29814. @see loadFrom
  29815. */
  29816. virtual Image* decodeImage (InputStream& input) = 0;
  29817. /** Attempts to write an image to a stream.
  29818. To specify extra information like encoding quality, there will be appropriate parameters
  29819. in the subclasses of the specific file types.
  29820. @returns true if it nothing went wrong.
  29821. */
  29822. virtual bool writeImageToStream (const Image& sourceImage,
  29823. OutputStream& destStream) = 0;
  29824. /** Tries the built-in decoders to see if it can find one to read this stream.
  29825. There are currently built-in decoders for PNG, JPEG and GIF formats.
  29826. The object that is returned should not be deleted by the caller.
  29827. @see canUnderstand, decodeImage, loadFrom
  29828. */
  29829. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  29830. /** Tries to load an image from a stream.
  29831. This will use the findImageFormatForStream() method to locate a suitable
  29832. codec, and use that to load the image.
  29833. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29834. caller's responsibility to delete this image when no longer needed.
  29835. */
  29836. static Image* loadFrom (InputStream& input);
  29837. /** Tries to load an image from a file.
  29838. This will use the findImageFormatForStream() method to locate a suitable
  29839. codec, and use that to load the image.
  29840. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29841. caller's responsibility to delete this image when no longer needed.
  29842. */
  29843. static Image* loadFrom (const File& file);
  29844. /** Tries to load an image from a block of raw image data.
  29845. This will use the findImageFormatForStream() method to locate a suitable
  29846. codec, and use that to load the image.
  29847. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29848. caller's responsibility to delete this image when no longer needed.
  29849. */
  29850. static Image* loadFrom (const void* rawData,
  29851. const int numBytesOfData);
  29852. };
  29853. /**
  29854. A type of ImageFileFormat for reading and writing PNG files.
  29855. @see ImageFileFormat, JPEGImageFormat
  29856. */
  29857. class PNGImageFormat : public ImageFileFormat
  29858. {
  29859. public:
  29860. PNGImageFormat() throw();
  29861. ~PNGImageFormat() throw();
  29862. const String getFormatName();
  29863. bool canUnderstand (InputStream& input);
  29864. Image* decodeImage (InputStream& input);
  29865. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29866. };
  29867. /**
  29868. A type of ImageFileFormat for reading and writing JPEG files.
  29869. @see ImageFileFormat, PNGImageFormat
  29870. */
  29871. class JPEGImageFormat : public ImageFileFormat
  29872. {
  29873. public:
  29874. JPEGImageFormat() throw();
  29875. ~JPEGImageFormat() throw();
  29876. /** Specifies the quality to be used when writing a JPEG file.
  29877. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  29878. any negative value is "default" quality
  29879. */
  29880. void setQuality (const float newQuality);
  29881. const String getFormatName();
  29882. bool canUnderstand (InputStream& input);
  29883. Image* decodeImage (InputStream& input);
  29884. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29885. private:
  29886. float quality;
  29887. };
  29888. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29889. /********* End of inlined file: juce_ImageFileFormat.h *********/
  29890. #endif
  29891. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29892. /********* Start of inlined file: juce_Drawable.h *********/
  29893. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29894. #define __JUCE_DRAWABLE_JUCEHEADER__
  29895. /**
  29896. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  29897. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29898. */
  29899. class JUCE_API Drawable
  29900. {
  29901. protected:
  29902. /** The base class can't be instantiated directly.
  29903. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29904. */
  29905. Drawable();
  29906. public:
  29907. /** Destructor. */
  29908. virtual ~Drawable();
  29909. /** Creates a deep copy of this Drawable object.
  29910. Use this to create a new copy of this and any sub-objects in the tree.
  29911. */
  29912. virtual Drawable* createCopy() const = 0;
  29913. /** Renders this Drawable object.
  29914. This is the main rendering method you should call to render a Drawable.
  29915. @see drawWithin
  29916. */
  29917. virtual void draw (Graphics& g,
  29918. const AffineTransform& transform = AffineTransform::identity) const = 0;
  29919. /** Renders the Drawable at a given offset within the Graphics context.
  29920. The co-ordinates passed-in are used to translate the object relative to its own
  29921. origin before drawing it - this is basically a quick way of saying:
  29922. @code
  29923. draw (g, AffineTransform::translation (x, y)).
  29924. @endcode
  29925. */
  29926. void drawAt (Graphics& g,
  29927. const float x,
  29928. const float y) const;
  29929. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  29930. changing its aspect-ratio.
  29931. The object can placed arbitrarily within the rectangle based on a Justification type,
  29932. and can either be made as big as possible, or just reduced to fit.
  29933. @param g the graphics context to render onto
  29934. @param destX top-left of the target rectangle to fit it into
  29935. @param destY top-left of the target rectangle to fit it into
  29936. @param destWidth size of the target rectangle to fit the image into
  29937. @param destHeight size of the target rectangle to fit the image into
  29938. @param placement defines the alignment and rescaling to use to fit
  29939. this object within the target rectangle.
  29940. */
  29941. void drawWithin (Graphics& g,
  29942. const int destX,
  29943. const int destY,
  29944. const int destWidth,
  29945. const int destHeight,
  29946. const RectanglePlacement& placement) const;
  29947. /** Returns the smallest rectangle that can contain this Drawable object.
  29948. Co-ordinates are relative to the object's own origin.
  29949. */
  29950. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  29951. /** Returns true if the given point is somewhere inside this Drawable.
  29952. Co-ordinates are relative to the object's own origin.
  29953. */
  29954. virtual bool hitTest (float x, float y) const = 0;
  29955. /** Returns the name given to this drawable.
  29956. @see setName
  29957. */
  29958. const String& getName() const throw() { return name; }
  29959. /** Assigns a name to this drawable. */
  29960. void setName (const String& newName) throw() { name = newName; }
  29961. /** Tries to turn some kind of image file into a drawable.
  29962. The data could be an image that the ImageFileFormat class understands, or it
  29963. could be SVG.
  29964. */
  29965. static Drawable* createFromImageData (const void* data, const int numBytes);
  29966. /** Tries to turn a stream containing some kind of image data into a drawable.
  29967. The data could be an image that the ImageFileFormat class understands, or it
  29968. could be SVG.
  29969. */
  29970. static Drawable* createFromImageDataStream (InputStream& dataSource);
  29971. /** Tries to turn a file containing some kind of image data into a drawable.
  29972. The data could be an image that the ImageFileFormat class understands, or it
  29973. could be SVG.
  29974. */
  29975. static Drawable* createFromImageFile (const File& file);
  29976. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  29977. into a Drawable tree.
  29978. The object returned must be deleted by the caller. If something goes wrong
  29979. while parsing, it may return 0.
  29980. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  29981. implementation, but it can return the basic vector objects.
  29982. */
  29983. static Drawable* createFromSVG (const XmlElement& svgDocument);
  29984. juce_UseDebuggingNewOperator
  29985. private:
  29986. Drawable (const Drawable&);
  29987. const Drawable& operator= (const Drawable&);
  29988. String name;
  29989. };
  29990. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  29991. /********* End of inlined file: juce_Drawable.h *********/
  29992. #endif
  29993. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29994. /********* Start of inlined file: juce_DrawableComposite.h *********/
  29995. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29996. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29997. /**
  29998. A drawable object which acts as a container for a set of other Drawables.
  29999. @see Drawable
  30000. */
  30001. class JUCE_API DrawableComposite : public Drawable
  30002. {
  30003. public:
  30004. /** Creates a composite Drawable.
  30005. */
  30006. DrawableComposite();
  30007. /** Destructor. */
  30008. virtual ~DrawableComposite();
  30009. /** Adds a new sub-drawable to this one.
  30010. This passes in a Drawable pointer for this object to look after. To add a copy
  30011. of a drawable, use the form of this method that takes a Drawable reference instead.
  30012. @param drawable the object to add - this will be deleted automatically
  30013. when no longer needed, so the caller mustn't keep any
  30014. pointers to it.
  30015. @param transform the transform to apply to this drawable when it's being
  30016. drawn
  30017. @param index where to insert it in the list of drawables. 0 is the back,
  30018. -1 is the front, or any value from 0 and getNumDrawables()
  30019. can be used
  30020. @see removeDrawable
  30021. */
  30022. void insertDrawable (Drawable* drawable,
  30023. const AffineTransform& transform = AffineTransform::identity,
  30024. const int index = -1);
  30025. /** Adds a new sub-drawable to this one.
  30026. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30027. for this object to look after, use the form of this method that takes a Drawable
  30028. pointer instead.
  30029. @param drawable the object to add - an internal copy will be made of this object
  30030. @param transform the transform to apply to this drawable when it's being
  30031. drawn
  30032. @param index where to insert it in the list of drawables. 0 is the back,
  30033. -1 is the front, or any value from 0 and getNumDrawables()
  30034. can be used
  30035. @see removeDrawable
  30036. */
  30037. void insertDrawable (const Drawable& drawable,
  30038. const AffineTransform& transform = AffineTransform::identity,
  30039. const int index = -1);
  30040. /** Deletes one of the Drawable objects.
  30041. @param index the index of the drawable to delete, between 0
  30042. and (getNumDrawables() - 1).
  30043. @see insertDrawable, getNumDrawables
  30044. */
  30045. void removeDrawable (const int index);
  30046. /** Returns the number of drawables contained inside this one.
  30047. @see getDrawable
  30048. */
  30049. int getNumDrawables() const throw() { return drawables.size(); }
  30050. /** Returns one of the drawables that are contained in this one.
  30051. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30052. to find it.
  30053. The pointer returned is managed by this object and will be deleted when no longer
  30054. needed, so be careful what you do with it.
  30055. @see getNumDrawables
  30056. */
  30057. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30058. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30059. The pointer returned is managed by this object and will be deleted when no longer
  30060. needed, so be careful what you do with it.
  30061. @see getNumDrawables
  30062. */
  30063. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30064. /** Brings one of the Drawables to the front.
  30065. @param index the index of the drawable to move, between 0
  30066. and (getNumDrawables() - 1).
  30067. @see insertDrawable, getNumDrawables
  30068. */
  30069. void bringToFront (const int index);
  30070. /** @internal */
  30071. void draw (Graphics& g, const AffineTransform& transform) const;
  30072. /** @internal */
  30073. void getBounds (float& x, float& y, float& width, float& height) const;
  30074. /** @internal */
  30075. bool hitTest (float x, float y) const;
  30076. /** @internal */
  30077. Drawable* createCopy() const;
  30078. juce_UseDebuggingNewOperator
  30079. private:
  30080. OwnedArray <Drawable> drawables;
  30081. OwnedArray <AffineTransform> transforms;
  30082. DrawableComposite (const DrawableComposite&);
  30083. const DrawableComposite& operator= (const DrawableComposite&);
  30084. };
  30085. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30086. /********* End of inlined file: juce_DrawableComposite.h *********/
  30087. #endif
  30088. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30089. /********* Start of inlined file: juce_DrawableImage.h *********/
  30090. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30091. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30092. /**
  30093. A drawable object which is a bitmap image.
  30094. @see Drawable
  30095. */
  30096. class JUCE_API DrawableImage : public Drawable
  30097. {
  30098. public:
  30099. DrawableImage();
  30100. /** Destructor. */
  30101. virtual ~DrawableImage();
  30102. /** Sets the image that this drawable will render.
  30103. An internal copy is made of the image passed-in. If you want to provide an
  30104. image that this object can take charge of without needing to create a copy,
  30105. use the other setImage() method.
  30106. */
  30107. void setImage (const Image& imageToCopy);
  30108. /** Sets the image that this drawable will render.
  30109. An internal copy of this will not be made, so the caller mustn't delete
  30110. the image while it's still being used by this object.
  30111. A good way to use this is with the ImageCache - if you create an image
  30112. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30113. it'll be released neatly with its reference count being decreased.
  30114. @param imageToUse the image to render
  30115. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30116. then the image will be deleted when this object no longer
  30117. needs it - unless the image was created by the ImageCache,
  30118. in which case it will be released with ImageCache::release().
  30119. */
  30120. void setImage (Image* imageToUse,
  30121. const bool releaseWhenNotNeeded);
  30122. /** Returns the current image. */
  30123. Image* getImage() const throw() { return image; }
  30124. /** Clears (and possibly deletes) the currently set image. */
  30125. void clearImage();
  30126. /** Sets the opacity to use when drawing the image. */
  30127. void setOpacity (const float newOpacity);
  30128. /** Returns the image's opacity. */
  30129. float getOpacity() const throw() { return opacity; }
  30130. /** Sets a colour to draw over the image's alpha channel.
  30131. By default this is transparent so isn't drawn, but if you set a non-transparent
  30132. colour here, then it will be overlaid on the image, using the image's alpha
  30133. channel as a mask.
  30134. This is handy for doing things like darkening or lightening an image by overlaying
  30135. it with semi-transparent black or white.
  30136. */
  30137. void setOverlayColour (const Colour& newOverlayColour);
  30138. /** Returns the overlay colour. */
  30139. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30140. /** @internal */
  30141. void draw (Graphics& g, const AffineTransform& transform) const;
  30142. /** @internal */
  30143. void getBounds (float& x, float& y, float& width, float& height) const;
  30144. /** @internal */
  30145. bool hitTest (float x, float y) const;
  30146. /** @internal */
  30147. Drawable* createCopy() const;
  30148. juce_UseDebuggingNewOperator
  30149. private:
  30150. Image* image;
  30151. bool canDeleteImage;
  30152. float opacity;
  30153. Colour overlayColour;
  30154. DrawableImage (const DrawableImage&);
  30155. const DrawableImage& operator= (const DrawableImage&);
  30156. };
  30157. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30158. /********* End of inlined file: juce_DrawableImage.h *********/
  30159. #endif
  30160. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30161. /********* Start of inlined file: juce_DrawablePath.h *********/
  30162. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30163. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30164. /**
  30165. A drawable object which renders a filled or outlined shape.
  30166. @see Drawable
  30167. */
  30168. class JUCE_API DrawablePath : public Drawable
  30169. {
  30170. public:
  30171. /** Creates a DrawablePath.
  30172. */
  30173. DrawablePath();
  30174. /** Destructor. */
  30175. virtual ~DrawablePath();
  30176. /** Changes the path that will be drawn.
  30177. @see setSolidFill, setOutline
  30178. */
  30179. void setPath (const Path& newPath);
  30180. /** Returns the current path. */
  30181. const Path& getPath() const throw() { return path; }
  30182. /** Sets a colour to fill the path with.
  30183. This colour is used to fill the path - if you don't want the path to be
  30184. filled (e.g. if you're just drawing an outline), set this colour to be
  30185. transparent.
  30186. @see setPath, setOutline
  30187. */
  30188. void setSolidFill (const Colour& newColour);
  30189. /** Sets a custom brush to use to fill the path.
  30190. @see setSolidFill
  30191. */
  30192. void setFillBrush (const Brush& newBrush);
  30193. /** Returns the brush currently being used to fill the shape. */
  30194. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30195. /** Changes the properties of the outline that will be drawn around the path.
  30196. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30197. colour passed-in here will be used for it.
  30198. @see setPath, setSolidFill
  30199. */
  30200. void setOutline (const float thickness,
  30201. const Colour& outlineColour);
  30202. /** Changes the properties of the outline that will be drawn around the path.
  30203. If the stroke type has 0 thickness, no outline will be drawn.
  30204. @see setPath, setSolidFill
  30205. */
  30206. void setOutline (const PathStrokeType& strokeType,
  30207. const Brush& strokeBrush);
  30208. /** Returns the current outline style. */
  30209. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30210. /** Returns the brush currently being used to draw the outline. */
  30211. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30212. /** @internal */
  30213. void draw (Graphics& g, const AffineTransform& transform) const;
  30214. /** @internal */
  30215. void getBounds (float& x, float& y, float& width, float& height) const;
  30216. /** @internal */
  30217. bool hitTest (float x, float y) const;
  30218. /** @internal */
  30219. Drawable* createCopy() const;
  30220. juce_UseDebuggingNewOperator
  30221. private:
  30222. Path path, outline;
  30223. Brush* fillBrush;
  30224. Brush* strokeBrush;
  30225. PathStrokeType strokeType;
  30226. void updateOutline();
  30227. DrawablePath (const DrawablePath&);
  30228. const DrawablePath& operator= (const DrawablePath&);
  30229. };
  30230. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30231. /********* End of inlined file: juce_DrawablePath.h *********/
  30232. #endif
  30233. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30234. /********* Start of inlined file: juce_DrawableText.h *********/
  30235. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30236. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30237. /**
  30238. A drawable object which renders a line of text.
  30239. @see Drawable
  30240. */
  30241. class JUCE_API DrawableText : public Drawable
  30242. {
  30243. public:
  30244. /** Creates a DrawableText object. */
  30245. DrawableText();
  30246. /** Destructor. */
  30247. virtual ~DrawableText();
  30248. /** Sets the block of text to render */
  30249. void setText (const GlyphArrangement& newText);
  30250. /** Sets a single line of text to render.
  30251. This is a convenient method of adding a single line - for
  30252. more complex text, use the setText() that takes a
  30253. GlyphArrangement instead.
  30254. */
  30255. void setText (const String& newText, const Font& fontToUse);
  30256. /** Returns the text arrangement that was set with setText(). */
  30257. const GlyphArrangement& getText() const throw() { return text; }
  30258. /** Sets the colour of the text. */
  30259. void setColour (const Colour& newColour);
  30260. /** Returns the current text colour. */
  30261. const Colour& getColour() const throw() { return colour; }
  30262. /** @internal */
  30263. void draw (Graphics& g, const AffineTransform& transform) const;
  30264. /** @internal */
  30265. void getBounds (float& x, float& y, float& width, float& height) const;
  30266. /** @internal */
  30267. bool hitTest (float x, float y) const;
  30268. /** @internal */
  30269. Drawable* createCopy() const;
  30270. juce_UseDebuggingNewOperator
  30271. private:
  30272. GlyphArrangement text;
  30273. Colour colour;
  30274. DrawableText (const DrawableText&);
  30275. const DrawableText& operator= (const DrawableText&);
  30276. };
  30277. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30278. /********* End of inlined file: juce_DrawableText.h *********/
  30279. #endif
  30280. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30281. #endif
  30282. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30283. #endif
  30284. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30285. #endif
  30286. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30287. #endif
  30288. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30289. /********* Start of inlined file: juce_ArrowButton.h *********/
  30290. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30291. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30292. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30293. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30294. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30295. /**
  30296. An effect filter that adds a drop-shadow behind the image's content.
  30297. (This will only work on images/components that aren't opaque, of course).
  30298. When added to a component, this effect will draw a soft-edged
  30299. shadow based on what gets drawn inside it. The shadow will also
  30300. be applied to the component's children.
  30301. For speed, this doesn't use a proper gaussian blur, but cheats by
  30302. using a simple bilinear filter. If you need a really high-quality
  30303. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30304. @see Component::setComponentEffect
  30305. */
  30306. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30307. {
  30308. public:
  30309. /** Creates a default drop-shadow effect.
  30310. To customise the shadow's appearance, use the setShadowProperties()
  30311. method.
  30312. */
  30313. DropShadowEffect();
  30314. /** Destructor. */
  30315. ~DropShadowEffect();
  30316. /** Sets up parameters affecting the shadow's appearance.
  30317. @param newRadius the (approximate) radius of the blur used
  30318. @param newOpacity the opacity with which the shadow is rendered
  30319. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30320. component's contents
  30321. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30322. component's contents
  30323. */
  30324. void setShadowProperties (const float newRadius,
  30325. const float newOpacity,
  30326. const int newShadowOffsetX,
  30327. const int newShadowOffsetY);
  30328. /** @internal */
  30329. void applyEffect (Image& sourceImage, Graphics& destContext);
  30330. juce_UseDebuggingNewOperator
  30331. private:
  30332. int offsetX, offsetY;
  30333. float radius, opacity;
  30334. };
  30335. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30336. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30337. /**
  30338. A button with an arrow in it.
  30339. @see Button
  30340. */
  30341. class JUCE_API ArrowButton : public Button
  30342. {
  30343. public:
  30344. /** Creates an ArrowButton.
  30345. @param buttonName the name to give the button
  30346. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30347. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30348. @param arrowColour the colour to use for the arrow
  30349. */
  30350. ArrowButton (const String& buttonName,
  30351. float arrowDirection,
  30352. const Colour& arrowColour);
  30353. /** Destructor. */
  30354. ~ArrowButton();
  30355. juce_UseDebuggingNewOperator
  30356. protected:
  30357. /** @internal */
  30358. void paintButton (Graphics& g,
  30359. bool isMouseOverButton,
  30360. bool isButtonDown);
  30361. /** @internal */
  30362. void buttonStateChanged();
  30363. private:
  30364. Colour colour;
  30365. DropShadowEffect shadow;
  30366. Path path;
  30367. int offset;
  30368. ArrowButton (const ArrowButton&);
  30369. const ArrowButton& operator= (const ArrowButton&);
  30370. };
  30371. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30372. /********* End of inlined file: juce_ArrowButton.h *********/
  30373. #endif
  30374. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30375. #endif
  30376. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30377. /********* Start of inlined file: juce_DrawableButton.h *********/
  30378. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30379. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30380. /**
  30381. A button that displays a Drawable.
  30382. Up to three Drawable objects can be given to this button, to represent the
  30383. 'normal', 'over' and 'down' states.
  30384. @see Button
  30385. */
  30386. class JUCE_API DrawableButton : public Button
  30387. {
  30388. public:
  30389. enum ButtonStyle
  30390. {
  30391. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30392. ImageRaw, /**< The button will just display the images in their normal size and position.
  30393. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30394. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30395. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30396. };
  30397. /** Creates a DrawableButton.
  30398. After creating one of these, use setImages() to specify the drawables to use.
  30399. @param buttonName the name to give the component
  30400. @param buttonStyle the layout to use
  30401. @see ButtonStyle, setButtonStyle, setImages
  30402. */
  30403. DrawableButton (const String& buttonName,
  30404. const ButtonStyle buttonStyle);
  30405. /** Destructor. */
  30406. ~DrawableButton();
  30407. /** Sets up the images to draw for the various button states.
  30408. The button will keep its own internal copies of these drawables.
  30409. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30410. will be made of the object passed-in if it is non-zero.
  30411. @param overImage the thing to draw for the button's 'over' state - if this is
  30412. zero, the button's normal image will be used when the mouse is
  30413. over it. An internal copy will be made of the object passed-in
  30414. if it is non-zero.
  30415. @param downImage the thing to draw for the button's 'down' state - if this is
  30416. zero, the 'over' image will be used instead (or the normal image
  30417. as a last resort). An internal copy will be made of the object
  30418. passed-in if it is non-zero.
  30419. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30420. the normal image will be drawn with a reduced opacity instead.
  30421. An internal copy will be made of the object passed-in if it is
  30422. non-zero.
  30423. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30424. state is 'on'. If this is 0, the normal image is used instead
  30425. @param overImageOn same as the overImage, but this is used when the button's toggle
  30426. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30427. @param downImageOn same as the downImage, but this is used when the button's toggle
  30428. state is 'on'. If this is 0, the overImageOn is drawn instead
  30429. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30430. state is 'on'. If this is 0, the normal image will be drawn instead
  30431. with a reduced opacity
  30432. */
  30433. void setImages (const Drawable* normalImage,
  30434. const Drawable* overImage = 0,
  30435. const Drawable* downImage = 0,
  30436. const Drawable* disabledImage = 0,
  30437. const Drawable* normalImageOn = 0,
  30438. const Drawable* overImageOn = 0,
  30439. const Drawable* downImageOn = 0,
  30440. const Drawable* disabledImageOn = 0);
  30441. /** Changes the button's style.
  30442. @see ButtonStyle
  30443. */
  30444. void setButtonStyle (const ButtonStyle newStyle);
  30445. /** Changes the button's background colours.
  30446. The toggledOffColour is the colour to use when the button's toggle state
  30447. is off, and toggledOnColour when it's on.
  30448. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30449. used to fill the background of the component.
  30450. For an ImageOnButtonBackground style, the colour is used to draw the
  30451. button's lozenge shape and exactly how the colour's used will depend
  30452. on the LookAndFeel.
  30453. */
  30454. void setBackgroundColours (const Colour& toggledOffColour,
  30455. const Colour& toggledOnColour);
  30456. /** Returns the current background colour being used.
  30457. @see setBackgroundColour
  30458. */
  30459. const Colour& getBackgroundColour() const throw();
  30460. /** Gives the button an optional amount of space around the edge of the drawable.
  30461. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30462. ones on a button background. If the button is too small for the given gap, a
  30463. smaller gap will be used.
  30464. By default there's a gap of about 3 pixels.
  30465. */
  30466. void setEdgeIndent (const int numPixelsIndent);
  30467. /** Returns the image that the button is currently displaying. */
  30468. const Drawable* getCurrentImage() const throw();
  30469. const Drawable* getNormalImage() const throw();
  30470. const Drawable* getOverImage() const throw();
  30471. const Drawable* getDownImage() const throw();
  30472. juce_UseDebuggingNewOperator
  30473. protected:
  30474. /** @internal */
  30475. void paintButton (Graphics& g,
  30476. bool isMouseOverButton,
  30477. bool isButtonDown);
  30478. private:
  30479. ButtonStyle style;
  30480. Drawable* normalImage;
  30481. Drawable* overImage;
  30482. Drawable* downImage;
  30483. Drawable* disabledImage;
  30484. Drawable* normalImageOn;
  30485. Drawable* overImageOn;
  30486. Drawable* downImageOn;
  30487. Drawable* disabledImageOn;
  30488. Colour backgroundOff, backgroundOn;
  30489. int edgeIndent;
  30490. void deleteImages();
  30491. DrawableButton (const DrawableButton&);
  30492. const DrawableButton& operator= (const DrawableButton&);
  30493. };
  30494. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30495. /********* End of inlined file: juce_DrawableButton.h *********/
  30496. #endif
  30497. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30498. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30499. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30500. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30501. /**
  30502. A button showing an underlined weblink, that will launch the link
  30503. when it's clicked.
  30504. @see Button
  30505. */
  30506. class JUCE_API HyperlinkButton : public Button
  30507. {
  30508. public:
  30509. /** Creates a HyperlinkButton.
  30510. @param linkText the text that will be displayed in the button - this is
  30511. also set as the Component's name, but the text can be
  30512. changed later with the Button::getButtonText() method
  30513. @param linkURL the URL to launch when the user clicks the button
  30514. */
  30515. HyperlinkButton (const String& linkText,
  30516. const URL& linkURL);
  30517. /** Destructor. */
  30518. ~HyperlinkButton();
  30519. /** Changes the font to use for the text.
  30520. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30521. to match the size of the component.
  30522. */
  30523. void setFont (const Font& newFont,
  30524. const bool resizeToMatchComponentHeight,
  30525. const Justification& justificationType = Justification::horizontallyCentred);
  30526. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30527. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30528. methods.
  30529. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30530. */
  30531. enum ColourIds
  30532. {
  30533. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30534. };
  30535. /** Changes the URL that the button will trigger. */
  30536. void setURL (const URL& newURL) throw();
  30537. /** Returns the URL that the button will trigger. */
  30538. const URL& getURL() const throw() { return url; }
  30539. /** Resizes the button horizontally to fit snugly around the text.
  30540. This won't affect the button's height.
  30541. */
  30542. void changeWidthToFitText();
  30543. juce_UseDebuggingNewOperator
  30544. protected:
  30545. /** @internal */
  30546. void clicked();
  30547. /** @internal */
  30548. void colourChanged();
  30549. /** @internal */
  30550. void paintButton (Graphics& g,
  30551. bool isMouseOverButton,
  30552. bool isButtonDown);
  30553. private:
  30554. URL url;
  30555. Font font;
  30556. bool resizeFont;
  30557. Justification justification;
  30558. const Font getFontToUse() const;
  30559. HyperlinkButton (const HyperlinkButton&);
  30560. const HyperlinkButton& operator= (const HyperlinkButton&);
  30561. };
  30562. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30563. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30564. #endif
  30565. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30566. /********* Start of inlined file: juce_ImageButton.h *********/
  30567. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30568. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30569. /**
  30570. As the title suggests, this is a button containing an image.
  30571. The colour and transparency of the image can be set to vary when the
  30572. button state changes.
  30573. @see Button, ShapeButton, TextButton
  30574. */
  30575. class JUCE_API ImageButton : public Button
  30576. {
  30577. public:
  30578. /** Creates an ImageButton.
  30579. Use setImage() to specify the image to use. The colours and opacities that
  30580. are specified here can be changed later using setDrawingOptions().
  30581. @param name the name to give the component
  30582. */
  30583. ImageButton (const String& name);
  30584. /** Destructor. */
  30585. ~ImageButton();
  30586. /** Sets up the images to draw in various states.
  30587. Important! Bear in mind that if you pass the same image in for more than one of
  30588. these parameters, this button will delete it (or release from the ImageCache)
  30589. multiple times!
  30590. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30591. resized to the same dimensions as the normal image
  30592. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30593. button when the button's size changes
  30594. @param preserveImageProportions if true then any rescaling of the image to fit
  30595. the button will keep the image's x and y proportions
  30596. correct - i.e. it won't distort its shape, although
  30597. this might create gaps around the edges
  30598. @param normalImage the image to use when the button is in its normal state. The
  30599. image passed in will be deleted (or released if it
  30600. was created by the ImageCache class) when the
  30601. button no longer needs it.
  30602. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30603. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30604. normal image - if this colour is transparent, no overlay
  30605. will be drawn. The overlay will be drawn over the top of the
  30606. image, so you can basically add a solid or semi-transparent
  30607. colour to the image to brighten or darken it
  30608. @param overImage the image to use when the mouse is over the button. If
  30609. you want to use the same image as was set in the normalImage
  30610. parameter, this value can be 0. As for normalImage, it
  30611. will be deleted or released by the button when no longer
  30612. needed
  30613. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30614. is over the button
  30615. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30616. image when the mouse is over - if this colour is transparent,
  30617. no overlay will be drawn
  30618. @param downImage an image to use when the button is pressed down. If set
  30619. to zero, the 'over' image will be drawn instead (or the
  30620. normal image if there isn't an 'over' image either). This
  30621. image will be deleted or released by the button when no
  30622. longer needed
  30623. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30624. is pressed
  30625. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30626. image when the button is pressed down - if this colour is
  30627. transparent, no overlay will be drawn
  30628. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30629. whenever it's inside the button's bounding rectangle. If
  30630. set to values higher than 0, the mouse will only be
  30631. considered to be over the image when the value of the
  30632. image's alpha channel at that position is greater than
  30633. this level.
  30634. */
  30635. void setImages (const bool resizeButtonNowToFitThisImage,
  30636. const bool rescaleImagesWhenButtonSizeChanges,
  30637. const bool preserveImageProportions,
  30638. Image* const normalImage,
  30639. const float imageOpacityWhenNormal,
  30640. const Colour& overlayColourWhenNormal,
  30641. Image* const overImage,
  30642. const float imageOpacityWhenOver,
  30643. const Colour& overlayColourWhenOver,
  30644. Image* const downImage,
  30645. const float imageOpacityWhenDown,
  30646. const Colour& overlayColourWhenDown,
  30647. const float hitTestAlphaThreshold = 0.0f);
  30648. /** Returns the currently set 'normal' image. */
  30649. Image* getNormalImage() const throw();
  30650. /** Returns the image that's drawn when the mouse is over the button.
  30651. If an 'over' image has been set, this will return it; otherwise it'll
  30652. just return the normal image.
  30653. */
  30654. Image* getOverImage() const throw();
  30655. /** Returns the image that's drawn when the button is held down.
  30656. If a 'down' image has been set, this will return it; otherwise it'll
  30657. return the 'over' image or normal image, depending on what's available.
  30658. */
  30659. Image* getDownImage() const throw();
  30660. juce_UseDebuggingNewOperator
  30661. protected:
  30662. /** @internal */
  30663. bool hitTest (int x, int y);
  30664. /** @internal */
  30665. void paintButton (Graphics& g,
  30666. bool isMouseOverButton,
  30667. bool isButtonDown);
  30668. private:
  30669. bool scaleImageToFit, preserveProportions;
  30670. unsigned char alphaThreshold;
  30671. int imageX, imageY, imageW, imageH;
  30672. Image* normalImage;
  30673. Image* overImage;
  30674. Image* downImage;
  30675. float normalOpacity, overOpacity, downOpacity;
  30676. Colour normalOverlay, overOverlay, downOverlay;
  30677. Image* getCurrentImage() const;
  30678. void deleteImages();
  30679. ImageButton (const ImageButton&);
  30680. const ImageButton& operator= (const ImageButton&);
  30681. };
  30682. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30683. /********* End of inlined file: juce_ImageButton.h *********/
  30684. #endif
  30685. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30686. /********* Start of inlined file: juce_ShapeButton.h *********/
  30687. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30688. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30689. /**
  30690. A button that contains a filled shape.
  30691. @see Button, ImageButton, TextButton, ArrowButton
  30692. */
  30693. class JUCE_API ShapeButton : public Button
  30694. {
  30695. public:
  30696. /** Creates a ShapeButton.
  30697. @param name a name to give the component - see Component::setName()
  30698. @param normalColour the colour to fill the shape with when the mouse isn't over
  30699. @param overColour the colour to use when the mouse is over the shape
  30700. @param downColour the colour to use when the button is in the pressed-down state
  30701. */
  30702. ShapeButton (const String& name,
  30703. const Colour& normalColour,
  30704. const Colour& overColour,
  30705. const Colour& downColour);
  30706. /** Destructor. */
  30707. ~ShapeButton();
  30708. /** Sets the shape to use.
  30709. @param newShape the shape to use
  30710. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30711. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30712. the button is resized
  30713. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30714. */
  30715. void setShape (const Path& newShape,
  30716. const bool resizeNowToFitThisShape,
  30717. const bool maintainShapeProportions,
  30718. const bool hasDropShadow);
  30719. /** Set the colours to use for drawing the shape.
  30720. @param normalColour the colour to fill the shape with when the mouse isn't over
  30721. @param overColour the colour to use when the mouse is over the shape
  30722. @param downColour the colour to use when the button is in the pressed-down state
  30723. */
  30724. void setColours (const Colour& normalColour,
  30725. const Colour& overColour,
  30726. const Colour& downColour);
  30727. /** Sets up an outline to draw around the shape.
  30728. @param outlineColour the colour to use
  30729. @param outlineStrokeWidth the thickness of line to draw
  30730. */
  30731. void setOutline (const Colour& outlineColour,
  30732. const float outlineStrokeWidth);
  30733. juce_UseDebuggingNewOperator
  30734. protected:
  30735. /** @internal */
  30736. void paintButton (Graphics& g,
  30737. bool isMouseOverButton,
  30738. bool isButtonDown);
  30739. private:
  30740. Colour normalColour, overColour, downColour, outlineColour;
  30741. DropShadowEffect shadow;
  30742. Path shape;
  30743. bool maintainShapeProportions;
  30744. float outlineWidth;
  30745. ShapeButton (const ShapeButton&);
  30746. const ShapeButton& operator= (const ShapeButton&);
  30747. };
  30748. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  30749. /********* End of inlined file: juce_ShapeButton.h *********/
  30750. #endif
  30751. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30752. #endif
  30753. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30754. /********* Start of inlined file: juce_ToggleButton.h *********/
  30755. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30756. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30757. /**
  30758. A button that can be toggled on/off.
  30759. All buttons can be toggle buttons, but this lets you create one of the
  30760. standard ones which has a tick-box and a text label next to it.
  30761. @see Button, DrawableButton, TextButton
  30762. */
  30763. class JUCE_API ToggleButton : public Button
  30764. {
  30765. public:
  30766. /** Creates a ToggleButton.
  30767. @param buttonText the text to put in the button (the component's name is also
  30768. initially set to this string, but these can be changed later
  30769. using the setName() and setButtonText() methods)
  30770. */
  30771. ToggleButton (const String& buttonText);
  30772. /** Destructor. */
  30773. ~ToggleButton();
  30774. /** Resizes the button to fit neatly around its current text.
  30775. The button's height won't be affected, only its width.
  30776. */
  30777. void changeWidthToFitText();
  30778. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30779. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30780. methods.
  30781. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30782. */
  30783. enum ColourIds
  30784. {
  30785. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  30786. };
  30787. juce_UseDebuggingNewOperator
  30788. protected:
  30789. /** @internal */
  30790. void paintButton (Graphics& g,
  30791. bool isMouseOverButton,
  30792. bool isButtonDown);
  30793. /** @internal */
  30794. void colourChanged();
  30795. private:
  30796. ToggleButton (const ToggleButton&);
  30797. const ToggleButton& operator= (const ToggleButton&);
  30798. };
  30799. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30800. /********* End of inlined file: juce_ToggleButton.h *********/
  30801. #endif
  30802. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30803. /********* Start of inlined file: juce_ToolbarButton.h *********/
  30804. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30805. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30806. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  30807. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30808. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30809. /********* Start of inlined file: juce_Toolbar.h *********/
  30810. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  30811. #define __JUCE_TOOLBAR_JUCEHEADER__
  30812. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  30813. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30814. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30815. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  30816. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30817. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30818. /**
  30819. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  30820. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  30821. derive your component from this class, and make sure that it is somewhere inside a
  30822. DragAndDropContainer component.
  30823. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30824. the operating system onto your component, you don't need any of these classes: instead
  30825. see the FileDragAndDropTarget class.
  30826. @see DragAndDropContainer, FileDragAndDropTarget
  30827. */
  30828. class JUCE_API DragAndDropTarget
  30829. {
  30830. public:
  30831. /** Destructor. */
  30832. virtual ~DragAndDropTarget() {}
  30833. /** Callback to check whether this target is interested in the type of object being
  30834. dragged.
  30835. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30836. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30837. @returns true if this component wants to receive the other callbacks regarging this
  30838. type of object; if it returns false, no other callbacks will be made.
  30839. */
  30840. virtual bool isInterestedInDragSource (const String& sourceDescription,
  30841. Component* sourceComponent) = 0;
  30842. /** Callback to indicate that something is being dragged over this component.
  30843. This gets called when the user moves the mouse into this component while dragging
  30844. something.
  30845. Use this callback as a trigger to make your component repaint itself to give the
  30846. user feedback about whether the item can be dropped here or not.
  30847. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30848. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30849. @param x the mouse x position, relative to this component
  30850. @param y the mouse y position, relative to this component
  30851. @see itemDragExit
  30852. */
  30853. virtual void itemDragEnter (const String& sourceDescription,
  30854. Component* sourceComponent,
  30855. int x,
  30856. int y);
  30857. /** Callback to indicate that the user is dragging something over this component.
  30858. This gets called when the user moves the mouse over this component while dragging
  30859. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  30860. this lets you know what happens in-between.
  30861. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30862. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30863. @param x the mouse x position, relative to this component
  30864. @param y the mouse y position, relative to this component
  30865. */
  30866. virtual void itemDragMove (const String& sourceDescription,
  30867. Component* sourceComponent,
  30868. int x,
  30869. int y);
  30870. /** Callback to indicate that something has been dragged off the edge of this component.
  30871. This gets called when the user moves the mouse out of this component while dragging
  30872. something.
  30873. If you've used itemDragEnter() to repaint your component and give feedback, use this
  30874. as a signal to repaint it in its normal state.
  30875. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30876. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30877. @see itemDragEnter
  30878. */
  30879. virtual void itemDragExit (const String& sourceDescription,
  30880. Component* sourceComponent);
  30881. /** Callback to indicate that the user has dropped something onto this component.
  30882. When the user drops an item this get called, and you can use the description to
  30883. work out whether your object wants to deal with it or not.
  30884. Note that after this is called, the itemDragExit method may not be called, so you should
  30885. clean up in here if there's anything you need to do when the drag finishes.
  30886. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30887. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30888. @param x the mouse x position, relative to this component
  30889. @param y the mouse y position, relative to this component
  30890. */
  30891. virtual void itemDropped (const String& sourceDescription,
  30892. Component* sourceComponent,
  30893. int x,
  30894. int y) = 0;
  30895. /** Overriding this allows the target to tell the drag container whether to
  30896. draw the drag image while the cursor is over it.
  30897. By default it returns true, but if you return false, then the normal drag
  30898. image will not be shown when the cursor is over this target.
  30899. */
  30900. virtual bool shouldDrawDragImageWhenOver();
  30901. };
  30902. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30903. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  30904. /**
  30905. Enables drag-and-drop behaviour for a component and all its sub-components.
  30906. For a component to be able to make or receive drag-and-drop events, one of its parent
  30907. components must derive from this class. It's probably best for the top-level
  30908. component to implement it.
  30909. Then to start a drag operation, any sub-component can just call the startDragging()
  30910. method, and this object will take over, tracking the mouse and sending appropriate
  30911. callbacks to any child components derived from DragAndDropTarget which the mouse
  30912. moves over.
  30913. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30914. the operating system onto your component, you don't need any of these classes: you can do this
  30915. simply by overriding Component::filesDropped().
  30916. @see DragAndDropTarget
  30917. */
  30918. class JUCE_API DragAndDropContainer
  30919. {
  30920. public:
  30921. /** Creates a DragAndDropContainer.
  30922. The object that derives from this class must also be a Component.
  30923. */
  30924. DragAndDropContainer();
  30925. /** Destructor. */
  30926. virtual ~DragAndDropContainer();
  30927. /** Begins a drag-and-drop operation.
  30928. This starts a drag-and-drop operation - call it when the user drags the
  30929. mouse in your drag-source component, and this object will track mouse
  30930. movements until the user lets go of the mouse button, and will send
  30931. appropriate messages to DragAndDropTarget objects that the mouse moves
  30932. over.
  30933. findParentDragContainerFor() is a handy method to call to find the
  30934. drag container to use for a component.
  30935. @param sourceDescription a string to use as the description of the thing being
  30936. dragged - this will be passed to the objects that might be
  30937. dropped-onto so they can decide if they want to handle it or
  30938. not
  30939. @param sourceComponent the component that is being dragged
  30940. @param dragImage the image to drag around underneath the mouse. If this is
  30941. zero, a snapshot of the sourceComponent will be used instead. An
  30942. image passed-in will be deleted by this object when no longer
  30943. needed.
  30944. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  30945. window, and can be dragged to DragAndDropTargets that are the
  30946. children of components other than this one.
  30947. */
  30948. void startDragging (const String& sourceDescription,
  30949. Component* sourceComponent,
  30950. Image* dragImage = 0,
  30951. const bool allowDraggingToOtherJuceWindows = false);
  30952. /** Returns true if something is currently being dragged. */
  30953. bool isDragAndDropActive() const;
  30954. /** Returns the description of the thing that's currently being dragged.
  30955. If nothing's being dragged, this will return an empty string, otherwise it's the
  30956. string that was passed into startDragging().
  30957. @see startDragging
  30958. */
  30959. const String getCurrentDragDescription() const;
  30960. /** Utility to find the DragAndDropContainer for a given Component.
  30961. This will search up this component's parent hierarchy looking for the first
  30962. parent component which is a DragAndDropContainer.
  30963. It's useful when a component wants to call startDragging but doesn't know
  30964. the DragAndDropContainer it should to use.
  30965. Obviously this may return 0 if it doesn't find a suitable component.
  30966. */
  30967. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  30968. /** This performs a synchronous drag-and-drop of a set of files to some external
  30969. application.
  30970. You can call this function in response to a mouseDrag callback, and it will
  30971. block, running its own internal message loop and tracking the mouse, while it
  30972. uses a native operating system drag-and-drop operation to move or copy some
  30973. files to another application.
  30974. @param files a list of filenames to drag
  30975. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  30976. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  30977. @returns true if the files were successfully dropped somewhere, or false if it
  30978. was interrupted
  30979. @see performExternalDragDropOfText
  30980. */
  30981. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  30982. /** This performs a synchronous drag-and-drop of a block of text to some external
  30983. application.
  30984. You can call this function in response to a mouseDrag callback, and it will
  30985. block, running its own internal message loop and tracking the mouse, while it
  30986. uses a native operating system drag-and-drop operation to move or copy some
  30987. text to another application.
  30988. @param text the text to copy
  30989. @returns true if the text was successfully dropped somewhere, or false if it
  30990. was interrupted
  30991. @see performExternalDragDropOfFiles
  30992. */
  30993. static bool performExternalDragDropOfText (const String& text);
  30994. juce_UseDebuggingNewOperator
  30995. protected:
  30996. /** Override this if you want to be able to perform an external drag a set of files
  30997. when the user drags outside of this container component.
  30998. This method will be called when a drag operation moves outside the Juce-based window,
  30999. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31000. to the array passed in, and return true.
  31001. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31002. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31003. @param files on return, the filenames you want to drag
  31004. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31005. it must make a copy of them (see the performExternalDragDropOfFiles()
  31006. method)
  31007. @see performExternalDragDropOfFiles
  31008. */
  31009. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31010. Component* dragSourceComponent,
  31011. StringArray& files,
  31012. bool& canMoveFiles);
  31013. private:
  31014. friend class DragImageComponent;
  31015. Component* dragImageComponent;
  31016. String currentDragDesc;
  31017. };
  31018. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31019. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31020. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31021. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31022. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31023. /**
  31024. Animates a set of components, moving it to a new position.
  31025. To use this, create a ComponentAnimator, and use its animateComponent() method
  31026. to tell it to move components to destination positions. Any number of
  31027. components can be animated by one ComponentAnimator object (if you've got a
  31028. lot of components to move, it's much more efficient to share a single animator
  31029. than to have many animators running at once).
  31030. You'll need to make sure the animator object isn't deleted before it finishes
  31031. moving the components.
  31032. */
  31033. class JUCE_API ComponentAnimator : private Timer
  31034. {
  31035. public:
  31036. /** Creates a ComponentAnimator. */
  31037. ComponentAnimator();
  31038. /** Destructor. */
  31039. ~ComponentAnimator();
  31040. /** Starts a component moving from its current position to a specified position.
  31041. If the component is already in the middle of an animation, that will be abandoned,
  31042. and a new animation will begin, moving the component from its current location.
  31043. The start and end speed parameters let you apply some acceleration to the component's
  31044. movement.
  31045. @param component the component to move
  31046. @param finalPosition the destination position and size to move it to
  31047. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31048. to arrive at its destination
  31049. @param startSpeed a value to indicate the relative start speed of the
  31050. animation. If this is 0, the component will start
  31051. by accelerating from rest; higher values mean that it
  31052. will have an initial speed greater than zero. If the
  31053. value if greater than 1, it will decelerate towards the
  31054. middle of its journey. To move the component at a constant
  31055. rate for its entire animation, set both the start and
  31056. end speeds to 1.0
  31057. @param endSpeed a relative speed at which the component should be moving
  31058. when the animation finishes. If this is 0, the component
  31059. will decelerate to a standstill at its final position; higher
  31060. values mean the component will still be moving when it stops.
  31061. To move the component at a constant rate for its entire
  31062. animation, set both the start and end speeds to 1.0
  31063. */
  31064. void animateComponent (Component* const component,
  31065. const Rectangle& finalPosition,
  31066. const int millisecondsToSpendMoving,
  31067. const double startSpeed = 1.0,
  31068. const double endSpeed = 1.0);
  31069. /** Stops a component if it's currently being animated.
  31070. If moveComponentToItsFinalPosition is true, then the component will
  31071. be immediately moved to its destination position and size. If false, it will be
  31072. left in whatever location it currently occupies.
  31073. */
  31074. void cancelAnimation (Component* const component,
  31075. const bool moveComponentToItsFinalPosition);
  31076. /** Clears all of the active animations.
  31077. If moveComponentsToTheirFinalPositions is true, all the components will
  31078. be immediately set to their final positions. If false, they will be
  31079. left in whatever locations they currently occupy.
  31080. */
  31081. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31082. /** Returns the destination position for a component.
  31083. If the component is being animated, this will return the target position that
  31084. was specified when animateComponent() was called.
  31085. If the specified component isn't currently being animated, this method will just
  31086. return its current position.
  31087. */
  31088. const Rectangle getComponentDestination (Component* const component);
  31089. juce_UseDebuggingNewOperator
  31090. private:
  31091. VoidArray tasks;
  31092. uint32 lastTime;
  31093. void* findTaskFor (Component* const component) const;
  31094. void timerCallback();
  31095. };
  31096. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31097. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31098. class ToolbarItemComponent;
  31099. class ToolbarItemFactory;
  31100. class MissingItemsComponent;
  31101. /**
  31102. A toolbar component.
  31103. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31104. and looks after their order and layout.
  31105. Items (icon buttons or other custom components) are added to a toolbar using a
  31106. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31107. toolbar might contain more than one instance of a particular item type.
  31108. Toolbars can be interactively customised, allowing the user to drag the items
  31109. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31110. component as a source of new items.
  31111. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31112. */
  31113. class JUCE_API Toolbar : public Component,
  31114. public DragAndDropContainer,
  31115. public DragAndDropTarget,
  31116. private ButtonListener
  31117. {
  31118. public:
  31119. /** Creates an empty toolbar component.
  31120. To add some icons or other components to your toolbar, you'll need to
  31121. create a ToolbarItemFactory class that can create a suitable set of
  31122. ToolbarItemComponents.
  31123. @see ToolbarItemFactory, ToolbarItemComponents
  31124. */
  31125. Toolbar();
  31126. /** Destructor.
  31127. Any items on the bar will be deleted when the toolbar is deleted.
  31128. */
  31129. ~Toolbar();
  31130. /** Changes the bar's orientation.
  31131. @see isVertical
  31132. */
  31133. void setVertical (const bool shouldBeVertical);
  31134. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31135. You can change the bar's orientation with setVertical().
  31136. */
  31137. bool isVertical() const throw() { return vertical; }
  31138. /** Returns the depth of the bar.
  31139. If the bar is horizontal, this will return its height; if it's vertical, it
  31140. will return its width.
  31141. @see getLength
  31142. */
  31143. int getThickness() const throw();
  31144. /** Returns the length of the bar.
  31145. If the bar is horizontal, this will return its width; if it's vertical, it
  31146. will return its height.
  31147. @see getThickness
  31148. */
  31149. int getLength() const throw();
  31150. /** Deletes all items from the bar.
  31151. */
  31152. void clear();
  31153. /** Adds an item to the toolbar.
  31154. The factory's ToolbarItemFactory::createItem() will be called by this method
  31155. to create the component that will actually be added to the bar.
  31156. The new item will be inserted at the specified index (if the index is -1, it
  31157. will be added to the right-hand or bottom end of the bar).
  31158. Once added, the component will be automatically deleted by this object when it
  31159. is no longer needed.
  31160. @see ToolbarItemFactory
  31161. */
  31162. void addItem (ToolbarItemFactory& factory,
  31163. const int itemId,
  31164. const int insertIndex = -1);
  31165. /** Deletes one of the items from the bar.
  31166. */
  31167. void removeToolbarItem (const int itemIndex);
  31168. /** Returns the number of items currently on the toolbar.
  31169. @see getItemId, getItemComponent
  31170. */
  31171. int getNumItems() const throw();
  31172. /** Returns the ID of the item with the given index.
  31173. If the index is less than zero or greater than the number of items,
  31174. this will return 0.
  31175. @see getNumItems
  31176. */
  31177. int getItemId (const int itemIndex) const throw();
  31178. /** Returns the component being used for the item with the given index.
  31179. If the index is less than zero or greater than the number of items,
  31180. this will return 0.
  31181. @see getNumItems
  31182. */
  31183. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31184. /** Clears this toolbar and adds to it the default set of items that the specified
  31185. factory creates.
  31186. @see ToolbarItemFactory::getDefaultItemSet
  31187. */
  31188. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31189. /** Options for the way items should be displayed.
  31190. @see setStyle, getStyle
  31191. */
  31192. enum ToolbarItemStyle
  31193. {
  31194. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31195. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31196. textOnly /**< Means that the toolbar only display text labels for each item. */
  31197. };
  31198. /** Returns the toolbar's current style.
  31199. @see ToolbarItemStyle, setStyle
  31200. */
  31201. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31202. /** Changes the toolbar's current style.
  31203. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31204. */
  31205. void setStyle (const ToolbarItemStyle& newStyle);
  31206. /** Flags used by the showCustomisationDialog() method. */
  31207. enum CustomisationFlags
  31208. {
  31209. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31210. show the "icons only" option on its choice of toolbar styles. */
  31211. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31212. show the "icons with text" option on its choice of toolbar styles. */
  31213. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31214. show the "text only" option on its choice of toolbar styles. */
  31215. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31216. show a button to reset the toolbar to its default set of items. */
  31217. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31218. };
  31219. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31220. The dialog contains a ToolbarItemPalette and various controls for editing other
  31221. aspects of the toolbar. This method will block and run the dialog box modally,
  31222. returning when the user closes it.
  31223. The factory is used to determine the set of items that will be shown on the
  31224. palette.
  31225. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31226. enum.
  31227. @see ToolbarItemPalette
  31228. */
  31229. void showCustomisationDialog (ToolbarItemFactory& factory,
  31230. const int optionFlags = allCustomisationOptionsEnabled);
  31231. /** Turns on or off the toolbar's editing mode, in which its items can be
  31232. rearranged by the user.
  31233. (In most cases it's easier just to use showCustomisationDialog() instead of
  31234. trying to enable editing directly).
  31235. @see ToolbarItemPalette
  31236. */
  31237. void setEditingActive (const bool editingEnabled);
  31238. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31239. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31240. methods.
  31241. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31242. */
  31243. enum ColourIds
  31244. {
  31245. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31246. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31247. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31248. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31249. over them. */
  31250. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31251. held down on them. */
  31252. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31253. when the style is set to iconsWithText or textOnly. */
  31254. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31255. the customisation dialog is active and the mouse moves over them. */
  31256. };
  31257. /** Returns a string that represents the toolbar's current set of items.
  31258. This lets you later restore the same item layout using restoreFromString().
  31259. @see restoreFromString
  31260. */
  31261. const String toString() const;
  31262. /** Restores a set of items that was previously stored in a string by the toString()
  31263. method.
  31264. The factory object is used to create any item components that are needed.
  31265. @see toString
  31266. */
  31267. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31268. const String& savedVersion);
  31269. /** @internal */
  31270. void paint (Graphics& g);
  31271. /** @internal */
  31272. void resized();
  31273. /** @internal */
  31274. void buttonClicked (Button*);
  31275. /** @internal */
  31276. void mouseDown (const MouseEvent&);
  31277. /** @internal */
  31278. bool isInterestedInDragSource (const String&, Component*);
  31279. /** @internal */
  31280. void itemDragMove (const String&, Component*, int, int);
  31281. /** @internal */
  31282. void itemDragExit (const String&, Component*);
  31283. /** @internal */
  31284. void itemDropped (const String&, Component*, int, int);
  31285. /** @internal */
  31286. void updateAllItemPositions (const bool animate);
  31287. /** @internal */
  31288. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31289. juce_UseDebuggingNewOperator
  31290. private:
  31291. Button* missingItemsButton;
  31292. bool vertical, isEditingActive;
  31293. ToolbarItemStyle toolbarStyle;
  31294. ComponentAnimator animator;
  31295. friend class MissingItemsComponent;
  31296. Array <ToolbarItemComponent*> items;
  31297. friend class ItemDragAndDropOverlayComponent;
  31298. static const tchar* const toolbarDragDescriptor;
  31299. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31300. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31301. Toolbar (const Toolbar&);
  31302. const Toolbar& operator= (const Toolbar&);
  31303. };
  31304. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31305. /********* End of inlined file: juce_Toolbar.h *********/
  31306. class ItemDragAndDropOverlayComponent;
  31307. /**
  31308. A component that can be used as one of the items in a Toolbar.
  31309. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31310. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31311. class for further info about creating them.
  31312. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31313. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31314. calling the constructor, and override contentAreaChanged(), in which you can position
  31315. any sub-components you need to add.
  31316. To add basic buttons without writing a special subclass, have a look at the
  31317. ToolbarButton class.
  31318. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31319. */
  31320. class JUCE_API ToolbarItemComponent : public Button
  31321. {
  31322. public:
  31323. /** Constructor.
  31324. @param itemId the ID of the type of toolbar item which this represents
  31325. @param labelText the text to display if the toolbar's style is set to
  31326. Toolbar::iconsWithText or Toolbar::textOnly
  31327. @param isBeingUsedAsAButton set this to false if you don't want the button
  31328. to draw itself with button over/down states when the mouse
  31329. moves over it or clicks
  31330. */
  31331. ToolbarItemComponent (const int itemId,
  31332. const String& labelText,
  31333. const bool isBeingUsedAsAButton);
  31334. /** Destructor. */
  31335. ~ToolbarItemComponent();
  31336. /** Returns the item type ID that this component represents.
  31337. This value is in the constructor.
  31338. */
  31339. int getItemId() const throw() { return itemId; }
  31340. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31341. inside one.
  31342. */
  31343. Toolbar* getToolbar() const;
  31344. /** Returns true if this component is currently inside a toolbar which is vertical.
  31345. @see Toolbar::isVertical
  31346. */
  31347. bool isToolbarVertical() const;
  31348. /** Returns the current style setting of this item.
  31349. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31350. @see setStyle, Toolbar::getStyle
  31351. */
  31352. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31353. /** Changes the current style setting of this item.
  31354. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31355. by the toolbar that holds this item.
  31356. @see setStyle, Toolbar::setStyle
  31357. */
  31358. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31359. /** Returns the area of the component that should be used to display the button image or
  31360. other contents of the item.
  31361. This content area may change when the item's style changes, and may leave a space around the
  31362. edge of the component where the text label can be shown.
  31363. @see contentAreaChanged
  31364. */
  31365. const Rectangle getContentArea() const throw() { return contentArea; }
  31366. /** This method must return the size criteria for this item, based on a given toolbar
  31367. size and orientation.
  31368. The preferredSize, minSize and maxSize values must all be set by your implementation
  31369. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31370. toolbar, they refer to the item's height.
  31371. The preferredSize is the size that the component would like to be, and this must be
  31372. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31373. the same value.
  31374. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31375. Toolbar::getThickness().
  31376. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31377. vertically.
  31378. */
  31379. virtual bool getToolbarItemSizes (int toolbarThickness,
  31380. bool isToolbarVertical,
  31381. int& preferredSize,
  31382. int& minSize,
  31383. int& maxSize) = 0;
  31384. /** Your subclass should use this method to draw its content area.
  31385. The graphics object that is passed-in will have been clipped and had its origin
  31386. moved to fit the content area as specified get getContentArea(). The width and height
  31387. parameters are the width and height of the content area.
  31388. If the component you're writing isn't a button, you can just do nothing in this method.
  31389. */
  31390. virtual void paintButtonArea (Graphics& g,
  31391. int width, int height,
  31392. bool isMouseOver, bool isMouseDown) = 0;
  31393. /** Callback to indicate that the content area of this item has changed.
  31394. This might be because the component was resized, or because the style changed and
  31395. the space needed for the text label is different.
  31396. See getContentArea() for a description of what the area is.
  31397. */
  31398. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31399. /** Editing modes.
  31400. These are used by setEditingMode(), but will be rarely needed in user code.
  31401. */
  31402. enum ToolbarEditingMode
  31403. {
  31404. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31405. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31406. customisation mode, and the items can be dragged around. */
  31407. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31408. dragged onto a toolbar to add it to that bar.*/
  31409. };
  31410. /** Changes the editing mode of this component.
  31411. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31412. and is unlikely to be of much use in end-user-code.
  31413. */
  31414. void setEditingMode (const ToolbarEditingMode newMode);
  31415. /** Returns the current editing mode of this component.
  31416. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31417. and is unlikely to be of much use in end-user-code.
  31418. */
  31419. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31420. /** @internal */
  31421. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31422. /** @internal */
  31423. void resized();
  31424. juce_UseDebuggingNewOperator
  31425. private:
  31426. friend class Toolbar;
  31427. friend class ItemDragAndDropOverlayComponent;
  31428. const int itemId;
  31429. ToolbarEditingMode mode;
  31430. Toolbar::ToolbarItemStyle toolbarStyle;
  31431. Component* overlayComp;
  31432. int dragOffsetX, dragOffsetY;
  31433. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31434. Rectangle contentArea;
  31435. ToolbarItemComponent (const ToolbarItemComponent&);
  31436. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31437. };
  31438. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31439. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31440. /**
  31441. A type of button designed to go on a toolbar.
  31442. This simple button can have two Drawable objects specified - one for normal
  31443. use and another one (optionally) for the button's "on" state if it's a
  31444. toggle button.
  31445. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31446. */
  31447. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31448. {
  31449. public:
  31450. /** Creates a ToolbarButton.
  31451. @param itemId the ID for this toolbar item type. This is passed through to the
  31452. ToolbarItemComponent constructor
  31453. @param labelText the text to display on the button (if the toolbar is using a style
  31454. that shows text labels). This is passed through to the
  31455. ToolbarItemComponent constructor
  31456. @param normalImage a drawable object that the button should use as its icon. The object
  31457. that is passed-in here will be kept by this object and will be
  31458. deleted when no longer needed or when this button is deleted.
  31459. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31460. is in a toggled-on state (see the Button::getToggleState() method). If
  31461. 0 is passed-in here, then the normal image will be used instead, regardless
  31462. of the toggle state. The object that is passed-in here will be kept by
  31463. this object and will be deleted when no longer needed or when this button
  31464. is deleted.
  31465. */
  31466. ToolbarButton (const int itemId,
  31467. const String& labelText,
  31468. Drawable* const normalImage,
  31469. Drawable* const toggledOnImage);
  31470. /** Destructor. */
  31471. ~ToolbarButton();
  31472. /** @internal */
  31473. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31474. int& minSize, int& maxSize);
  31475. /** @internal */
  31476. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31477. /** @internal */
  31478. void contentAreaChanged (const Rectangle& newBounds);
  31479. juce_UseDebuggingNewOperator
  31480. private:
  31481. Drawable* const normalImage;
  31482. Drawable* const toggledOnImage;
  31483. ToolbarButton (const ToolbarButton&);
  31484. const ToolbarButton& operator= (const ToolbarButton&);
  31485. };
  31486. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31487. /********* End of inlined file: juce_ToolbarButton.h *********/
  31488. #endif
  31489. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31490. #endif
  31491. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31492. /********* Start of inlined file: juce_GlowEffect.h *********/
  31493. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31494. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31495. /**
  31496. A component effect that adds a coloured blur around the component's contents.
  31497. (This will only work on non-opaque components).
  31498. @see Component::setComponentEffect, DropShadowEffect
  31499. */
  31500. class JUCE_API GlowEffect : public ImageEffectFilter
  31501. {
  31502. public:
  31503. /** Creates a default 'glow' effect.
  31504. To customise its appearance, use the setGlowProperties() method.
  31505. */
  31506. GlowEffect();
  31507. /** Destructor. */
  31508. ~GlowEffect();
  31509. /** Sets the glow's radius and colour.
  31510. The radius is how large the blur should be, and the colour is
  31511. used to render it (for a less intense glow, lower the colour's
  31512. opacity).
  31513. */
  31514. void setGlowProperties (const float newRadius,
  31515. const Colour& newColour);
  31516. /** @internal */
  31517. void applyEffect (Image& sourceImage, Graphics& destContext);
  31518. juce_UseDebuggingNewOperator
  31519. private:
  31520. float radius;
  31521. Colour colour;
  31522. };
  31523. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31524. /********* End of inlined file: juce_GlowEffect.h *********/
  31525. #endif
  31526. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31527. #endif
  31528. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31529. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31530. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31531. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31532. /**
  31533. An effect filter that reduces the image's opacity.
  31534. This can be used to make a component (and its child components) more
  31535. transparent.
  31536. @see Component::setComponentEffect
  31537. */
  31538. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31539. {
  31540. public:
  31541. /** Creates the effect object.
  31542. The opacity of the component to which the effect is applied will be
  31543. scaled by the given factor (in the range 0 to 1.0f).
  31544. */
  31545. ReduceOpacityEffect (const float opacity = 1.0f);
  31546. /** Destructor. */
  31547. ~ReduceOpacityEffect();
  31548. /** Sets how much to scale the component's opacity.
  31549. @param newOpacity should be between 0 and 1.0f
  31550. */
  31551. void setOpacity (const float newOpacity);
  31552. /** @internal */
  31553. void applyEffect (Image& sourceImage, Graphics& destContext);
  31554. juce_UseDebuggingNewOperator
  31555. private:
  31556. float opacity;
  31557. };
  31558. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31559. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31560. #endif
  31561. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31562. #endif
  31563. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31564. #endif
  31565. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31566. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31567. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31568. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31569. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31570. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31571. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31572. /**
  31573. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31574. command in a ApplicationCommandManager.
  31575. Normally, you won't actually create a KeyPressMappingSet directly, because
  31576. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  31577. you'd create yourself an ApplicationCommandManager, and call its
  31578. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  31579. KeyPressMappingSet.
  31580. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  31581. to the top-level component for which you want to handle keystrokes. So for example:
  31582. @code
  31583. class MyMainWindow : public Component
  31584. {
  31585. ApplicationCommandManager* myCommandManager;
  31586. public:
  31587. MyMainWindow()
  31588. {
  31589. myCommandManager = new ApplicationCommandManager();
  31590. // first, make sure the command manager has registered all the commands that its
  31591. // targets can perform..
  31592. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  31593. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  31594. // this will use the command manager to initialise the KeyPressMappingSet with
  31595. // the default keypresses that were specified when the targets added their commands
  31596. // to the manager.
  31597. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  31598. // having set up the default key-mappings, you might now want to load the last set
  31599. // of mappings that the user configured.
  31600. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  31601. // Now tell our top-level window to send any keypresses that arrive to the
  31602. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  31603. addKeyListener (myCommandManager->getKeyMappings());
  31604. }
  31605. ...
  31606. }
  31607. @endcode
  31608. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  31609. register to be told when a command or mapping is added, removed, etc.
  31610. There's also a UI component called KeyMappingEditorComponent that can be used
  31611. to easily edit the key mappings.
  31612. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  31613. */
  31614. class JUCE_API KeyPressMappingSet : public KeyListener,
  31615. public ChangeBroadcaster,
  31616. public FocusChangeListener
  31617. {
  31618. public:
  31619. /** Creates a KeyPressMappingSet for a given command manager.
  31620. Normally, you won't actually create a KeyPressMappingSet directly, because
  31621. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  31622. best thing to do is to create your ApplicationCommandManager, and use the
  31623. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  31624. When a suitable keypress happens, the manager's invoke() method will be
  31625. used to invoke the appropriate command.
  31626. @see ApplicationCommandManager
  31627. */
  31628. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  31629. /** Creates an copy of a KeyPressMappingSet. */
  31630. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  31631. /** Destructor. */
  31632. ~KeyPressMappingSet();
  31633. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  31634. /** Returns a list of keypresses that are assigned to a particular command.
  31635. @param commandID the command's ID
  31636. */
  31637. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  31638. /** Assigns a keypress to a command.
  31639. If the keypress is already assigned to a different command, it will first be
  31640. removed from that command, to avoid it triggering multiple functions.
  31641. @param commandID the ID of the command that you want to add a keypress to. If
  31642. this is 0, the keypress will be removed from anything that it
  31643. was previously assigned to, but not re-assigned
  31644. @param newKeyPress the new key-press
  31645. @param insertIndex if this is less than zero, the key will be appended to the
  31646. end of the list of keypresses; otherwise the new keypress will
  31647. be inserted into the existing list at this index
  31648. */
  31649. void addKeyPress (const CommandID commandID,
  31650. const KeyPress& newKeyPress,
  31651. int insertIndex = -1) throw();
  31652. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  31653. @see resetToDefaultMapping
  31654. */
  31655. void resetToDefaultMappings() throw();
  31656. /** Resets all key-mappings to the defaults for a particular command.
  31657. @see resetToDefaultMappings
  31658. */
  31659. void resetToDefaultMapping (const CommandID commandID) throw();
  31660. /** Removes all keypresses that are assigned to any commands. */
  31661. void clearAllKeyPresses() throw();
  31662. /** Removes all keypresses that are assigned to a particular command. */
  31663. void clearAllKeyPresses (const CommandID commandID) throw();
  31664. /** Removes one of the keypresses that are assigned to a command.
  31665. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  31666. which the keyPressIndex refers.
  31667. */
  31668. void removeKeyPress (const CommandID commandID,
  31669. const int keyPressIndex) throw();
  31670. /** Removes a keypress from any command that it may be assigned to.
  31671. */
  31672. void removeKeyPress (const KeyPress& keypress) throw();
  31673. /** Returns true if the given command is linked to this key. */
  31674. bool containsMapping (const CommandID commandID,
  31675. const KeyPress& keyPress) const throw();
  31676. /** Looks for a command that corresponds to a keypress.
  31677. @returns the UID of the command or 0 if none was found
  31678. */
  31679. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  31680. /** Tries to recreate the mappings from a previously stored state.
  31681. The XML passed in must have been created by the createXml() method.
  31682. If the stored state makes any reference to commands that aren't
  31683. currently available, these will be ignored.
  31684. If the set of mappings being loaded was a set of differences (using createXml (true)),
  31685. then this will call resetToDefaultMappings() and then merge the saved mappings
  31686. on top. If the saved set was created with createXml (false), then this method
  31687. will first clear all existing mappings and load the saved ones as a complete set.
  31688. @returns true if it manages to load the XML correctly
  31689. @see createXml
  31690. */
  31691. bool restoreFromXml (const XmlElement& xmlVersion);
  31692. /** Creates an XML representation of the current mappings.
  31693. This will produce a lump of XML that can be later reloaded using
  31694. restoreFromXml() to recreate the current mapping state.
  31695. The object that is returned must be deleted by the caller.
  31696. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  31697. will be saved into the XML. If it's true, then the XML will
  31698. only store the differences between the current mappings and
  31699. the default mappings you'd get from calling resetToDefaultMappings().
  31700. The advantage of saving a set of differences from the default is that
  31701. if you change the default mappings (in a new version of your app, for
  31702. example), then these will be merged into a user's saved preferences.
  31703. @see restoreFromXml
  31704. */
  31705. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  31706. /** @internal */
  31707. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31708. /** @internal */
  31709. bool keyStateChanged (Component* originatingComponent);
  31710. /** @internal */
  31711. void globalFocusChanged (Component* focusedComponent);
  31712. juce_UseDebuggingNewOperator
  31713. private:
  31714. ApplicationCommandManager* commandManager;
  31715. struct CommandMapping
  31716. {
  31717. CommandID commandID;
  31718. Array <KeyPress> keypresses;
  31719. bool wantsKeyUpDownCallbacks;
  31720. };
  31721. OwnedArray <CommandMapping> mappings;
  31722. struct KeyPressTime
  31723. {
  31724. KeyPress key;
  31725. uint32 timeWhenPressed;
  31726. };
  31727. OwnedArray <KeyPressTime> keysDown;
  31728. void handleMessage (const Message& message);
  31729. void invokeCommand (const CommandID commandID,
  31730. const KeyPress& keyPress,
  31731. const bool isKeyDown,
  31732. const int millisecsSinceKeyPressed,
  31733. Component* const originatingComponent) const;
  31734. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  31735. };
  31736. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31737. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  31738. /********* Start of inlined file: juce_TreeView.h *********/
  31739. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  31740. #define __JUCE_TREEVIEW_JUCEHEADER__
  31741. class TreeView;
  31742. /**
  31743. An item in a treeview.
  31744. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  31745. own sub-items.
  31746. To implement an item that contains sub-items, override the itemOpennessChanged()
  31747. method so that when it is opened, it adds the new sub-items to itself using the
  31748. addSubItem method. Depending on the nature of the item it might choose to only
  31749. do this the first time it's opened, or it might want to refresh itself each time.
  31750. It also has the option of deleting its sub-items when it is closed, or leaving them
  31751. in place.
  31752. */
  31753. class JUCE_API TreeViewItem
  31754. {
  31755. public:
  31756. /** Constructor. */
  31757. TreeViewItem();
  31758. /** Destructor. */
  31759. virtual ~TreeViewItem();
  31760. /** Returns the number of sub-items that have been added to this item.
  31761. Note that this doesn't mean much if the node isn't open.
  31762. @see getSubItem, mightContainSubItems, addSubItem
  31763. */
  31764. int getNumSubItems() const throw();
  31765. /** Returns one of the item's sub-items.
  31766. Remember that the object returned might get deleted at any time when its parent
  31767. item is closed or refreshed, depending on the nature of the items you're using.
  31768. @see getNumSubItems
  31769. */
  31770. TreeViewItem* getSubItem (const int index) const throw();
  31771. /** Removes any sub-items. */
  31772. void clearSubItems();
  31773. /** Adds a sub-item.
  31774. @param newItem the object to add to the item's sub-item list. Once added, these can be
  31775. found using getSubItem(). When the items are later removed with
  31776. removeSubItem() (or when this item is deleted), they will be deleted.
  31777. @param insertPosition the index which the new item should have when it's added. If this
  31778. value is less than 0, the item will be added to the end of the list.
  31779. */
  31780. void addSubItem (TreeViewItem* const newItem,
  31781. const int insertPosition = -1);
  31782. /** Removes one of the sub-items.
  31783. @param index the item to remove
  31784. @param deleteItem if true, the item that is removed will also be deleted.
  31785. */
  31786. void removeSubItem (const int index,
  31787. const bool deleteItem = true);
  31788. /** Returns the TreeView to which this item belongs. */
  31789. TreeView* getOwnerView() const throw() { return ownerView; }
  31790. /** Returns the item within which this item is contained. */
  31791. TreeViewItem* getParentItem() const throw() { return parentItem; }
  31792. /** True if this item is currently open in the treeview. */
  31793. bool isOpen() const throw();
  31794. /** Opens or closes the item.
  31795. When opened or closed, the item's itemOpennessChanged() method will be called,
  31796. and a subclass should use this callback to create and add any sub-items that
  31797. it needs to.
  31798. @see itemOpennessChanged, mightContainSubItems
  31799. */
  31800. void setOpen (const bool shouldBeOpen);
  31801. /** True if this item is currently selected.
  31802. Use this when painting the node, to decide whether to draw it as selected or not.
  31803. */
  31804. bool isSelected() const throw();
  31805. /** Selects or deselects the item.
  31806. This will cause a callback to itemSelectionChanged()
  31807. */
  31808. void setSelected (const bool shouldBeSelected,
  31809. const bool deselectOtherItemsFirst);
  31810. /** Returns the rectangle that this item occupies.
  31811. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  31812. top-left of the TreeView comp, so this will depend on the scroll-position of
  31813. the tree. If false, it is relative to the top-left of the topmost item in the
  31814. tree (so this would be unaffected by scrolling the view).
  31815. */
  31816. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  31817. /** Sends a signal to the treeview to make it refresh itself.
  31818. Call this if your items have changed and you want the tree to update to reflect
  31819. this.
  31820. */
  31821. void treeHasChanged() const throw();
  31822. /** Returns the row number of this item in the tree.
  31823. The row number of an item will change according to which items are open.
  31824. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  31825. */
  31826. int getRowNumberInTree() const throw();
  31827. /** Changes whether lines are drawn to connect any sub-items to this item.
  31828. By default, line-drawing is turned on.
  31829. */
  31830. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  31831. /** Tells the tree whether this item can potentially be opened.
  31832. If your item could contain sub-items, this should return true; if it returns
  31833. false then the tree will not try to open the item. This determines whether or
  31834. not the item will be drawn with a 'plus' button next to it.
  31835. */
  31836. virtual bool mightContainSubItems() = 0;
  31837. /** Returns a string to uniquely identify this item.
  31838. If you're planning on using the TreeView::getOpennessState() method, then
  31839. these strings will be used to identify which nodes are open. The string
  31840. should be unique amongst the item's sibling items, but it's ok for there
  31841. to be duplicates at other levels of the tree.
  31842. If you're not going to store the state, then it's ok not to bother implementing
  31843. this method.
  31844. */
  31845. virtual const String getUniqueName() const;
  31846. /** Called when an item is opened or closed.
  31847. When setOpen() is called and the item has specified that it might
  31848. have sub-items with the mightContainSubItems() method, this method
  31849. is called to let the item create or manage its sub-items.
  31850. So when this is called with isNowOpen set to true (i.e. when the item is being
  31851. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  31852. refresh its sub-item list.
  31853. When this is called with isNowOpen set to false, the subclass might want
  31854. to use clearSubItems() to save on space, or it might choose to leave them,
  31855. depending on the nature of the tree.
  31856. You could also use this callback as a trigger to start a background process
  31857. which asynchronously creates sub-items and adds them, if that's more
  31858. appropriate for the task in hand.
  31859. @see mightContainSubItems
  31860. */
  31861. virtual void itemOpennessChanged (bool isNowOpen);
  31862. /** Must return the width required by this item.
  31863. If your item needs to have a particular width in pixels, return that value; if
  31864. you'd rather have it just fill whatever space is available in the treeview,
  31865. return -1.
  31866. If all your items return -1, no horizontal scrollbar will be shown, but if any
  31867. items have fixed widths and extend beyond the width of the treeview, a
  31868. scrollbar will appear.
  31869. Each item can be a different width, but if they change width, you should call
  31870. treeHasChanged() to update the tree.
  31871. */
  31872. virtual int getItemWidth() const { return -1; }
  31873. /** Must return the height required by this item.
  31874. This is the height in pixels that the item will take up. Items in the tree
  31875. can be different heights, but if they change height, you should call
  31876. treeHasChanged() to update the tree.
  31877. */
  31878. virtual int getItemHeight() const { return 20; }
  31879. /** Creates a component that will be used to represent this item.
  31880. You don't have to implement this method - if it returns 0 then no component
  31881. will be used for the item, and you can just draw it using the paintItem()
  31882. callback. But if you do return a component, it will be positioned in the
  31883. treeview so that it can be used to represent this item.
  31884. The component returned will be managed by the treeview, so always return
  31885. a new component, and don't keep a reference to it, as the treeview will
  31886. delete it later when it goes off the screen or is no longer needed. Also
  31887. bear in mind that if the component keeps a reference to the item that
  31888. created it, that item could be deleted before the component. Its position
  31889. and size will be completely managed by the tree, so don't attempt to move it
  31890. around.
  31891. Something you may want to do with your component is to give it a pointer to
  31892. the TreeView that created it. This is perfectly safe, and there's no danger
  31893. of it becoming a dangling pointer because the TreeView will always delete
  31894. the component before it is itself deleted.
  31895. As long as you stick to these rules you can return whatever kind of
  31896. component you like. It's most useful if you're doing things like drag-and-drop
  31897. of items, or want to use a Label component to edit item names, etc.
  31898. */
  31899. virtual Component* createItemComponent() { return 0; }
  31900. /** Draws the item's contents.
  31901. You can choose to either implement this method and draw each item, or you
  31902. can use createItemComponent() to create a component that will represent the
  31903. item.
  31904. If all you need in your tree is to be able to draw the items and detect when
  31905. the user selects or double-clicks one of them, it's probably enough to
  31906. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  31907. complicated interactions, you may need to use createItemComponent() instead.
  31908. @param g the graphics context to draw into
  31909. @param width the width of the area available for drawing
  31910. @param height the height of the area available for drawing
  31911. */
  31912. virtual void paintItem (Graphics& g, int width, int height);
  31913. /** Called when the user clicks on this item.
  31914. If you're using createItemComponent() to create a custom component for the
  31915. item, the mouse-clicks might not make it through to the treeview, but this
  31916. is how you find out about clicks when just drawing each item individually.
  31917. The associated mouse-event details are passed in, so you can find out about
  31918. which button, where it was, etc.
  31919. @see itemDoubleClicked
  31920. */
  31921. virtual void itemClicked (const MouseEvent& e);
  31922. /** Called when the user double-clicks on this item.
  31923. If you're using createItemComponent() to create a custom component for the
  31924. item, the mouse-clicks might not make it through to the treeview, but this
  31925. is how you find out about clicks when just drawing each item individually.
  31926. The associated mouse-event details are passed in, so you can find out about
  31927. which button, where it was, etc.
  31928. If not overridden, the base class method here will open or close the item as
  31929. if the 'plus' button had been clicked.
  31930. @see itemClicked
  31931. */
  31932. virtual void itemDoubleClicked (const MouseEvent& e);
  31933. /** Called when the item is selected or deselected.
  31934. Use this if you want to do something special when the item's selectedness
  31935. changes. By default it'll get repainted when this happens.
  31936. */
  31937. virtual void itemSelectionChanged (bool isNowSelected);
  31938. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  31939. If this returns a non-empty name then when the user drags an item, the treeview will
  31940. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  31941. a drag-and-drop operation, using this string as the source description, with the treeview
  31942. itself as the source component.
  31943. If you need more complex drag-and-drop behaviour, you can use custom components for
  31944. the items, and use those to trigger the drag.
  31945. @see DragAndDropContainer::startDragging
  31946. */
  31947. virtual const String getDragSourceDescription();
  31948. juce_UseDebuggingNewOperator
  31949. private:
  31950. TreeView* ownerView;
  31951. TreeViewItem* parentItem;
  31952. OwnedArray <TreeViewItem> subItems;
  31953. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  31954. int uid;
  31955. bool selected : 1;
  31956. bool redrawNeeded : 1;
  31957. bool drawLinesInside : 1;
  31958. unsigned int openness : 2;
  31959. friend class TreeView;
  31960. friend class TreeViewContentComponent;
  31961. void updatePositions (int newY);
  31962. int getIndentX() const throw();
  31963. void setOwnerView (TreeView* const newOwner) throw();
  31964. void paintRecursively (Graphics& g, int width);
  31965. TreeViewItem* findItemRecursively (int y) throw();
  31966. TreeViewItem* getDeepestOpenParentItem() throw();
  31967. void restoreFromXml (const XmlElement& e);
  31968. XmlElement* createXmlOpenness() const;
  31969. bool isLastOfSiblings() const throw();
  31970. TreeViewItem* getTopLevelItem() throw();
  31971. int getNumRows() const throw();
  31972. TreeViewItem* getItemOnRow (int index) throw();
  31973. void deselectAllRecursively();
  31974. int countSelectedItemsRecursively() const throw();
  31975. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  31976. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  31977. TreeViewItem (const TreeViewItem&);
  31978. const TreeViewItem& operator= (const TreeViewItem&);
  31979. };
  31980. /**
  31981. A tree-view component.
  31982. Use one of these to hold and display a structure of TreeViewItem objects.
  31983. */
  31984. class JUCE_API TreeView : public Component,
  31985. public SettableTooltipClient,
  31986. private AsyncUpdater
  31987. {
  31988. public:
  31989. /** Creates an empty treeview.
  31990. Once you've got a treeview component, you'll need to give it something to
  31991. display, using the setRootItem() method.
  31992. */
  31993. TreeView (const String& componentName = String::empty);
  31994. /** Destructor. */
  31995. ~TreeView();
  31996. /** Sets the item that is displayed in the treeview.
  31997. A tree has a single root item which contains as many sub-items as it needs. If
  31998. you want the tree to contain a number of root items, you should still use a single
  31999. root item above these, but hide it using setRootItemVisible().
  32000. You can pass in 0 to this method to clear the tree and remove its current root item.
  32001. The object passed in will not be deleted by the treeview, it's up to the caller
  32002. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32003. this item until you've removed it from the tree, either by calling setRootItem (0),
  32004. or by deleting the tree first.
  32005. */
  32006. void setRootItem (TreeViewItem* const newRootItem);
  32007. /** Returns the tree's root item.
  32008. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32009. */
  32010. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32011. /** Changes whether the tree's root item is shown or not.
  32012. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32013. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32014. will also make sure the root item is open (otherwise the treeview would look empty).
  32015. */
  32016. void setRootItemVisible (const bool shouldBeVisible);
  32017. /** Returns true if the root item is visible.
  32018. @see setRootItemVisible
  32019. */
  32020. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32021. /** Sets whether items are open or closed by default.
  32022. Normally, items are closed until the user opens them, but you can use this
  32023. to make them default to being open until explicitly closed.
  32024. @see areItemsOpenByDefault
  32025. */
  32026. void setDefaultOpenness (const bool isOpenByDefault);
  32027. /** Returns true if the tree's items default to being open.
  32028. @see setDefaultOpenness
  32029. */
  32030. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32031. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32032. You can always select multiple items internally by calling the
  32033. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32034. is allowed to multi-select by clicking on the tree.
  32035. By default it is disabled.
  32036. @see isMultiSelectEnabled
  32037. */
  32038. void setMultiSelectEnabled (const bool canMultiSelect);
  32039. /** Returns whether multi-select has been enabled for the tree.
  32040. @see setMultiSelectEnabled
  32041. */
  32042. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32043. /** Deselects any items that are currently selected. */
  32044. void clearSelectedItems();
  32045. /** Returns the number of items that are currently selected.
  32046. @see getSelectedItem, clearSelectedItems
  32047. */
  32048. int getNumSelectedItems() const throw();
  32049. /** Returns one of the selected items in the tree.
  32050. @param index the index, 0 to (getNumSelectedItems() - 1)
  32051. */
  32052. TreeViewItem* getSelectedItem (const int index) const throw();
  32053. /** Returns the number of rows the tree is using.
  32054. This will depend on which items are open.
  32055. @see TreeViewItem::getRowNumberInTree()
  32056. */
  32057. int getNumRowsInTree() const;
  32058. /** Returns the item on a particular row of the tree.
  32059. If the index is out of range, this will return 0.
  32060. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  32061. */
  32062. TreeViewItem* getItemOnRow (int index) const;
  32063. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  32064. void scrollToKeepItemVisible (TreeViewItem* item);
  32065. /** Returns the treeview's Viewport object. */
  32066. Viewport* getViewport() const throw() { return viewport; }
  32067. /** Returns the number of pixels by which each nested level of the tree is indented.
  32068. @see setIndentSize
  32069. */
  32070. int getIndentSize() const throw() { return indentSize; }
  32071. /** Changes the distance by which each nested level of the tree is indented.
  32072. @see getIndentSize
  32073. */
  32074. void setIndentSize (const int newIndentSize);
  32075. /** Saves the current state of open/closed nodes so it can be restored later.
  32076. This takes a snapshot of which nodes have been explicitly opened or closed,
  32077. and records it as XML. To identify node objects it uses the
  32078. TreeViewItem::getUniqueName() method to create named paths. This
  32079. means that the same state of open/closed nodes can be restored to a
  32080. completely different instance of the tree, as long as it contains nodes
  32081. whose unique names are the same.
  32082. The caller is responsible for deleting the object that is returned.
  32083. @param alsoIncludeScrollPosition if this is true, the state will also
  32084. include information about where the
  32085. tree has been scrolled to vertically,
  32086. so this can also be restored
  32087. @see restoreOpennessState
  32088. */
  32089. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32090. /** Restores a previously saved arrangement of open/closed nodes.
  32091. This will try to restore a snapshot of the tree's state that was created by
  32092. the getOpennessState() method. If any of the nodes named in the original
  32093. XML aren't present in this tree, they will be ignored.
  32094. @see getOpennessState
  32095. */
  32096. void restoreOpennessState (const XmlElement& newState);
  32097. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32098. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32099. methods.
  32100. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32101. */
  32102. enum ColourIds
  32103. {
  32104. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32105. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32106. };
  32107. /** @internal */
  32108. void paint (Graphics& g);
  32109. /** @internal */
  32110. void resized();
  32111. /** @internal */
  32112. bool keyPressed (const KeyPress& key);
  32113. /** @internal */
  32114. void colourChanged();
  32115. juce_UseDebuggingNewOperator
  32116. private:
  32117. friend class TreeViewItem;
  32118. friend class TreeViewContentComponent;
  32119. Viewport* viewport;
  32120. CriticalSection nodeAlterationLock;
  32121. TreeViewItem* rootItem;
  32122. int indentSize;
  32123. bool defaultOpenness : 1;
  32124. bool needsRecalculating : 1;
  32125. bool rootItemVisible : 1;
  32126. bool multiSelectEnabled : 1;
  32127. void itemsChanged() throw();
  32128. void handleAsyncUpdate();
  32129. void moveSelectedRow (int delta);
  32130. TreeView (const TreeView&);
  32131. const TreeView& operator= (const TreeView&);
  32132. };
  32133. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32134. /********* End of inlined file: juce_TreeView.h *********/
  32135. /**
  32136. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32137. object.
  32138. @see KeyPressMappingSet
  32139. */
  32140. class JUCE_API KeyMappingEditorComponent : public Component,
  32141. public TreeViewItem,
  32142. public ChangeListener,
  32143. private ButtonListener
  32144. {
  32145. public:
  32146. /** Creates a KeyMappingEditorComponent.
  32147. @param mappingSet this is the set of mappings to display and
  32148. edit. Make sure the mappings object is not
  32149. deleted before this component!
  32150. @param showResetToDefaultButton if true, then at the bottom of the
  32151. list, the component will include a 'reset to
  32152. defaults' button.
  32153. */
  32154. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32155. const bool showResetToDefaultButton);
  32156. /** Destructor. */
  32157. virtual ~KeyMappingEditorComponent();
  32158. /** Sets up the colours to use for parts of the component.
  32159. @param mainBackground colour to use for most of the background
  32160. @param textColour colour to use for the text
  32161. */
  32162. void setColours (const Colour& mainBackground,
  32163. const Colour& textColour);
  32164. /** Returns the KeyPressMappingSet that this component is acting upon.
  32165. */
  32166. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32167. /** Can be overridden if some commands need to be excluded from the list.
  32168. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32169. method to decide what to return, but you can override it to handle special cases.
  32170. */
  32171. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32172. /** Can be overridden to indicate that some commands are shown as read-only.
  32173. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32174. method to decide what to return, but you can override it to handle special cases.
  32175. */
  32176. virtual bool isCommandReadOnly (const CommandID commandID);
  32177. /** This can be overridden to let you change the format of the string used
  32178. to describe a keypress.
  32179. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32180. keys that are triggered by something else externally. If you override the
  32181. method, be sure to let the base class's method handle keys you're not
  32182. interested in.
  32183. */
  32184. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32185. /** @internal */
  32186. void parentHierarchyChanged();
  32187. /** @internal */
  32188. void resized();
  32189. /** @internal */
  32190. void changeListenerCallback (void*);
  32191. /** @internal */
  32192. bool mightContainSubItems();
  32193. /** @internal */
  32194. const String getUniqueName() const;
  32195. /** @internal */
  32196. void buttonClicked (Button* button);
  32197. juce_UseDebuggingNewOperator
  32198. private:
  32199. KeyPressMappingSet* mappings;
  32200. TreeView* tree;
  32201. friend class KeyMappingTreeViewItem;
  32202. friend class KeyCategoryTreeViewItem;
  32203. friend class KeyMappingItemComponent;
  32204. friend class KeyMappingChangeButton;
  32205. Colour backgroundColour, textColour;
  32206. TextButton* resetButton;
  32207. void assignNewKey (const CommandID commandID, int index);
  32208. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32209. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32210. };
  32211. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32212. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32213. #endif
  32214. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32215. #endif
  32216. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32217. #endif
  32218. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32219. #endif
  32220. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32221. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32222. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32223. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32224. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32225. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32226. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32227. class MenuBarModel;
  32228. /**
  32229. A class to receive callbacks when a MenuBarModel changes.
  32230. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32231. */
  32232. class JUCE_API MenuBarModelListener
  32233. {
  32234. public:
  32235. /** Destructor. */
  32236. virtual ~MenuBarModelListener() {}
  32237. /** This callback is made when items are changed in the menu bar model.
  32238. */
  32239. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32240. /** This callback is made when an application command is invoked that
  32241. is represented by one of the items in the menu bar model.
  32242. */
  32243. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32244. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32245. };
  32246. /**
  32247. A class for controlling MenuBar components.
  32248. This class is used to tell a MenuBar what menus to show, and to respond
  32249. to a menu being selected.
  32250. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32251. */
  32252. class JUCE_API MenuBarModel : private AsyncUpdater,
  32253. private ApplicationCommandManagerListener
  32254. {
  32255. public:
  32256. MenuBarModel() throw();
  32257. /** Destructor. */
  32258. virtual ~MenuBarModel();
  32259. /** Call this when some of your menu items have changed.
  32260. This method will cause a callback to any MenuBarListener objects that
  32261. are registered with this model.
  32262. If this model is displaying items from an ApplicationCommandManager, you
  32263. can use the setApplicationCommandManagerToWatch() method to cause
  32264. change messages to be sent automatically when the ApplicationCommandManager
  32265. is changed.
  32266. @see addListener, removeListener, MenuBarListener
  32267. */
  32268. void menuItemsChanged();
  32269. /** Tells the menu bar to listen to the specified command manager, and to update
  32270. itself when the commands change.
  32271. This will also allow it to flash a menu name when a command from that menu
  32272. is invoked using a keystroke.
  32273. */
  32274. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32275. /** Registers a listener for callbacks when the menu items in this model change.
  32276. The listener object will get callbacks when this object's menuItemsChanged()
  32277. method is called.
  32278. @see removeListener
  32279. */
  32280. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32281. /** Removes a listener.
  32282. @see addListener
  32283. */
  32284. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32285. /** This method must return a list of the names of the menus. */
  32286. virtual const StringArray getMenuBarNames() = 0;
  32287. /** This should return the popup menu to display for a given top-level menu.
  32288. @param topLevelMenuIndex the index of the top-level menu to show
  32289. @param menuName the name of the top-level menu item to show
  32290. */
  32291. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32292. const String& menuName) = 0;
  32293. /** This is called when a menu item has been clicked on.
  32294. @param menuItemID the item ID of the PopupMenu item that was selected
  32295. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32296. chosen (just in case you've used duplicate ID numbers
  32297. on more than one of the popup menus)
  32298. */
  32299. virtual void menuItemSelected (int menuItemID,
  32300. int topLevelMenuIndex) = 0;
  32301. #if JUCE_MAC || DOXYGEN
  32302. /** MAC ONLY - Sets the model that is currently being shown as the main
  32303. menu bar at the top of the screen on the Mac.
  32304. You can pass 0 to stop the current model being displayed. Be careful
  32305. not to delete a model while it is being used.
  32306. An optional extra menu can be specified, containing items to add to the top of
  32307. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  32308. an apple, it's the one next to it, with your application's name at the top
  32309. and the services menu etc on it). When one of these items is selected, the
  32310. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  32311. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  32312. object then newMenuBarModel must be non-null.
  32313. */
  32314. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  32315. const PopupMenu* extraAppleMenuItems = 0) throw();
  32316. /** MAC ONLY - Returns the menu model that is currently being shown as
  32317. the main menu bar.
  32318. */
  32319. static MenuBarModel* getMacMainMenu() throw();
  32320. #endif
  32321. /** @internal */
  32322. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32323. /** @internal */
  32324. void applicationCommandListChanged();
  32325. /** @internal */
  32326. void handleAsyncUpdate();
  32327. juce_UseDebuggingNewOperator
  32328. private:
  32329. ApplicationCommandManager* manager;
  32330. SortedSet <void*> listeners;
  32331. MenuBarModel (const MenuBarModel&);
  32332. const MenuBarModel& operator= (const MenuBarModel&);
  32333. };
  32334. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32335. /********* End of inlined file: juce_MenuBarModel.h *********/
  32336. /**
  32337. A menu bar component.
  32338. @see MenuBarModel
  32339. */
  32340. class JUCE_API MenuBarComponent : public Component,
  32341. private MenuBarModelListener,
  32342. private Timer
  32343. {
  32344. public:
  32345. /** Creates a menu bar.
  32346. @param model the model object to use to control this bar. You can
  32347. pass 0 into this if you like, and set the model later
  32348. using the setModel() method
  32349. */
  32350. MenuBarComponent (MenuBarModel* const model);
  32351. /** Destructor. */
  32352. ~MenuBarComponent();
  32353. /** Changes the model object to use to control the bar.
  32354. This can be 0, in which case the bar will be empty. Don't delete the object
  32355. that is passed-in while it's still being used by this MenuBar.
  32356. */
  32357. void setModel (MenuBarModel* const newModel);
  32358. /** Pops up one of the menu items.
  32359. This lets you manually open one of the menus - it could be triggered by a
  32360. key shortcut, for example.
  32361. */
  32362. void showMenu (const int menuIndex);
  32363. /** @internal */
  32364. void paint (Graphics& g);
  32365. /** @internal */
  32366. void resized();
  32367. /** @internal */
  32368. void mouseEnter (const MouseEvent& e);
  32369. /** @internal */
  32370. void mouseExit (const MouseEvent& e);
  32371. /** @internal */
  32372. void mouseDown (const MouseEvent& e);
  32373. /** @internal */
  32374. void mouseDrag (const MouseEvent& e);
  32375. /** @internal */
  32376. void mouseUp (const MouseEvent& e);
  32377. /** @internal */
  32378. void mouseMove (const MouseEvent& e);
  32379. /** @internal */
  32380. void inputAttemptWhenModal();
  32381. /** @internal */
  32382. void handleCommandMessage (int commandId);
  32383. /** @internal */
  32384. bool keyPressed (const KeyPress& key);
  32385. /** @internal */
  32386. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32387. /** @internal */
  32388. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32389. const ApplicationCommandTarget::InvocationInfo& info);
  32390. juce_UseDebuggingNewOperator
  32391. private:
  32392. MenuBarModel* model;
  32393. StringArray menuNames;
  32394. Array <int> xPositions;
  32395. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32396. int lastMouseX, lastMouseY;
  32397. bool inModalState;
  32398. Component* currentPopup;
  32399. int getItemAt (int x, int y);
  32400. void updateItemUnderMouse (const int x, const int y);
  32401. void hideCurrentMenu();
  32402. void timerCallback();
  32403. void repaintMenuItem (int index);
  32404. MenuBarComponent (const MenuBarComponent&);
  32405. const MenuBarComponent& operator= (const MenuBarComponent&);
  32406. };
  32407. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32408. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32409. #endif
  32410. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32411. #endif
  32412. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32413. #endif
  32414. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32415. #endif
  32416. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32417. /********* Start of inlined file: juce_ComponentDragger.h *********/
  32418. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32419. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32420. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32421. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32422. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32423. /**
  32424. A class that imposes restrictions on a Component's size or position.
  32425. This is used by classes such as ResizableCornerComponent,
  32426. ResizableBorderComponent and ResizableWindow.
  32427. The base class can impose some basic size and position limits, but you can
  32428. also subclass this for custom uses.
  32429. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  32430. */
  32431. class JUCE_API ComponentBoundsConstrainer
  32432. {
  32433. public:
  32434. /** When first created, the object will not impose any restrictions on the components. */
  32435. ComponentBoundsConstrainer() throw();
  32436. /** Destructor. */
  32437. virtual ~ComponentBoundsConstrainer();
  32438. /** Imposes a minimum width limit. */
  32439. void setMinimumWidth (const int minimumWidth) throw();
  32440. /** Returns the current minimum width. */
  32441. int getMinimumWidth() const throw() { return minW; }
  32442. /** Imposes a maximum width limit. */
  32443. void setMaximumWidth (const int maximumWidth) throw();
  32444. /** Returns the current maximum width. */
  32445. int getMaximumWidth() const throw() { return maxW; }
  32446. /** Imposes a minimum height limit. */
  32447. void setMinimumHeight (const int minimumHeight) throw();
  32448. /** Returns the current minimum height. */
  32449. int getMinimumHeight() const throw() { return minH; }
  32450. /** Imposes a maximum height limit. */
  32451. void setMaximumHeight (const int maximumHeight) throw();
  32452. /** Returns the current maximum height. */
  32453. int getMaximumHeight() const throw() { return maxH; }
  32454. /** Imposes a minimum width and height limit. */
  32455. void setMinimumSize (const int minimumWidth,
  32456. const int minimumHeight) throw();
  32457. /** Imposes a maximum width and height limit. */
  32458. void setMaximumSize (const int maximumWidth,
  32459. const int maximumHeight) throw();
  32460. /** Set all the maximum and minimum dimensions. */
  32461. void setSizeLimits (const int minimumWidth,
  32462. const int minimumHeight,
  32463. const int maximumWidth,
  32464. const int maximumHeight) throw();
  32465. /** Sets the amount by which the component is allowed to go off-screen.
  32466. The values indicate how many pixels must remain on-screen when dragged off
  32467. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  32468. when the component goes off the top of the screen, its y-position will be
  32469. clipped so that there are always at least 10 pixels on-screen. In other words,
  32470. the lowest y-position it can take would be (10 - the component's height).
  32471. If you pass 0 or less for one of these amounts, the component is allowed
  32472. to move beyond that edge completely, with no restrictions at all.
  32473. If you pass a very large number (i.e. larger that the dimensions of the
  32474. component itself), then the component won't be allowed to overlap that
  32475. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  32476. the component will bump into the left side of the screen and go no further.
  32477. */
  32478. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  32479. const int minimumWhenOffTheLeft,
  32480. const int minimumWhenOffTheBottom,
  32481. const int minimumWhenOffTheRight) throw();
  32482. /** Specifies a width-to-height ratio that the resizer should always maintain.
  32483. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  32484. will always be maintained as this multiple of the height.
  32485. @see setResizeLimits
  32486. */
  32487. void setFixedAspectRatio (const double widthOverHeight) throw();
  32488. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  32489. If no aspect ratio is being enforced, this will return 0.
  32490. */
  32491. double getFixedAspectRatio() const throw();
  32492. /** This callback changes the given co-ordinates to impose whatever the current
  32493. constraints are set to be.
  32494. @param x the x position that should be examined and adjusted
  32495. @param y the y position that should be examined and adjusted
  32496. @param w the width that should be examined and adjusted
  32497. @param h the height that should be examined and adjusted
  32498. @param previousBounds the component's current size
  32499. @param limits the region in which the component can be positioned
  32500. @param isStretchingTop whether the top edge of the component is being resized
  32501. @param isStretchingLeft whether the left edge of the component is being resized
  32502. @param isStretchingBottom whether the bottom edge of the component is being resized
  32503. @param isStretchingRight whether the right edge of the component is being resized
  32504. */
  32505. virtual void checkBounds (int& x, int& y, int& w, int& h,
  32506. const Rectangle& previousBounds,
  32507. const Rectangle& limits,
  32508. const bool isStretchingTop,
  32509. const bool isStretchingLeft,
  32510. const bool isStretchingBottom,
  32511. const bool isStretchingRight);
  32512. /** This callback happens when the resizer is about to start dragging. */
  32513. virtual void resizeStart();
  32514. /** This callback happens when the resizer has finished dragging. */
  32515. virtual void resizeEnd();
  32516. /** Checks the given bounds, and then sets the component to the corrected size. */
  32517. void setBoundsForComponent (Component* const component,
  32518. int x, int y, int w, int h,
  32519. const bool isStretchingTop,
  32520. const bool isStretchingLeft,
  32521. const bool isStretchingBottom,
  32522. const bool isStretchingRight);
  32523. /** Called by setBoundsForComponent() to apply a new constrained size to a
  32524. component.
  32525. By default this just calls setBounds(), but it virtual in case it's needed for
  32526. extremely cunning purposes.
  32527. */
  32528. virtual void applyBoundsToComponent (Component* component,
  32529. int x, int y, int w, int h);
  32530. juce_UseDebuggingNewOperator
  32531. private:
  32532. int minW, maxW, minH, maxH;
  32533. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  32534. double aspectRatio;
  32535. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  32536. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  32537. };
  32538. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32539. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32540. /**
  32541. An object to take care of the logic for dragging components around with the mouse.
  32542. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  32543. then in your mouseDrag() callback, call dragComponent().
  32544. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  32545. to limit the component's position and keep it on-screen.
  32546. e.g. @code
  32547. class MyDraggableComp
  32548. {
  32549. ComponentDragger myDragger;
  32550. void mouseDown (const MouseEvent& e)
  32551. {
  32552. myDragger.startDraggingComponent (this, 0);
  32553. }
  32554. void mouseDrag (const MouseEvent& e)
  32555. {
  32556. myDragger.dragComponent (this, e);
  32557. }
  32558. };
  32559. @endcode
  32560. */
  32561. class JUCE_API ComponentDragger
  32562. {
  32563. public:
  32564. /** Creates a ComponentDragger. */
  32565. ComponentDragger();
  32566. /** Destructor. */
  32567. virtual ~ComponentDragger();
  32568. /** Call this from your component's mouseDown() method, to prepare for dragging.
  32569. @param componentToDrag the component that you want to drag
  32570. @param constrainer a constrainer object to use to keep the component
  32571. from going offscreen
  32572. @see dragComponent
  32573. */
  32574. void startDraggingComponent (Component* const componentToDrag,
  32575. ComponentBoundsConstrainer* constrainer);
  32576. /** Call this from your mouseDrag() callback to move the component.
  32577. This will move the component, but will first check the validity of the
  32578. component's new position using the checkPosition() method, which you
  32579. can override if you need to enforce special positioning limits on the
  32580. component.
  32581. @param componentToDrag the component that you want to drag
  32582. @param e the current mouse-drag event
  32583. @see dragComponent
  32584. */
  32585. void dragComponent (Component* const componentToDrag,
  32586. const MouseEvent& e);
  32587. juce_UseDebuggingNewOperator
  32588. private:
  32589. ComponentBoundsConstrainer* constrainer;
  32590. int originalX, originalY;
  32591. };
  32592. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32593. /********* End of inlined file: juce_ComponentDragger.h *********/
  32594. #endif
  32595. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32596. #endif
  32597. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32598. #endif
  32599. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32600. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32601. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32602. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32603. /**
  32604. Components derived from this class can have files dropped onto them by an external application.
  32605. @see DragAndDropContainer
  32606. */
  32607. class JUCE_API FileDragAndDropTarget
  32608. {
  32609. public:
  32610. /** Destructor. */
  32611. virtual ~FileDragAndDropTarget() {}
  32612. /** Callback to check whether this target is interested in the set of files being offered.
  32613. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32614. component, so don't do anything time-consuming in here, like opening the files to have a look
  32615. inside them!
  32616. @param files the set of (absolute) pathnames of the files that the user is dragging
  32617. @returns true if this component wants to receive the other callbacks regarging this
  32618. type of object; if it returns false, no other callbacks will be made.
  32619. */
  32620. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32621. /** Callback to indicate that some files are being dragged over this component.
  32622. This gets called when the user moves the mouse into this component while dragging.
  32623. Use this callback as a trigger to make your component repaint itself to give the
  32624. user feedback about whether the files can be dropped here or not.
  32625. @param files the set of (absolute) pathnames of the files that the user is dragging
  32626. @param x the mouse x position, relative to this component
  32627. @param y the mouse y position, relative to this component
  32628. */
  32629. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32630. /** Callback to indicate that the user is dragging some files over this component.
  32631. This gets called when the user moves the mouse over this component while dragging.
  32632. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32633. this lets you know what happens in-between.
  32634. @param files the set of (absolute) pathnames of the files that the user is dragging
  32635. @param x the mouse x position, relative to this component
  32636. @param y the mouse y position, relative to this component
  32637. */
  32638. virtual void fileDragMove (const StringArray& files, int x, int y);
  32639. /** Callback to indicate that the mouse has moved away from this component.
  32640. This gets called when the user moves the mouse out of this component while dragging
  32641. the files.
  32642. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32643. as a signal to repaint it in its normal state.
  32644. @param files the set of (absolute) pathnames of the files that the user is dragging
  32645. */
  32646. virtual void fileDragExit (const StringArray& files);
  32647. /** Callback to indicate that the user has dropped the files onto this component.
  32648. When the user drops the files, this get called, and you can use the files in whatever
  32649. way is appropriate.
  32650. Note that after this is called, the fileDragExit method may not be called, so you should
  32651. clean up in here if there's anything you need to do when the drag finishes.
  32652. @param files the set of (absolute) pathnames of the files that the user is dragging
  32653. @param x the mouse x position, relative to this component
  32654. @param y the mouse y position, relative to this component
  32655. */
  32656. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32657. };
  32658. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32659. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32660. #endif
  32661. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32662. /********* Start of inlined file: juce_LassoComponent.h *********/
  32663. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32664. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32665. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  32666. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32667. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32668. /** Manages a list of selectable items.
  32669. Use one of these to keep a track of things that the user has highlighted, like
  32670. icons or things in a list.
  32671. The class is templated so that you can use it to hold either a set of pointers
  32672. to objects, or a set of ID numbers or handles, for cases where each item may
  32673. not always have a corresponding object.
  32674. To be informed when items are selected/deselected, register a ChangeListener with
  32675. this object.
  32676. @see SelectableObject
  32677. */
  32678. template <class SelectableItemType>
  32679. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  32680. {
  32681. public:
  32682. /** Creates an empty set. */
  32683. SelectedItemSet()
  32684. {
  32685. }
  32686. /** Creates a set based on an array of items. */
  32687. SelectedItemSet (const Array <SelectableItemType>& items)
  32688. : selectedItems (items)
  32689. {
  32690. }
  32691. /** Creates a copy of another set. */
  32692. SelectedItemSet (const SelectedItemSet& other)
  32693. : selectedItems (other.selectedItems)
  32694. {
  32695. }
  32696. /** Creates a copy of another set. */
  32697. const SelectedItemSet& operator= (const SelectedItemSet& other)
  32698. {
  32699. if (selectedItems != other.selectedItems)
  32700. {
  32701. selectedItems = other.selectedItems;
  32702. changed();
  32703. }
  32704. return *this;
  32705. }
  32706. /** Destructor. */
  32707. ~SelectedItemSet()
  32708. {
  32709. }
  32710. /** Clears any other currently selected items, and selects this item.
  32711. If this item is already the only thing selected, no change notification
  32712. will be sent out.
  32713. @see addToSelection, addToSelectionBasedOnModifiers
  32714. */
  32715. void selectOnly (SelectableItemType item)
  32716. {
  32717. if (isSelected (item))
  32718. {
  32719. for (int i = selectedItems.size(); --i >= 0;)
  32720. {
  32721. if (selectedItems.getUnchecked(i) != item)
  32722. {
  32723. deselect (selectedItems.getUnchecked(i));
  32724. i = jmin (i, selectedItems.size());
  32725. }
  32726. }
  32727. }
  32728. else
  32729. {
  32730. deselectAll();
  32731. changed();
  32732. selectedItems.add (item);
  32733. itemSelected (item);
  32734. }
  32735. }
  32736. /** Selects an item.
  32737. If the item is already selected, no change notification will be sent out.
  32738. @see selectOnly, addToSelectionBasedOnModifiers
  32739. */
  32740. void addToSelection (SelectableItemType item)
  32741. {
  32742. if (! isSelected (item))
  32743. {
  32744. changed();
  32745. selectedItems.add (item);
  32746. itemSelected (item);
  32747. }
  32748. }
  32749. /** Selects or deselects an item.
  32750. This will use the modifier keys to decide whether to deselect other items
  32751. first.
  32752. So if the shift key is held down, the item will be added without deselecting
  32753. anything (same as calling addToSelection() )
  32754. If no modifiers are down, the current selection will be cleared first (same
  32755. as calling selectOnly() )
  32756. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  32757. so it'll be added to the set unless it's already there, in which case it'll be
  32758. deselected.
  32759. If the items that you're selecting can also be dragged, you may need to use the
  32760. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  32761. subtleties of this kind of usage.
  32762. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  32763. */
  32764. void addToSelectionBasedOnModifiers (SelectableItemType item,
  32765. const ModifierKeys& modifiers)
  32766. {
  32767. if (modifiers.isShiftDown())
  32768. {
  32769. addToSelection (item);
  32770. }
  32771. else if (modifiers.isCommandDown())
  32772. {
  32773. if (isSelected (item))
  32774. deselect (item);
  32775. else
  32776. addToSelection (item);
  32777. }
  32778. else
  32779. {
  32780. selectOnly (item);
  32781. }
  32782. }
  32783. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  32784. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  32785. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  32786. makes it easy to handle multiple-selection of sets of objects that can also
  32787. be dragged.
  32788. For example, if you have several items already selected, and you click on
  32789. one of them (without dragging), then you'd expect this to deselect the other, and
  32790. just select the item you clicked on. But if you had clicked on this item and
  32791. dragged it, you'd have expected them all to stay selected.
  32792. When you call this method, you'll need to store the boolean result, because the
  32793. addToSelectionOnMouseUp() method will need to be know this value.
  32794. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  32795. */
  32796. bool addToSelectionOnMouseDown (SelectableItemType item,
  32797. const ModifierKeys& modifiers)
  32798. {
  32799. if (isSelected (item))
  32800. {
  32801. return ! modifiers.isPopupMenu();
  32802. }
  32803. else
  32804. {
  32805. addToSelectionBasedOnModifiers (item, modifiers);
  32806. return false;
  32807. }
  32808. }
  32809. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  32810. Call this during a mouseUp callback, when you have previously called the
  32811. addToSelectionOnMouseDown() method during your mouseDown event.
  32812. See addToSelectionOnMouseDown() for more info
  32813. @param item the item to select (or deselect)
  32814. @param modifiers the modifiers from the mouse-up event
  32815. @param wasItemDragged true if your item was dragged during the mouse click
  32816. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  32817. back from the addToSelectionOnMouseDown() call that you
  32818. should have made during the matching mouseDown event
  32819. */
  32820. void addToSelectionOnMouseUp (SelectableItemType item,
  32821. const ModifierKeys& modifiers,
  32822. const bool wasItemDragged,
  32823. const bool resultOfMouseDownSelectMethod)
  32824. {
  32825. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  32826. addToSelectionBasedOnModifiers (item, modifiers);
  32827. }
  32828. /** Deselects an item. */
  32829. void deselect (SelectableItemType item)
  32830. {
  32831. const int i = selectedItems.indexOf (item);
  32832. if (i >= 0)
  32833. {
  32834. changed();
  32835. itemDeselected (selectedItems.remove (i));
  32836. }
  32837. }
  32838. /** Deselects all items. */
  32839. void deselectAll()
  32840. {
  32841. if (selectedItems.size() > 0)
  32842. {
  32843. changed();
  32844. for (int i = selectedItems.size(); --i >= 0;)
  32845. {
  32846. itemDeselected (selectedItems.remove (i));
  32847. i = jmin (i, selectedItems.size());
  32848. }
  32849. }
  32850. }
  32851. /** Returns the number of currently selected items.
  32852. @see getSelectedItem
  32853. */
  32854. int getNumSelected() const throw()
  32855. {
  32856. return selectedItems.size();
  32857. }
  32858. /** Returns one of the currently selected items.
  32859. Returns 0 if the index is out-of-range.
  32860. @see getNumSelected
  32861. */
  32862. SelectableItemType getSelectedItem (const int index) const throw()
  32863. {
  32864. return selectedItems [index];
  32865. }
  32866. /** True if this item is currently selected. */
  32867. bool isSelected (const SelectableItemType item) const throw()
  32868. {
  32869. return selectedItems.contains (item);
  32870. }
  32871. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  32872. /** Can be overridden to do special handling when an item is selected.
  32873. For example, if the item is an object, you might want to call it and tell
  32874. it that it's being selected.
  32875. */
  32876. virtual void itemSelected (SelectableItemType item) {}
  32877. /** Can be overridden to do special handling when an item is deselected.
  32878. For example, if the item is an object, you might want to call it and tell
  32879. it that it's being deselected.
  32880. */
  32881. virtual void itemDeselected (SelectableItemType item) {}
  32882. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  32883. */
  32884. void changed (const bool synchronous = false)
  32885. {
  32886. if (synchronous)
  32887. sendSynchronousChangeMessage (this);
  32888. else
  32889. sendChangeMessage (this);
  32890. }
  32891. juce_UseDebuggingNewOperator
  32892. private:
  32893. Array <SelectableItemType> selectedItems;
  32894. };
  32895. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32896. /********* End of inlined file: juce_SelectedItemSet.h *********/
  32897. /**
  32898. A class used by the LassoComponent to manage the things that it selects.
  32899. This allows the LassoComponent to find out which items are within the lasso,
  32900. and to change the list of selected items.
  32901. @see LassoComponent, SelectedItemSet
  32902. */
  32903. template <class SelectableItemType>
  32904. class LassoSource
  32905. {
  32906. public:
  32907. /** Destructor. */
  32908. virtual ~LassoSource() {}
  32909. /** Returns the set of items that lie within a given lassoable region.
  32910. Your implementation of this method must find all the relevent items that lie
  32911. within the given rectangle. and add them to the itemsFound array.
  32912. The co-ordinates are relative to the top-left of the lasso component's parent
  32913. component. (i.e. they are the same as the size and position of the lasso
  32914. component itself).
  32915. */
  32916. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  32917. int x, int y, int width, int height) = 0;
  32918. /** Returns the SelectedItemSet that the lasso should update.
  32919. This set will be continuously updated by the LassoComponent as it gets
  32920. dragged around, so make sure that you've got a ChangeListener attached to
  32921. the set so that your UI objects will know when the selection changes and
  32922. be able to update themselves appropriately.
  32923. */
  32924. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  32925. };
  32926. /**
  32927. A component that acts as a rectangular selection region, which you drag with
  32928. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  32929. To use one of these:
  32930. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  32931. component, and call its beginLasso() method, giving it a
  32932. suitable LassoSource object that it can use to find out which items are in
  32933. the active area.
  32934. - Each time your parent component gets a mouseDrag event, call dragLasso()
  32935. to update the lasso's position - it will use its LassoSource to calculate and
  32936. update the current selection.
  32937. - After the drag has finished and you get a mouseUp callback, you should call
  32938. endLasso() to clean up. This will make the lasso component invisible, and you
  32939. can remove it from the parent component, or delete it.
  32940. The class takes into account the modifier keys that are being held down while
  32941. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  32942. be added to the original selection; if ctrl or command is pressed, they will be
  32943. xor'ed with any previously selected items.
  32944. @see LassoSource, SelectedItemSet
  32945. */
  32946. template <class SelectableItemType>
  32947. class LassoComponent : public Component
  32948. {
  32949. public:
  32950. /** Creates a Lasso component.
  32951. The fill colour is used to fill the lasso'ed rectangle, and the outline
  32952. colour is used to draw a line around its edge.
  32953. */
  32954. LassoComponent (const int outlineThickness_ = 1)
  32955. : source (0),
  32956. outlineThickness (outlineThickness_)
  32957. {
  32958. }
  32959. /** Destructor. */
  32960. ~LassoComponent()
  32961. {
  32962. }
  32963. /** Call this in your mouseDown event, to initialise a drag.
  32964. Pass in a suitable LassoSource object which the lasso will use to find
  32965. the items and change the selection.
  32966. After using this method to initialise the lasso, repeatedly call dragLasso()
  32967. in your component's mouseDrag callback.
  32968. @see dragLasso, endLasso, LassoSource
  32969. */
  32970. void beginLasso (const MouseEvent& e,
  32971. LassoSource <SelectableItemType>* const lassoSource)
  32972. {
  32973. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  32974. jassert (lassoSource != 0); // the source can't be null!
  32975. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  32976. source = lassoSource;
  32977. if (lassoSource != 0)
  32978. originalSelection = lassoSource->getLassoSelection().getItemArray();
  32979. setSize (0, 0);
  32980. }
  32981. /** Call this in your mouseDrag event, to update the lasso's position.
  32982. This must be repeatedly calling when the mouse is dragged, after you've
  32983. first initialised the lasso with beginLasso().
  32984. This method takes into account the modifier keys that are being held down, so
  32985. if shift is pressed, then the lassoed items will be added to any that were
  32986. previously selected; if ctrl or command is pressed, then they will be xor'ed
  32987. with previously selected items.
  32988. @see beginLasso, endLasso
  32989. */
  32990. void dragLasso (const MouseEvent& e)
  32991. {
  32992. if (source != 0)
  32993. {
  32994. const int x1 = e.getMouseDownX();
  32995. const int y1 = e.getMouseDownY();
  32996. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  32997. setVisible (true);
  32998. Array <SelectableItemType> itemsInLasso;
  32999. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33000. if (e.mods.isShiftDown())
  33001. {
  33002. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33003. itemsInLasso.addArray (originalSelection);
  33004. }
  33005. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33006. {
  33007. Array <SelectableItemType> originalMinusNew (originalSelection);
  33008. originalMinusNew.removeValuesIn (itemsInLasso);
  33009. itemsInLasso.removeValuesIn (originalSelection);
  33010. itemsInLasso.addArray (originalMinusNew);
  33011. }
  33012. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33013. }
  33014. }
  33015. /** Call this in your mouseUp event, after the lasso has been dragged.
  33016. @see beginLasso, dragLasso
  33017. */
  33018. void endLasso()
  33019. {
  33020. source = 0;
  33021. originalSelection.clear();
  33022. setVisible (false);
  33023. }
  33024. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33025. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33026. methods.
  33027. Note that you can also use the constants from TextEditor::ColourIds to change the
  33028. colour of the text editor that is opened when a label is editable.
  33029. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33030. */
  33031. enum ColourIds
  33032. {
  33033. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  33034. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  33035. };
  33036. /** @internal */
  33037. void paint (Graphics& g)
  33038. {
  33039. g.fillAll (findColour (lassoFillColourId));
  33040. g.setColour (findColour (lassoOutlineColourId));
  33041. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33042. // this suggests that you've left a lasso comp lying around after the
  33043. // mouse drag has finished.. Be careful to call endLasso() when you get a
  33044. // mouse-up event.
  33045. jassert (isMouseButtonDownAnywhere());
  33046. }
  33047. /** @internal */
  33048. bool hitTest (int x, int y) { return false; }
  33049. juce_UseDebuggingNewOperator
  33050. private:
  33051. Array <SelectableItemType> originalSelection;
  33052. LassoSource <SelectableItemType>* source;
  33053. int outlineThickness;
  33054. };
  33055. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33056. /********* End of inlined file: juce_LassoComponent.h *********/
  33057. #endif
  33058. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  33059. #endif
  33060. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  33061. #endif
  33062. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33063. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  33064. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33065. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33066. /**
  33067. Monitors a component for mouse activity, and triggers a callback
  33068. when the mouse hovers in one place for a specified length of time.
  33069. To use a hover-detector, just create one and call its setHoverComponent()
  33070. method to start it watching a component. You can call setHoverComponent (0)
  33071. to make it inactive.
  33072. (Be careful not to delete a component that's being monitored without first
  33073. stopping or deleting the hover detector).
  33074. */
  33075. class JUCE_API MouseHoverDetector
  33076. {
  33077. public:
  33078. /** Creates a hover detector.
  33079. Initially the object is inactive, and you need to tell it which component
  33080. to monitor, using the setHoverComponent() method.
  33081. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  33082. needs to stay still before the mouseHovered() method
  33083. is invoked. You can change this setting later with
  33084. the setHoverTimeMillisecs() method
  33085. */
  33086. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  33087. /** Destructor. */
  33088. virtual ~MouseHoverDetector();
  33089. /** Changes the time for which the mouse has to stay still before it's considered
  33090. to be hovering.
  33091. */
  33092. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  33093. /** Changes the component that's being monitored for hovering.
  33094. Be careful not to delete a component that's being monitored without first
  33095. stopping or deleting the hover detector.
  33096. */
  33097. void setHoverComponent (Component* const newSourceComponent);
  33098. protected:
  33099. /** Called back when the mouse hovers.
  33100. After the mouse has stayed still over the component for the length of time
  33101. specified by setHoverTimeMillisecs(), this method will be invoked.
  33102. When the mouse is first moved after this callback has occurred, the
  33103. mouseMovedAfterHover() method will be called.
  33104. @param mouseX the mouse's X position relative to the component being monitored
  33105. @param mouseY the mouse's Y position relative to the component being monitored
  33106. */
  33107. virtual void mouseHovered (int mouseX,
  33108. int mouseY) = 0;
  33109. /** Called when the mouse is moved away after just having hovered. */
  33110. virtual void mouseMovedAfterHover() = 0;
  33111. private:
  33112. class JUCE_API HoverDetectorInternal : public MouseListener,
  33113. public Timer
  33114. {
  33115. public:
  33116. MouseHoverDetector* owner;
  33117. int lastX, lastY;
  33118. void timerCallback();
  33119. void mouseEnter (const MouseEvent&);
  33120. void mouseExit (const MouseEvent&);
  33121. void mouseDown (const MouseEvent&);
  33122. void mouseUp (const MouseEvent&);
  33123. void mouseMove (const MouseEvent&);
  33124. void mouseWheelMove (const MouseEvent&, float, float);
  33125. } internalTimer;
  33126. friend class HoverDetectorInternal;
  33127. Component* source;
  33128. int hoverTimeMillisecs;
  33129. bool hasJustHovered;
  33130. void hoverTimerCallback();
  33131. void checkJustHoveredCallback();
  33132. };
  33133. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33134. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33135. #endif
  33136. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33137. #endif
  33138. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33139. #endif
  33140. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33141. #endif
  33142. #ifndef __JUCE_LABEL_JUCEHEADER__
  33143. #endif
  33144. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33145. #endif
  33146. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33147. /********* Start of inlined file: juce_ProgressBar.h *********/
  33148. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33149. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33150. /**
  33151. A progress bar component.
  33152. To use this, just create one and make it visible. It'll run its own timer
  33153. to keep an eye on a variable that you give it, and will automatically
  33154. redraw itself when the variable changes.
  33155. For an easy way of running a background task with a dialog box showing its
  33156. progress, see the ThreadWithProgressWindow class.
  33157. @see ThreadWithProgressWindow
  33158. */
  33159. class JUCE_API ProgressBar : public Component,
  33160. public SettableTooltipClient,
  33161. private Timer
  33162. {
  33163. public:
  33164. /** Creates a ProgressBar.
  33165. @param progress pass in a reference to a double that you're going to
  33166. update with your task's progress. The ProgressBar will
  33167. monitor the value of this variable and will redraw itself
  33168. when the value changes. The range is from 0 to 1.0. Obviously
  33169. you'd better be careful not to delete this variable while the
  33170. ProgressBar still exists!
  33171. */
  33172. ProgressBar (double& progress);
  33173. /** Destructor. */
  33174. ~ProgressBar();
  33175. /** Turns the percentage display on or off.
  33176. By default this is on, and the progress bar will display a text string showing
  33177. its current percentage.
  33178. */
  33179. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33180. /** Gives the progress bar a string to display inside it.
  33181. If you call this, it will turn off the percentage display.
  33182. @see setPercentageDisplay
  33183. */
  33184. void setTextToDisplay (const String& text);
  33185. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33186. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33187. methods.
  33188. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33189. */
  33190. enum ColourIds
  33191. {
  33192. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33193. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33194. classes will probably use variations on this colour. */
  33195. };
  33196. juce_UseDebuggingNewOperator
  33197. protected:
  33198. /** @internal */
  33199. void paint (Graphics& g);
  33200. /** @internal */
  33201. void lookAndFeelChanged();
  33202. /** @internal */
  33203. void visibilityChanged();
  33204. /** @internal */
  33205. void colourChanged();
  33206. private:
  33207. double& progress;
  33208. double currentValue;
  33209. bool displayPercentage;
  33210. String displayedMessage, currentMessage;
  33211. void timerCallback();
  33212. ProgressBar (const ProgressBar&);
  33213. const ProgressBar& operator= (const ProgressBar&);
  33214. };
  33215. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33216. /********* End of inlined file: juce_ProgressBar.h *********/
  33217. #endif
  33218. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33219. /********* Start of inlined file: juce_Slider.h *********/
  33220. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33221. #define __JUCE_SLIDER_JUCEHEADER__
  33222. /********* Start of inlined file: juce_SliderListener.h *********/
  33223. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33224. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33225. class Slider;
  33226. /**
  33227. A class for receiving callbacks from a Slider.
  33228. To be told when a slider's value changes, you can register a SliderListener
  33229. object using Slider::addListener().
  33230. @see Slider::addListener, Slider::removeListener
  33231. */
  33232. class JUCE_API SliderListener
  33233. {
  33234. public:
  33235. /** Destructor. */
  33236. virtual ~SliderListener() {}
  33237. /** Called when the slider's value is changed.
  33238. This may be caused by dragging it, or by typing in its text entry box,
  33239. or by a call to Slider::setValue().
  33240. You can find out the new value using Slider::getValue().
  33241. @see Slider::valueChanged
  33242. */
  33243. virtual void sliderValueChanged (Slider* slider) = 0;
  33244. /** Called when the slider is about to be dragged.
  33245. This is called when a drag begins, then it's followed by multiple calls
  33246. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33247. user lets go.
  33248. @see sliderDragEnded, Slider::startedDragging
  33249. */
  33250. virtual void sliderDragStarted (Slider* slider);
  33251. /** Called after a drag operation has finished.
  33252. @see sliderDragStarted, Slider::stoppedDragging
  33253. */
  33254. virtual void sliderDragEnded (Slider* slider);
  33255. };
  33256. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33257. /********* End of inlined file: juce_SliderListener.h *********/
  33258. /**
  33259. A slider control for changing a value.
  33260. The slider can be horizontal, vertical, or rotary, and can optionally have
  33261. a text-box inside it to show an editable display of the current value.
  33262. To use it, create a Slider object and use the setSliderStyle() method
  33263. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33264. To define the values that it can be set to, see the setRange() and setValue() methods.
  33265. There are also lots of custom tweaks you can do by subclassing and overriding
  33266. some of the virtual methods, such as changing the scaling, changing the format of
  33267. the text display, custom ways of limiting the values, etc.
  33268. You can register SliderListeners with a slider, which will be informed when the value
  33269. changes, or a subclass can override valueChanged() to be informed synchronously.
  33270. @see SliderListener
  33271. */
  33272. class JUCE_API Slider : public Component,
  33273. public SettableTooltipClient,
  33274. private AsyncUpdater,
  33275. private ButtonListener,
  33276. private LabelListener
  33277. {
  33278. public:
  33279. /** Creates a slider.
  33280. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33281. setRange(), etc.
  33282. */
  33283. Slider (const String& componentName);
  33284. /** Destructor. */
  33285. ~Slider();
  33286. /** The types of slider available.
  33287. @see setSliderStyle, setRotaryParameters
  33288. */
  33289. enum SliderStyle
  33290. {
  33291. LinearHorizontal, /**< A traditional horizontal slider. */
  33292. LinearVertical, /**< A traditional vertical slider. */
  33293. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33294. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33295. @see setRotaryParameters */
  33296. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33297. @see setRotaryParameters */
  33298. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33299. @see setRotaryParameters */
  33300. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33301. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33302. @see setMinValue, setMaxValue */
  33303. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33304. @see setMinValue, setMaxValue */
  33305. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33306. value, with the current value being somewhere between them.
  33307. @see setMinValue, setMaxValue */
  33308. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33309. value, with the current value being somewhere between them.
  33310. @see setMinValue, setMaxValue */
  33311. };
  33312. /** Changes the type of slider interface being used.
  33313. @param newStyle the type of interface
  33314. @see setRotaryParameters, setVelocityBasedMode,
  33315. */
  33316. void setSliderStyle (const SliderStyle newStyle);
  33317. /** Returns the slider's current style.
  33318. @see setSliderStyle
  33319. */
  33320. SliderStyle getSliderStyle() const throw() { return style; }
  33321. /** Changes the properties of a rotary slider.
  33322. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33323. the slider's minimum value is represented
  33324. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33325. the slider's maximum value is represented. This must be
  33326. greater than startAngleRadians
  33327. @param stopAtEnd if true, then when the slider is dragged around past the
  33328. minimum or maximum, it'll stop there; if false, it'll wrap
  33329. back to the opposite value
  33330. */
  33331. void setRotaryParameters (const float startAngleRadians,
  33332. const float endAngleRadians,
  33333. const bool stopAtEnd);
  33334. /** Sets the distance the mouse has to move to drag the slider across
  33335. the full extent of its range.
  33336. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33337. relative mouse movements to adjust the slider.
  33338. */
  33339. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33340. /** Changes the way the the mouse is used when dragging the slider.
  33341. If true, this will turn on velocity-sensitive dragging, so that
  33342. the faster the mouse moves, the bigger the movement to the slider. This
  33343. helps when making accurate adjustments if the slider's range is quite large.
  33344. If false, the slider will just try to snap to wherever the mouse is.
  33345. */
  33346. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33347. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33348. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33349. or if you're holding down ctrl.
  33350. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33351. @param threshold the minimum number of pixels that the mouse needs to move for it
  33352. to be treated as a movement
  33353. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33354. the threshold is reached
  33355. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33356. key to toggle velocity-sensitive mode
  33357. */
  33358. void setVelocityModeParameters (const double sensitivity = 1.0,
  33359. const int threshold = 1,
  33360. const double offset = 0.0,
  33361. const bool userCanPressKeyToSwapMode = true) throw();
  33362. /** Sets up a skew factor to alter the way values are distributed.
  33363. You may want to use a range of values on the slider where more accuracy
  33364. is required towards one end of the range, so this will logarithmically
  33365. spread the values across the length of the slider.
  33366. If the factor is < 1.0, the lower end of the range will fill more of the
  33367. slider's length; if the factor is > 1.0, the upper end of the range
  33368. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33369. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33370. method instead.
  33371. @see getSkewFactor, setSkewFactorFromMidPoint
  33372. */
  33373. void setSkewFactor (const double factor) throw();
  33374. /** Sets up a skew factor to alter the way values are distributed.
  33375. This allows you to specify the slider value that should appear in the
  33376. centre of the slider's visible range.
  33377. @see setSkewFactor, getSkewFactor
  33378. */
  33379. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33380. /** Returns the current skew factor.
  33381. See setSkewFactor for more info.
  33382. @see setSkewFactor, setSkewFactorFromMidPoint
  33383. */
  33384. double getSkewFactor() const throw() { return skewFactor; }
  33385. /** Used by setIncDecButtonsMode().
  33386. */
  33387. enum IncDecButtonMode
  33388. {
  33389. incDecButtonsNotDraggable,
  33390. incDecButtonsDraggable_AutoDirection,
  33391. incDecButtonsDraggable_Horizontal,
  33392. incDecButtonsDraggable_Vertical
  33393. };
  33394. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33395. can be dragged on the buttons to drag the values.
  33396. By default this is turned off. When enabled, clicking on the buttons still works
  33397. them as normal, but by holding down the mouse on a button and dragging it a little
  33398. distance, it flips into a mode where the value can be dragged. The drag direction can
  33399. either be set explicitly to be vertical or horizontal, or can be set to
  33400. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33401. are side-by-side or above each other.
  33402. */
  33403. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33404. /** The position of the slider's text-entry box.
  33405. @see setTextBoxStyle
  33406. */
  33407. enum TextEntryBoxPosition
  33408. {
  33409. NoTextBox, /**< Doesn't display a text box. */
  33410. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33411. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33412. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33413. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33414. };
  33415. /** Changes the location and properties of the text-entry box.
  33416. @param newPosition where it should go (or NoTextBox to not have one at all)
  33417. @param isReadOnly if true, it's a read-only display
  33418. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33419. room for the slider as well!
  33420. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33421. room for the slider as well!
  33422. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33423. */
  33424. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33425. const bool isReadOnly,
  33426. const int textEntryBoxWidth,
  33427. const int textEntryBoxHeight);
  33428. /** Returns the status of the text-box.
  33429. @see setTextBoxStyle
  33430. */
  33431. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33432. /** Returns the width used for the text-box.
  33433. @see setTextBoxStyle
  33434. */
  33435. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33436. /** Returns the height used for the text-box.
  33437. @see setTextBoxStyle
  33438. */
  33439. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33440. /** Makes the text-box editable.
  33441. By default this is true, and the user can enter values into the textbox,
  33442. but it can be turned off if that's not suitable.
  33443. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33444. */
  33445. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33446. /** Returns true if the text-box is read-only.
  33447. @see setTextBoxStyle
  33448. */
  33449. bool isTextBoxEditable() const throw() { return editableText; }
  33450. /** If the text-box is editable, this will give it the focus so that the user can
  33451. type directly into it.
  33452. This is basically the effect as the user clicking on it.
  33453. */
  33454. void showTextBox();
  33455. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33456. focus away from it.
  33457. @param discardCurrentEditorContents if true, the slider's value will be left
  33458. unchanged; if false, the current contents of the
  33459. text editor will be used to set the slider position
  33460. before it is hidden.
  33461. */
  33462. void hideTextBox (const bool discardCurrentEditorContents);
  33463. /** Changes the slider's current value.
  33464. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33465. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33466. want to handle it.
  33467. @param newValue the new value to set - this will be restricted by the
  33468. minimum and maximum range, and will be snapped to the
  33469. nearest interval if one has been set
  33470. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33471. any SliderListeners or the valueChanged() method
  33472. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33473. synchronously; if false, it will be asynchronous
  33474. */
  33475. void setValue (double newValue,
  33476. const bool sendUpdateMessage = true,
  33477. const bool sendMessageSynchronously = false);
  33478. /** Returns the slider's current value. */
  33479. double getValue() const throw();
  33480. /** Sets the limits that the slider's value can take.
  33481. @param newMinimum the lowest value allowed
  33482. @param newMaximum the highest value allowed
  33483. @param newInterval the steps in which the value is allowed to increase - if this
  33484. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33485. */
  33486. void setRange (const double newMinimum,
  33487. const double newMaximum,
  33488. const double newInterval = 0);
  33489. /** Returns the current maximum value.
  33490. @see setRange
  33491. */
  33492. double getMaximum() const throw() { return maximum; }
  33493. /** Returns the current minimum value.
  33494. @see setRange
  33495. */
  33496. double getMinimum() const throw() { return minimum; }
  33497. /** Returns the current step-size for values.
  33498. @see setRange
  33499. */
  33500. double getInterval() const throw() { return interval; }
  33501. /** For a slider with two or three thumbs, this returns the lower of its values.
  33502. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33503. A slider with three values also uses the normal getValue() and setValue() methods to
  33504. control the middle value.
  33505. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33506. */
  33507. double getMinValue() const throw();
  33508. /** For a slider with two or three thumbs, this sets the lower of its values.
  33509. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33510. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33511. want to handle it.
  33512. @param newValue the new value to set - this will be restricted by the
  33513. minimum and maximum range, and the max value (in a two-value
  33514. slider) or the mid value (in a three-value slider), and
  33515. will be snapped to the nearest interval if one has been set.
  33516. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33517. any SliderListeners or the valueChanged() method
  33518. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33519. synchronously; if false, it will be asynchronous
  33520. @see getMinValue, setMaxValue, setValue
  33521. */
  33522. void setMinValue (double newValue,
  33523. const bool sendUpdateMessage = true,
  33524. const bool sendMessageSynchronously = false);
  33525. /** For a slider with two or three thumbs, this returns the higher of its values.
  33526. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33527. A slider with three values also uses the normal getValue() and setValue() methods to
  33528. control the middle value.
  33529. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33530. */
  33531. double getMaxValue() const throw();
  33532. /** For a slider with two or three thumbs, this sets the lower of its values.
  33533. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33534. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33535. want to handle it.
  33536. @param newValue the new value to set - this will be restricted by the
  33537. minimum and maximum range, and the max value (in a two-value
  33538. slider) or the mid value (in a three-value slider), and
  33539. will be snapped to the nearest interval if one has been set.
  33540. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33541. any SliderListeners or the valueChanged() method
  33542. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33543. synchronously; if false, it will be asynchronous
  33544. @see getMaxValue, setMinValue, setValue
  33545. */
  33546. void setMaxValue (double newValue,
  33547. const bool sendUpdateMessage = true,
  33548. const bool sendMessageSynchronously = false);
  33549. /** Adds a listener to be called when this slider's value changes. */
  33550. void addListener (SliderListener* const listener) throw();
  33551. /** Removes a previously-registered listener. */
  33552. void removeListener (SliderListener* const listener) throw();
  33553. /** This lets you choose whether double-clicking moves the slider to a given position.
  33554. By default this is turned off, but it's handy if you want a double-click to act
  33555. as a quick way of resetting a slider. Just pass in the value you want it to
  33556. go to when double-clicked.
  33557. @see getDoubleClickReturnValue
  33558. */
  33559. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  33560. const double valueToSetOnDoubleClick) throw();
  33561. /** Returns the values last set by setDoubleClickReturnValue() method.
  33562. Sets isEnabled to true if double-click is enabled, and returns the value
  33563. that was set.
  33564. @see setDoubleClickReturnValue
  33565. */
  33566. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  33567. /** Tells the slider whether to keep sending change messages while the user
  33568. is dragging the slider.
  33569. If set to true, a change message will only be sent when the user has
  33570. dragged the slider and let go. If set to false (the default), then messages
  33571. will be continuously sent as they drag it while the mouse button is still
  33572. held down.
  33573. */
  33574. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  33575. /** This lets you change whether the slider thumb jumps to the mouse position
  33576. when you click.
  33577. By default, this is true. If it's false, then the slider moves with relative
  33578. motion when you drag it.
  33579. This only applies to linear bars, and won't affect two- or three- value
  33580. sliders.
  33581. */
  33582. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  33583. /** If enabled, this gives the slider a pop-up bubble which appears while the
  33584. slider is being dragged.
  33585. This can be handy if your slider doesn't have a text-box, so that users can
  33586. see the value just when they're changing it.
  33587. If you pass a component as the parentComponentToUse parameter, the pop-up
  33588. bubble will be added as a child of that component when it's needed. If you
  33589. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  33590. transparent window, so if you're using an OS that can't do transparent windows
  33591. you'll have to add it to a parent component instead).
  33592. */
  33593. void setPopupDisplayEnabled (const bool isEnabled,
  33594. Component* const parentComponentToUse) throw();
  33595. /** If this is set to true, then right-clicking on the slider will pop-up
  33596. a menu to let the user change the way it works.
  33597. By default this is turned off, but when turned on, the menu will include
  33598. things like velocity sensitivity, and for rotary sliders, whether they
  33599. use a linear or rotary mouse-drag to move them.
  33600. */
  33601. void setPopupMenuEnabled (const bool menuEnabled) throw();
  33602. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  33603. By default it's enabled.
  33604. */
  33605. void setScrollWheelEnabled (const bool enabled) throw();
  33606. /** Returns a number to indicate which thumb is currently being dragged by the
  33607. mouse.
  33608. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  33609. the maximum-value thumb, or -1 if none is currently down.
  33610. */
  33611. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  33612. /** Callback to indicate that the user is about to start dragging the slider.
  33613. @see SliderListener::sliderDragStarted
  33614. */
  33615. virtual void startedDragging();
  33616. /** Callback to indicate that the user has just stopped dragging the slider.
  33617. @see SliderListener::sliderDragEnded
  33618. */
  33619. virtual void stoppedDragging();
  33620. /** Callback to indicate that the user has just moved the slider.
  33621. @see SliderListener::sliderValueChanged
  33622. */
  33623. virtual void valueChanged();
  33624. /** Callback to indicate that the user has just moved the slider.
  33625. Note - the valueChanged() method has changed its format and now no longer has
  33626. any parameters. Update your code to use the new version.
  33627. This version has been left here with an int as its return value to cause
  33628. a syntax error if you've got existing code that uses the old version.
  33629. */
  33630. virtual int valueChanged (double) { jassertfalse; return 0; }
  33631. /** Subclasses can override this to convert a text string to a value.
  33632. When the user enters something into the text-entry box, this method is
  33633. called to convert it to a value.
  33634. The default routine just tries to convert it to a double.
  33635. @see getTextFromValue
  33636. */
  33637. virtual double getValueFromText (const String& text);
  33638. /** Turns the slider's current value into a text string.
  33639. Subclasses can override this to customise the formatting of the text-entry box.
  33640. The default implementation just turns the value into a string, using
  33641. a number of decimal places based on the range interval. If a suffix string
  33642. has been set using setTextValueSuffix(), this will be appended to the text.
  33643. @see getValueFromText
  33644. */
  33645. virtual const String getTextFromValue (double value);
  33646. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  33647. a string.
  33648. This is used by the default implementation of getTextFromValue(), and is just
  33649. appended to the numeric value. For more advanced formatting, you can override
  33650. getTextFromValue() and do something else.
  33651. */
  33652. void setTextValueSuffix (const String& suffix);
  33653. /** Allows a user-defined mapping of distance along the slider to its value.
  33654. The default implementation for this performs the skewing operation that
  33655. can be set up in the setSkewFactor() method. Override it if you need
  33656. some kind of custom mapping instead, but make sure you also implement the
  33657. inverse function in valueToProportionOfLength().
  33658. @param proportion a value 0 to 1.0, indicating a distance along the slider
  33659. @returns the slider value that is represented by this position
  33660. @see valueToProportionOfLength
  33661. */
  33662. virtual double proportionOfLengthToValue (double proportion);
  33663. /** Allows a user-defined mapping of value to the position of the slider along its length.
  33664. The default implementation for this performs the skewing operation that
  33665. can be set up in the setSkewFactor() method. Override it if you need
  33666. some kind of custom mapping instead, but make sure you also implement the
  33667. inverse function in proportionOfLengthToValue().
  33668. @param value a valid slider value, between the range of values specified in
  33669. setRange()
  33670. @returns a value 0 to 1.0 indicating the distance along the slider that
  33671. represents this value
  33672. @see proportionOfLengthToValue
  33673. */
  33674. virtual double valueToProportionOfLength (double value);
  33675. /** Returns the X or Y coordinate of a value along the slider's length.
  33676. If the slider is horizontal, this will be the X coordinate of the given
  33677. value, relative to the left of the slider. If it's vertical, then this will
  33678. be the Y coordinate, relative to the top of the slider.
  33679. If the slider is rotary, this will throw an assertion and return 0. If the
  33680. value is out-of-range, it will be constrained to the length of the slider.
  33681. */
  33682. float getPositionOfValue (const double value);
  33683. /** This can be overridden to allow the slider to snap to user-definable values.
  33684. If overridden, it will be called when the user tries to move the slider to
  33685. a given position, and allows a subclass to sanity-check this value, possibly
  33686. returning a different value to use instead.
  33687. @param attemptedValue the value the user is trying to enter
  33688. @param userIsDragging true if the user is dragging with the mouse; false if
  33689. they are entering the value using the text box
  33690. @returns the value to use instead
  33691. */
  33692. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  33693. /** This can be called to force the text box to update its contents.
  33694. (Not normally needed, as this is done automatically).
  33695. */
  33696. void updateText();
  33697. /** True if the slider moves horizontally. */
  33698. bool isHorizontal() const throw();
  33699. /** True if the slider moves vertically. */
  33700. bool isVertical() const throw();
  33701. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  33702. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33703. methods.
  33704. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33705. */
  33706. enum ColourIds
  33707. {
  33708. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  33709. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  33710. and feel class how this is used. */
  33711. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  33712. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  33713. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  33714. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  33715. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  33716. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  33717. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  33718. };
  33719. juce_UseDebuggingNewOperator
  33720. protected:
  33721. /** @internal */
  33722. void labelTextChanged (Label*);
  33723. /** @internal */
  33724. void paint (Graphics& g);
  33725. /** @internal */
  33726. void resized();
  33727. /** @internal */
  33728. void mouseDown (const MouseEvent& e);
  33729. /** @internal */
  33730. void mouseUp (const MouseEvent& e);
  33731. /** @internal */
  33732. void mouseDrag (const MouseEvent& e);
  33733. /** @internal */
  33734. void mouseDoubleClick (const MouseEvent& e);
  33735. /** @internal */
  33736. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33737. /** @internal */
  33738. void modifierKeysChanged (const ModifierKeys& modifiers);
  33739. /** @internal */
  33740. void buttonClicked (Button* button);
  33741. /** @internal */
  33742. void lookAndFeelChanged();
  33743. /** @internal */
  33744. void enablementChanged();
  33745. /** @internal */
  33746. void focusOfChildComponentChanged (FocusChangeType cause);
  33747. /** @internal */
  33748. void handleAsyncUpdate();
  33749. /** @internal */
  33750. void colourChanged();
  33751. private:
  33752. SortedSet <void*> listeners;
  33753. double currentValue, valueMin, valueMax;
  33754. double minimum, maximum, interval, doubleClickReturnValue;
  33755. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  33756. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  33757. int velocityModeThreshold;
  33758. float rotaryStart, rotaryEnd;
  33759. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  33760. int sliderRegionStart, sliderRegionSize;
  33761. int sliderBeingDragged;
  33762. int pixelsForFullDragExtent;
  33763. Rectangle sliderRect;
  33764. String textSuffix;
  33765. SliderStyle style;
  33766. TextEntryBoxPosition textBoxPos;
  33767. int textBoxWidth, textBoxHeight;
  33768. IncDecButtonMode incDecButtonMode;
  33769. bool editableText : 1, doubleClickToValue : 1;
  33770. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  33771. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  33772. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  33773. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  33774. Font font;
  33775. Label* valueBox;
  33776. Button* incButton;
  33777. Button* decButton;
  33778. Component* popupDisplay;
  33779. Component* parentForPopupDisplay;
  33780. float getLinearSliderPos (const double value);
  33781. void restoreMouseIfHidden();
  33782. void sendDragStart();
  33783. void sendDragEnd();
  33784. double constrainedValue (double value) const throw();
  33785. void triggerChangeMessage (const bool synchronous);
  33786. bool incDecDragDirectionIsHorizontal() const throw();
  33787. Slider (const Slider&);
  33788. const Slider& operator= (const Slider&);
  33789. };
  33790. #endif // __JUCE_SLIDER_JUCEHEADER__
  33791. /********* End of inlined file: juce_Slider.h *********/
  33792. #endif
  33793. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33794. #endif
  33795. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33796. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  33797. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33798. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33799. class TableHeaderComponent;
  33800. /**
  33801. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  33802. You can register one of these objects for table events using TableHeaderComponent::addListener()
  33803. and TableHeaderComponent::removeListener().
  33804. @see TableHeaderComponent
  33805. */
  33806. class JUCE_API TableHeaderListener
  33807. {
  33808. public:
  33809. TableHeaderListener() {}
  33810. /** Destructor. */
  33811. virtual ~TableHeaderListener() {}
  33812. /** This is called when some of the table's columns are added, removed, hidden,
  33813. or rearranged.
  33814. */
  33815. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  33816. /** This is called when one or more of the table's columns are resized.
  33817. */
  33818. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  33819. /** This is called when the column by which the table should be sorted is changed.
  33820. */
  33821. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  33822. /** This is called when the user begins or ends dragging one of the columns around.
  33823. When the user starts dragging a column, this is called with the ID of that
  33824. column. When they finish dragging, it is called again with 0 as the ID.
  33825. */
  33826. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  33827. int columnIdNowBeingDragged);
  33828. };
  33829. /**
  33830. A component that displays a strip of column headings for a table, and allows these
  33831. to be resized, dragged around, etc.
  33832. This is just the component that goes at the top of a table. You can use it
  33833. directly for custom components, or to create a simple table, use the
  33834. TableListBox class.
  33835. To use one of these, create it and use addColumn() to add all the columns that you need.
  33836. Each column must be given a unique ID number that's used to refer to it.
  33837. @see TableListBox, TableHeaderListener
  33838. */
  33839. class JUCE_API TableHeaderComponent : public Component,
  33840. private AsyncUpdater
  33841. {
  33842. public:
  33843. /** Creates an empty table header.
  33844. */
  33845. TableHeaderComponent();
  33846. /** Destructor. */
  33847. ~TableHeaderComponent();
  33848. /** A combination of these flags are passed into the addColumn() method to specify
  33849. the properties of a column.
  33850. */
  33851. enum ColumnPropertyFlags
  33852. {
  33853. 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. */
  33854. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  33855. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  33856. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  33857. 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. */
  33858. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  33859. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  33860. /** This set of default flags is used as the default parameter value in addColumn(). */
  33861. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  33862. /** A quick way of combining flags for a column that's not resizable. */
  33863. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  33864. /** A quick way of combining flags for a column that's not resizable or sortable. */
  33865. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  33866. /** A quick way of combining flags for a column that's not sortable. */
  33867. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  33868. };
  33869. /** Adds a column to the table.
  33870. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  33871. registered listeners.
  33872. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  33873. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  33874. a unique ID. This is used to identify the column later on, after the user may have
  33875. changed the order that they appear in
  33876. @param width the initial width of the column, in pixels
  33877. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  33878. if the 'resizable' flag is specified for this column
  33879. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  33880. if the 'resizable' flag is specified for this column
  33881. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  33882. properties of this column
  33883. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  33884. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  33885. all columns, not just the index amongst those that are currently visible
  33886. */
  33887. void addColumn (const String& columnName,
  33888. const int columnId,
  33889. const int width,
  33890. const int minimumWidth = 30,
  33891. const int maximumWidth = -1,
  33892. const int propertyFlags = defaultFlags,
  33893. const int insertIndex = -1);
  33894. /** Removes a column with the given ID.
  33895. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  33896. registered listeners.
  33897. */
  33898. void removeColumn (const int columnIdToRemove);
  33899. /** Deletes all columns from the table.
  33900. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  33901. registered listeners.
  33902. */
  33903. void removeAllColumns();
  33904. /** Returns the number of columns in the table.
  33905. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  33906. return the total number of columns, including hidden ones.
  33907. @see isColumnVisible
  33908. */
  33909. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  33910. /** Returns the name for a column.
  33911. @see setColumnName
  33912. */
  33913. const String getColumnName (const int columnId) const throw();
  33914. /** Changes the name of a column. */
  33915. void setColumnName (const int columnId, const String& newName);
  33916. /** Moves a column to a different index in the table.
  33917. @param columnId the column to move
  33918. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  33919. */
  33920. void moveColumn (const int columnId, int newVisibleIndex);
  33921. /** Changes the width of a column.
  33922. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  33923. */
  33924. void setColumnWidth (const int columnId, const int newWidth);
  33925. /** Shows or hides a column.
  33926. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  33927. @see isColumnVisible
  33928. */
  33929. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  33930. /** Returns true if this column is currently visible.
  33931. @see setColumnVisible
  33932. */
  33933. bool isColumnVisible (const int columnId) const;
  33934. /** Changes the column which is the sort column.
  33935. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  33936. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  33937. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  33938. @see getSortColumnId, isSortedForwards, reSortTable
  33939. */
  33940. void setSortColumnId (const int columnId, const bool sortForwards);
  33941. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  33942. @see setSortColumnId, isSortedForwards
  33943. */
  33944. int getSortColumnId() const throw();
  33945. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  33946. @see setSortColumnId
  33947. */
  33948. bool isSortedForwards() const throw();
  33949. /** Triggers a re-sort of the table according to the current sort-column.
  33950. If you modifiy the table's contents, you can call this to signal that the table needs
  33951. to be re-sorted.
  33952. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  33953. tableSortOrderChanged() method of any listeners).
  33954. */
  33955. void reSortTable();
  33956. /** Returns the total width of all the visible columns in the table.
  33957. */
  33958. int getTotalWidth() const throw();
  33959. /** Returns the index of a given column.
  33960. If there's no such column ID, this will return -1.
  33961. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  33962. otherwise it'll return the index amongst all the columns, including any hidden ones.
  33963. */
  33964. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  33965. /** Returns the ID of the column at a given index.
  33966. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  33967. otherwise it'll count it amongst all the columns, including any hidden ones.
  33968. If the index is out-of-range, it'll return 0.
  33969. */
  33970. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  33971. /** Returns the rectangle containing of one of the columns.
  33972. The index is an index from 0 to the number of columns that are currently visible (hidden
  33973. ones are not counted). It returns a rectangle showing the position of the column relative
  33974. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  33975. */
  33976. const Rectangle getColumnPosition (const int index) const throw();
  33977. /** Finds the column ID at a given x-position in the component.
  33978. If there is a column at this point this returns its ID, or if not, it will return 0.
  33979. */
  33980. int getColumnIdAtX (const int xToFind) const throw();
  33981. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  33982. entire width of the component.
  33983. By default this is disabled. Turning it on also means that when resizing a column, those
  33984. on the right will be squashed to fit.
  33985. */
  33986. void setStretchToFitActive (const bool shouldStretchToFit);
  33987. /** Returns true if stretch-to-fit has been enabled.
  33988. @see setStretchToFitActive
  33989. */
  33990. bool isStretchToFitActive() const throw();
  33991. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  33992. specified width, keeping their relative proportions the same.
  33993. If the minimum widths of the columns are too wide to fit into this space, it may
  33994. actually end up wider.
  33995. */
  33996. void resizeAllColumnsToFit (int targetTotalWidth);
  33997. /** Enables or disables the pop-up menu.
  33998. The default menu allows the user to show or hide columns. You can add custom
  33999. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34000. By default the menu is enabled.
  34001. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34002. */
  34003. void setPopupMenuActive (const bool hasMenu);
  34004. /** Returns true if the pop-up menu is enabled.
  34005. @see setPopupMenuActive
  34006. */
  34007. bool isPopupMenuActive() const throw();
  34008. /** Returns a string that encapsulates the table's current layout.
  34009. This can be restored later using restoreFromString(). It saves the order of
  34010. the columns, the currently-sorted column, and the widths.
  34011. @see restoreFromString
  34012. */
  34013. const String toString() const;
  34014. /** Restores the state of the table, based on a string previously created with
  34015. toString().
  34016. @see toString
  34017. */
  34018. void restoreFromString (const String& storedVersion);
  34019. /** Adds a listener to be informed about things that happen to the header. */
  34020. void addListener (TableHeaderListener* const newListener) throw();
  34021. /** Removes a previously-registered listener. */
  34022. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34023. /** This can be overridden to handle a mouse-click on one of the column headers.
  34024. The default implementation will use this click to call getSortColumnId() and
  34025. change the sort order.
  34026. */
  34027. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34028. /** This can be overridden to add custom items to the pop-up menu.
  34029. If you override this, you should call the superclass's method to add its
  34030. column show/hide items, if you want them on the menu as well.
  34031. Then to handle the result, override reactToMenuItem().
  34032. @see reactToMenuItem
  34033. */
  34034. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  34035. /** Override this to handle any custom items that you have added to the
  34036. pop-up menu with an addMenuItems() override.
  34037. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34038. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34039. handle the items that it had added.
  34040. @see addMenuItems
  34041. */
  34042. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  34043. /** @internal */
  34044. void paint (Graphics& g);
  34045. /** @internal */
  34046. void resized();
  34047. /** @internal */
  34048. void mouseMove (const MouseEvent&);
  34049. /** @internal */
  34050. void mouseEnter (const MouseEvent&);
  34051. /** @internal */
  34052. void mouseExit (const MouseEvent&);
  34053. /** @internal */
  34054. void mouseDown (const MouseEvent&);
  34055. /** @internal */
  34056. void mouseDrag (const MouseEvent&);
  34057. /** @internal */
  34058. void mouseUp (const MouseEvent&);
  34059. /** @internal */
  34060. const MouseCursor getMouseCursor();
  34061. juce_UseDebuggingNewOperator
  34062. private:
  34063. struct ColumnInfo
  34064. {
  34065. String name;
  34066. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34067. double lastDeliberateWidth;
  34068. bool isVisible() const throw();
  34069. };
  34070. OwnedArray <ColumnInfo> columns;
  34071. Array <TableHeaderListener*> listeners;
  34072. Component* dragOverlayComp;
  34073. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34074. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34075. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34076. ColumnInfo* getInfoForId (const int columnId) const throw();
  34077. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  34078. void sendColumnsChanged();
  34079. void handleAsyncUpdate();
  34080. void beginDrag (const MouseEvent&);
  34081. void endDrag (const int finalIndex);
  34082. int getResizeDraggerAt (const int mouseX) const throw();
  34083. void updateColumnUnderMouse (int x, int y);
  34084. void showColumnChooserMenu (const int);
  34085. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34086. TableHeaderComponent (const TableHeaderComponent&);
  34087. const TableHeaderComponent operator= (const TableHeaderComponent&);
  34088. };
  34089. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34090. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  34091. #endif
  34092. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34093. /********* Start of inlined file: juce_TableListBox.h *********/
  34094. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34095. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34096. /**
  34097. One of these is used by a TableListBox as the data model for the table's contents.
  34098. The virtual methods that you override in this class take care of drawing the
  34099. table cells, and reacting to events.
  34100. @see TableListBox
  34101. */
  34102. class JUCE_API TableListBoxModel
  34103. {
  34104. public:
  34105. TableListBoxModel() {}
  34106. /** Destructor. */
  34107. virtual ~TableListBoxModel() {}
  34108. /** This must return the number of rows currently in the table.
  34109. If the number of rows changes, you must call TableListBox::updateContent() to
  34110. cause it to refresh the list.
  34111. */
  34112. virtual int getNumRows() = 0;
  34113. /** This must draw the background behind one of the rows in the table.
  34114. The graphics context has its origin at the row's top-left, and your method
  34115. should fill the area specified by the width and height parameters.
  34116. */
  34117. virtual void paintRowBackground (Graphics& g,
  34118. int rowNumber,
  34119. int width, int height,
  34120. bool rowIsSelected) = 0;
  34121. /** This must draw one of the cells.
  34122. The graphics context's origin will already be set to the top-left of the cell,
  34123. whose size is specified by (width, height).
  34124. */
  34125. virtual void paintCell (Graphics& g,
  34126. int rowNumber,
  34127. int columnId,
  34128. int width, int height,
  34129. bool rowIsSelected) = 0;
  34130. /** This is used to create or update a custom component to go in a cell.
  34131. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34132. and handle mouse clicks with cellClicked().
  34133. This method will be called whenever a custom component might need to be updated - e.g.
  34134. when the table is changed, or TableListBox::updateContent() is called.
  34135. If you don't need a custom component for the specified cell, then return 0.
  34136. If you do want a custom component, and the existingComponentToUpdate is null, then
  34137. this method must create a new component suitable for the cell, and return it.
  34138. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34139. by this method. In this case, the method must either update it to make sure it's correctly representing
  34140. the given cell (which may be different from the one that the component was created for), or it can
  34141. delete this component and return a new one.
  34142. */
  34143. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34144. Component* existingComponentToUpdate);
  34145. /** This callback is made when the user clicks on one of the cells in the table.
  34146. The mouse event's coordinates will be relative to the entire table row.
  34147. @see cellDoubleClicked, backgroundClicked
  34148. */
  34149. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34150. /** This callback is made when the user clicks on one of the cells in the table.
  34151. The mouse event's coordinates will be relative to the entire table row.
  34152. @see cellClicked, backgroundClicked
  34153. */
  34154. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34155. /** This can be overridden to react to the user double-clicking on a part of the list where
  34156. there are no rows.
  34157. @see cellClicked
  34158. */
  34159. virtual void backgroundClicked();
  34160. /** This callback is made when the table's sort order is changed.
  34161. This could be because the user has clicked a column header, or because the
  34162. TableHeaderComponent::setSortColumnId() method was called.
  34163. If you implement this, your method should re-sort the table using the given
  34164. column as the key.
  34165. */
  34166. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34167. /** Returns the best width for one of the columns.
  34168. If you implement this method, you should measure the width of all the items
  34169. in this column, and return the best size.
  34170. Returning 0 means that the column shouldn't be changed.
  34171. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34172. */
  34173. virtual int getColumnAutoSizeWidth (int columnId);
  34174. /** Override this to be informed when rows are selected or deselected.
  34175. @see ListBox::selectedRowsChanged()
  34176. */
  34177. virtual void selectedRowsChanged (int lastRowSelected);
  34178. /** Override this to be informed when the delete key is pressed.
  34179. @see ListBox::deleteKeyPressed()
  34180. */
  34181. virtual void deleteKeyPressed (int lastRowSelected);
  34182. /** Override this to be informed when the return key is pressed.
  34183. @see ListBox::returnKeyPressed()
  34184. */
  34185. virtual void returnKeyPressed (int lastRowSelected);
  34186. /** Override this to be informed when the list is scrolled.
  34187. This might be caused by the user moving the scrollbar, or by programmatic changes
  34188. to the list position.
  34189. */
  34190. virtual void listWasScrolled();
  34191. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34192. If this returns a non-empty name then when the user drags a row, the table will try to
  34193. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34194. drag-and-drop operation, using this string as the source description, and the listbox
  34195. itself as the source component.
  34196. @see DragAndDropContainer::startDragging
  34197. */
  34198. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34199. };
  34200. /**
  34201. A table of cells, using a TableHeaderComponent as its header.
  34202. This component makes it easy to create a table by providing a TableListBoxModel as
  34203. the data source.
  34204. @see TableListBoxModel, TableHeaderComponent
  34205. */
  34206. class JUCE_API TableListBox : public ListBox,
  34207. private ListBoxModel,
  34208. private TableHeaderListener
  34209. {
  34210. public:
  34211. /** Creates a TableListBox.
  34212. The model pointer passed-in can be null, in which case you can set it later
  34213. with setModel().
  34214. */
  34215. TableListBox (const String& componentName,
  34216. TableListBoxModel* const model);
  34217. /** Destructor. */
  34218. ~TableListBox();
  34219. /** Changes the TableListBoxModel that is being used for this table.
  34220. */
  34221. void setModel (TableListBoxModel* const newModel);
  34222. /** Returns the model currently in use. */
  34223. TableListBoxModel* getModel() const throw() { return model; }
  34224. /** Returns the header component being used in this table. */
  34225. TableHeaderComponent* getHeader() const throw() { return header; }
  34226. /** Changes the height of the table header component.
  34227. @see getHeaderHeight
  34228. */
  34229. void setHeaderHeight (const int newHeight);
  34230. /** Returns the height of the table header.
  34231. @see setHeaderHeight
  34232. */
  34233. int getHeaderHeight() const throw();
  34234. /** Resizes a column to fit its contents.
  34235. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34236. and applies that to the column.
  34237. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34238. */
  34239. void autoSizeColumn (const int columnId);
  34240. /** Calls autoSizeColumn() for all columns in the table. */
  34241. void autoSizeAllColumns();
  34242. /** Enables or disables the auto size options on the popup menu.
  34243. By default, these are enabled.
  34244. */
  34245. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34246. /** True if the auto-size options should be shown on the menu.
  34247. @see setAutoSizeMenuOptionsShown
  34248. */
  34249. bool isAutoSizeMenuOptionShown() const throw();
  34250. /** Returns the position of one of the cells in the table.
  34251. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34252. the table component's top-left. The row number isn't checked to see if it's
  34253. in-range, but the column ID must exist or this will return an empty rectangle.
  34254. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34255. top-left of the table's top-left cell.
  34256. */
  34257. const Rectangle getCellPosition (const int columnId,
  34258. const int rowNumber,
  34259. const bool relativeToComponentTopLeft) const;
  34260. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34261. @see ListBox::scrollToEnsureRowIsOnscreen
  34262. */
  34263. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34264. /** @internal */
  34265. int getNumRows();
  34266. /** @internal */
  34267. void paintListBoxItem (int, Graphics&, int, int, bool);
  34268. /** @internal */
  34269. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34270. /** @internal */
  34271. void selectedRowsChanged (int lastRowSelected);
  34272. /** @internal */
  34273. void deleteKeyPressed (int currentSelectedRow);
  34274. /** @internal */
  34275. void returnKeyPressed (int currentSelectedRow);
  34276. /** @internal */
  34277. void backgroundClicked();
  34278. /** @internal */
  34279. void listWasScrolled();
  34280. /** @internal */
  34281. void tableColumnsChanged (TableHeaderComponent*);
  34282. /** @internal */
  34283. void tableColumnsResized (TableHeaderComponent*);
  34284. /** @internal */
  34285. void tableSortOrderChanged (TableHeaderComponent*);
  34286. /** @internal */
  34287. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34288. /** @internal */
  34289. void resized();
  34290. juce_UseDebuggingNewOperator
  34291. private:
  34292. TableHeaderComponent* header;
  34293. TableListBoxModel* model;
  34294. int columnIdNowBeingDragged;
  34295. bool autoSizeOptionsShown;
  34296. void updateColumnComponents() const;
  34297. TableListBox (const TableListBox&);
  34298. const TableListBox& operator= (const TableListBox&);
  34299. };
  34300. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34301. /********* End of inlined file: juce_TableListBox.h *********/
  34302. #endif
  34303. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34304. #endif
  34305. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34306. #endif
  34307. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34308. #endif
  34309. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34310. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  34311. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34312. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34313. /**
  34314. A factory object which can create ToolbarItemComponent objects.
  34315. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34316. that it can create.
  34317. Each type of item is identified by a unique ID, and multiple instances of an
  34318. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34319. bars).
  34320. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34321. */
  34322. class JUCE_API ToolbarItemFactory
  34323. {
  34324. public:
  34325. ToolbarItemFactory();
  34326. /** Destructor. */
  34327. virtual ~ToolbarItemFactory();
  34328. /** A set of reserved item ID values, used for the built-in item types.
  34329. */
  34330. enum SpecialItemIds
  34331. {
  34332. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34333. can be placed between sets of items to break them into groups. */
  34334. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34335. items.*/
  34336. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34337. either side of it, filling any available space. */
  34338. };
  34339. /** Must return a list of the IDs for all the item types that this factory can create.
  34340. The ids should be added to the array that is passed-in.
  34341. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34342. and the predefined IDs in the SpecialItemIds enum.
  34343. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34344. to this list if you want your toolbar to be able to contain those items.
  34345. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34346. of available items, and their order on the palette will reflect the order in which
  34347. they appear on this list.
  34348. @see ToolbarItemPalette
  34349. */
  34350. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34351. /** Must return the set of items that should be added to a toolbar as its default set.
  34352. This method is used by Toolbar::addDefaultItems() to determine which items to
  34353. create.
  34354. The items that your method adds to the array that is passed-in will be added to the
  34355. toolbar in the same order. Items can appear in the list more than once.
  34356. */
  34357. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34358. /** Must create an instance of one of the items that the factory lists in its
  34359. getAllToolbarItemIds() method.
  34360. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34361. method, except for the built-in item types from the SpecialItemIds enum, which
  34362. are created internally by the toolbar code.
  34363. Try not to keep a pointer to the object that is returned, as it will be deleted
  34364. automatically by the toolbar, and remember that multiple instances of the same
  34365. item type are likely to exist at the same time.
  34366. */
  34367. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  34368. };
  34369. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34370. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  34371. #endif
  34372. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34373. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  34374. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34375. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34376. /**
  34377. A component containing a list of toolbar items, which the user can drag onto
  34378. a toolbar to add them.
  34379. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34380. which automatically shows one of these in a dialog box with lots of extra controls.
  34381. @see Toolbar
  34382. */
  34383. class JUCE_API ToolbarItemPalette : public Component,
  34384. public DragAndDropContainer
  34385. {
  34386. public:
  34387. /** Creates a palette of items for a given factory, with the aim of adding them
  34388. to the specified toolbar.
  34389. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34390. set of items that are shown in this palette.
  34391. The toolbar and factory must not be deleted while this object exists.
  34392. */
  34393. ToolbarItemPalette (ToolbarItemFactory& factory,
  34394. Toolbar* const toolbar);
  34395. /** Destructor. */
  34396. ~ToolbarItemPalette();
  34397. /** @internal */
  34398. void resized();
  34399. juce_UseDebuggingNewOperator
  34400. private:
  34401. ToolbarItemFactory& factory;
  34402. Toolbar* toolbar;
  34403. Viewport* viewport;
  34404. friend class Toolbar;
  34405. void replaceComponent (ToolbarItemComponent* const comp);
  34406. ToolbarItemPalette (const ToolbarItemPalette&);
  34407. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34408. };
  34409. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34410. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  34411. #endif
  34412. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34413. #endif
  34414. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34415. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34416. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34417. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34418. /**
  34419. A PropertyComponent that contains an on/off toggle button.
  34420. This type of property component can be used if you have a boolean value to
  34421. toggle on/off.
  34422. @see PropertyComponent
  34423. */
  34424. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  34425. private ButtonListener
  34426. {
  34427. public:
  34428. /** Creates a button component.
  34429. @param propertyName the property name to be passed to the PropertyComponent
  34430. @param buttonTextWhenTrue the text shown in the button when the value is true
  34431. @param buttonTextWhenFalse the text shown in the button when the value is false
  34432. */
  34433. BooleanPropertyComponent (const String& propertyName,
  34434. const String& buttonTextWhenTrue,
  34435. const String& buttonTextWhenFalse);
  34436. /** Destructor. */
  34437. ~BooleanPropertyComponent();
  34438. /** Called to change the state of the boolean value. */
  34439. virtual void setState (const bool newState) = 0;
  34440. /** Must return the current value of the property. */
  34441. virtual bool getState() const = 0;
  34442. /** @internal */
  34443. void paint (Graphics& g);
  34444. /** @internal */
  34445. void refresh();
  34446. /** @internal */
  34447. void buttonClicked (Button*);
  34448. juce_UseDebuggingNewOperator
  34449. private:
  34450. ToggleButton* button;
  34451. String onText, offText;
  34452. };
  34453. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34454. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  34455. #endif
  34456. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34457. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  34458. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34459. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34460. /**
  34461. A PropertyComponent that contains a button.
  34462. This type of property component can be used if you need a button to trigger some
  34463. kind of action.
  34464. @see PropertyComponent
  34465. */
  34466. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  34467. private ButtonListener
  34468. {
  34469. public:
  34470. /** Creates a button component.
  34471. @param propertyName the property name to be passed to the PropertyComponent
  34472. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  34473. */
  34474. ButtonPropertyComponent (const String& propertyName,
  34475. const bool triggerOnMouseDown);
  34476. /** Destructor. */
  34477. ~ButtonPropertyComponent();
  34478. /** Called when the user clicks the button.
  34479. */
  34480. virtual void buttonClicked() = 0;
  34481. /** Returns the string that should be displayed in the button.
  34482. If you need to change this string, call refresh() to update the component.
  34483. */
  34484. virtual const String getButtonText() const = 0;
  34485. /** @internal */
  34486. void refresh();
  34487. /** @internal */
  34488. void buttonClicked (Button*);
  34489. juce_UseDebuggingNewOperator
  34490. private:
  34491. TextButton* button;
  34492. };
  34493. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34494. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  34495. #endif
  34496. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34497. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  34498. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34499. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34500. /**
  34501. A PropertyComponent that shows its value as a combo box.
  34502. This type of property component contains a list of options and has a
  34503. combo box to choose one.
  34504. Your subclass's constructor must add some strings to the choices StringArray
  34505. and these are shown in the list.
  34506. The getIndex() method will be called to find out which option is the currently
  34507. selected one. If you call refresh() it will call getIndex() to check whether
  34508. the value has changed, and will update the combo box if needed.
  34509. If the user selects a different item from the list, setIndex() will be
  34510. called to let your class process this.
  34511. @see PropertyComponent, PropertyPanel
  34512. */
  34513. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  34514. private ComboBoxListener
  34515. {
  34516. public:
  34517. /** Creates the component.
  34518. Your subclass's constructor must add a list of options to the choices
  34519. member variable.
  34520. */
  34521. ChoicePropertyComponent (const String& propertyName);
  34522. /** Destructor. */
  34523. ~ChoicePropertyComponent();
  34524. /** Called when the user selects an item from the combo box.
  34525. Your subclass must use this callback to update the value that this component
  34526. represents. The index is the index of the chosen item in the choices
  34527. StringArray.
  34528. */
  34529. virtual void setIndex (const int newIndex) = 0;
  34530. /** Returns the index of the item that should currently be shown.
  34531. This is the index of the item in the choices StringArray that will be
  34532. shown.
  34533. */
  34534. virtual int getIndex() const = 0;
  34535. /** Returns the list of options. */
  34536. const StringArray& getChoices() const throw();
  34537. /** @internal */
  34538. void refresh();
  34539. /** @internal */
  34540. void comboBoxChanged (ComboBox*);
  34541. juce_UseDebuggingNewOperator
  34542. protected:
  34543. /** The list of options that will be shown in the combo box.
  34544. Your subclass must populate this array in its constructor. If any empty
  34545. strings are added, these will be replaced with horizontal separators (see
  34546. ComboBox::addSeparator() for more info).
  34547. */
  34548. StringArray choices;
  34549. private:
  34550. ComboBox* comboBox;
  34551. };
  34552. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34553. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  34554. #endif
  34555. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  34556. #endif
  34557. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  34558. #endif
  34559. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34560. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34561. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34562. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34563. /**
  34564. A PropertyComponent that shows its value as a slider.
  34565. @see PropertyComponent, Slider
  34566. */
  34567. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  34568. private SliderListener
  34569. {
  34570. public:
  34571. /** Creates the property component.
  34572. The ranges, interval and skew factor are passed to the Slider component.
  34573. If you need to customise the slider in other ways, your constructor can
  34574. access the slider member variable and change it directly.
  34575. */
  34576. SliderPropertyComponent (const String& propertyName,
  34577. const double rangeMin,
  34578. const double rangeMax,
  34579. const double interval,
  34580. const double skewFactor = 1.0);
  34581. /** Destructor. */
  34582. ~SliderPropertyComponent();
  34583. /** Called when the user moves the slider to change its value.
  34584. Your subclass must use this method to update whatever item this property
  34585. represents.
  34586. */
  34587. virtual void setValue (const double newValue) = 0;
  34588. /** Returns the value that the slider should show. */
  34589. virtual const double getValue() const = 0;
  34590. /** @internal */
  34591. void refresh();
  34592. /** @internal */
  34593. void changeListenerCallback (void*);
  34594. /** @internal */
  34595. void sliderValueChanged (Slider*);
  34596. juce_UseDebuggingNewOperator
  34597. protected:
  34598. /** The slider component being used in this component.
  34599. Your subclass has access to this in case it needs to customise it in some way.
  34600. */
  34601. Slider* slider;
  34602. };
  34603. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34604. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  34605. #endif
  34606. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34607. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  34608. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34609. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34610. /**
  34611. A PropertyComponent that shows its value as editable text.
  34612. @see PropertyComponent
  34613. */
  34614. class JUCE_API TextPropertyComponent : public PropertyComponent
  34615. {
  34616. public:
  34617. /** Creates a text property component.
  34618. The maxNumChars is used to set the length of string allowable, and isMultiLine
  34619. sets whether the text editor allows carriage returns.
  34620. @see TextEditor
  34621. */
  34622. TextPropertyComponent (const String& propertyName,
  34623. const int maxNumChars,
  34624. const bool isMultiLine);
  34625. /** Destructor. */
  34626. ~TextPropertyComponent();
  34627. /** Called when the user edits the text.
  34628. Your subclass must use this callback to change the value of whatever item
  34629. this property component represents.
  34630. */
  34631. virtual void setText (const String& newText) = 0;
  34632. /** Returns the text that should be shown in the text editor.
  34633. */
  34634. virtual const String getText() const = 0;
  34635. /** @internal */
  34636. void refresh();
  34637. /** @internal */
  34638. void textWasEdited();
  34639. juce_UseDebuggingNewOperator
  34640. private:
  34641. Label* textEditor;
  34642. };
  34643. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34644. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  34645. #endif
  34646. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  34647. #endif
  34648. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34649. #endif
  34650. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34651. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  34652. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34653. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34654. /** An object that watches for any movement of a component or any of its parent components.
  34655. This makes it easy to check when a component is moved relative to its top-level
  34656. peer window. The normal Component::moved() method is only called when a component
  34657. moves relative to its immediate parent, and sometimes you want to know if any of
  34658. components higher up the tree have moved (which of course will affect the overall
  34659. position of all their sub-components).
  34660. It also includes a callback that lets you know when the top-level peer is changed.
  34661. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  34662. because they need to keep their custom windows in the right place and respond to
  34663. changes in the peer.
  34664. */
  34665. class JUCE_API ComponentMovementWatcher : public ComponentListener
  34666. {
  34667. public:
  34668. /** Creates a ComponentMovementWatcher to watch a given target component. */
  34669. ComponentMovementWatcher (Component* const component);
  34670. /** Destructor. */
  34671. ~ComponentMovementWatcher();
  34672. /** This callback happens when the component that is being watched is moved
  34673. relative to its top-level peer window, or when it is resized.
  34674. */
  34675. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  34676. /** This callback happens when the component's top-level peer is changed.
  34677. */
  34678. virtual void componentPeerChanged() = 0;
  34679. juce_UseDebuggingNewOperator
  34680. /** @internal */
  34681. void componentParentHierarchyChanged (Component& component);
  34682. /** @internal */
  34683. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34684. private:
  34685. Component* const component;
  34686. ComponentPeer* lastPeer;
  34687. VoidArray registeredParentComps;
  34688. bool reentrant;
  34689. int lastX, lastY, lastWidth, lastHeight;
  34690. #ifdef JUCE_DEBUG
  34691. ComponentDeletionWatcher* deletionWatcher;
  34692. #endif
  34693. void unregister() throw();
  34694. void registerWithParentComps() throw();
  34695. ComponentMovementWatcher (const ComponentMovementWatcher&);
  34696. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  34697. };
  34698. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34699. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  34700. #endif
  34701. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34702. /********* Start of inlined file: juce_GroupComponent.h *********/
  34703. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34704. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34705. /**
  34706. A component that draws an outline around itself and has an optional title at
  34707. the top, for drawing an outline around a group of controls.
  34708. */
  34709. class JUCE_API GroupComponent : public Component
  34710. {
  34711. public:
  34712. /** Creates a GroupComponent.
  34713. @param componentName the name to give the component
  34714. @param labelText the text to show at the top of the outline
  34715. */
  34716. GroupComponent (const String& componentName,
  34717. const String& labelText);
  34718. /** Destructor. */
  34719. ~GroupComponent();
  34720. /** Changes the text that's shown at the top of the component. */
  34721. void setText (const String& newText) throw();
  34722. /** Returns the currently displayed text label. */
  34723. const String getText() const throw();
  34724. /** Sets the positioning of the text label.
  34725. (The default is Justification::left)
  34726. @see getTextLabelPosition
  34727. */
  34728. void setTextLabelPosition (const Justification& justification);
  34729. /** Returns the current text label position.
  34730. @see setTextLabelPosition
  34731. */
  34732. const Justification getTextLabelPosition() const throw() { return justification; }
  34733. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34734. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34735. methods.
  34736. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34737. */
  34738. enum ColourIds
  34739. {
  34740. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  34741. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  34742. };
  34743. /** @internal */
  34744. void paint (Graphics& g);
  34745. /** @internal */
  34746. void enablementChanged();
  34747. /** @internal */
  34748. void colourChanged();
  34749. private:
  34750. String text;
  34751. Justification justification;
  34752. GroupComponent (const GroupComponent&);
  34753. const GroupComponent& operator= (const GroupComponent&);
  34754. };
  34755. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34756. /********* End of inlined file: juce_GroupComponent.h *********/
  34757. #endif
  34758. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34759. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  34760. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34761. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34762. /********* Start of inlined file: juce_TabbedComponent.h *********/
  34763. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34764. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34765. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  34766. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34767. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34768. class TabbedButtonBar;
  34769. /** In a TabbedButtonBar, this component is used for each of the buttons.
  34770. If you want to create a TabbedButtonBar with custom tab components, derive
  34771. your component from this class, and override the TabbedButtonBar::createTabButton()
  34772. method to create it instead of the default one.
  34773. @see TabbedButtonBar
  34774. */
  34775. class JUCE_API TabBarButton : public Button
  34776. {
  34777. public:
  34778. /** Creates the tab button. */
  34779. TabBarButton (const String& name,
  34780. TabbedButtonBar* const ownerBar,
  34781. const int tabIndex);
  34782. /** Destructor. */
  34783. ~TabBarButton();
  34784. /** Chooses the best length for the tab, given the specified depth.
  34785. If the tab is horizontal, this should return its width, and the depth
  34786. specifies its height. If it's vertical, it should return the height, and
  34787. the depth is actually its width.
  34788. */
  34789. virtual int getBestTabLength (const int depth);
  34790. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  34791. void clicked (const ModifierKeys& mods);
  34792. bool hitTest (int x, int y);
  34793. juce_UseDebuggingNewOperator
  34794. protected:
  34795. friend class TabbedButtonBar;
  34796. TabbedButtonBar* const owner;
  34797. int tabIndex, overlapPixels;
  34798. DropShadowEffect shadow;
  34799. /** Returns an area of the component that's safe to draw in.
  34800. This deals with the orientation of the tabs, which affects which side is
  34801. touching the tabbed box's content component.
  34802. */
  34803. void getActiveArea (int& x, int& y, int& w, int& h);
  34804. private:
  34805. TabBarButton (const TabBarButton&);
  34806. const TabBarButton& operator= (const TabBarButton&);
  34807. };
  34808. /**
  34809. A vertical or horizontal bar containing tabs that you can select.
  34810. You can use one of these to generate things like a dialog box that has
  34811. tabbed pages you can flip between. Attach a ChangeListener to the
  34812. button bar to be told when the user changes the page.
  34813. An easier method than doing this is to use a TabbedComponent, which
  34814. contains its own TabbedButtonBar and which takes care of the layout
  34815. and other housekeeping.
  34816. @see TabbedComponent
  34817. */
  34818. class JUCE_API TabbedButtonBar : public Component,
  34819. public ChangeBroadcaster,
  34820. public ButtonListener
  34821. {
  34822. public:
  34823. /** The placement of the tab-bar
  34824. @see setOrientation, getOrientation
  34825. */
  34826. enum Orientation
  34827. {
  34828. TabsAtTop,
  34829. TabsAtBottom,
  34830. TabsAtLeft,
  34831. TabsAtRight
  34832. };
  34833. /** Creates a TabbedButtonBar with a given placement.
  34834. You can change the orientation later if you need to.
  34835. */
  34836. TabbedButtonBar (const Orientation orientation);
  34837. /** Destructor. */
  34838. ~TabbedButtonBar();
  34839. /** Changes the bar's orientation.
  34840. This won't change the bar's actual size - you'll need to do that yourself,
  34841. but this determines which direction the tabs go in, and which side they're
  34842. stuck to.
  34843. */
  34844. void setOrientation (const Orientation orientation);
  34845. /** Returns the current orientation.
  34846. @see setOrientation
  34847. */
  34848. Orientation getOrientation() const throw() { return orientation; }
  34849. /** Deletes all the tabs from the bar.
  34850. @see addTab
  34851. */
  34852. void clearTabs();
  34853. /** Adds a tab to the bar.
  34854. Tabs are added in left-to-right reading order.
  34855. If this is the first tab added, it'll also be automatically selected.
  34856. */
  34857. void addTab (const String& tabName,
  34858. const Colour& tabBackgroundColour,
  34859. int insertIndex = -1);
  34860. /** Changes the name of one of the tabs. */
  34861. void setTabName (const int tabIndex,
  34862. const String& newName);
  34863. /** Gets rid of one of the tabs. */
  34864. void removeTab (const int tabIndex);
  34865. /** Moves a tab to a new index in the list.
  34866. Pass -1 as the index to move it to the end of the list.
  34867. */
  34868. void moveTab (const int currentIndex,
  34869. const int newIndex);
  34870. /** Returns the number of tabs in the bar. */
  34871. int getNumTabs() const;
  34872. /** Returns a list of all the tab names in the bar. */
  34873. const StringArray getTabNames() const;
  34874. /** Changes the currently selected tab.
  34875. This will send a change message and cause a synchronous callback to
  34876. the currentTabChanged() method. (But if the given tab is already selected,
  34877. nothing will be done).
  34878. To deselect all the tabs, use an index of -1.
  34879. */
  34880. void setCurrentTabIndex (int newTabIndex);
  34881. /** Returns the name of the currently selected tab.
  34882. This could be an empty string if none are selected.
  34883. */
  34884. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  34885. /** Returns the index of the currently selected tab.
  34886. This could return -1 if none are selected.
  34887. */
  34888. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  34889. /** Callback method to indicate the selected tab has been changed.
  34890. @see setCurrentTabIndex
  34891. */
  34892. virtual void currentTabChanged (const int newCurrentTabIndex,
  34893. const String& newCurrentTabName);
  34894. /** Callback method to indicate that the user has right-clicked on a tab.
  34895. (Or ctrl-clicked on the Mac)
  34896. */
  34897. virtual void popupMenuClickOnTab (const int tabIndex,
  34898. const String& tabName);
  34899. /** Returns the colour of a tab.
  34900. This is the colour that was specified in addTab().
  34901. */
  34902. const Colour getTabBackgroundColour (const int tabIndex);
  34903. /** Changes the background colour of a tab.
  34904. @see addTab, getTabBackgroundColour
  34905. */
  34906. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  34907. /** @internal */
  34908. void resized();
  34909. /** @internal */
  34910. void buttonClicked (Button* button);
  34911. /** @internal */
  34912. void lookAndFeelChanged();
  34913. juce_UseDebuggingNewOperator
  34914. protected:
  34915. /** This creates one of the tabs.
  34916. If you need to use custom tab components, you can override this method and
  34917. return your own class instead of the default.
  34918. */
  34919. virtual TabBarButton* createTabButton (const String& tabName,
  34920. const int tabIndex);
  34921. private:
  34922. Orientation orientation;
  34923. StringArray tabs;
  34924. Array <Colour> tabColours;
  34925. int currentTabIndex;
  34926. Component* behindFrontTab;
  34927. Button* extraTabsButton;
  34928. TabBarButton* getTabButton (const int index) const;
  34929. TabbedButtonBar (const TabbedButtonBar&);
  34930. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  34931. };
  34932. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34933. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  34934. /**
  34935. A component with a TabbedButtonBar along one of its sides.
  34936. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  34937. with addTab(), and this will take care of showing the pages for you when the
  34938. user clicks on a different tab.
  34939. @see TabbedButtonBar
  34940. */
  34941. class JUCE_API TabbedComponent : public Component
  34942. {
  34943. public:
  34944. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  34945. Once created, add some tabs with the addTab() method.
  34946. */
  34947. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  34948. /** Destructor. */
  34949. ~TabbedComponent();
  34950. /** Changes the placement of the tabs.
  34951. This will rearrange the layout to place the tabs along the appropriate
  34952. side of this component, and will shift the content component accordingly.
  34953. @see TabbedButtonBar::setOrientation
  34954. */
  34955. void setOrientation (const TabbedButtonBar::Orientation orientation);
  34956. /** Returns the current tab placement.
  34957. @see setOrientation, TabbedButtonBar::getOrientation
  34958. */
  34959. TabbedButtonBar::Orientation getOrientation() const throw();
  34960. /** Specifies how many pixels wide or high the tab-bar should be.
  34961. If the tabs are placed along the top or bottom, this specified the height
  34962. of the bar; if they're along the left or right edges, it'll be the width
  34963. of the bar.
  34964. */
  34965. void setTabBarDepth (const int newDepth);
  34966. /** Returns the current thickness of the tab bar.
  34967. @see setTabBarDepth
  34968. */
  34969. int getTabBarDepth() const throw() { return tabDepth; }
  34970. /** Specifies an outline that should be drawn around the entire content component.
  34971. If this thickness is > 0, a line of the specified colour will be drawn around
  34972. the three sides of the content component which don't touch the tab-bar, and
  34973. the content component will be inset by this amount.
  34974. */
  34975. void setOutline (const Colour& newOutlineColour,
  34976. const int newThickness);
  34977. /** Specifies a gap to leave around the edge of the content component.
  34978. Each edge of the content component will be indented by the given number of pixels.
  34979. */
  34980. void setIndent (const int indentThickness);
  34981. /** Removes all the tabs from the bar.
  34982. @see TabbedButtonBar::clearTabs
  34983. */
  34984. void clearTabs();
  34985. /** Adds a tab to the tab-bar.
  34986. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  34987. is true, it will be deleted when the tab is removed or when this object is
  34988. deleted.
  34989. @see TabbedButtonBar::addTab
  34990. */
  34991. void addTab (const String& tabName,
  34992. const Colour& tabBackgroundColour,
  34993. Component* const contentComponent,
  34994. const bool deleteComponentWhenNotNeeded,
  34995. const int insertIndex = -1);
  34996. /** Changes the name of one of the tabs. */
  34997. void setTabName (const int tabIndex,
  34998. const String& newName);
  34999. /** Gets rid of one of the tabs. */
  35000. void removeTab (const int tabIndex);
  35001. /** Returns the number of tabs in the bar. */
  35002. int getNumTabs() const;
  35003. /** Returns a list of all the tab names in the bar. */
  35004. const StringArray getTabNames() const;
  35005. /** Returns the content component that was added for the given index.
  35006. Be sure not to use or delete the components that are returned, as this may interfere
  35007. with the TabbedComponent's use of them.
  35008. */
  35009. Component* getTabContentComponent (const int tabIndex) const throw();
  35010. /** Returns the colour of one of the tabs. */
  35011. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  35012. /** Changes the background colour of one of the tabs. */
  35013. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35014. /** Changes the currently-selected tab.
  35015. To deselect all the tabs, pass -1 as the index.
  35016. @see TabbedButtonBar::setCurrentTabIndex
  35017. */
  35018. void setCurrentTabIndex (const int newTabIndex);
  35019. /** Returns the index of the currently selected tab.
  35020. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  35021. */
  35022. int getCurrentTabIndex() const;
  35023. /** Returns the name of the currently selected tab.
  35024. @see addTab, TabbedButtonBar::getCurrentTabName()
  35025. */
  35026. const String& getCurrentTabName() const;
  35027. /** Returns the current component that's filling the panel.
  35028. This will return 0 if there isn't one.
  35029. */
  35030. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  35031. /** Callback method to indicate the selected tab has been changed.
  35032. @see setCurrentTabIndex
  35033. */
  35034. virtual void currentTabChanged (const int newCurrentTabIndex,
  35035. const String& newCurrentTabName);
  35036. /** Callback method to indicate that the user has right-clicked on a tab.
  35037. (Or ctrl-clicked on the Mac)
  35038. */
  35039. virtual void popupMenuClickOnTab (const int tabIndex,
  35040. const String& tabName);
  35041. /** Returns the tab button bar component that is being used.
  35042. */
  35043. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  35044. /** @internal */
  35045. void paint (Graphics& g);
  35046. /** @internal */
  35047. void resized();
  35048. /** @internal */
  35049. void lookAndFeelChanged();
  35050. juce_UseDebuggingNewOperator
  35051. protected:
  35052. TabbedButtonBar* tabs;
  35053. /** This creates one of the tab buttons.
  35054. If you need to use custom tab components, you can override this method and
  35055. return your own class instead of the default.
  35056. */
  35057. virtual TabBarButton* createTabButton (const String& tabName,
  35058. const int tabIndex);
  35059. private:
  35060. Array <Component*> contentComponents;
  35061. Component* panelComponent;
  35062. int tabDepth;
  35063. Colour outlineColour;
  35064. int outlineThickness, edgeIndent;
  35065. friend class TabCompButtonBar;
  35066. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  35067. TabbedComponent (const TabbedComponent&);
  35068. const TabbedComponent& operator= (const TabbedComponent&);
  35069. };
  35070. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35071. /********* End of inlined file: juce_TabbedComponent.h *********/
  35072. /********* Start of inlined file: juce_DocumentWindow.h *********/
  35073. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35074. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35075. /********* Start of inlined file: juce_ResizableWindow.h *********/
  35076. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35077. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35078. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  35079. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35080. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35081. /********* Start of inlined file: juce_DropShadower.h *********/
  35082. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  35083. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  35084. /**
  35085. Adds a drop-shadow to a component.
  35086. This object creates and manages a set of components which sit around a
  35087. component, creating a gaussian shadow around it. The components will track
  35088. the position of the component and if it's brought to the front they'll also
  35089. follow this.
  35090. For desktop windows you don't need to use this class directly - just
  35091. set the Component::windowHasDropShadow flag when calling
  35092. Component::addToDesktop(), and the system will create one of these if it's
  35093. needed (which it obviously isn't on the Mac, for example).
  35094. */
  35095. class JUCE_API DropShadower : public ComponentListener
  35096. {
  35097. public:
  35098. /** Creates a DropShadower.
  35099. @param alpha the opacity of the shadows, from 0 to 1.0
  35100. @param xOffset the horizontal displacement of the shadow, in pixels
  35101. @param yOffset the vertical displacement of the shadow, in pixels
  35102. @param blurRadius the radius of the blur to use for creating the shadow
  35103. */
  35104. DropShadower (const float alpha = 0.5f,
  35105. const int xOffset = 1,
  35106. const int yOffset = 5,
  35107. const float blurRadius = 10.0f);
  35108. /** Destructor. */
  35109. virtual ~DropShadower();
  35110. /** Attaches the DropShadower to the component you want to shadow. */
  35111. void setOwner (Component* componentToFollow);
  35112. /** @internal */
  35113. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35114. /** @internal */
  35115. void componentBroughtToFront (Component& component);
  35116. /** @internal */
  35117. void componentChildrenChanged (Component& component);
  35118. /** @internal */
  35119. void componentParentHierarchyChanged (Component& component);
  35120. /** @internal */
  35121. void componentVisibilityChanged (Component& component);
  35122. juce_UseDebuggingNewOperator
  35123. private:
  35124. Component* owner;
  35125. int numShadows;
  35126. Component* shadowWindows[4];
  35127. Image* shadowImageSections[12];
  35128. const int shadowEdge, xOffset, yOffset;
  35129. const float alpha, blurRadius;
  35130. bool inDestructor, reentrant;
  35131. void updateShadows();
  35132. void setShadowImage (Image* const src,
  35133. const int num,
  35134. const int w, const int h,
  35135. const int sx, const int sy) throw();
  35136. void bringShadowWindowsToFront();
  35137. void deleteShadowWindows();
  35138. DropShadower (const DropShadower&);
  35139. const DropShadower& operator= (const DropShadower&);
  35140. };
  35141. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35142. /********* End of inlined file: juce_DropShadower.h *********/
  35143. /**
  35144. A base class for top-level windows.
  35145. This class is used for components that are considered a major part of your
  35146. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35147. etc. Things like menus that pop up briefly aren't derived from it.
  35148. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35149. could itself be the child of another component.
  35150. The class manages a list of all instances of top-level windows that are in use,
  35151. and each one is also given the concept of being "active". The active window is
  35152. one that is actively being used by the user. This isn't quite the same as the
  35153. component with the keyboard focus, because there may be a popup menu or other
  35154. temporary window which gets keyboard focus while the active top level window is
  35155. unchanged.
  35156. A top-level window also has an optional drop-shadow.
  35157. @see ResizableWindow, DocumentWindow, DialogWindow
  35158. */
  35159. class JUCE_API TopLevelWindow : public Component
  35160. {
  35161. public:
  35162. /** Creates a TopLevelWindow.
  35163. @param name the name to give the component
  35164. @param addToDesktop if true, the window will be automatically added to the
  35165. desktop; if false, you can use it as a child component
  35166. */
  35167. TopLevelWindow (const String& name,
  35168. const bool addToDesktop);
  35169. /** Destructor. */
  35170. ~TopLevelWindow();
  35171. /** True if this is currently the TopLevelWindow that is actively being used.
  35172. This isn't quite the same as having keyboard focus, because the focus may be
  35173. on a child component or a temporary pop-up menu, etc, while this window is
  35174. still considered to be active.
  35175. @see activeWindowStatusChanged
  35176. */
  35177. bool isActiveWindow() const throw() { return windowIsActive_; }
  35178. /** This will set the bounds of the window so that it's centred in front of another
  35179. window.
  35180. If your app has a few windows open and want to pop up a dialog box for one of
  35181. them, you can use this to show it in front of the relevent parent window, which
  35182. is a bit neater than just having it appear in the middle of the screen.
  35183. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35184. be used instead. If no window is focused, it'll just default to the middle of the
  35185. screen.
  35186. */
  35187. void centreAroundComponent (Component* componentToCentreAround,
  35188. const int width, const int height);
  35189. /** Turns the drop-shadow on and off. */
  35190. void setDropShadowEnabled (const bool useShadow);
  35191. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35192. @see isUsingNativeTitleBar
  35193. */
  35194. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35195. /** Returns true if the window is currently using an OS-native title bar.
  35196. @see setUsingNativeTitleBar
  35197. */
  35198. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35199. /** Returns the number of TopLevelWindow objects currently in use.
  35200. @see getTopLevelWindow
  35201. */
  35202. static int getNumTopLevelWindows() throw();
  35203. /** Returns one of the TopLevelWindow objects currently in use.
  35204. The index is 0 to (getNumTopLevelWindows() - 1).
  35205. */
  35206. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35207. /** Returns the currently-active top level window.
  35208. There might not be one, of course, so this can return 0.
  35209. */
  35210. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35211. juce_UseDebuggingNewOperator
  35212. /** @internal */
  35213. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35214. protected:
  35215. /** This callback happens when this window becomes active or inactive.
  35216. @see isActiveWindow
  35217. */
  35218. virtual void activeWindowStatusChanged();
  35219. /** @internal */
  35220. void focusOfChildComponentChanged (FocusChangeType cause);
  35221. /** @internal */
  35222. void parentHierarchyChanged();
  35223. /** @internal */
  35224. void visibilityChanged();
  35225. /** @internal */
  35226. virtual int getDesktopWindowStyleFlags() const;
  35227. /** @internal */
  35228. void recreateDesktopWindow();
  35229. private:
  35230. friend class TopLevelWindowManager;
  35231. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35232. DropShadower* shadower;
  35233. void setWindowActive (const bool isNowActive) throw();
  35234. TopLevelWindow (const TopLevelWindow&);
  35235. const TopLevelWindow& operator= (const TopLevelWindow&);
  35236. };
  35237. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35238. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35239. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35240. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35241. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35242. /**
  35243. A component that resizes its parent window when dragged.
  35244. This component forms a frame around the edge of a component, allowing it to
  35245. be dragged by the edges or corners to resize it - like the way windows are
  35246. resized in MSWindows or Linux.
  35247. To use it, just add it to your component, making it fill the entire parent component
  35248. (there's a mouse hit-test that only traps mouse-events which land around the
  35249. edge of the component, so it's even ok to put it on top of any other components
  35250. you're using). Make sure you rescale the resizer component to fill the parent
  35251. each time the parent's size changes.
  35252. @see ResizableCornerComponent
  35253. */
  35254. class JUCE_API ResizableBorderComponent : public Component
  35255. {
  35256. public:
  35257. /** Creates a resizer.
  35258. Pass in the target component which you want to be resized when this one is
  35259. dragged.
  35260. The target component will usually be a parent of the resizer component, but this
  35261. isn't mandatory.
  35262. Remember that when the target component is resized, it'll need to move and
  35263. resize this component to keep it in place, as this won't happen automatically.
  35264. If the constrainer parameter is non-zero, then this object will be used to enforce
  35265. limits on the size and position that the component can be stretched to. Make sure
  35266. that the constrainer isn't deleted while still in use by this object.
  35267. @see ComponentBoundsConstrainer
  35268. */
  35269. ResizableBorderComponent (Component* const componentToResize,
  35270. ComponentBoundsConstrainer* const constrainer);
  35271. /** Destructor. */
  35272. ~ResizableBorderComponent();
  35273. /** Specifies how many pixels wide the draggable edges of this component are.
  35274. @see getBorderThickness
  35275. */
  35276. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35277. /** Returns the number of pixels wide that the draggable edges of this component are.
  35278. @see setBorderThickness
  35279. */
  35280. const BorderSize getBorderThickness() const throw();
  35281. juce_UseDebuggingNewOperator
  35282. protected:
  35283. /** @internal */
  35284. void paint (Graphics& g);
  35285. /** @internal */
  35286. void mouseEnter (const MouseEvent& e);
  35287. /** @internal */
  35288. void mouseMove (const MouseEvent& e);
  35289. /** @internal */
  35290. void mouseDown (const MouseEvent& e);
  35291. /** @internal */
  35292. void mouseDrag (const MouseEvent& e);
  35293. /** @internal */
  35294. void mouseUp (const MouseEvent& e);
  35295. /** @internal */
  35296. bool hitTest (int x, int y);
  35297. private:
  35298. Component* const component;
  35299. ComponentBoundsConstrainer* constrainer;
  35300. BorderSize borderSize;
  35301. int originalX, originalY, originalW, originalH;
  35302. int mouseZone;
  35303. void updateMouseZone (const MouseEvent& e) throw();
  35304. ResizableBorderComponent (const ResizableBorderComponent&);
  35305. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35306. };
  35307. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35308. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35309. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35310. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35311. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35312. /** A component that resizes a parent window when dragged.
  35313. This is the small triangular stripey resizer component you get in the bottom-right
  35314. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35315. a larger component and it will automatically resize its parent when it gets dragged
  35316. around.
  35317. @see ResizableFrameComponent
  35318. */
  35319. class JUCE_API ResizableCornerComponent : public Component
  35320. {
  35321. public:
  35322. /** Creates a resizer.
  35323. Pass in the target component which you want to be resized when this one is
  35324. dragged.
  35325. The target component will usually be a parent of the resizer component, but this
  35326. isn't mandatory.
  35327. Remember that when the target component is resized, it'll need to move and
  35328. resize this component to keep it in place, as this won't happen automatically.
  35329. If the constrainer parameter is non-zero, then this object will be used to enforce
  35330. limits on the size and position that the component can be stretched to. Make sure
  35331. that the constrainer isn't deleted while still in use by this object. If you
  35332. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35333. @see ComponentBoundsConstrainer
  35334. */
  35335. ResizableCornerComponent (Component* const componentToResize,
  35336. ComponentBoundsConstrainer* const constrainer);
  35337. /** Destructor. */
  35338. ~ResizableCornerComponent();
  35339. juce_UseDebuggingNewOperator
  35340. protected:
  35341. /** @internal */
  35342. void paint (Graphics& g);
  35343. /** @internal */
  35344. void mouseDown (const MouseEvent& e);
  35345. /** @internal */
  35346. void mouseDrag (const MouseEvent& e);
  35347. /** @internal */
  35348. void mouseUp (const MouseEvent& e);
  35349. /** @internal */
  35350. bool hitTest (int x, int y);
  35351. private:
  35352. Component* const component;
  35353. ComponentBoundsConstrainer* constrainer;
  35354. int originalX, originalY, originalW, originalH;
  35355. ResizableCornerComponent (const ResizableCornerComponent&);
  35356. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35357. };
  35358. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35359. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35360. /**
  35361. A base class for top-level windows that can be dragged around and resized.
  35362. To add content to the window, use its setContentComponent() method to
  35363. give it a component that will remain positioned inside it (leaving a gap around
  35364. the edges for a border).
  35365. It's not advisable to add child components directly to a ResizableWindow: put them
  35366. inside your content component instead. And overriding methods like resized(), moved(), etc
  35367. is also not recommended - instead override these methods for your content component.
  35368. (If for some obscure reason you do need to override these methods, always remember to
  35369. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35370. decorations correctly).
  35371. By default resizing isn't enabled - use the setResizable() method to enable it and
  35372. to choose the style of resizing to use.
  35373. @see TopLevelWindow
  35374. */
  35375. class JUCE_API ResizableWindow : public TopLevelWindow
  35376. {
  35377. public:
  35378. /** Creates a ResizableWindow.
  35379. @param name the name to give the component
  35380. @param backgroundColour the colour to use for filling the window's background.
  35381. @param addToDesktop if true, the window will be automatically added to the
  35382. desktop; if false, you can use it as a child component
  35383. */
  35384. ResizableWindow (const String& name,
  35385. const Colour& backgroundColour,
  35386. const bool addToDesktop);
  35387. /** Destructor.
  35388. If a content component has been set with setContentComponent(), it
  35389. will be deleted.
  35390. */
  35391. ~ResizableWindow();
  35392. /** Returns the colour currently being used for the window's background.
  35393. As a convenience the window will fill itself with this colour, but you
  35394. can override the paint() method if you need more customised behaviour.
  35395. @see setBackgroundColour
  35396. */
  35397. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35398. /** Changes the colour currently being used for the window's background.
  35399. As a convenience the window will fill itself with this colour, but you
  35400. can override the paint() method if you need more customised behaviour.
  35401. Note that the opaque state of this window is altered by this call to reflect
  35402. the opacity of the colour passed-in. On window systems which can't support
  35403. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35404. be using this class as a base for a semi-transparent component anyway).
  35405. @see getBackgroundColour
  35406. */
  35407. void setBackgroundColour (const Colour& newColour);
  35408. /** Make the window resizable or fixed.
  35409. @param shouldBeResizable whether it's resizable at all
  35410. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35411. bottom-right; if false, it'll use a ResizableBorderComponent
  35412. around the edge
  35413. @see setResizeLimits, isResizable
  35414. */
  35415. void setResizable (const bool shouldBeResizable,
  35416. const bool useBottomRightCornerResizer);
  35417. /** True if resizing is enabled.
  35418. @see setResizable
  35419. */
  35420. bool isResizable() const throw();
  35421. /** This sets the maximum and minimum sizes for the window.
  35422. If the window's current size is outside these limits, it will be resized to
  35423. make sure it's within them.
  35424. Calling setBounds() on the component will bypass any size checking - it's only when
  35425. the window is being resized by the user that these values are enforced.
  35426. @see setResizable, setFixedAspectRatio
  35427. */
  35428. void setResizeLimits (const int newMinimumWidth,
  35429. const int newMinimumHeight,
  35430. const int newMaximumWidth,
  35431. const int newMaximumHeight) throw();
  35432. /** Returns the bounds constrainer object that this window is using.
  35433. You can access this to change its properties.
  35434. */
  35435. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35436. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35437. A pointer to the object you pass in will be kept, but it won't be deleted
  35438. by this object, so it's the caller's responsiblity to manage it.
  35439. If you pass 0, then no contraints will be placed on the positioning of the window.
  35440. */
  35441. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35442. /** Calls the window's setBounds method, after first checking these bounds
  35443. with the current constrainer.
  35444. @see setConstrainer
  35445. */
  35446. void setBoundsConstrained (int x, int y, int width, int height);
  35447. /** Returns true if the window is currently in full-screen mode.
  35448. @see setFullScreen
  35449. */
  35450. bool isFullScreen() const;
  35451. /** Puts the window into full-screen mode, or restores it to its normal size.
  35452. If true, the window will become full-screen; if false, it will return to the
  35453. last size it was before being made full-screen.
  35454. @see isFullScreen
  35455. */
  35456. void setFullScreen (const bool shouldBeFullScreen);
  35457. /** Returns true if the window is currently minimised.
  35458. @see setMinimised
  35459. */
  35460. bool isMinimised() const;
  35461. /** Minimises the window, or restores it to its previous position and size.
  35462. When being un-minimised, it'll return to the last position and size it
  35463. was in before being minimised.
  35464. @see isMinimised
  35465. */
  35466. void setMinimised (const bool shouldMinimise);
  35467. /** Returns a string which encodes the window's current size and position.
  35468. This string will encapsulate the window's size, position, and whether it's
  35469. in full-screen mode. It's intended for letting your application save and
  35470. restore a window's position.
  35471. Use the restoreWindowStateFromString() to restore from a saved state.
  35472. @see restoreWindowStateFromString
  35473. */
  35474. const String getWindowStateAsString();
  35475. /** Restores the window to a previously-saved size and position.
  35476. This restores the window's size, positon and full-screen status from an
  35477. string that was previously created with the getWindowStateAsString()
  35478. method.
  35479. @returns false if the string wasn't a valid window state
  35480. @see getWindowStateAsString
  35481. */
  35482. bool restoreWindowStateFromString (const String& previousState);
  35483. /** Returns the current content component.
  35484. This will be the component set by setContentComponent(), or 0 if none
  35485. has yet been specified.
  35486. @see setContentComponent
  35487. */
  35488. Component* getContentComponent() const throw() { return contentComponent; }
  35489. /** Changes the current content component.
  35490. This sets a component that will be placed in the centre of the ResizableWindow,
  35491. (leaving a space around the edge for the border).
  35492. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35493. with addChildComponent(). Instead, add them to the content component.
  35494. @param newContentComponent the new component to use (or null to not use one) - this
  35495. component will be deleted either when replaced by another call
  35496. to this method, or when the ResizableWindow is deleted.
  35497. To remove a content component without deleting it, use
  35498. setContentComponent (0, false).
  35499. @param deleteOldOne if true, the previous content component will be deleted; if
  35500. false, the previous component will just be removed without
  35501. deleting it.
  35502. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35503. it always fits around the size of the content component. If false, the
  35504. new content will be resized to fit the current space available.
  35505. */
  35506. void setContentComponent (Component* const newContentComponent,
  35507. const bool deleteOldOne = true,
  35508. const bool resizeToFit = false);
  35509. /** Changes the window so that the content component ends up with the specified size.
  35510. This is basically a setSize call on the window, but which adds on the borders,
  35511. so you can specify the content component's target size.
  35512. */
  35513. void setContentComponentSize (int width, int height);
  35514. juce_UseDebuggingNewOperator
  35515. protected:
  35516. /** @internal */
  35517. void paint (Graphics& g);
  35518. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35519. void moved();
  35520. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35521. void resized();
  35522. /** @internal */
  35523. void mouseDown (const MouseEvent& e);
  35524. /** @internal */
  35525. void mouseDrag (const MouseEvent& e);
  35526. /** @internal */
  35527. void lookAndFeelChanged();
  35528. /** @internal */
  35529. void childBoundsChanged (Component* child);
  35530. /** @internal */
  35531. void parentSizeChanged();
  35532. /** @internal */
  35533. void visibilityChanged();
  35534. /** @internal */
  35535. void activeWindowStatusChanged();
  35536. /** @internal */
  35537. int getDesktopWindowStyleFlags() const;
  35538. /** Returns the width of the border to use around the window.
  35539. @see getContentComponentBorder
  35540. */
  35541. virtual const BorderSize getBorderThickness();
  35542. /** Returns the insets to use when positioning the content component.
  35543. @see getBorderThickness
  35544. */
  35545. virtual const BorderSize getContentComponentBorder();
  35546. #ifdef JUCE_DEBUG
  35547. /** Overridden to warn people about adding components directly to this component
  35548. instead of using setContentComponent().
  35549. If you know what you're doing and are sure you really want to add a component, specify
  35550. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35551. */
  35552. void addChildComponent (Component* const child, int zOrder = -1);
  35553. /** Overridden to warn people about adding components directly to this component
  35554. instead of using setContentComponent().
  35555. If you know what you're doing and are sure you really want to add a component, specify
  35556. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35557. */
  35558. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35559. #endif
  35560. ResizableCornerComponent* resizableCorner;
  35561. ResizableBorderComponent* resizableBorder;
  35562. private:
  35563. Component* contentComponent;
  35564. bool resizeToFitContent, fullscreen;
  35565. Colour backgroundColour;
  35566. ComponentDragger dragger;
  35567. Rectangle lastNonFullScreenPos;
  35568. ComponentBoundsConstrainer defaultConstrainer;
  35569. ComponentBoundsConstrainer* constrainer;
  35570. #ifdef JUCE_DEBUG
  35571. bool hasBeenResized;
  35572. #endif
  35573. void updateLastPos();
  35574. ResizableWindow (const ResizableWindow&);
  35575. const ResizableWindow& operator= (const ResizableWindow&);
  35576. // (xxx remove these eventually)
  35577. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35578. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35579. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35580. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35581. };
  35582. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35583. /********* End of inlined file: juce_ResizableWindow.h *********/
  35584. /**
  35585. A resizable window with a title bar and maximise, minimise and close buttons.
  35586. This subclass of ResizableWindow creates a fairly standard type of window with
  35587. a title bar and various buttons. The name of the component is shown in the
  35588. title bar, and an icon can optionally be specified with setIcon().
  35589. All the methods available to a ResizableWindow are also available to this,
  35590. so it can easily be made resizable, minimised, maximised, etc.
  35591. It's not advisable to add child components directly to a DocumentWindow: put them
  35592. inside your content component instead. And overriding methods like resized(), moved(), etc
  35593. is also not recommended - instead override these methods for your content component.
  35594. (If for some obscure reason you do need to override these methods, always remember to
  35595. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35596. decorations correctly).
  35597. You can also automatically add a menu bar to the window, using the setMenuBar()
  35598. method.
  35599. @see ResizableWindow, DialogWindow
  35600. */
  35601. class JUCE_API DocumentWindow : public ResizableWindow
  35602. {
  35603. public:
  35604. /** The set of available button-types that can be put on the title bar.
  35605. @see setTitleBarButtonsRequired
  35606. */
  35607. enum TitleBarButtons
  35608. {
  35609. minimiseButton = 1,
  35610. maximiseButton = 2,
  35611. closeButton = 4,
  35612. /** A combination of all the buttons above. */
  35613. allButtons = 7
  35614. };
  35615. /** Creates a DocumentWindow.
  35616. @param name the name to give the component - this is also
  35617. the title shown at the top of the window. To change
  35618. this later, use setName()
  35619. @param backgroundColour the colour to use for filling the window's background.
  35620. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35621. should be shown on the title bar. This value is a bitwise
  35622. combination of values from the TitleBarButtons enum. Note
  35623. that it can be "allButtons" to get them all. You
  35624. can change this later with the setTitleBarButtonsRequired()
  35625. method, which can also specify where they are positioned.
  35626. @param addToDesktop if true, the window will be automatically added to the
  35627. desktop; if false, you can use it as a child component
  35628. @see TitleBarButtons
  35629. */
  35630. DocumentWindow (const String& name,
  35631. const Colour& backgroundColour,
  35632. const int requiredButtons,
  35633. const bool addToDesktop = true);
  35634. /** Destructor.
  35635. If a content component has been set with setContentComponent(), it
  35636. will be deleted.
  35637. */
  35638. ~DocumentWindow();
  35639. /** Changes the component's name.
  35640. (This is overridden from Component::setName() to cause a repaint, as
  35641. the name is what gets drawn across the window's title bar).
  35642. */
  35643. void setName (const String& newName);
  35644. /** Sets an icon to show in the title bar, next to the title.
  35645. A copy is made internally of the image, so the caller can delete the
  35646. image after calling this. If 0 is passed-in, any existing icon will be
  35647. removed.
  35648. */
  35649. void setIcon (const Image* imageToUse);
  35650. /** Changes the height of the title-bar. */
  35651. void setTitleBarHeight (const int newHeight);
  35652. /** Returns the current title bar height. */
  35653. int getTitleBarHeight() const;
  35654. /** Changes the set of title-bar buttons being shown.
  35655. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35656. should be shown on the title bar. This value is a bitwise
  35657. combination of values from the TitleBarButtons enum. Note
  35658. that it can be "allButtons" to get them all.
  35659. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  35660. left side of the bar; if false, they'll be placed at the right
  35661. */
  35662. void setTitleBarButtonsRequired (const int requiredButtons,
  35663. const bool positionTitleBarButtonsOnLeft);
  35664. /** Sets whether the title should be centred within the window.
  35665. If true, the title text is shown in the middle of the title-bar; if false,
  35666. it'll be shown at the left of the bar.
  35667. */
  35668. void setTitleBarTextCentred (const bool textShouldBeCentred);
  35669. /** Creates a menu inside this window.
  35670. @param menuBarModel this specifies a MenuBarModel that should be used to
  35671. generate the contents of a menu bar that will be placed
  35672. just below the title bar, and just above any content
  35673. component. If this value is zero, any existing menu bar
  35674. will be removed from the component; if non-zero, one will
  35675. be added if it's required.
  35676. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  35677. or less to use the look-and-feel's default size.
  35678. */
  35679. void setMenuBar (MenuBarModel* menuBarModel,
  35680. const int menuBarHeight = 0);
  35681. /** This method is called when the user tries to close the window.
  35682. This is triggered by the user clicking the close button, or using some other
  35683. OS-specific key shortcut or OS menu for getting rid of a window.
  35684. If the window is just a pop-up, you should override this closeButtonPressed()
  35685. method and make it delete the window in whatever way is appropriate for your
  35686. app. E.g. you might just want to call "delete this".
  35687. If your app is centred around this window such that the whole app should quit when
  35688. the window is closed, then you will probably want to use this method as an opportunity
  35689. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  35690. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  35691. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  35692. or closing it via the taskbar icon on Windows).
  35693. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  35694. redirects it to call this method, so any methods of closing the window that are
  35695. caught by userTriedToCloseWindow() will also end up here).
  35696. */
  35697. virtual void closeButtonPressed();
  35698. /** Callback that is triggered when the minimise button is pressed.
  35699. The default implementation of this calls ResizableWindow::setMinimised(), but
  35700. you can override it to do more customised behaviour.
  35701. */
  35702. virtual void minimiseButtonPressed();
  35703. /** Callback that is triggered when the maximise button is pressed, or when the
  35704. title-bar is double-clicked.
  35705. The default implementation of this calls ResizableWindow::setFullScreen(), but
  35706. you can override it to do more customised behaviour.
  35707. */
  35708. virtual void maximiseButtonPressed();
  35709. /** Returns the close button, (or 0 if there isn't one). */
  35710. Button* getCloseButton() const throw();
  35711. /** Returns the minimise button, (or 0 if there isn't one). */
  35712. Button* getMinimiseButton() const throw();
  35713. /** Returns the maximise button, (or 0 if there isn't one). */
  35714. Button* getMaximiseButton() const throw();
  35715. /** @internal */
  35716. void paint (Graphics& g);
  35717. /** @internal */
  35718. void resized();
  35719. /** @internal */
  35720. void lookAndFeelChanged();
  35721. /** @internal */
  35722. const BorderSize getBorderThickness();
  35723. /** @internal */
  35724. const BorderSize getContentComponentBorder();
  35725. /** @internal */
  35726. void mouseDoubleClick (const MouseEvent& e);
  35727. /** @internal */
  35728. void userTriedToCloseWindow();
  35729. /** @internal */
  35730. void activeWindowStatusChanged();
  35731. /** @internal */
  35732. int getDesktopWindowStyleFlags() const;
  35733. /** @internal */
  35734. void parentHierarchyChanged();
  35735. juce_UseDebuggingNewOperator
  35736. private:
  35737. int titleBarHeight, menuBarHeight, requiredButtons;
  35738. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  35739. Button* titleBarButtons [3];
  35740. Image* titleBarIcon;
  35741. MenuBarComponent* menuBar;
  35742. MenuBarModel* menuBarModel;
  35743. class ButtonListenerProxy : public ButtonListener
  35744. {
  35745. public:
  35746. ButtonListenerProxy();
  35747. void buttonClicked (Button* button);
  35748. DocumentWindow* owner;
  35749. } buttonListener;
  35750. int getBorderSize() const;
  35751. void repaintTitleBar();
  35752. DocumentWindow (const DocumentWindow&);
  35753. const DocumentWindow& operator= (const DocumentWindow&);
  35754. };
  35755. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35756. /********* End of inlined file: juce_DocumentWindow.h *********/
  35757. class MultiDocumentPanel;
  35758. class MDITabbedComponentInternal;
  35759. /**
  35760. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  35761. component.
  35762. It's like a normal DocumentWindow but has some extra functionality to make sure
  35763. everything works nicely inside a MultiDocumentPanel.
  35764. @see MultiDocumentPanel
  35765. */
  35766. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  35767. {
  35768. public:
  35769. /**
  35770. */
  35771. MultiDocumentPanelWindow (const Colour& backgroundColour);
  35772. /** Destructor. */
  35773. ~MultiDocumentPanelWindow();
  35774. /** @internal */
  35775. void maximiseButtonPressed();
  35776. /** @internal */
  35777. void closeButtonPressed();
  35778. /** @internal */
  35779. void activeWindowStatusChanged();
  35780. /** @internal */
  35781. void broughtToFront();
  35782. juce_UseDebuggingNewOperator
  35783. private:
  35784. void updateOrder();
  35785. MultiDocumentPanel* getOwner() const throw();
  35786. };
  35787. /**
  35788. A component that contains a set of other components either in floating windows
  35789. or tabs.
  35790. This acts as a panel that can be used to hold a set of open document windows, with
  35791. different layout modes.
  35792. Use addDocument() and closeDocument() to add or remove components from the
  35793. panel - never use any of the Component methods to access the panel's child
  35794. components directly, as these are managed internally.
  35795. */
  35796. class JUCE_API MultiDocumentPanel : public Component,
  35797. private ComponentListener
  35798. {
  35799. public:
  35800. /** Creates an empty panel.
  35801. Use addDocument() and closeDocument() to add or remove components from the
  35802. panel - never use any of the Component methods to access the panel's child
  35803. components directly, as these are managed internally.
  35804. */
  35805. MultiDocumentPanel();
  35806. /** Destructor.
  35807. When deleted, this will call closeAllDocuments (false) to make sure all its
  35808. components are deleted. If you need to make sure all documents are saved
  35809. before closing, then you should call closeAllDocuments (true) and check that
  35810. it returns true before deleting the panel.
  35811. */
  35812. ~MultiDocumentPanel();
  35813. /** Tries to close all the documents.
  35814. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35815. be called for each open document, and any of these calls fails, this method
  35816. will stop and return false, leaving some documents still open.
  35817. If checkItsOkToCloseFirst is false, then all documents will be closed
  35818. unconditionally.
  35819. @see closeDocument
  35820. */
  35821. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  35822. /** Adds a document component to the panel.
  35823. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  35824. this will fail and return false. (If it does fail, the component passed-in will not be
  35825. deleted, even if deleteWhenRemoved was set to true).
  35826. The MultiDocumentPanel will deal with creating a window border to go around your component,
  35827. so just pass in the bare content component here, no need to give it a ResizableWindow
  35828. or DocumentWindow.
  35829. @param component the component to add
  35830. @param backgroundColour the background colour to use to fill the component's
  35831. window or tab
  35832. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  35833. or closeAllDocuments(), then it will be deleted. If false, then
  35834. the caller must handle the component's deletion
  35835. */
  35836. bool addDocument (Component* const component,
  35837. const Colour& backgroundColour,
  35838. const bool deleteWhenRemoved);
  35839. /** Closes one of the documents.
  35840. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35841. be called, and if it fails, this method will return false without closing the
  35842. document.
  35843. If checkItsOkToCloseFirst is false, then the documents will be closed
  35844. unconditionally.
  35845. The component will be deleted if the deleteWhenRemoved parameter was set to
  35846. true when it was added with addDocument.
  35847. @see addDocument, closeAllDocuments
  35848. */
  35849. bool closeDocument (Component* component,
  35850. const bool checkItsOkToCloseFirst);
  35851. /** Returns the number of open document windows.
  35852. @see getDocument
  35853. */
  35854. int getNumDocuments() const throw();
  35855. /** Returns one of the open documents.
  35856. The order of the documents in this array may change when they are added, removed
  35857. or moved around.
  35858. @see getNumDocuments
  35859. */
  35860. Component* getDocument (const int index) const throw();
  35861. /** Returns the document component that is currently focused or on top.
  35862. If currently using floating windows, then this will be the component in the currently
  35863. active window, or the top component if none are active.
  35864. If it's currently in tabbed mode, then it'll return the component in the active tab.
  35865. @see setActiveDocument
  35866. */
  35867. Component* getActiveDocument() const throw();
  35868. /** Makes one of the components active and brings it to the top.
  35869. @see getActiveDocument
  35870. */
  35871. void setActiveDocument (Component* component);
  35872. /** Callback which gets invoked when the currently-active document changes. */
  35873. virtual void activeDocumentChanged();
  35874. /** Sets a limit on how many windows can be open at once.
  35875. If this is zero or less there's no limit (the default). addDocument() will fail
  35876. if this number is exceeded.
  35877. */
  35878. void setMaximumNumDocuments (const int maximumNumDocuments);
  35879. /** Sets an option to make the document fullscreen if there's only one document open.
  35880. If set to true, then if there's only one document, it'll fill the whole of this
  35881. component without tabs or a window border. If false, then tabs or a window
  35882. will always be shown, even if there's only one document. If there's more than
  35883. one document open, then this option makes no difference.
  35884. */
  35885. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  35886. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  35887. */
  35888. bool isFullscreenWhenOneDocument() const throw();
  35889. /** The different layout modes available. */
  35890. enum LayoutMode
  35891. {
  35892. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  35893. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  35894. };
  35895. /** Changes the panel's mode.
  35896. @see LayoutMode, getLayoutMode
  35897. */
  35898. void setLayoutMode (const LayoutMode newLayoutMode);
  35899. /** Returns the current layout mode. */
  35900. LayoutMode getLayoutMode() const throw() { return mode; }
  35901. /** Sets the background colour for the whole panel.
  35902. Each document has its own background colour, but this is the one used to fill the areas
  35903. behind them.
  35904. */
  35905. void setBackgroundColour (const Colour& newBackgroundColour);
  35906. /** Returns the current background colour.
  35907. @see setBackgroundColour
  35908. */
  35909. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35910. /** A subclass must override this to say whether its currently ok for a document
  35911. to be closed.
  35912. This method is called by closeDocument() and closeAllDocuments() to indicate that
  35913. a document should be saved if possible, ready for it to be closed.
  35914. If this method returns true, then it means the document is ok and can be closed.
  35915. If it returns false, then it means that the closeDocument() method should stop
  35916. and not close.
  35917. Normally, you'd use this method to ask the user if they want to save any changes,
  35918. then return true if the save operation went ok. If the user cancelled the save
  35919. operation you could return false here to abort the close operation.
  35920. If your component is based on the FileBasedDocument class, then you'd probably want
  35921. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  35922. FileBasedDocument::savedOk
  35923. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  35924. */
  35925. virtual bool tryToCloseDocument (Component* component) = 0;
  35926. /** Creates a new window to be used for a document.
  35927. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  35928. but you might want to override it to return a custom component.
  35929. */
  35930. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  35931. /** @internal */
  35932. void paint (Graphics& g);
  35933. /** @internal */
  35934. void resized();
  35935. /** @internal */
  35936. void componentNameChanged (Component&);
  35937. juce_UseDebuggingNewOperator
  35938. private:
  35939. LayoutMode mode;
  35940. Array <Component*> components;
  35941. TabbedComponent* tabComponent;
  35942. Colour backgroundColour;
  35943. int maximumNumDocuments, numDocsBeforeTabsUsed;
  35944. friend class MultiDocumentPanelWindow;
  35945. friend class MDITabbedComponentInternal;
  35946. Component* getContainerComp (Component* c) const;
  35947. void updateOrder();
  35948. void addWindow (Component* component);
  35949. };
  35950. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35951. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  35952. #endif
  35953. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35954. #endif
  35955. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35956. #endif
  35957. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  35958. #endif
  35959. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35960. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  35961. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35962. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35963. /**
  35964. For laying out a set of components, where the components have preferred sizes
  35965. and size limits, but where they are allowed to stretch to fill the available
  35966. space.
  35967. For example, if you have a component containing several other components, and
  35968. each one should be given a share of the total size, you could use one of these
  35969. to resize the child components when the parent component is resized. Then
  35970. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  35971. A StretchableLayoutManager operates only in one dimension, so if you have a set
  35972. of components stacked vertically on top of each other, you'd use one to manage their
  35973. heights. To build up complex arrangements of components, e.g. for applications
  35974. with multiple nested panels, you would use more than one StretchableLayoutManager.
  35975. E.g. by using two (one vertical, one horizontal), you could create a resizable
  35976. spreadsheet-style table.
  35977. E.g.
  35978. @code
  35979. class MyComp : public Component
  35980. {
  35981. StretchableLayoutManager myLayout;
  35982. MyComp()
  35983. {
  35984. myLayout.setItemLayout (0, // for item 0
  35985. 50, 100, // must be between 50 and 100 pixels in size
  35986. -0.6); // and its preferred size is 60% of the total available space
  35987. myLayout.setItemLayout (1, // for item 1
  35988. -0.2, -0.6, // size must be between 20% and 60% of the available space
  35989. 50); // and its preferred size is 50 pixels
  35990. }
  35991. void resized()
  35992. {
  35993. // make a list of two of our child components that we want to reposition
  35994. Component* comps[] = { myComp1, myComp2 };
  35995. // this will position the 2 components, one above the other, to fit
  35996. // vertically into the rectangle provided.
  35997. myLayout.layOutComponents (comps, 2,
  35998. 0, 0, getWidth(), getHeight(),
  35999. true);
  36000. }
  36001. };
  36002. @endcode
  36003. @see StretchableLayoutResizerBar
  36004. */
  36005. class JUCE_API StretchableLayoutManager
  36006. {
  36007. public:
  36008. /** Creates an empty layout.
  36009. You'll need to add some item properties to the layout before it can be used
  36010. to resize things - see setItemLayout().
  36011. */
  36012. StretchableLayoutManager();
  36013. /** Destructor. */
  36014. ~StretchableLayoutManager();
  36015. /** For a numbered item, this sets its size limits and preferred size.
  36016. @param itemIndex the index of the item to change.
  36017. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36018. indicates an absolute size in pixels. A negative number indicates a
  36019. proportion of the available space (e.g -0.5 is 50%)
  36020. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36021. indicates an absolute size in pixels. A negative number indicates a
  36022. proportion of the available space
  36023. @param preferredSize the size that this item would like to be, if there's enough room. A
  36024. positive number indicates an absolute size in pixels. A negative number
  36025. indicates a proportion of the available space
  36026. @see getItemLayout
  36027. */
  36028. void setItemLayout (const int itemIndex,
  36029. const double minimumSize,
  36030. const double maximumSize,
  36031. const double preferredSize);
  36032. /** For a numbered item, this returns its size limits and preferred size.
  36033. @param itemIndex the index of the item.
  36034. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36035. indicates an absolute size in pixels. A negative number indicates a
  36036. proportion of the available space (e.g -0.5 is 50%)
  36037. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36038. indicates an absolute size in pixels. A negative number indicates a
  36039. proportion of the available space
  36040. @param preferredSize the size that this item would like to be, if there's enough room. A
  36041. positive number indicates an absolute size in pixels. A negative number
  36042. indicates a proportion of the available space
  36043. @returns false if the item's properties hadn't been set
  36044. @see setItemLayout
  36045. */
  36046. bool getItemLayout (const int itemIndex,
  36047. double& minimumSize,
  36048. double& maximumSize,
  36049. double& preferredSize) const;
  36050. /** Clears all the properties that have been set with setItemLayout() and resets
  36051. this object to its initial state.
  36052. */
  36053. void clearAllItems();
  36054. /** Takes a set of components that correspond to the layout's items, and positions
  36055. them to fill a space.
  36056. This will try to give each item its preferred size, whether that's a relative size
  36057. or an absolute one.
  36058. @param components an array of components that correspond to each of the
  36059. numbered items that the StretchableLayoutManager object
  36060. has been told about with setItemLayout()
  36061. @param numComponents the number of components in the array that is passed-in. This
  36062. should be the same as the number of items this object has been
  36063. told about.
  36064. @param x the left of the rectangle in which the components should
  36065. be laid out
  36066. @param y the top of the rectangle in which the components should
  36067. be laid out
  36068. @param width the width of the rectangle in which the components should
  36069. be laid out
  36070. @param height the height of the rectangle in which the components should
  36071. be laid out
  36072. @param vertically if true, the components will be positioned in a vertical stack,
  36073. so that they fill the height of the rectangle. If false, they
  36074. will be placed side-by-side in a horizontal line, filling the
  36075. available width
  36076. @param resizeOtherDimension if true, this means that the components will have their
  36077. other dimension resized to fit the space - i.e. if the 'vertically'
  36078. parameter is true, their x-positions and widths are adjusted to fit
  36079. the x and width parameters; if 'vertically' is false, their y-positions
  36080. and heights are adjusted to fit the y and height parameters.
  36081. */
  36082. void layOutComponents (Component** const components,
  36083. int numComponents,
  36084. int x, int y, int width, int height,
  36085. const bool vertically,
  36086. const bool resizeOtherDimension);
  36087. /** Returns the current position of one of the items.
  36088. This is only a valid call after layOutComponents() has been called, as it
  36089. returns the last position that this item was placed at. If the layout was
  36090. vertical, the value returned will be the y position of the top of the item,
  36091. relative to the top of the rectangle in which the items were placed (so for
  36092. example, item 0 will always have position of 0, even in the rectangle passed
  36093. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  36094. the position returned is the item's left-hand position, again relative to the
  36095. x position of the rectangle used.
  36096. @see getItemCurrentSize, setItemPosition
  36097. */
  36098. int getItemCurrentPosition (const int itemIndex) const;
  36099. /** Returns the current size of one of the items.
  36100. This is only meaningful after layOutComponents() has been called, as it
  36101. returns the last size that this item was given. If the layout was done
  36102. vertically, it'll return the item's height in pixels; if it was horizontal,
  36103. it'll return its width.
  36104. @see getItemCurrentRelativeSize
  36105. */
  36106. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36107. /** Returns the current size of one of the items.
  36108. This is only meaningful after layOutComponents() has been called, as it
  36109. returns the last size that this item was given. If the layout was done
  36110. vertically, it'll return a negative value representing the item's height relative
  36111. to the last size used for laying the components out; if the layout was done
  36112. horizontally it'll be the proportion of its width.
  36113. @see getItemCurrentAbsoluteSize
  36114. */
  36115. double getItemCurrentRelativeSize (const int itemIndex) const;
  36116. /** Moves one of the items, shifting along any other items as necessary in
  36117. order to get it to the desired position.
  36118. Calling this method will also update the preferred sizes of the items it
  36119. shuffles along, so that they reflect their new positions.
  36120. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36121. about when it's dragged).
  36122. @param itemIndex the item to move
  36123. @param newPosition the absolute position that you'd like this item to move
  36124. to. The item might not be able to always reach exactly this position,
  36125. because other items may have minimum sizes that constrain how
  36126. far it can go
  36127. */
  36128. void setItemPosition (const int itemIndex,
  36129. int newPosition);
  36130. juce_UseDebuggingNewOperator
  36131. private:
  36132. struct ItemLayoutProperties
  36133. {
  36134. int itemIndex;
  36135. int currentSize;
  36136. double minSize, maxSize, preferredSize;
  36137. };
  36138. OwnedArray <ItemLayoutProperties> items;
  36139. int totalSize;
  36140. static int sizeToRealSize (double size, int totalSpace);
  36141. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36142. void setTotalSize (const int newTotalSize);
  36143. int fitComponentsIntoSpace (const int startIndex,
  36144. const int endIndex,
  36145. const int availableSpace,
  36146. int startPos);
  36147. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36148. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36149. void updatePrefSizesToMatchCurrentPositions();
  36150. StretchableLayoutManager (const StretchableLayoutManager&);
  36151. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36152. };
  36153. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36154. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36155. #endif
  36156. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36157. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36158. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36159. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36160. /**
  36161. A component that acts as one of the vertical or horizontal bars you see being
  36162. used to resize panels in a window.
  36163. One of these acts with a StretchableLayoutManager to resize the other components.
  36164. @see StretchableLayoutManager
  36165. */
  36166. class JUCE_API StretchableLayoutResizerBar : public Component
  36167. {
  36168. public:
  36169. /** Creates a resizer bar for use on a specified layout.
  36170. @param layoutToUse the layout that will be affected when this bar
  36171. is dragged
  36172. @param itemIndexInLayout the item index in the layout that corresponds to
  36173. this bar component. You'll need to set up the item
  36174. properties in a suitable way for a divider bar, e.g.
  36175. for an 8-pixel wide bar which, you could call
  36176. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36177. @param isBarVertical true if it's an upright bar that you drag left and
  36178. right; false for a horizontal one that you drag up and
  36179. down
  36180. */
  36181. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36182. const int itemIndexInLayout,
  36183. const bool isBarVertical);
  36184. /** Destructor. */
  36185. ~StretchableLayoutResizerBar();
  36186. /** This is called when the bar is dragged.
  36187. This method must update the positions of any components whose position is
  36188. determined by the StretchableLayoutManager, because they might have just
  36189. moved.
  36190. The default implementation calls the resized() method of this component's
  36191. parent component, because that's often where you're likely to apply the
  36192. layout, but it can be overridden for more specific needs.
  36193. */
  36194. virtual void hasBeenMoved();
  36195. /** @internal */
  36196. void paint (Graphics& g);
  36197. /** @internal */
  36198. void mouseDown (const MouseEvent& e);
  36199. /** @internal */
  36200. void mouseDrag (const MouseEvent& e);
  36201. juce_UseDebuggingNewOperator
  36202. private:
  36203. StretchableLayoutManager* layout;
  36204. int itemIndex, mouseDownPos;
  36205. bool isVertical;
  36206. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36207. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36208. };
  36209. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36210. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36211. #endif
  36212. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36213. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36214. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36215. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36216. /**
  36217. A utility class for fitting a set of objects whose sizes can vary between
  36218. a minimum and maximum size, into a space.
  36219. This is a trickier algorithm than it would first seem, so I've put it in this
  36220. class to allow it to be shared by various bits of code.
  36221. To use it, create one of these objects, call addItem() to add the list of items
  36222. you need, then call resizeToFit(), which will change all their sizes. You can
  36223. then retrieve the new sizes with getItemSize() and getNumItems().
  36224. It's currently used by the TableHeaderComponent for stretching out the table
  36225. headings to fill the table's width.
  36226. */
  36227. class StretchableObjectResizer
  36228. {
  36229. public:
  36230. /** Creates an empty object resizer. */
  36231. StretchableObjectResizer();
  36232. /** Destructor. */
  36233. ~StretchableObjectResizer();
  36234. /** Adds an item to the list.
  36235. The order parameter lets you specify groups of items that are resized first when some
  36236. space needs to be found. Those items with an order of 0 will be the first ones to be
  36237. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36238. will then try resizing the items with an order of 1, then 2, and so on.
  36239. */
  36240. void addItem (const double currentSize,
  36241. const double minSize,
  36242. const double maxSize,
  36243. const int order = 0);
  36244. /** Resizes all the items to fit this amount of space.
  36245. This will attempt to fit them in without exceeding each item's miniumum and
  36246. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36247. further, the final size may be greater or less than the size passed in.
  36248. After calling this method, you can retrieve the new sizes with the getItemSize()
  36249. method.
  36250. */
  36251. void resizeToFit (const double targetSize);
  36252. /** Returns the number of items that have been added. */
  36253. int getNumItems() const throw() { return items.size(); }
  36254. /** Returns the size of one of the items. */
  36255. double getItemSize (const int index) const throw();
  36256. juce_UseDebuggingNewOperator
  36257. private:
  36258. struct Item
  36259. {
  36260. double size;
  36261. double minSize;
  36262. double maxSize;
  36263. int order;
  36264. };
  36265. OwnedArray <Item> items;
  36266. StretchableObjectResizer (const StretchableObjectResizer&);
  36267. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36268. };
  36269. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36270. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36271. #endif
  36272. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36273. #endif
  36274. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36275. #endif
  36276. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36277. #endif
  36278. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36279. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36280. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36281. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36282. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  36283. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36284. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36285. /********* Start of inlined file: juce_FileFilter.h *********/
  36286. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36287. #define __JUCE_FILEFILTER_JUCEHEADER__
  36288. /**
  36289. Interface for deciding which files are suitable for something.
  36290. For example, this is used by DirectoryContentsList to select which files
  36291. go into the list.
  36292. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36293. */
  36294. class JUCE_API FileFilter
  36295. {
  36296. public:
  36297. /** Creates a filter with the given description.
  36298. The description can be returned later with the getDescription() method.
  36299. */
  36300. FileFilter (const String& filterDescription);
  36301. /** Destructor. */
  36302. virtual ~FileFilter();
  36303. /** Returns the description that the filter was created with. */
  36304. const String& getDescription() const throw();
  36305. /** Should return true if this file is suitable for inclusion in whatever context
  36306. the object is being used.
  36307. */
  36308. virtual bool isFileSuitable (const File& file) const = 0;
  36309. /** Should return true if this directory is suitable for inclusion in whatever context
  36310. the object is being used.
  36311. */
  36312. virtual bool isDirectorySuitable (const File& file) const = 0;
  36313. protected:
  36314. String description;
  36315. };
  36316. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36317. /********* End of inlined file: juce_FileFilter.h *********/
  36318. /**
  36319. A class to asynchronously scan for details about the files in a directory.
  36320. This keeps a list of files and some information about them, using a background
  36321. thread to scan for more files. As files are found, it broadcasts change messages
  36322. to tell any listeners.
  36323. @see FileListComponent, FileBrowserComponent
  36324. */
  36325. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36326. public TimeSliceClient
  36327. {
  36328. public:
  36329. /** Creates a directory list.
  36330. To set the directory it should point to, use setDirectory(), which will
  36331. also start it scanning for files on the background thread.
  36332. When the background thread finds and adds new files to this list, the
  36333. ChangeBroadcaster class will send a change message, so you can register
  36334. listeners and update them when the list changes.
  36335. @param fileFilter an optional filter to select which files are
  36336. included in the list. If this is 0, then all files
  36337. and directories are included. Make sure that the
  36338. filter doesn't get deleted during the lifetime of this
  36339. object
  36340. @param threadToUse a thread object that this list can use
  36341. to scan for files as a background task. Make sure
  36342. that the thread you give it has been started, or you
  36343. won't get any files!
  36344. */
  36345. DirectoryContentsList (const FileFilter* const fileFilter,
  36346. TimeSliceThread& threadToUse);
  36347. /** Destructor. */
  36348. ~DirectoryContentsList();
  36349. /** Sets the directory to look in for files.
  36350. If the directory that's passed in is different to the current one, this will
  36351. also start the background thread scanning it for files.
  36352. */
  36353. void setDirectory (const File& directory,
  36354. const bool includeDirectories,
  36355. const bool includeFiles);
  36356. /** Returns the directory that's currently being used. */
  36357. const File& getDirectory() const throw();
  36358. /** Clears the list, and stops the thread scanning for files. */
  36359. void clear();
  36360. /** Clears the list and restarts scanning the directory for files. */
  36361. void refresh();
  36362. /** True if the background thread hasn't yet finished scanning for files. */
  36363. bool isStillLoading() const;
  36364. /** Tells the list whether or not to ignore hidden files.
  36365. By default these are ignored.
  36366. */
  36367. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  36368. /** Contains cached information about one of the files in a DirectoryContentsList.
  36369. */
  36370. struct FileInfo
  36371. {
  36372. /** The filename.
  36373. This isn't a full pathname, it's just the last part of the path, same as you'd
  36374. get from File::getFileName().
  36375. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36376. */
  36377. String filename;
  36378. /** File size in bytes. */
  36379. int64 fileSize;
  36380. /** File modification time.
  36381. As supplied by File::getLastModificationTime().
  36382. */
  36383. Time modificationTime;
  36384. /** File creation time.
  36385. As supplied by File::getCreationTime().
  36386. */
  36387. Time creationTime;
  36388. /** True if the file is a directory. */
  36389. bool isDirectory;
  36390. /** True if the file is read-only. */
  36391. bool isReadOnly;
  36392. };
  36393. /** Returns the number of files currently available in the list.
  36394. The info about one of these files can be retrieved with getFileInfo() or
  36395. getFile().
  36396. Obviously as the background thread runs and scans the directory for files, this
  36397. number will change.
  36398. @see getFileInfo, getFile
  36399. */
  36400. int getNumFiles() const;
  36401. /** Returns the cached information about one of the files in the list.
  36402. If the index is in-range, this will return true and will copy the file's details
  36403. to the structure that is passed-in.
  36404. If it returns false, then the index wasn't in range, and the structure won't
  36405. be affected.
  36406. @see getNumFiles, getFile
  36407. */
  36408. bool getFileInfo (const int index,
  36409. FileInfo& resultInfo) const;
  36410. /** Returns one of the files in the list.
  36411. @param index should be less than getNumFiles(). If this is out-of-range, the
  36412. return value will be File::nonexistent
  36413. @see getNumFiles, getFileInfo
  36414. */
  36415. const File getFile (const int index) const;
  36416. /** Returns the file filter being used.
  36417. The filter is specified in the constructor.
  36418. */
  36419. const FileFilter* getFilter() const throw() { return fileFilter; }
  36420. /** @internal */
  36421. bool useTimeSlice();
  36422. /** @internal */
  36423. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  36424. /** @internal */
  36425. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  36426. const DirectoryContentsList::FileInfo* const second) throw();
  36427. juce_UseDebuggingNewOperator
  36428. private:
  36429. File root;
  36430. const FileFilter* fileFilter;
  36431. TimeSliceThread& thread;
  36432. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  36433. CriticalSection fileListLock;
  36434. OwnedArray <FileInfo> files;
  36435. void* volatile fileFindHandle;
  36436. bool volatile shouldStop;
  36437. void changed();
  36438. bool checkNextFile (bool& hasChanged);
  36439. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  36440. const int64 fileSize, const Time& modTime,
  36441. const Time& creationTime, const bool isReadOnly);
  36442. DirectoryContentsList (const DirectoryContentsList&);
  36443. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  36444. };
  36445. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36446. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  36447. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  36448. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36449. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36450. /**
  36451. A listener for user selection events in a file browser.
  36452. This is used by a FileBrowserComponent or FileListComponent.
  36453. */
  36454. class JUCE_API FileBrowserListener
  36455. {
  36456. public:
  36457. /** Destructor. */
  36458. virtual ~FileBrowserListener();
  36459. /** Callback when the user selects a different file in the browser. */
  36460. virtual void selectionChanged() = 0;
  36461. /** Callback when the user clicks on a file in the browser. */
  36462. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36463. /** Callback when the user double-clicks on a file in the browser. */
  36464. virtual void fileDoubleClicked (const File& file) = 0;
  36465. };
  36466. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36467. /********* End of inlined file: juce_FileBrowserListener.h *********/
  36468. /**
  36469. A base class for components that display a list of the files in a directory.
  36470. @see DirectoryContentsList
  36471. */
  36472. class JUCE_API DirectoryContentsDisplayComponent
  36473. {
  36474. public:
  36475. /**
  36476. */
  36477. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36478. /** Destructor. */
  36479. virtual ~DirectoryContentsDisplayComponent();
  36480. /** Returns the file that the user has currently selected.
  36481. Returns File::nonexistent if none is selected.
  36482. */
  36483. virtual const File getSelectedFile() const = 0;
  36484. /** Scrolls this view to the top. */
  36485. virtual void scrollToTop() = 0;
  36486. /** Adds a listener to be told when files are selected or clicked.
  36487. @see removeListener
  36488. */
  36489. void addListener (FileBrowserListener* const listener) throw();
  36490. /** Removes a listener.
  36491. @see addListener
  36492. */
  36493. void removeListener (FileBrowserListener* const listener) throw();
  36494. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36495. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36496. methods.
  36497. Note that you can also use the constants from TextEditor::ColourIds to change the
  36498. colour of the text editor that is opened when a label is editable.
  36499. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36500. */
  36501. enum ColourIds
  36502. {
  36503. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36504. textColourId = 0x1000541, /**< The colour for the text. */
  36505. };
  36506. /** @internal */
  36507. void sendSelectionChangeMessage();
  36508. /** @internal */
  36509. void sendDoubleClickMessage (const File& file);
  36510. /** @internal */
  36511. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36512. juce_UseDebuggingNewOperator
  36513. protected:
  36514. DirectoryContentsList& fileList;
  36515. SortedSet <void*> listeners;
  36516. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36517. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36518. };
  36519. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36520. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36521. #endif
  36522. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36523. #endif
  36524. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36525. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  36526. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36527. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36528. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  36529. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36530. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36531. /**
  36532. Base class for components that live inside a file chooser dialog box and
  36533. show previews of the files that get selected.
  36534. One of these allows special extra information to be displayed for files
  36535. in a dialog box as the user selects them. Each time the current file or
  36536. directory is changed, the selectedFileChanged() method will be called
  36537. to allow it to update itself appropriately.
  36538. @see FileChooser, ImagePreviewComponent
  36539. */
  36540. class JUCE_API FilePreviewComponent : public Component
  36541. {
  36542. public:
  36543. /** Creates a FilePreviewComponent. */
  36544. FilePreviewComponent();
  36545. /** Destructor. */
  36546. ~FilePreviewComponent();
  36547. /** Called to indicate that the user's currently selected file has changed.
  36548. @param newSelectedFile the newly selected file or directory, which may be
  36549. File::nonexistent if none is selected.
  36550. */
  36551. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36552. juce_UseDebuggingNewOperator
  36553. private:
  36554. FilePreviewComponent (const FilePreviewComponent&);
  36555. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  36556. };
  36557. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36558. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  36559. /**
  36560. A component for browsing and selecting a file or directory to open or save.
  36561. This contains a FileListComponent and adds various boxes and controls for
  36562. navigating and selecting a file. It can work in different modes so that it can
  36563. be used for loading or saving a file, or for choosing a directory.
  36564. @see FileChooserDialogBox, FileChooser, FileListComponent
  36565. */
  36566. class JUCE_API FileBrowserComponent : public Component,
  36567. public ChangeBroadcaster,
  36568. private FileBrowserListener,
  36569. private TextEditorListener,
  36570. private ButtonListener,
  36571. private ComboBoxListener
  36572. {
  36573. public:
  36574. /** Various modes that the browser can be used in.
  36575. One of these is passed into the constructor.
  36576. */
  36577. enum FileChooserMode
  36578. {
  36579. loadFileMode, /**< the component should allow the user to choose an existing
  36580. file with the intention of opening it. */
  36581. saveFileMode, /**< the component should allow the user to specify the name of
  36582. a file that will be used to save something. */
  36583. chooseDirectoryMode /**< the component should allow the user to select an existing
  36584. directory. */
  36585. };
  36586. /** Creates a FileBrowserComponent.
  36587. @param browserMode The intended purpose for the browser - see the
  36588. FileChooserMode enum for the various options
  36589. @param initialFileOrDirectory The file or directory that should be selected when
  36590. the component begins. If this is File::nonexistent,
  36591. a default directory will be chosen.
  36592. @param fileFilter an optional filter to use to determine which files
  36593. are shown. If this is 0 then all files are displayed. Note
  36594. that a pointer is kept internally to this object, so
  36595. make sure that it is not deleted before the browser object
  36596. is deleted.
  36597. @param previewComp an optional preview component that will be used to
  36598. show previews of files that the user selects
  36599. @param useTreeView if this is false, the files are shown in a list; if true,
  36600. they are shown in a treeview
  36601. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  36602. text into the filename box.
  36603. */
  36604. FileBrowserComponent (FileChooserMode browserMode,
  36605. const File& initialFileOrDirectory,
  36606. const FileFilter* fileFilter,
  36607. FilePreviewComponent* previewComp,
  36608. const bool useTreeView = false,
  36609. const bool filenameTextBoxIsReadOnly = false);
  36610. /** Destructor. */
  36611. ~FileBrowserComponent();
  36612. /**
  36613. */
  36614. const File getCurrentFile() const throw();
  36615. /** Returns true if the current file is usable.
  36616. This can be used to decide whether the user can press "ok" for the
  36617. current file. What it does depends on the mode, so for example in an "open"
  36618. mode, the current file is only valid if one has been selected and if the file
  36619. exists. In a "save" mode, a non-existent file would also be valid.
  36620. */
  36621. bool currentFileIsValid() const;
  36622. /** Returns the directory whose contents are currently being shown in the listbox. */
  36623. const File getRoot() const;
  36624. /** Changes the directory that's being shown in the listbox. */
  36625. void setRoot (const File& newRootDirectory);
  36626. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36627. void goUp();
  36628. /** Refreshes the directory that's currently being listed. */
  36629. void refresh();
  36630. /** Returns the browser's current mode. */
  36631. FileChooserMode getMode() const throw() { return mode; }
  36632. /** Returns a verb to describe what should happen when the file is accepted.
  36633. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36634. mode, it'll be "Save", etc.
  36635. */
  36636. virtual const String getActionVerb() const;
  36637. /** Adds a listener to be told when the user selects and clicks on files.
  36638. @see removeListener
  36639. */
  36640. void addListener (FileBrowserListener* const listener) throw();
  36641. /** Removes a listener.
  36642. @see addListener
  36643. */
  36644. void removeListener (FileBrowserListener* const listener) throw();
  36645. /** @internal */
  36646. void resized();
  36647. /** @internal */
  36648. void buttonClicked (Button* b);
  36649. /** @internal */
  36650. void comboBoxChanged (ComboBox*);
  36651. /** @internal */
  36652. void textEditorTextChanged (TextEditor& editor);
  36653. /** @internal */
  36654. void textEditorReturnKeyPressed (TextEditor& editor);
  36655. /** @internal */
  36656. void textEditorEscapeKeyPressed (TextEditor& editor);
  36657. /** @internal */
  36658. void textEditorFocusLost (TextEditor& editor);
  36659. /** @internal */
  36660. void selectionChanged();
  36661. /** @internal */
  36662. void fileClicked (const File& f, const MouseEvent& e);
  36663. /** @internal */
  36664. void fileDoubleClicked (const File& f);
  36665. /** @internal */
  36666. FilePreviewComponent* getPreviewComponent() const throw();
  36667. juce_UseDebuggingNewOperator
  36668. protected:
  36669. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  36670. private:
  36671. DirectoryContentsList* fileList;
  36672. FileFilter* directoriesOnlyFilter;
  36673. FileChooserMode mode;
  36674. File currentRoot;
  36675. SortedSet <void*> listeners;
  36676. DirectoryContentsDisplayComponent* fileListComponent;
  36677. FilePreviewComponent* previewComp;
  36678. ComboBox* currentPathBox;
  36679. TextEditor* filenameBox;
  36680. Button* goUpButton;
  36681. TimeSliceThread thread;
  36682. void sendListenerChangeMessage();
  36683. FileBrowserComponent (const FileBrowserComponent&);
  36684. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  36685. };
  36686. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36687. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  36688. #endif
  36689. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36690. #endif
  36691. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36692. /********* Start of inlined file: juce_FileChooser.h *********/
  36693. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36694. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36695. /**
  36696. Creates a dialog box to choose a file or directory to load or save.
  36697. To use a FileChooser:
  36698. - create one (as a local stack variable is the neatest way)
  36699. - call one of its browseFor.. methods
  36700. - if this returns true, the user has selected a file, so you can retrieve it
  36701. with the getResult() method.
  36702. e.g. @code
  36703. void loadMooseFile()
  36704. {
  36705. FileChooser myChooser ("Please select the moose you want to load...",
  36706. File::getSpecialLocation (File::userHomeDirectory),
  36707. "*.moose");
  36708. if (myChooser.browseForFileToOpen())
  36709. {
  36710. File mooseFile (myChooser.getResult());
  36711. loadMoose (mooseFile);
  36712. }
  36713. }
  36714. @endcode
  36715. */
  36716. class JUCE_API FileChooser
  36717. {
  36718. public:
  36719. /** Creates a FileChooser.
  36720. After creating one of these, use one of the browseFor... methods to display it.
  36721. @param dialogBoxTitle a text string to display in the dialog box to
  36722. tell the user what's going on
  36723. @param initialFileOrDirectory the file or directory that should be selected when
  36724. the dialog box opens. If this parameter is set to
  36725. File::nonexistent, a sensible default directory
  36726. will be used instead.
  36727. @param filePatternsAllowed a set of file patterns to specify which files can be
  36728. selected - each pattern should be separated by a
  36729. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36730. empty string means that all files are allowed
  36731. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36732. possible; if false, then a Juce-based browser dialog
  36733. box will always be used
  36734. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36735. */
  36736. FileChooser (const String& dialogBoxTitle,
  36737. const File& initialFileOrDirectory = File::nonexistent,
  36738. const String& filePatternsAllowed = String::empty,
  36739. const bool useOSNativeDialogBox = true);
  36740. /** Destructor. */
  36741. ~FileChooser();
  36742. /** Shows a dialog box to choose a file to open.
  36743. This will display the dialog box modally, using an "open file" mode, so that
  36744. it won't allow non-existent files or directories to be chosen.
  36745. @param previewComponent an optional component to display inside the dialog
  36746. box to show special info about the files that the user
  36747. is browsing. The component will not be deleted by this
  36748. object, so the caller must take care of it.
  36749. @returns true if the user selected a file, in which case, use the getResult()
  36750. method to find out what it was. Returns false if they cancelled instead.
  36751. @see browseForFileToSave, browseForDirectory
  36752. */
  36753. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36754. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36755. The files that are returned can be obtained by calling getResults(). See
  36756. browseForFileToOpen() for more info about the behaviour of this method.
  36757. */
  36758. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36759. /** Shows a dialog box to choose a file to save.
  36760. This will display the dialog box modally, using an "save file" mode, so it
  36761. will allow non-existent files to be chosen, but not directories.
  36762. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36763. the user if they're sure they want to overwrite a file that already
  36764. exists
  36765. @returns true if the user chose a file and pressed 'ok', in which case, use
  36766. the getResult() method to find out what the file was. Returns false
  36767. if they cancelled instead.
  36768. @see browseForFileToOpen, browseForDirectory
  36769. */
  36770. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  36771. /** Shows a dialog box to choose a directory.
  36772. This will display the dialog box modally, using an "open directory" mode, so it
  36773. will only allow directories to be returned, not files.
  36774. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36775. the getResult() method to find out what they chose. Returns false
  36776. if they cancelled instead.
  36777. @see browseForFileToOpen, browseForFileToSave
  36778. */
  36779. bool browseForDirectory();
  36780. /** Returns the last file that was chosen by one of the browseFor methods.
  36781. After calling the appropriate browseFor... method, this method lets you
  36782. find out what file or directory they chose.
  36783. Note that the file returned is only valid if the browse method returned true (i.e.
  36784. if the user pressed 'ok' rather than cancelling).
  36785. If you're using a multiple-file select, then use the getResults() method instead,
  36786. to obtain the list of all files chosen.
  36787. @see getResults
  36788. */
  36789. const File getResult() const;
  36790. /** Returns a list of all the files that were chosen during the last call to a
  36791. browse method.
  36792. This array may be empty if no files were chosen, or can contain multiple entries
  36793. if multiple files were chosen.
  36794. @see getResult
  36795. */
  36796. const OwnedArray <File>& getResults() const;
  36797. juce_UseDebuggingNewOperator
  36798. private:
  36799. String title, filters;
  36800. File startingFile;
  36801. OwnedArray <File> results;
  36802. bool useNativeDialogBox;
  36803. bool showDialog (const bool isDirectory,
  36804. const bool isSave,
  36805. const bool warnAboutOverwritingExistingFiles,
  36806. const bool selectMultipleFiles,
  36807. FilePreviewComponent* const previewComponent);
  36808. static void showPlatformDialog (OwnedArray<File>& results,
  36809. const String& title,
  36810. const File& file,
  36811. const String& filters,
  36812. bool isDirectory,
  36813. bool isSave,
  36814. bool warnAboutOverwritingExistingFiles,
  36815. bool selectMultipleFiles,
  36816. FilePreviewComponent* previewComponent);
  36817. };
  36818. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36819. /********* End of inlined file: juce_FileChooser.h *********/
  36820. #endif
  36821. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36822. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  36823. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36824. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36825. /**
  36826. A file open/save dialog box.
  36827. This is a Juce-based file dialog box; to use a native file chooser, see the
  36828. FileChooser class.
  36829. To use one of these, create it and call its show() method. e.g.
  36830. @code
  36831. {
  36832. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  36833. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  36834. File::nonexistent,
  36835. &wildcardFilter,
  36836. 0);
  36837. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  36838. T("Please choose some kind of file that you want to open..."),
  36839. browser,
  36840. getLookAndFeel().alertWindowBackground);
  36841. if (dialogBox.show())
  36842. {
  36843. File selectedFile = browser.getCurrentFile();
  36844. ...
  36845. }
  36846. }
  36847. @endcode
  36848. @see FileChooser
  36849. */
  36850. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  36851. public ButtonListener,
  36852. public FileBrowserListener
  36853. {
  36854. public:
  36855. /** Creates a file chooser box.
  36856. @param title the main title to show at the top of the box
  36857. @param instructions an optional longer piece of text to show below the title in
  36858. a smaller font, describing in more detail what's required.
  36859. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  36860. box. Make sure you delete this after (but not before!) the
  36861. dialog box has been deleted.
  36862. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  36863. if they try to select a file that already exists. (This
  36864. flag is only used when saving files)
  36865. @param backgroundColour the background colour for the top level window
  36866. @see FileBrowserComponent, FilePreviewComponent
  36867. */
  36868. FileChooserDialogBox (const String& title,
  36869. const String& instructions,
  36870. FileBrowserComponent& browserComponent,
  36871. const bool warnAboutOverwritingExistingFiles,
  36872. const Colour& backgroundColour);
  36873. /** Destructor. */
  36874. ~FileChooserDialogBox();
  36875. /** Displays and runs the dialog box modally.
  36876. This will show the box with the specified size, returning true if the user
  36877. pressed 'ok', or false if they cancelled.
  36878. Leave the width or height as 0 to use the default size
  36879. */
  36880. bool show (int width = 0,int height = 0);
  36881. /** @internal */
  36882. void buttonClicked (Button* button);
  36883. /** @internal */
  36884. void closeButtonPressed();
  36885. /** @internal */
  36886. void selectionChanged();
  36887. /** @internal */
  36888. void fileClicked (const File& file, const MouseEvent& e);
  36889. /** @internal */
  36890. void fileDoubleClicked (const File& file);
  36891. juce_UseDebuggingNewOperator
  36892. private:
  36893. class ContentComponent : public Component
  36894. {
  36895. public:
  36896. ContentComponent();
  36897. ~ContentComponent();
  36898. void paint (Graphics& g);
  36899. void resized();
  36900. String instructions;
  36901. GlyphArrangement text;
  36902. FileBrowserComponent* chooserComponent;
  36903. FilePreviewComponent* previewComponent;
  36904. TextButton* okButton;
  36905. TextButton* cancelButton;
  36906. };
  36907. ContentComponent* content;
  36908. const bool warnAboutOverwritingExistingFiles;
  36909. FileChooserDialogBox (const FileChooserDialogBox&);
  36910. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  36911. };
  36912. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36913. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  36914. #endif
  36915. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36916. #endif
  36917. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36918. /********* Start of inlined file: juce_FileListComponent.h *********/
  36919. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36920. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36921. /**
  36922. A component that displays the files in a directory as a listbox.
  36923. This implements the DirectoryContentsDisplayComponent base class so that
  36924. it can be used in a FileBrowserComponent.
  36925. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  36926. class and the FileBrowserListener class.
  36927. @see DirectoryContentsList, FileTreeComponent
  36928. */
  36929. class JUCE_API FileListComponent : public ListBox,
  36930. public DirectoryContentsDisplayComponent,
  36931. private ListBoxModel,
  36932. private ChangeListener
  36933. {
  36934. public:
  36935. /** Creates a listbox to show the contents of a specified directory.
  36936. */
  36937. FileListComponent (DirectoryContentsList& listToShow);
  36938. /** Destructor. */
  36939. ~FileListComponent();
  36940. /** Returns the file that the user has currently selected.
  36941. Returns File::nonexistent if none is selected.
  36942. */
  36943. const File getSelectedFile() const;
  36944. /** Scrolls to the top of the list. */
  36945. void scrollToTop();
  36946. /** @internal */
  36947. void changeListenerCallback (void*);
  36948. /** @internal */
  36949. int getNumRows();
  36950. /** @internal */
  36951. void paintListBoxItem (int, Graphics&, int, int, bool);
  36952. /** @internal */
  36953. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  36954. /** @internal */
  36955. void selectedRowsChanged (int lastRowSelected);
  36956. /** @internal */
  36957. void deleteKeyPressed (int currentSelectedRow);
  36958. /** @internal */
  36959. void returnKeyPressed (int currentSelectedRow);
  36960. juce_UseDebuggingNewOperator
  36961. private:
  36962. FileListComponent (const FileListComponent&);
  36963. const FileListComponent& operator= (const FileListComponent&);
  36964. File lastDirectory;
  36965. };
  36966. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36967. /********* End of inlined file: juce_FileListComponent.h *********/
  36968. #endif
  36969. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36970. /********* Start of inlined file: juce_FilenameComponent.h *********/
  36971. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36972. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36973. class FilenameComponent;
  36974. /**
  36975. Listens for events happening to a FilenameComponent.
  36976. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  36977. register one of these objects for event callbacks when the filename is changed.
  36978. @See FilenameComponent
  36979. */
  36980. class JUCE_API FilenameComponentListener
  36981. {
  36982. public:
  36983. /** Destructor. */
  36984. virtual ~FilenameComponentListener() {}
  36985. /** This method is called after the FilenameComponent's file has been changed. */
  36986. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  36987. };
  36988. /**
  36989. Shows a filename as an editable text box, with a 'browse' button and a
  36990. drop-down list for recently selected files.
  36991. A handy component for dialogue boxes where you want the user to be able to
  36992. select a file or directory.
  36993. Attach an FilenameComponentListener using the addListener() method, and it will
  36994. get called each time the user changes the filename, either by browsing for a file
  36995. and clicking 'ok', or by typing a new filename into the box and pressing return.
  36996. @see FileChooser, ComboBox
  36997. */
  36998. class JUCE_API FilenameComponent : public Component,
  36999. public SettableTooltipClient,
  37000. public FileDragAndDropTarget,
  37001. private AsyncUpdater,
  37002. private ButtonListener,
  37003. private ComboBoxListener
  37004. {
  37005. public:
  37006. /** Creates a FilenameComponent.
  37007. @param name the name for this component.
  37008. @param currentFile the file to initially show in the box
  37009. @param canEditFilename if true, the user can manually edit the filename; if false,
  37010. they can only change it by browsing for a new file
  37011. @param isDirectory if true, the file will be treated as a directory, and
  37012. an appropriate directory browser used
  37013. @param isForSaving if true, the file browser will allow non-existent files to
  37014. be picked, as the file is assumed to be used for saving rather
  37015. than loading
  37016. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37017. If an empty string is passed in, then the pattern is assumed to be "*"
  37018. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37019. to any filenames that are entered or chosen
  37020. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37021. will only appear if the initial file isn't valid)
  37022. */
  37023. FilenameComponent (const String& name,
  37024. const File& currentFile,
  37025. const bool canEditFilename,
  37026. const bool isDirectory,
  37027. const bool isForSaving,
  37028. const String& fileBrowserWildcard,
  37029. const String& enforcedSuffix,
  37030. const String& textWhenNothingSelected);
  37031. /** Destructor. */
  37032. ~FilenameComponent();
  37033. /** Returns the currently displayed filename. */
  37034. const File getCurrentFile() const;
  37035. /** Changes the current filename.
  37036. If addToRecentlyUsedList is true, the filename will also be added to the
  37037. drop-down list of recent files.
  37038. If sendChangeNotification is false, then the listeners won't be told of the
  37039. change.
  37040. */
  37041. void setCurrentFile (File newFile,
  37042. const bool addToRecentlyUsedList,
  37043. const bool sendChangeNotification = true);
  37044. /** Changes whether the use can type into the filename box.
  37045. */
  37046. void setFilenameIsEditable (const bool shouldBeEditable);
  37047. /** Sets a file or directory to be the default starting point for the browser to show.
  37048. This is only used if the current file hasn't been set.
  37049. */
  37050. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37051. /** Returns all the entries on the recent files list.
  37052. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37053. state of this list.
  37054. @see setRecentlyUsedFilenames
  37055. */
  37056. const StringArray getRecentlyUsedFilenames() const;
  37057. /** Sets all the entries on the recent files list.
  37058. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37059. state of this list.
  37060. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37061. */
  37062. void setRecentlyUsedFilenames (const StringArray& filenames);
  37063. /** Adds an entry to the recently-used files dropdown list.
  37064. If the file is already in the list, it will be moved to the top. A limit
  37065. is also placed on the number of items that are kept in the list.
  37066. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37067. */
  37068. void addRecentlyUsedFile (const File& file);
  37069. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37070. */
  37071. void setMaxNumberOfRecentFiles (const int newMaximum);
  37072. /** Changes the text shown on the 'browse' button.
  37073. By default this button just says "..." but you can change it. The button itself
  37074. can be changed using the look-and-feel classes, so it might not actually have any
  37075. text on it.
  37076. */
  37077. void setBrowseButtonText (const String& browseButtonText);
  37078. /** Adds a listener that will be called when the selected file is changed. */
  37079. void addListener (FilenameComponentListener* const listener) throw();
  37080. /** Removes a previously-registered listener. */
  37081. void removeListener (FilenameComponentListener* const listener) throw();
  37082. /** Gives the component a tooltip. */
  37083. void setTooltip (const String& newTooltip);
  37084. /** @internal */
  37085. void paintOverChildren (Graphics& g);
  37086. /** @internal */
  37087. void resized();
  37088. /** @internal */
  37089. void lookAndFeelChanged();
  37090. /** @internal */
  37091. bool isInterestedInFileDrag (const StringArray& files);
  37092. /** @internal */
  37093. void filesDropped (const StringArray& files, int, int);
  37094. /** @internal */
  37095. void fileDragEnter (const StringArray& files, int, int);
  37096. /** @internal */
  37097. void fileDragExit (const StringArray& files);
  37098. juce_UseDebuggingNewOperator
  37099. private:
  37100. ComboBox* filenameBox;
  37101. String lastFilename;
  37102. Button* browseButton;
  37103. int maxRecentFiles;
  37104. bool isDir, isSaving, isFileDragOver;
  37105. String wildcard, enforcedSuffix, browseButtonText;
  37106. SortedSet <void*> listeners;
  37107. File defaultBrowseFile;
  37108. void comboBoxChanged (ComboBox*);
  37109. void buttonClicked (Button* button);
  37110. void handleAsyncUpdate();
  37111. FilenameComponent (const FilenameComponent&);
  37112. const FilenameComponent& operator= (const FilenameComponent&);
  37113. };
  37114. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37115. /********* End of inlined file: juce_FilenameComponent.h *********/
  37116. #endif
  37117. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37118. #endif
  37119. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37120. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37121. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37122. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37123. /**
  37124. Shows a set of file paths in a list, allowing them to be added, removed or
  37125. re-ordered.
  37126. @see FileSearchPath
  37127. */
  37128. class JUCE_API FileSearchPathListComponent : public Component,
  37129. public SettableTooltipClient,
  37130. public FileDragAndDropTarget,
  37131. private ButtonListener,
  37132. private ListBoxModel
  37133. {
  37134. public:
  37135. /** Creates an empty FileSearchPathListComponent.
  37136. */
  37137. FileSearchPathListComponent();
  37138. /** Destructor. */
  37139. ~FileSearchPathListComponent();
  37140. /** Returns the path as it is currently shown. */
  37141. const FileSearchPath& getPath() const throw() { return path; }
  37142. /** Changes the current path. */
  37143. void setPath (const FileSearchPath& newPath);
  37144. /** Sets a file or directory to be the default starting point for the browser to show.
  37145. This is only used if the current file hasn't been set.
  37146. */
  37147. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37148. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37149. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37150. methods.
  37151. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37152. */
  37153. enum ColourIds
  37154. {
  37155. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37156. Make this transparent if you don't want the background to be filled. */
  37157. };
  37158. /** @internal */
  37159. int getNumRows();
  37160. /** @internal */
  37161. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37162. /** @internal */
  37163. void deleteKeyPressed (int lastRowSelected);
  37164. /** @internal */
  37165. void returnKeyPressed (int lastRowSelected);
  37166. /** @internal */
  37167. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37168. /** @internal */
  37169. void selectedRowsChanged (int lastRowSelected);
  37170. /** @internal */
  37171. void resized();
  37172. /** @internal */
  37173. void paint (Graphics& g);
  37174. /** @internal */
  37175. bool isInterestedInFileDrag (const StringArray& files);
  37176. /** @internal */
  37177. void filesDropped (const StringArray& files, int, int);
  37178. /** @internal */
  37179. void buttonClicked (Button* button);
  37180. juce_UseDebuggingNewOperator
  37181. private:
  37182. FileSearchPath path;
  37183. File defaultBrowseTarget;
  37184. ListBox* listBox;
  37185. Button* addButton;
  37186. Button* removeButton;
  37187. Button* changeButton;
  37188. Button* upButton;
  37189. Button* downButton;
  37190. void changed() throw();
  37191. void updateButtons() throw();
  37192. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37193. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37194. };
  37195. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37196. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37197. #endif
  37198. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37199. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37200. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37201. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37202. /**
  37203. A component that displays the files in a directory as a treeview.
  37204. This implements the DirectoryContentsDisplayComponent base class so that
  37205. it can be used in a FileBrowserComponent.
  37206. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37207. class and the FileBrowserListener class.
  37208. @see DirectoryContentsList, FileListComponent
  37209. */
  37210. class JUCE_API FileTreeComponent : public TreeView,
  37211. public DirectoryContentsDisplayComponent
  37212. {
  37213. public:
  37214. /** Creates a listbox to show the contents of a specified directory.
  37215. */
  37216. FileTreeComponent (DirectoryContentsList& listToShow);
  37217. /** Destructor. */
  37218. ~FileTreeComponent();
  37219. /** Returns the number of selected files in the tree.
  37220. */
  37221. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37222. /** Returns one of the files that the user has currently selected.
  37223. Returns File::nonexistent if none is selected.
  37224. */
  37225. const File getSelectedFile (int index) const throw();
  37226. /** Returns the first of the files that the user has currently selected.
  37227. Returns File::nonexistent if none is selected.
  37228. */
  37229. const File getSelectedFile() const;
  37230. /** Scrolls the list to the top. */
  37231. void scrollToTop();
  37232. /** Setting a name for this allows tree items to be dragged.
  37233. The string that you pass in here will be returned by the getDragSourceDescription()
  37234. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37235. */
  37236. void setDragAndDropDescription (const String& description) throw();
  37237. /** Returns the last value that was set by setDragAndDropDescription().
  37238. */
  37239. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37240. juce_UseDebuggingNewOperator
  37241. private:
  37242. String dragAndDropDescription;
  37243. FileTreeComponent (const FileTreeComponent&);
  37244. const FileTreeComponent& operator= (const FileTreeComponent&);
  37245. };
  37246. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37247. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37248. #endif
  37249. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37250. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37251. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37252. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37253. /**
  37254. A simple preview component that shows thumbnails of image files.
  37255. @see FileChooserDialogBox, FilePreviewComponent
  37256. */
  37257. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37258. private Timer
  37259. {
  37260. public:
  37261. /** Creates an ImagePreviewComponent. */
  37262. ImagePreviewComponent();
  37263. /** Destructor. */
  37264. ~ImagePreviewComponent();
  37265. /** @internal */
  37266. void selectedFileChanged (const File& newSelectedFile);
  37267. /** @internal */
  37268. void paint (Graphics& g);
  37269. /** @internal */
  37270. void timerCallback();
  37271. juce_UseDebuggingNewOperator
  37272. private:
  37273. File fileToLoad;
  37274. Image* currentThumbnail;
  37275. String currentDetails;
  37276. void getThumbSize (int& w, int& h) const;
  37277. ImagePreviewComponent (const ImagePreviewComponent&);
  37278. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37279. };
  37280. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37281. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37282. #endif
  37283. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37284. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37285. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37286. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37287. /**
  37288. A type of FileFilter that works by wildcard pattern matching.
  37289. This filter only allows files that match one of the specified patterns, but
  37290. allows all directories through.
  37291. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37292. */
  37293. class JUCE_API WildcardFileFilter : public FileFilter
  37294. {
  37295. public:
  37296. /**
  37297. Creates a wildcard filter for one or more patterns.
  37298. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37299. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37300. or .aiff.
  37301. The description is a name to show the user in a list of possible patterns, so
  37302. for the wav/aiff example, your description might be "audio files".
  37303. */
  37304. WildcardFileFilter (const String& wildcardPatterns,
  37305. const String& description);
  37306. /** Destructor. */
  37307. ~WildcardFileFilter();
  37308. /** Returns true if the filename matches one of the patterns specified. */
  37309. bool isFileSuitable (const File& file) const;
  37310. /** This always returns true. */
  37311. bool isDirectorySuitable (const File& file) const;
  37312. juce_UseDebuggingNewOperator
  37313. private:
  37314. StringArray wildcards;
  37315. };
  37316. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37317. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37318. #endif
  37319. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37320. /********* Start of inlined file: juce_AlertWindow.h *********/
  37321. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37322. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37323. /** A window that displays a message and has buttons for the user to react to it.
  37324. For simple dialog boxes with just a couple of buttons on them, there are
  37325. some static methods for running these.
  37326. For more complex dialogs, an AlertWindow can be created, then it can have some
  37327. buttons and components added to it, and its runModalLoop() method is then used to
  37328. show it. The value returned by runModalLoop() shows which button the
  37329. user pressed to dismiss the box.
  37330. @see ThreadWithProgressWindow
  37331. */
  37332. class JUCE_API AlertWindow : public TopLevelWindow,
  37333. private ButtonListener
  37334. {
  37335. public:
  37336. /** The type of icon to show in the dialog box. */
  37337. enum AlertIconType
  37338. {
  37339. NoIcon, /**< No icon will be shown on the dialog box. */
  37340. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37341. user to answer a question. */
  37342. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37343. warning about something and shouldn't be ignored. */
  37344. InfoIcon /**< An icon that indicates that the dialog box is just
  37345. giving the user some information, which doesn't require
  37346. a response from them. */
  37347. };
  37348. /** Creates an AlertWindow.
  37349. @param title the headline to show at the top of the dialog box
  37350. @param message a longer, more descriptive message to show underneath the
  37351. headline
  37352. @param iconType the type of icon to display
  37353. */
  37354. AlertWindow (const String& title,
  37355. const String& message,
  37356. AlertIconType iconType);
  37357. /** Destroys the AlertWindow */
  37358. ~AlertWindow();
  37359. /** Returns the type of alert icon that was specified when the window
  37360. was created. */
  37361. AlertIconType getAlertType() const throw() { return alertIconType; }
  37362. /** Changes the dialog box's message.
  37363. This will also resize the window to fit the new message if required.
  37364. */
  37365. void setMessage (const String& message);
  37366. /** Adds a button to the window.
  37367. @param name the text to show on the button
  37368. @param returnValue the value that should be returned from runModalLoop()
  37369. if this is the button that the user presses.
  37370. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37371. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37372. */
  37373. void addButton (const String& name,
  37374. const int returnValue,
  37375. const KeyPress& shortcutKey1 = KeyPress(),
  37376. const KeyPress& shortcutKey2 = KeyPress());
  37377. /** Returns the number of buttons that the window currently has. */
  37378. int getNumButtons() const;
  37379. /** Adds a textbox to the window for entering strings.
  37380. @param name an internal name for the text-box. This is the name to pass to
  37381. the getTextEditorContents() method to find out what the
  37382. user typed-in.
  37383. @param initialContents a string to show in the text box when it's first shown
  37384. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37385. text-box to label it.
  37386. @param isPasswordBox if true, the text editor will display asterisks instead of
  37387. the actual text
  37388. @see getTextEditorContents
  37389. */
  37390. void addTextEditor (const String& name,
  37391. const String& initialContents,
  37392. const String& onScreenLabel = String::empty,
  37393. const bool isPasswordBox = false);
  37394. /** Returns the contents of a named textbox.
  37395. After showing an AlertWindow that contains a text editor, this can be
  37396. used to find out what the user has typed into it.
  37397. @param nameOfTextEditor the name of the text box that you're interested in
  37398. @see addTextEditor
  37399. */
  37400. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37401. /** Adds a drop-down list of choices to the box.
  37402. After the box has been shown, the getComboBoxComponent() method can
  37403. be used to find out which item the user picked.
  37404. @param name the label to use for the drop-down list
  37405. @param items the list of items to show in it
  37406. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37407. combo-box to label it.
  37408. @see getComboBoxComponent
  37409. */
  37410. void addComboBox (const String& name,
  37411. const StringArray& items,
  37412. const String& onScreenLabel = String::empty);
  37413. /** Returns a drop-down list that was added to the AlertWindow.
  37414. @param nameOfList the name that was passed into the addComboBox() method
  37415. when creating the drop-down
  37416. @returns the ComboBox component, or 0 if none was found for the given name.
  37417. */
  37418. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37419. /** Adds a block of text.
  37420. This is handy for adding a multi-line note next to a textbox or combo-box,
  37421. to provide more details about what's going on.
  37422. */
  37423. void addTextBlock (const String& text);
  37424. /** Adds a progress-bar to the window.
  37425. @param progressValue a variable that will be repeatedly checked while the
  37426. dialog box is visible, to see how far the process has
  37427. got. The value should be in the range 0 to 1.0
  37428. */
  37429. void addProgressBarComponent (double& progressValue);
  37430. /** Adds a user-defined component to the dialog box.
  37431. @param component the component to add - its size should be set up correctly
  37432. before it is passed in. The caller is responsible for deleting
  37433. the component later on - the AlertWindow won't delete it.
  37434. */
  37435. void addCustomComponent (Component* const component);
  37436. /** Returns the number of custom components in the dialog box.
  37437. @see getCustomComponent, addCustomComponent
  37438. */
  37439. int getNumCustomComponents() const;
  37440. /** Returns one of the custom components in the dialog box.
  37441. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37442. will return 0
  37443. @see getNumCustomComponents, addCustomComponent
  37444. */
  37445. Component* getCustomComponent (const int index) const;
  37446. /** Removes one of the custom components in the dialog box.
  37447. Note that this won't delete it, it just removes the component from the window
  37448. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37449. will return 0
  37450. @returns the component that was removed (or zero)
  37451. @see getNumCustomComponents, addCustomComponent
  37452. */
  37453. Component* removeCustomComponent (const int index);
  37454. /** Returns true if the window contains any components other than just buttons.*/
  37455. bool containsAnyExtraComponents() const;
  37456. // easy-to-use message box functions:
  37457. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37458. The box is shown modally, and the method returns after the user
  37459. has clicked the button (or pressed the escape or return keys).
  37460. @param iconType the type of icon to show
  37461. @param title the headline to show at the top of the box
  37462. @param message a longer, more descriptive message to show underneath the
  37463. headline
  37464. @param buttonText the text to show in the button - if this string is empty, the
  37465. default string "ok" (or a localised version) will be used.
  37466. */
  37467. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37468. const String& title,
  37469. const String& message,
  37470. const String& buttonText = String::empty);
  37471. /** Shows a dialog box with two buttons.
  37472. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37473. to trigger the first button, and the escape key for the second button.
  37474. @param iconType the type of icon to show
  37475. @param title the headline to show at the top of the box
  37476. @param message a longer, more descriptive message to show underneath the
  37477. headline
  37478. @param button1Text the text to show in the first button - if this string is
  37479. empty, the default string "ok" (or a localised version of it)
  37480. will be used.
  37481. @param button2Text the text to show in the second button - if this string is
  37482. empty, the default string "cancel" (or a localised version of it)
  37483. will be used.
  37484. @returns true if button 1 was clicked, false if it was button 2
  37485. */
  37486. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37487. const String& title,
  37488. const String& message,
  37489. const String& button1Text = String::empty,
  37490. const String& button2Text = String::empty);
  37491. /** Shows a dialog box with three buttons.
  37492. Ideal for yes/no/cancel boxes.
  37493. The escape key can be used to trigger the third button.
  37494. @param iconType the type of icon to show
  37495. @param title the headline to show at the top of the box
  37496. @param message a longer, more descriptive message to show underneath the
  37497. headline
  37498. @param button1Text the text to show in the first button - if an empty string, then
  37499. "yes" will be used (or a localised version of it)
  37500. @param button2Text the text to show in the first button - if an empty string, then
  37501. "no" will be used (or a localised version of it)
  37502. @param button3Text the text to show in the first button - if an empty string, then
  37503. "cancel" will be used (or a localised version of it)
  37504. @returns one of the following values:
  37505. - 0 if the third button was pressed (normally used for 'cancel')
  37506. - 1 if the first button was pressed (normally used for 'yes')
  37507. - 2 if the middle button was pressed (normally used for 'no')
  37508. */
  37509. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  37510. const String& title,
  37511. const String& message,
  37512. const String& button1Text = String::empty,
  37513. const String& button2Text = String::empty,
  37514. const String& button3Text = String::empty);
  37515. /** Shows an operating-system native dialog box.
  37516. @param title the title to use at the top
  37517. @param bodyText the longer message to show
  37518. @param isOkCancel if true, this will show an ok/cancel box, if false,
  37519. it'll show a box with just an ok button
  37520. @returns true if the ok button was pressed, false if they pressed cancel.
  37521. */
  37522. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  37523. const String& bodyText,
  37524. bool isOkCancel);
  37525. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  37526. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37527. methods.
  37528. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37529. */
  37530. enum ColourIds
  37531. {
  37532. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  37533. textColourId = 0x1001810, /**< The colour for the text. */
  37534. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  37535. };
  37536. juce_UseDebuggingNewOperator
  37537. protected:
  37538. /** @internal */
  37539. void paint (Graphics& g);
  37540. /** @internal */
  37541. void mouseDown (const MouseEvent& e);
  37542. /** @internal */
  37543. void mouseDrag (const MouseEvent& e);
  37544. /** @internal */
  37545. bool keyPressed (const KeyPress& key);
  37546. /** @internal */
  37547. void buttonClicked (Button* button);
  37548. /** @internal */
  37549. void lookAndFeelChanged();
  37550. private:
  37551. String text;
  37552. TextLayout textLayout;
  37553. AlertIconType alertIconType;
  37554. ComponentBoundsConstrainer constrainer;
  37555. ComponentDragger dragger;
  37556. Rectangle textArea;
  37557. VoidArray buttons, textBoxes, comboBoxes;
  37558. VoidArray progressBars, customComps, textBlocks, allComps;
  37559. StringArray textboxNames, comboBoxNames;
  37560. Font font;
  37561. void updateLayout (const bool onlyIncreaseSize);
  37562. // disable copy constructor
  37563. AlertWindow (const AlertWindow&);
  37564. const AlertWindow& operator= (const AlertWindow&);
  37565. };
  37566. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  37567. /********* End of inlined file: juce_AlertWindow.h *********/
  37568. #endif
  37569. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  37570. #endif
  37571. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37572. /********* Start of inlined file: juce_DialogWindow.h *********/
  37573. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37574. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  37575. /**
  37576. A dialog-box style window.
  37577. This class is a convenient way of creating a DocumentWindow with a close button
  37578. that can be triggered by pressing the escape key.
  37579. Any of the methods available to a DocumentWindow or ResizableWindow are also
  37580. available to this, so it can be made resizable, have a menu bar, etc.
  37581. To add items to the box, see the ResizableWindow::setContentComponent() method.
  37582. Don't add components directly to this class - always put them in a content component!
  37583. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  37584. the user clicking the close button - for more info, see the DocumentWindow
  37585. help.
  37586. @see DocumentWindow, ResizableWindow
  37587. */
  37588. class JUCE_API DialogWindow : public DocumentWindow
  37589. {
  37590. public:
  37591. /** Creates a DialogWindow.
  37592. @param name the name to give the component - this is also
  37593. the title shown at the top of the window. To change
  37594. this later, use setName()
  37595. @param backgroundColour the colour to use for filling the window's background.
  37596. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37597. close button to be triggered
  37598. @param addToDesktop if true, the window will be automatically added to the
  37599. desktop; if false, you can use it as a child component
  37600. */
  37601. DialogWindow (const String& name,
  37602. const Colour& backgroundColour,
  37603. const bool escapeKeyTriggersCloseButton,
  37604. const bool addToDesktop = true);
  37605. /** Destructor.
  37606. If a content component has been set with setContentComponent(), it
  37607. will be deleted.
  37608. */
  37609. ~DialogWindow();
  37610. /** Easy way of quickly showing a dialog box containing a given component.
  37611. This will open and display a DialogWindow containing a given component, returning
  37612. when the user clicks its close button.
  37613. It returns the value that was returned by the dialog box's runModalLoop() call.
  37614. To close the dialog programatically, you should call exitModalState (returnValue) on
  37615. the DialogWindow that is created. To find a pointer to this window from your
  37616. contentComponent, you can do something like this:
  37617. @code
  37618. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  37619. if (dw != 0)
  37620. dw->exitModalState (1234);
  37621. @endcode
  37622. @param dialogTitle the dialog box's title
  37623. @param contentComponent the content component for the dialog box. Make sure
  37624. that this has been set to the size you want it to
  37625. be before calling this method. The component won't
  37626. be deleted by this call, so you can re-use it or delete
  37627. it afterwards
  37628. @param componentToCentreAround if this is non-zero, it indicates a component that
  37629. you'd like to show this dialog box in front of. See the
  37630. DocumentWindow::centreAroundComponent() method for more
  37631. info on this parameter
  37632. @param backgroundColour a colour to use for the dialog box's background colour
  37633. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37634. close button to be triggered
  37635. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  37636. a corner resizer
  37637. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  37638. to use a border or corner resizer component. See ResizableWindow::setResizable()
  37639. */
  37640. static int showModalDialog (const String& dialogTitle,
  37641. Component* contentComponent,
  37642. Component* componentToCentreAround,
  37643. const Colour& backgroundColour,
  37644. const bool escapeKeyTriggersCloseButton,
  37645. const bool shouldBeResizable = false,
  37646. const bool useBottomRightCornerResizer = false);
  37647. juce_UseDebuggingNewOperator
  37648. protected:
  37649. /** @internal */
  37650. void resized();
  37651. private:
  37652. bool escapeKeyTriggersCloseButton;
  37653. DialogWindow (const DialogWindow&);
  37654. const DialogWindow& operator= (const DialogWindow&);
  37655. };
  37656. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  37657. /********* End of inlined file: juce_DialogWindow.h *********/
  37658. #endif
  37659. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37660. #endif
  37661. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37662. #endif
  37663. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37664. /********* Start of inlined file: juce_SplashScreen.h *********/
  37665. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37666. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  37667. /** A component for showing a splash screen while your app starts up.
  37668. This will automatically position itself, and delete itself when the app has
  37669. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  37670. this).
  37671. To use it, just create one of these in your JUCEApplication::initialise() method,
  37672. call its show() method and let the object delete itself later.
  37673. E.g. @code
  37674. void MyApp::initialise (const String& commandLine)
  37675. {
  37676. SplashScreen* splash = new SplashScreen();
  37677. splash->show (T("welcome to my app"),
  37678. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  37679. 4000, false);
  37680. .. no need to delete the splash screen - it'll do that itself.
  37681. }
  37682. @endcode
  37683. */
  37684. class JUCE_API SplashScreen : public Component,
  37685. public Timer,
  37686. private DeletedAtShutdown
  37687. {
  37688. public:
  37689. /** Creates a SplashScreen object.
  37690. After creating one of these (or your subclass of it), call one of the show()
  37691. methods to display it.
  37692. */
  37693. SplashScreen();
  37694. /** Destructor. */
  37695. ~SplashScreen();
  37696. /** Creates a SplashScreen object that will display an image.
  37697. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37698. screen. This method will also dispatch any pending messages to make sure that when
  37699. it returns, the splash screen has been completely drawn, and your initialisation
  37700. code can carry on.
  37701. @param title the name to give the component
  37702. @param backgroundImage an image to draw on the component. The component's size
  37703. will be set to the size of this image, and if the image is
  37704. semi-transparent, the component will be made semi-transparent
  37705. too. This image will be deleted (or released from the ImageCache
  37706. if that's how it was created) by the splash screen object when
  37707. it is itself deleted.
  37708. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37709. should stay visible for. If the initialisation takes longer than
  37710. this time, the splash screen will wait for it to finish before
  37711. disappearing, but if initialisation is very quick, this lets
  37712. you make sure that people get a good look at your splash.
  37713. @param useDropShadow if true, the window will have a drop shadow
  37714. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37715. the mouse (anywhere)
  37716. */
  37717. void show (const String& title,
  37718. Image* const backgroundImage,
  37719. const int minimumTimeToDisplayFor,
  37720. const bool useDropShadow,
  37721. const bool removeOnMouseClick = true);
  37722. /** Creates a SplashScreen object with a specified size.
  37723. For a custom splash screen, you can use this method to display it at a certain size
  37724. and then override the paint() method yourself to do whatever's necessary.
  37725. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37726. screen. This method will also dispatch any pending messages to make sure that when
  37727. it returns, the splash screen has been completely drawn, and your initialisation
  37728. code can carry on.
  37729. @param title the name to give the component
  37730. @param width the width to use
  37731. @param height the height to use
  37732. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37733. should stay visible for. If the initialisation takes longer than
  37734. this time, the splash screen will wait for it to finish before
  37735. disappearing, but if initialisation is very quick, this lets
  37736. you make sure that people get a good look at your splash.
  37737. @param useDropShadow if true, the window will have a drop shadow
  37738. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37739. the mouse (anywhere)
  37740. */
  37741. void show (const String& title,
  37742. const int width,
  37743. const int height,
  37744. const int minimumTimeToDisplayFor,
  37745. const bool useDropShadow,
  37746. const bool removeOnMouseClick = true);
  37747. /** @internal */
  37748. void paint (Graphics& g);
  37749. /** @internal */
  37750. void timerCallback();
  37751. juce_UseDebuggingNewOperator
  37752. private:
  37753. Image* backgroundImage;
  37754. Time earliestTimeToDelete;
  37755. int originalClickCounter;
  37756. bool isImageInCache;
  37757. SplashScreen (const SplashScreen&);
  37758. const SplashScreen& operator= (const SplashScreen&);
  37759. };
  37760. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  37761. /********* End of inlined file: juce_SplashScreen.h *********/
  37762. #endif
  37763. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37764. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  37765. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37766. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37767. /**
  37768. A thread that automatically pops up a modal dialog box with a progress bar
  37769. and cancel button while it's busy running.
  37770. These are handy for performing some sort of task while giving the user feedback
  37771. about how long there is to go, etc.
  37772. E.g. @code
  37773. class MyTask : public ThreadWithProgressWindow
  37774. {
  37775. public:
  37776. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  37777. {
  37778. }
  37779. ~MyTask()
  37780. {
  37781. }
  37782. void run()
  37783. {
  37784. for (int i = 0; i < thingsToDo; ++i)
  37785. {
  37786. // must check this as often as possible, because this is
  37787. // how we know if the user's pressed 'cancel'
  37788. if (threadShouldExit())
  37789. break;
  37790. // this will update the progress bar on the dialog box
  37791. setProgress (i / (double) thingsToDo);
  37792. // ... do the business here...
  37793. }
  37794. }
  37795. };
  37796. void doTheTask()
  37797. {
  37798. MyTask m;
  37799. if (m.runThread())
  37800. {
  37801. // thread finished normally..
  37802. }
  37803. else
  37804. {
  37805. // user pressed the cancel button..
  37806. }
  37807. }
  37808. @endcode
  37809. @see Thread, AlertWindow
  37810. */
  37811. class JUCE_API ThreadWithProgressWindow : public Thread,
  37812. private Timer
  37813. {
  37814. public:
  37815. /** Creates the thread.
  37816. Initially, the dialog box won't be visible, it'll only appear when the
  37817. runThread() method is called.
  37818. @param windowTitle the title to go at the top of the dialog box
  37819. @param hasProgressBar whether the dialog box should have a progress bar (see
  37820. setProgress() )
  37821. @param hasCancelButton whether the dialog box should have a cancel button
  37822. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  37823. the thread to stop before killing it forcibly (see
  37824. Thread::stopThread() )
  37825. @param cancelButtonText the text that should be shown in the cancel button
  37826. (if it has one)
  37827. */
  37828. ThreadWithProgressWindow (const String& windowTitle,
  37829. const bool hasProgressBar,
  37830. const bool hasCancelButton,
  37831. const int timeOutMsWhenCancelling = 10000,
  37832. const String& cancelButtonText = JUCE_T("Cancel"));
  37833. /** Destructor. */
  37834. ~ThreadWithProgressWindow();
  37835. /** Starts the thread and waits for it to finish.
  37836. This will start the thread, make the dialog box appear, and wait until either
  37837. the thread finishes normally, or until the cancel button is pressed.
  37838. Before returning, the dialog box will be hidden.
  37839. @param threadPriority the priority to use when starting the thread - see
  37840. Thread::startThread() for values
  37841. @returns true if the thread finished normally; false if the user pressed cancel
  37842. */
  37843. bool runThread (const int threadPriority = 5);
  37844. /** The thread should call this periodically to update the position of the progress bar.
  37845. @param newProgress the progress, from 0.0 to 1.0
  37846. @see setStatusMessage
  37847. */
  37848. void setProgress (const double newProgress);
  37849. /** The thread can call this to change the message that's displayed in the dialog box.
  37850. */
  37851. void setStatusMessage (const String& newStatusMessage);
  37852. juce_UseDebuggingNewOperator
  37853. private:
  37854. void timerCallback();
  37855. double progress;
  37856. AlertWindow alertWindow;
  37857. String message;
  37858. CriticalSection messageLock;
  37859. const int timeOutMsWhenCancelling;
  37860. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  37861. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  37862. };
  37863. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37864. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  37865. #endif
  37866. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  37867. #endif
  37868. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37869. #endif
  37870. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37871. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  37872. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37873. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37874. #if JUCE_WIN32 || DOXYGEN
  37875. /**
  37876. A Windows-specific class that can create and embed an ActiveX control inside
  37877. itself.
  37878. To use it, create one of these, put it in place and make sure it's visible in a
  37879. window, then use createControl() to instantiate an ActiveX control. The control
  37880. will then be moved and resized to follow the movements of this component.
  37881. Of course, since the control is a heavyweight window, it'll obliterate any
  37882. juce components that may overlap this component, but that's life.
  37883. */
  37884. class JUCE_API ActiveXControlComponent : public Component
  37885. {
  37886. public:
  37887. /** Create an initially-empty container. */
  37888. ActiveXControlComponent();
  37889. /** Destructor. */
  37890. ~ActiveXControlComponent();
  37891. /** Tries to create an ActiveX control and embed it in this peer.
  37892. The peer controlIID is a pointer to an IID structure - it's treated
  37893. as a void* because when including the Juce headers, you might not always
  37894. have included windows.h first, in which case IID wouldn't be defined.
  37895. e.g. @code
  37896. const IID myIID = __uuidof (QTControl);
  37897. myControlComp->createControl (&myIID);
  37898. @endcode
  37899. */
  37900. bool createControl (const void* controlIID);
  37901. /** Deletes the ActiveX control, if one has been created.
  37902. */
  37903. void deleteControl();
  37904. /** Returns true if a control is currently in use. */
  37905. bool isControlOpen() const throw() { return control != 0; }
  37906. /** Does a QueryInterface call on the embedded control object.
  37907. This allows you to cast the control to whatever type of COM object you need.
  37908. The iid parameter is a pointer to an IID structure - it's treated
  37909. as a void* because when including the Juce headers, you might not always
  37910. have included windows.h first, in which case IID wouldn't be defined, but
  37911. you should just pass a pointer to an IID.
  37912. e.g. @code
  37913. const IID iid = __uuidof (IOleWindow);
  37914. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  37915. if (oleWindow != 0)
  37916. {
  37917. HWND hwnd;
  37918. oleWindow->GetWindow (&hwnd);
  37919. ...
  37920. oleWindow->Release();
  37921. }
  37922. @endcode
  37923. */
  37924. void* queryInterface (const void* iid) const;
  37925. /** Set this to false to stop mouse events being allowed through to the control.
  37926. */
  37927. void setMouseEventsAllowed (const bool eventsCanReachControl);
  37928. /** Returns true if mouse events are allowed to get through to the control.
  37929. */
  37930. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  37931. /** @internal */
  37932. void paint (Graphics& g);
  37933. /** @internal */
  37934. void* originalWndProc;
  37935. juce_UseDebuggingNewOperator
  37936. private:
  37937. friend class ActiveXControlData;
  37938. void* control;
  37939. bool mouseEventsAllowed;
  37940. ActiveXControlComponent (const ActiveXControlComponent&);
  37941. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  37942. void setControlBounds (const Rectangle& bounds) const;
  37943. void setControlVisible (const bool b) const;
  37944. };
  37945. #endif
  37946. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37947. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  37948. #endif
  37949. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37950. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  37951. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37952. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37953. class MidiInputSelectorComponentListBox;
  37954. /**
  37955. A component containing controls to let the user change the audio settings of
  37956. an AudioDeviceManager object.
  37957. Very easy to use - just create one of these and show it to the user.
  37958. @see AudioDeviceManager
  37959. */
  37960. class JUCE_API AudioDeviceSelectorComponent : public Component,
  37961. public ComboBoxListener,
  37962. public ButtonListener,
  37963. public ChangeListener
  37964. {
  37965. public:
  37966. /** Creates the component.
  37967. If your app needs only output channels, you might ask for a maximum of 0 input
  37968. channels, and the component won't display any options for choosing the input
  37969. channels. And likewise if you're doing an input-only app.
  37970. @param deviceManager the device manager that this component should control
  37971. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  37972. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  37973. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  37974. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  37975. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  37976. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  37977. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  37978. treated as a set of separate mono channels.
  37979. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  37980. are shown, with an "advanced" button that shows the rest of them
  37981. */
  37982. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  37983. const int minAudioInputChannels,
  37984. const int maxAudioInputChannels,
  37985. const int minAudioOutputChannels,
  37986. const int maxAudioOutputChannels,
  37987. const bool showMidiInputOptions,
  37988. const bool showMidiOutputSelector,
  37989. const bool showChannelsAsStereoPairs,
  37990. const bool hideAdvancedOptionsWithButton);
  37991. /** Destructor */
  37992. ~AudioDeviceSelectorComponent();
  37993. /** @internal */
  37994. void resized();
  37995. /** @internal */
  37996. void comboBoxChanged (ComboBox*);
  37997. /** @internal */
  37998. void buttonClicked (Button*);
  37999. /** @internal */
  38000. void changeListenerCallback (void*);
  38001. juce_UseDebuggingNewOperator
  38002. private:
  38003. AudioDeviceManager& deviceManager;
  38004. ComboBox* deviceTypeDropDown;
  38005. Label* deviceTypeDropDownLabel;
  38006. Component* audioDeviceSettingsComp;
  38007. String audioDeviceSettingsCompType;
  38008. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  38009. const bool showChannelsAsStereoPairs;
  38010. const bool hideAdvancedOptionsWithButton;
  38011. MidiInputSelectorComponentListBox* midiInputsList;
  38012. Label* midiInputsLabel;
  38013. ComboBox* midiOutputSelector;
  38014. Label* midiOutputLabel;
  38015. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  38016. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  38017. };
  38018. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38019. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38020. #endif
  38021. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38022. /********* Start of inlined file: juce_BubbleComponent.h *********/
  38023. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38024. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38025. /**
  38026. A component for showing a message or other graphics inside a speech-bubble-shaped
  38027. outline, pointing at a location on the screen.
  38028. This is a base class that just draws and positions the bubble shape, but leaves
  38029. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  38030. that draws a text message.
  38031. To use it, create your subclass, then either add it to a parent component or
  38032. put it on the desktop with addToDesktop (0), use setPosition() to
  38033. resize and position it, then make it visible.
  38034. @see BubbleMessageComponent
  38035. */
  38036. class JUCE_API BubbleComponent : public Component
  38037. {
  38038. protected:
  38039. /** Creates a BubbleComponent.
  38040. Your subclass will need to implement the getContentSize() and paintContent()
  38041. methods to draw the bubble's contents.
  38042. */
  38043. BubbleComponent();
  38044. public:
  38045. /** Destructor. */
  38046. ~BubbleComponent();
  38047. /** A list of permitted placements for the bubble, relative to the co-ordinates
  38048. at which it should be pointing.
  38049. @see setAllowedPlacement
  38050. */
  38051. enum BubblePlacement
  38052. {
  38053. above = 1,
  38054. below = 2,
  38055. left = 4,
  38056. right = 8
  38057. };
  38058. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  38059. point at which it's pointing.
  38060. By default when setPosition() is called, the bubble will place itself either
  38061. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  38062. the values in BubblePlacement to restrict this choice.
  38063. E.g. if you only want your bubble to appear above or below the target area,
  38064. use setAllowedPlacement (above | below);
  38065. @see BubblePlacement
  38066. */
  38067. void setAllowedPlacement (const int newPlacement);
  38068. /** Moves and resizes the bubble to point at a given component.
  38069. This will resize the bubble to fit its content, then find a position for it
  38070. so that it's next to, but doesn't overlap the given component.
  38071. It'll put itself either above, below, or to the side of the component depending
  38072. on where there's the most space, honouring any restrictions that were set
  38073. with setAllowedPlacement().
  38074. */
  38075. void setPosition (Component* componentToPointTo);
  38076. /** Moves and resizes the bubble to point at a given point.
  38077. This will resize the bubble to fit its content, then position it
  38078. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  38079. are relative to either the bubble component's parent component if it has one, or
  38080. they are screen co-ordinates if not.
  38081. It'll put itself either above, below, or to the side of this point, depending
  38082. on where there's the most space, honouring any restrictions that were set
  38083. with setAllowedPlacement().
  38084. */
  38085. void setPosition (const int arrowTipX,
  38086. const int arrowTipY);
  38087. /** Moves and resizes the bubble to point at a given rectangle.
  38088. This will resize the bubble to fit its content, then find a position for it
  38089. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  38090. co-ordinates are relative to either the bubble component's parent component
  38091. if it has one, or they are screen co-ordinates if not.
  38092. It'll put itself either above, below, or to the side of the component depending
  38093. on where there's the most space, honouring any restrictions that were set
  38094. with setAllowedPlacement().
  38095. */
  38096. void setPosition (const Rectangle& rectangleToPointTo);
  38097. protected:
  38098. /** Subclasses should override this to return the size of the content they
  38099. want to draw inside the bubble.
  38100. */
  38101. virtual void getContentSize (int& width, int& height) = 0;
  38102. /** Subclasses should override this to draw their bubble's contents.
  38103. The graphics object's clip region and the dimensions passed in here are
  38104. set up to paint just the rectangle inside the bubble.
  38105. */
  38106. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38107. public:
  38108. /** @internal */
  38109. void paint (Graphics& g);
  38110. juce_UseDebuggingNewOperator
  38111. private:
  38112. Rectangle content;
  38113. int side, allowablePlacements;
  38114. float arrowTipX, arrowTipY;
  38115. DropShadowEffect shadow;
  38116. BubbleComponent (const BubbleComponent&);
  38117. const BubbleComponent& operator= (const BubbleComponent&);
  38118. };
  38119. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38120. /********* End of inlined file: juce_BubbleComponent.h *********/
  38121. #endif
  38122. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38123. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38124. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38125. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38126. /**
  38127. A speech-bubble component that displays a short message.
  38128. This can be used to show a message with the tail of the speech bubble
  38129. pointing to a particular component or location on the screen.
  38130. @see BubbleComponent
  38131. */
  38132. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38133. private Timer
  38134. {
  38135. public:
  38136. /** Creates a bubble component.
  38137. After creating one a BubbleComponent, do the following:
  38138. - add it to an appropriate parent component, or put it on the
  38139. desktop with Component::addToDesktop (0).
  38140. - use the showAt() method to show a message.
  38141. - it will make itself invisible after it times-out (and can optionally
  38142. also delete itself), or you can reuse it somewhere else by calling
  38143. showAt() again.
  38144. */
  38145. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38146. /** Destructor. */
  38147. ~BubbleMessageComponent();
  38148. /** Shows a message bubble at a particular position.
  38149. This shows the bubble with its stem pointing to the given location
  38150. (co-ordinates being relative to its parent component).
  38151. For details about exactly how it decides where to position itself, see
  38152. BubbleComponent::updatePosition().
  38153. @param x the x co-ordinate of end of the bubble's tail
  38154. @param y the y co-ordinate of end of the bubble's tail
  38155. @param message the text to display
  38156. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38157. from its parent compnent. If this is 0 or less, it
  38158. will stay there until manually removed.
  38159. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38160. mouse button is pressed (anywhere on the screen)
  38161. @param deleteSelfAfterUse if true, then the component will delete itself after
  38162. it becomes invisible
  38163. */
  38164. void showAt (int x, int y,
  38165. const String& message,
  38166. const int numMillisecondsBeforeRemoving,
  38167. const bool removeWhenMouseClicked = true,
  38168. const bool deleteSelfAfterUse = false);
  38169. /** Shows a message bubble next to a particular component.
  38170. This shows the bubble with its stem pointing at the given component.
  38171. For details about exactly how it decides where to position itself, see
  38172. BubbleComponent::updatePosition().
  38173. @param component the component that you want to point at
  38174. @param message the text to display
  38175. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38176. from its parent compnent. If this is 0 or less, it
  38177. will stay there until manually removed.
  38178. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38179. mouse button is pressed (anywhere on the screen)
  38180. @param deleteSelfAfterUse if true, then the component will delete itself after
  38181. it becomes invisible
  38182. */
  38183. void showAt (Component* const component,
  38184. const String& message,
  38185. const int numMillisecondsBeforeRemoving,
  38186. const bool removeWhenMouseClicked = true,
  38187. const bool deleteSelfAfterUse = false);
  38188. /** @internal */
  38189. void getContentSize (int& w, int& h);
  38190. /** @internal */
  38191. void paintContent (Graphics& g, int w, int h);
  38192. /** @internal */
  38193. void timerCallback();
  38194. juce_UseDebuggingNewOperator
  38195. private:
  38196. int fadeOutLength, mouseClickCounter;
  38197. TextLayout textLayout;
  38198. int64 expiryTime;
  38199. bool deleteAfterUse;
  38200. void init (const int numMillisecondsBeforeRemoving,
  38201. const bool removeWhenMouseClicked,
  38202. const bool deleteSelfAfterUse);
  38203. BubbleMessageComponent (const BubbleMessageComponent&);
  38204. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38205. };
  38206. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38207. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38208. #endif
  38209. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38210. /********* Start of inlined file: juce_ColourSelector.h *********/
  38211. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38212. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38213. /**
  38214. A component that lets the user choose a colour.
  38215. This shows RGB sliders and a colourspace that the user can pick colours from.
  38216. This class is also a ChangeBroadcaster, so listeners can register to be told
  38217. when the colour changes.
  38218. */
  38219. class JUCE_API ColourSelector : public Component,
  38220. public ChangeBroadcaster,
  38221. protected SliderListener
  38222. {
  38223. public:
  38224. /** Options for the type of selector to show. These are passed into the constructor. */
  38225. enum ColourSelectorOptions
  38226. {
  38227. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38228. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38229. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38230. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38231. };
  38232. /** Creates a ColourSelector object.
  38233. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38234. which of the selector's features should be visible.
  38235. The edgeGap value specifies the amount of space to leave around the edge.
  38236. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38237. colourspace and hue selector components.
  38238. */
  38239. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38240. const int edgeGap = 4,
  38241. const int gapAroundColourSpaceComponent = 7);
  38242. /** Destructor. */
  38243. ~ColourSelector();
  38244. /** Returns the colour that the user has currently selected.
  38245. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38246. register to be told when the colour changes.
  38247. @see setCurrentColour
  38248. */
  38249. const Colour getCurrentColour() const;
  38250. /** Changes the colour that is currently being shown.
  38251. */
  38252. void setCurrentColour (const Colour& newColour);
  38253. /** Tells the selector how many preset colour swatches you want to have on the component.
  38254. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38255. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38256. their values.
  38257. */
  38258. virtual int getNumSwatches() const;
  38259. /** Called by the selector to find out the colour of one of the swatches.
  38260. Your subclass should return the colour of the swatch with the given index.
  38261. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38262. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38263. their values.
  38264. */
  38265. virtual const Colour getSwatchColour (const int index) const;
  38266. /** Called by the selector when the user puts a new colour into one of the swatches.
  38267. Your subclass should change the colour of the swatch with the given index.
  38268. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38269. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38270. their values.
  38271. */
  38272. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38273. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38274. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38275. methods.
  38276. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38277. */
  38278. enum ColourIds
  38279. {
  38280. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38281. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38282. };
  38283. juce_UseDebuggingNewOperator
  38284. private:
  38285. friend class ColourSpaceView;
  38286. friend class HueSelectorComp;
  38287. Colour colour;
  38288. float h, s, v;
  38289. Slider* sliders[4];
  38290. Component* colourSpace;
  38291. Component* hueSelector;
  38292. VoidArray swatchComponents;
  38293. const int flags;
  38294. int topSpace, edgeGap;
  38295. void setHue (float newH);
  38296. void setSV (float newS, float newV);
  38297. void updateHSV();
  38298. void update();
  38299. void sliderValueChanged (Slider*);
  38300. void paint (Graphics& g);
  38301. void resized();
  38302. ColourSelector (const ColourSelector&);
  38303. const ColourSelector& operator= (const ColourSelector&);
  38304. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38305. // have changed - if you get an error here, update your code to use the new constructor instead..
  38306. // (xxx - note to self: remember to remove this at some point in the future)
  38307. ColourSelector (const bool);
  38308. };
  38309. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38310. /********* End of inlined file: juce_ColourSelector.h *********/
  38311. #endif
  38312. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  38313. #endif
  38314. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38315. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  38316. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38317. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38318. /**
  38319. A component that contains another component, and can magnify or shrink it.
  38320. This component will continually update its size so that it fits the zoomed
  38321. version of the content component that you put inside it, so don't try to
  38322. change the size of this component directly - instead change that of the
  38323. content component.
  38324. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  38325. to remap mouse events correctly. This means that the content component won't
  38326. appear to be a direct child of this component, and instead will think its
  38327. on the desktop.
  38328. */
  38329. class JUCE_API MagnifierComponent : public Component
  38330. {
  38331. public:
  38332. /** Creates a MagnifierComponent.
  38333. This component will continually update its size so that it fits the zoomed
  38334. version of the content component that you put inside it, so don't try to
  38335. change the size of this component directly - instead change that of the
  38336. content component.
  38337. @param contentComponent the component to add as the magnified one
  38338. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  38339. be deleted when this component is deleted. If false,
  38340. it's the caller's responsibility to delete it later.
  38341. */
  38342. MagnifierComponent (Component* const contentComponent,
  38343. const bool deleteContentCompWhenNoLongerNeeded);
  38344. /** Destructor. */
  38345. ~MagnifierComponent();
  38346. /** Returns the current content component. */
  38347. Component* getContentComponent() const throw() { return content; }
  38348. /** Changes the zoom level.
  38349. The scale factor must be greater than zero. Values less than 1 will shrink the
  38350. image; values greater than 1 will multiply its size by this amount.
  38351. When this is called, this component will change its size to fit the full extent
  38352. of the newly zoomed content.
  38353. */
  38354. void setScaleFactor (double newScaleFactor);
  38355. /** Returns the current zoom factor. */
  38356. double getScaleFactor() const throw() { return scaleFactor; }
  38357. juce_UseDebuggingNewOperator
  38358. /** @internal */
  38359. void childBoundsChanged (Component*);
  38360. private:
  38361. Component* content;
  38362. Component* holderComp;
  38363. double scaleFactor;
  38364. ComponentPeer* peer;
  38365. bool deleteContent;
  38366. void paint (Graphics& g);
  38367. void mouseDown (const MouseEvent& e);
  38368. void mouseUp (const MouseEvent& e);
  38369. void mouseDrag (const MouseEvent& e);
  38370. void mouseMove (const MouseEvent& e);
  38371. void mouseEnter (const MouseEvent& e);
  38372. void mouseExit (const MouseEvent& e);
  38373. void mouseWheelMove (const MouseEvent& e, float, float);
  38374. int scaleInt (const int n) const throw();
  38375. MagnifierComponent (const MagnifierComponent&);
  38376. const MagnifierComponent& operator= (const MagnifierComponent&);
  38377. };
  38378. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38379. /********* End of inlined file: juce_MagnifierComponent.h *********/
  38380. #endif
  38381. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38382. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  38383. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38384. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38385. /**
  38386. A component that displays a piano keyboard, whose notes can be clicked on.
  38387. This component will mimic a physical midi keyboard, showing the current state of
  38388. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  38389. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  38390. Another feature is that the computer keyboard can also be used to play notes. By
  38391. default it maps the top two rows of a standard querty keyboard to the notes, but
  38392. these can be remapped if needed. It will only respond to keypresses when it has
  38393. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  38394. The component is also a ChangeBroadcaster, so if you want to be informed when the
  38395. keyboard is scrolled, you can register a ChangeListener for callbacks.
  38396. @see MidiKeyboardState
  38397. */
  38398. class JUCE_API MidiKeyboardComponent : public Component,
  38399. public MidiKeyboardStateListener,
  38400. public ChangeBroadcaster,
  38401. private Timer,
  38402. private AsyncUpdater
  38403. {
  38404. public:
  38405. /** The direction of the keyboard.
  38406. @see setOrientation
  38407. */
  38408. enum Orientation
  38409. {
  38410. horizontalKeyboard,
  38411. verticalKeyboardFacingLeft,
  38412. verticalKeyboardFacingRight,
  38413. };
  38414. /** Creates a MidiKeyboardComponent.
  38415. @param state the midi keyboard model that this component will represent
  38416. @param orientation whether the keyboard is horizonal or vertical
  38417. */
  38418. MidiKeyboardComponent (MidiKeyboardState& state,
  38419. const Orientation orientation);
  38420. /** Destructor. */
  38421. ~MidiKeyboardComponent();
  38422. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  38423. on the component.
  38424. Values are 0 to 1.0, where 1.0 is the heaviest.
  38425. @see setMidiChannel
  38426. */
  38427. void setVelocity (const float velocity);
  38428. /** Changes the midi channel number that will be used for events triggered by clicking
  38429. on the component.
  38430. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  38431. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  38432. Although this is the channel used for outgoing events, the component can display
  38433. incoming events from more than one channel - see setMidiChannelsToDisplay()
  38434. @see setVelocity
  38435. */
  38436. void setMidiChannel (const int midiChannelNumber);
  38437. /** Returns the midi channel that the keyboard is using for midi messages.
  38438. @see setMidiChannel
  38439. */
  38440. int getMidiChannel() const throw() { return midiChannel; }
  38441. /** Sets a mask to indicate which incoming midi channels should be represented by
  38442. key movements.
  38443. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  38444. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  38445. in this mask, the on-screen keys will also go down.
  38446. By default, this mask is set to 0xffff (all channels displayed).
  38447. @see setMidiChannel
  38448. */
  38449. void setMidiChannelsToDisplay (const int midiChannelMask);
  38450. /** Returns the current set of midi channels represented by the component.
  38451. This is the value that was set with setMidiChannelsToDisplay().
  38452. */
  38453. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  38454. /** Changes the width used to draw the white keys. */
  38455. void setKeyWidth (const float widthInPixels);
  38456. /** Returns the width that was set by setKeyWidth(). */
  38457. float getKeyWidth() const throw() { return keyWidth; }
  38458. /** Changes the keyboard's current direction. */
  38459. void setOrientation (const Orientation newOrientation);
  38460. /** Returns the keyboard's current direction. */
  38461. const Orientation getOrientation() const throw() { return orientation; }
  38462. /** Sets the range of midi notes that the keyboard will be limited to.
  38463. By default the range is 0 to 127 (inclusive), but you can limit this if you
  38464. only want a restricted set of the keys to be shown.
  38465. Note that the values here are inclusive and must be between 0 and 127.
  38466. */
  38467. void setAvailableRange (const int lowestNote,
  38468. const int highestNote);
  38469. /** Returns the first note in the available range.
  38470. @see setAvailableRange
  38471. */
  38472. int getRangeStart() const throw() { return rangeStart; }
  38473. /** Returns the last note in the available range.
  38474. @see setAvailableRange
  38475. */
  38476. int getRangeEnd() const throw() { return rangeEnd; }
  38477. /** If the keyboard extends beyond the size of the component, this will scroll
  38478. it to show the given key at the start.
  38479. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  38480. base class to send a callback to any ChangeListeners that have been registered.
  38481. */
  38482. void setLowestVisibleKey (int noteNumber);
  38483. /** Returns the number of the first key shown in the component.
  38484. @see setLowestVisibleKey
  38485. */
  38486. int getLowestVisibleKey() const throw() { return firstKey; }
  38487. /** If set to true, then scroll buttons will appear at either end of the keyboard
  38488. if there are too many notes to fit them all in the component at once.
  38489. */
  38490. void setScrollButtonsVisible (const bool canScroll);
  38491. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38492. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38493. methods.
  38494. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38495. */
  38496. enum ColourIds
  38497. {
  38498. whiteNoteColourId = 0x1005000,
  38499. blackNoteColourId = 0x1005001,
  38500. keySeparatorLineColourId = 0x1005002,
  38501. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  38502. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  38503. textLabelColourId = 0x1005005,
  38504. upDownButtonBackgroundColourId = 0x1005006,
  38505. upDownButtonArrowColourId = 0x1005007
  38506. };
  38507. /** Returns the position within the component of the left-hand edge of a key.
  38508. Depending on the keyboard's orientation, this may be a horizontal or vertical
  38509. distance, in either direction.
  38510. */
  38511. int getKeyStartPosition (const int midiNoteNumber) const;
  38512. /** Deletes all key-mappings.
  38513. @see setKeyPressForNote
  38514. */
  38515. void clearKeyMappings();
  38516. /** Maps a key-press to a given note.
  38517. @param key the key that should trigger the note
  38518. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  38519. be. The actual midi note that gets played will be
  38520. this value + (12 * the current base octave). To change
  38521. the base octave, see setKeyPressBaseOctave()
  38522. */
  38523. void setKeyPressForNote (const KeyPress& key,
  38524. const int midiNoteOffsetFromC);
  38525. /** Removes any key-mappings for a given note.
  38526. For a description of what the note number means, see setKeyPressForNote().
  38527. */
  38528. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  38529. /** Changes the base note above which key-press-triggered notes are played.
  38530. The set of key-mappings that trigger notes can be moved up and down to cover
  38531. the entire scale using this method.
  38532. The value passed in is an octave number between 0 and 10 (inclusive), and
  38533. indicates which C is the base note to which the key-mapped notes are
  38534. relative.
  38535. */
  38536. void setKeyPressBaseOctave (const int newOctaveNumber);
  38537. /** This sets the octave number which is shown as the octave number for middle C.
  38538. This affects only the default implementation of getWhiteNoteText(), which
  38539. passes this octave number to MidiMessage::getMidiNoteName() in order to
  38540. get the note text. See MidiMessage::getMidiNoteName() for more info about
  38541. the parameter.
  38542. By default this value is set to 3.
  38543. @see getOctaveForMiddleC
  38544. */
  38545. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  38546. /** This returns the value set by setOctaveForMiddleC().
  38547. @see setOctaveForMiddleC
  38548. */
  38549. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  38550. /** @internal */
  38551. void paint (Graphics& g);
  38552. /** @internal */
  38553. void resized();
  38554. /** @internal */
  38555. void mouseMove (const MouseEvent& e);
  38556. /** @internal */
  38557. void mouseDrag (const MouseEvent& e);
  38558. /** @internal */
  38559. void mouseDown (const MouseEvent& e);
  38560. /** @internal */
  38561. void mouseUp (const MouseEvent& e);
  38562. /** @internal */
  38563. void mouseEnter (const MouseEvent& e);
  38564. /** @internal */
  38565. void mouseExit (const MouseEvent& e);
  38566. /** @internal */
  38567. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38568. /** @internal */
  38569. void timerCallback();
  38570. /** @internal */
  38571. bool keyStateChanged();
  38572. /** @internal */
  38573. void focusLost (FocusChangeType cause);
  38574. /** @internal */
  38575. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  38576. /** @internal */
  38577. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  38578. /** @internal */
  38579. void handleAsyncUpdate();
  38580. /** @internal */
  38581. void colourChanged();
  38582. juce_UseDebuggingNewOperator
  38583. protected:
  38584. friend class MidiKeyboardUpDownButton;
  38585. /** Draws a white note in the given rectangle.
  38586. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38587. currently pressed down.
  38588. When doing this, be sure to note the keyboard's orientation.
  38589. */
  38590. virtual void drawWhiteNote (int midiNoteNumber,
  38591. Graphics& g,
  38592. int x, int y, int w, int h,
  38593. bool isDown, bool isOver,
  38594. const Colour& lineColour,
  38595. const Colour& textColour);
  38596. /** Draws a black note in the given rectangle.
  38597. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38598. currently pressed down.
  38599. When doing this, be sure to note the keyboard's orientation.
  38600. */
  38601. virtual void drawBlackNote (int midiNoteNumber,
  38602. Graphics& g,
  38603. int x, int y, int w, int h,
  38604. bool isDown, bool isOver,
  38605. const Colour& noteFillColour);
  38606. /** Allows text to be drawn on the white notes.
  38607. By default this is used to label the C in each octave, but could be used for other things.
  38608. @see setOctaveForMiddleC
  38609. */
  38610. virtual const String getWhiteNoteText (const int midiNoteNumber);
  38611. /** Draws the up and down buttons that change the base note. */
  38612. virtual void drawUpDownButton (Graphics& g, int w, int h,
  38613. const bool isMouseOver,
  38614. const bool isButtonPressed,
  38615. const bool movesOctavesUp);
  38616. /** Callback when the mouse is clicked on a key.
  38617. You could use this to do things like handle right-clicks on keys, etc.
  38618. Return true if you want the click to trigger the note, or false if you
  38619. want to handle it yourself and not have the note played.
  38620. @see mouseDraggedToKey
  38621. */
  38622. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  38623. /** Callback when the mouse is dragged from one key onto another.
  38624. @see mouseDownOnKey
  38625. */
  38626. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  38627. /** Calculates the positon of a given midi-note.
  38628. This can be overridden to create layouts with custom key-widths.
  38629. @param midiNoteNumber the note to find
  38630. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  38631. @param x the x position of the left-hand edge of the key (this method
  38632. always works in terms of a horizontal keyboard)
  38633. @param w the width of the key
  38634. */
  38635. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  38636. int& x, int& w) const;
  38637. private:
  38638. MidiKeyboardState& state;
  38639. int xOffset, blackNoteLength;
  38640. float keyWidth;
  38641. Orientation orientation;
  38642. int midiChannel, midiInChannelMask;
  38643. float velocity;
  38644. int noteUnderMouse, mouseDownNote;
  38645. BitArray keysPressed, keysCurrentlyDrawnDown;
  38646. int rangeStart, rangeEnd, firstKey;
  38647. bool canScroll, mouseDragging;
  38648. Button* scrollDown;
  38649. Button* scrollUp;
  38650. Array <KeyPress> keyPresses;
  38651. Array <int> keyPressNotes;
  38652. int keyMappingOctave;
  38653. int octaveNumForMiddleC;
  38654. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  38655. int xyToNote (int x, int y);
  38656. int remappedXYToNote (int x, int y) const;
  38657. void resetAnyKeysInUse();
  38658. void updateNoteUnderMouse (int x, int y);
  38659. void repaintNote (const int midiNoteNumber);
  38660. MidiKeyboardComponent (const MidiKeyboardComponent&);
  38661. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  38662. };
  38663. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38664. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  38665. #endif
  38666. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38667. /********* Start of inlined file: juce_NSViewComponent.h *********/
  38668. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38669. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38670. #if ! DOXYGEN
  38671. class NSViewComponentInternal;
  38672. #endif
  38673. #if JUCE_MAC || DOXYGEN
  38674. /**
  38675. A Mac-specific class that can create and embed an NSView inside itself.
  38676. To use it, create one of these, put it in place and make sure it's visible in a
  38677. window, then use setView() to assign an NSView to it. The view will then be
  38678. moved and resized to follow the movements of this component.
  38679. Of course, since the view is a native object, it'll obliterate any
  38680. juce components that may overlap this component, but that's life.
  38681. */
  38682. class JUCE_API NSViewComponent : public Component
  38683. {
  38684. public:
  38685. /** Create an initially-empty container. */
  38686. NSViewComponent();
  38687. /** Destructor. */
  38688. ~NSViewComponent();
  38689. /** Assigns an NSView to this peer.
  38690. The view will be retained and released by this component for as long as
  38691. it is needed. To remove the current view, just call setView (0).
  38692. Note: a void* is used here to avoid including the cocoa headers as
  38693. part of the juce.h, but the method expects an NSView*.
  38694. */
  38695. void setView (void* nsView);
  38696. /** Returns the current NSView.
  38697. Note: a void* is returned here to avoid including the cocoa headers as
  38698. a requirement of juce.h, so you should just cast the object to an NSView*.
  38699. */
  38700. void* getView() const;
  38701. /** @internal */
  38702. void paint (Graphics& g);
  38703. juce_UseDebuggingNewOperator
  38704. private:
  38705. friend class NSViewComponentInternal;
  38706. NSViewComponentInternal* info;
  38707. NSViewComponent (const NSViewComponent&);
  38708. const NSViewComponent& operator= (const NSViewComponent&);
  38709. };
  38710. #endif
  38711. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38712. /********* End of inlined file: juce_NSViewComponent.h *********/
  38713. #endif
  38714. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38715. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  38716. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38717. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38718. // this is used to disable OpenGL, and is defined in juce_Config.h
  38719. #if JUCE_OPENGL || DOXYGEN
  38720. class OpenGLComponentWatcher;
  38721. /**
  38722. Represents the various properties of an OpenGL bitmap format.
  38723. @see OpenGLComponent::setPixelFormat
  38724. */
  38725. struct OpenGLPixelFormat
  38726. {
  38727. /** Creates an OpenGLPixelFormat.
  38728. The default constructor just initialises the object as a simple 8-bit
  38729. RGBA format.
  38730. */
  38731. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  38732. const int alphaBits = 8,
  38733. const int depthBufferBits = 16,
  38734. const int stencilBufferBits = 0) throw();
  38735. int redBits; /**< The number of bits per pixel to use for the red channel. */
  38736. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  38737. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  38738. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  38739. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  38740. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  38741. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  38742. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  38743. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  38744. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  38745. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  38746. /** Returns a list of all the pixel formats that can be used in this system.
  38747. A reference component is needed in case there are multiple screens with different
  38748. capabilities - in which case, the one that the component is on will be used.
  38749. */
  38750. static void getAvailablePixelFormats (Component* component,
  38751. OwnedArray <OpenGLPixelFormat>& results);
  38752. bool operator== (const OpenGLPixelFormat&) const throw();
  38753. juce_UseDebuggingNewOperator
  38754. };
  38755. /**
  38756. A base class for types of OpenGL context.
  38757. An OpenGLComponent will supply its own context for drawing in its window.
  38758. */
  38759. class OpenGLContext
  38760. {
  38761. public:
  38762. /** Destructor. */
  38763. virtual ~OpenGLContext();
  38764. /** Makes this context the currently active one. */
  38765. virtual bool makeActive() const throw() = 0;
  38766. /** If this context is currently active, it is disactivated. */
  38767. virtual bool makeInactive() const throw() = 0;
  38768. /** Returns true if this context is currently active. */
  38769. virtual bool isActive() const throw() = 0;
  38770. /** Swaps the buffers (if the context can do this). */
  38771. virtual void swapBuffers() = 0;
  38772. /** Sets whether the context checks the vertical sync before swapping.
  38773. The value is the number of frames to allow between buffer-swapping. This is
  38774. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  38775. and greater numbers indicate that it should swap less often.
  38776. Returns true if it sets the value successfully.
  38777. */
  38778. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  38779. /** Returns the current swap-sync interval.
  38780. See setSwapInterval() for info about the value returned.
  38781. */
  38782. virtual int getSwapInterval() const = 0;
  38783. /** Returns the pixel format being used by this context. */
  38784. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  38785. /** For windowed contexts, this moves the context within the bounds of
  38786. its parent window.
  38787. */
  38788. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  38789. /** For windowed contexts, this triggers a repaint of the window.
  38790. (Not relevent on all platforms).
  38791. */
  38792. virtual void repaint() = 0;
  38793. /** Returns an OS-dependent handle to the raw GL context.
  38794. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  38795. a GLXContext.
  38796. */
  38797. virtual void* getRawContext() const throw() = 0;
  38798. /** This tries to create a context that can be used for drawing into the
  38799. area occupied by the specified component.
  38800. Note that you probably shouldn't use this method directly unless you know what
  38801. you're doing - the OpenGLComponent calls this and manages the context for you.
  38802. */
  38803. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  38804. const OpenGLPixelFormat& pixelFormat,
  38805. const OpenGLContext* const contextToShareWith);
  38806. /** Returns the context that's currently in active use by the calling thread.
  38807. Returns 0 if there isn't an active context.
  38808. */
  38809. static OpenGLContext* getCurrentContext();
  38810. juce_UseDebuggingNewOperator
  38811. protected:
  38812. OpenGLContext() throw();
  38813. };
  38814. /**
  38815. A component that contains an OpenGL canvas.
  38816. Override this, add it to whatever component you want to, and use the renderOpenGL()
  38817. method to draw its contents.
  38818. */
  38819. class JUCE_API OpenGLComponent : public Component
  38820. {
  38821. public:
  38822. /** Creates an OpenGLComponent.
  38823. */
  38824. OpenGLComponent();
  38825. /** Destructor. */
  38826. ~OpenGLComponent();
  38827. /** Changes the pixel format used by this component.
  38828. @see OpenGLPixelFormat::getAvailablePixelFormats()
  38829. */
  38830. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  38831. /** Returns the pixel format that this component is currently using. */
  38832. const OpenGLPixelFormat getPixelFormat() const;
  38833. /** Specifies an OpenGL context which should be shared with the one that this
  38834. component is using.
  38835. This is an OpenGL feature that lets two contexts share their texture data.
  38836. Note that this pointer is stored by the component, and when the component
  38837. needs to recreate its internal context for some reason, the same context
  38838. will be used again to share lists. So if you pass a context in here,
  38839. don't delete the context while this component is still using it! You can
  38840. call shareWith (0) to stop this component from sharing with it.
  38841. */
  38842. void shareWith (OpenGLContext* contextToShareListsWith);
  38843. /** Returns the context that this component is sharing with.
  38844. @see shareWith
  38845. */
  38846. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  38847. /** Flips the openGL buffers over. */
  38848. void swapBuffers();
  38849. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  38850. When this is called, makeCurrentContextActive() will already have been called
  38851. for you, so you just need to draw.
  38852. */
  38853. virtual void renderOpenGL() = 0;
  38854. /** This method is called when the component creates a new OpenGL context.
  38855. A new context may be created when the component is first used, or when it
  38856. is moved to a different window, or when the window is hidden and re-shown,
  38857. etc.
  38858. You can use this callback as an opportunity to set up things like textures
  38859. that your context needs.
  38860. New contexts are created on-demand by the makeCurrentContextActive() method - so
  38861. if the context is deleted, e.g. by changing the pixel format or window, no context
  38862. will be created until the next call to makeCurrentContextActive(), which will
  38863. synchronously create one and call this method. This means that if you're using
  38864. a non-GUI thread for rendering, you can make sure this method is be called by
  38865. your renderer thread.
  38866. When this callback happens, the context will already have been made current
  38867. using the makeCurrentContextActive() method, so there's no need to call it
  38868. again in your code.
  38869. */
  38870. virtual void newOpenGLContextCreated() = 0;
  38871. /** Returns the context that will draw into this component.
  38872. This may return 0 if the component is currently invisible or hasn't currently
  38873. got a context. The context object can be deleted and a new one created during
  38874. the lifetime of this component, and there may be times when it doesn't have one.
  38875. @see newOpenGLContextCreated()
  38876. */
  38877. OpenGLContext* getCurrentContext() const throw() { return context; }
  38878. /** Makes this component the current openGL context.
  38879. You might want to use this in things like your resize() method, before calling
  38880. GL commands.
  38881. If this returns false, then the context isn't active, so you should avoid
  38882. making any calls.
  38883. This call may actually create a context if one isn't currently initialised. If
  38884. it does this, it will also synchronously call the newOpenGLContextCreated()
  38885. method to let you initialise it as necessary.
  38886. @see OpenGLContext::makeActive
  38887. */
  38888. bool makeCurrentContextActive();
  38889. /** Stops the current component being the active OpenGL context.
  38890. This is the opposite of makeCurrentContextActive()
  38891. @see OpenGLContext::makeInactive
  38892. */
  38893. void makeCurrentContextInactive();
  38894. /** Returns true if this component is the active openGL context for the
  38895. current thread.
  38896. @see OpenGLContext::isActive
  38897. */
  38898. bool isActiveContext() const throw();
  38899. /** Calls the rendering callback, and swaps the buffers afterwards.
  38900. This is called automatically by paint() when the component needs to be rendered.
  38901. It can be overridden if you need to decouple the rendering from the paint callback
  38902. and render with a custom thread.
  38903. Returns true if the operation succeeded.
  38904. */
  38905. virtual bool renderAndSwapBuffers();
  38906. /** This returns a critical section that can be used to lock the current context.
  38907. Because the context that is used by this component can change, e.g. when the
  38908. component is shown or hidden, then if you're rendering to it on a background
  38909. thread, this allows you to lock the context for the duration of your rendering
  38910. routine.
  38911. */
  38912. CriticalSection& getContextLock() throw() { return contextLock; }
  38913. /** @internal */
  38914. void paint (Graphics& g);
  38915. /** Returns the native handle of an embedded heavyweight window, if there is one.
  38916. E.g. On windows, this will return the HWND of the sub-window containing
  38917. the opengl context, on the mac it'll be the NSOpenGLView.
  38918. */
  38919. void* getNativeWindowHandle() const;
  38920. juce_UseDebuggingNewOperator
  38921. private:
  38922. friend class OpenGLComponentWatcher;
  38923. OpenGLComponentWatcher* componentWatcher;
  38924. OpenGLContext* context;
  38925. OpenGLContext* contextToShareListsWith;
  38926. CriticalSection contextLock;
  38927. OpenGLPixelFormat preferredPixelFormat;
  38928. bool needToUpdateViewport;
  38929. void deleteContext();
  38930. void updateContextPosition();
  38931. void internalRepaint (int x, int y, int w, int h);
  38932. OpenGLComponent (const OpenGLComponent&);
  38933. const OpenGLComponent& operator= (const OpenGLComponent&);
  38934. };
  38935. #endif
  38936. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38937. /********* End of inlined file: juce_OpenGLComponent.h *********/
  38938. #endif
  38939. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38940. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  38941. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38942. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38943. /**
  38944. A component with a set of buttons at the top for changing between pages of
  38945. preferences.
  38946. This is just a handy way of writing a Mac-style preferences panel where you
  38947. have a row of buttons along the top for the different preference categories,
  38948. each button having an icon above its name. Clicking these will show an
  38949. appropriate prefs page below it.
  38950. You can either put one of these inside your own component, or just use the
  38951. showInDialogBox() method to show it in a window and run it modally.
  38952. To use it, just add a set of named pages with the addSettingsPage() method,
  38953. and implement the createComponentForPage() method to create suitable components
  38954. for each of these pages.
  38955. */
  38956. class JUCE_API PreferencesPanel : public Component,
  38957. private ButtonListener
  38958. {
  38959. public:
  38960. /** Creates an empty panel.
  38961. Use addSettingsPage() to add some pages to it in your constructor.
  38962. */
  38963. PreferencesPanel();
  38964. /** Destructor. */
  38965. ~PreferencesPanel();
  38966. /** Creates a page using a set of drawables to define the page's icon.
  38967. Note that the other version of this method is much easier if you're using
  38968. an image instead of a custom drawable.
  38969. @param pageTitle the name of this preferences page - you'll need to
  38970. make sure your createComponentForPage() method creates
  38971. a suitable component when it is passed this name
  38972. @param normalIcon the drawable to display in the page's button normally
  38973. @param overIcon the drawable to display in the page's button when the mouse is over
  38974. @param downIcon the drawable to display in the page's button when the button is down
  38975. @see DrawableButton
  38976. */
  38977. void addSettingsPage (const String& pageTitle,
  38978. const Drawable* normalIcon,
  38979. const Drawable* overIcon,
  38980. const Drawable* downIcon);
  38981. /** Creates a page using a set of drawables to define the page's icon.
  38982. The other version of this method gives you more control over the icon, but this
  38983. one is much easier if you're just loading it from a file.
  38984. @param pageTitle the name of this preferences page - you'll need to
  38985. make sure your createComponentForPage() method creates
  38986. a suitable component when it is passed this name
  38987. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  38988. For this to look good, you'll probably want to use a nice
  38989. transparent png file.
  38990. @param imageDataSize the size of the image data, in bytes
  38991. */
  38992. void addSettingsPage (const String& pageTitle,
  38993. const char* imageData,
  38994. const int imageDataSize);
  38995. /** Utility method to display this panel in a DialogWindow.
  38996. Calling this will create a DialogWindow containing this panel with the
  38997. given size and title, and will run it modally, returning when the user
  38998. closes the dialog box.
  38999. */
  39000. void showInDialogBox (const String& dialogtitle,
  39001. int dialogWidth,
  39002. int dialogHeight,
  39003. const Colour& backgroundColour = Colours::white);
  39004. /** Subclasses must override this to return a component for each preferences page.
  39005. The subclass should return a pointer to a new component representing the named
  39006. page, which the panel will then display.
  39007. The panel will delete the component later when the user goes to another page
  39008. or deletes the panel.
  39009. */
  39010. virtual Component* createComponentForPage (const String& pageName) = 0;
  39011. /** Changes the current page being displayed. */
  39012. void setCurrentPage (const String& pageName);
  39013. /** @internal */
  39014. void resized();
  39015. /** @internal */
  39016. void paint (Graphics& g);
  39017. /** @internal */
  39018. void buttonClicked (Button* button);
  39019. juce_UseDebuggingNewOperator
  39020. private:
  39021. String currentPageName;
  39022. Component* currentPage;
  39023. int buttonSize;
  39024. PreferencesPanel (const PreferencesPanel&);
  39025. const PreferencesPanel& operator= (const PreferencesPanel&);
  39026. };
  39027. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39028. /********* End of inlined file: juce_PreferencesPanel.h *********/
  39029. #endif
  39030. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39031. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  39032. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39033. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39034. // this is used to disable QuickTime, and is defined in juce_Config.h
  39035. #if JUCE_QUICKTIME || DOXYGEN
  39036. #if JUCE_WIN32
  39037. typedef ActiveXControlComponent QTCompBaseClass;
  39038. #else
  39039. typedef NSViewComponent QTCompBaseClass;
  39040. #endif
  39041. /**
  39042. A window that can play back a QuickTime movie.
  39043. */
  39044. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  39045. {
  39046. public:
  39047. /** Creates a QuickTimeMovieComponent, initially blank.
  39048. Use the loadMovie() method to load a movie once you've added the
  39049. component to a window, (or put it on the desktop as a heavyweight window).
  39050. Loading a movie when the component isn't visible can cause problems, as
  39051. QuickTime needs a window handle to initialise properly.
  39052. */
  39053. QuickTimeMovieComponent();
  39054. /** Destructor. */
  39055. ~QuickTimeMovieComponent();
  39056. /** Returns true if QT is installed and working on this machine.
  39057. */
  39058. static bool isQuickTimeAvailable() throw();
  39059. /** Tries to load a QuickTime movie into the player.
  39060. It's best to call this function once you've added the component to a window,
  39061. (or put it on the desktop as a heavyweight window). Loading a movie when the
  39062. component isn't visible can cause problems, because QuickTime needs a window
  39063. handle to do its stuff.
  39064. @param movieFile the .mov file to open
  39065. @param isControllerVisible whether to show a controller bar at the bottom
  39066. @returns true if the movie opens successfully
  39067. */
  39068. bool loadMovie (const File& movieFile,
  39069. const bool isControllerVisible);
  39070. bool loadMovie (InputStream* movieStream,
  39071. const bool isControllerVisible);
  39072. /** Closes the movie, if one is open. */
  39073. void closeMovie();
  39074. /** Returns the movie file that is currently open.
  39075. If there isn't one, this returns File::nonexistent
  39076. */
  39077. const File getCurrentMovieFile() const;
  39078. /** Returns true if there's currently a movie open. */
  39079. bool isMovieOpen() const;
  39080. /** Returns the length of the movie, in seconds. */
  39081. double getMovieDuration() const;
  39082. /** Returns the movie's natural size, in pixels.
  39083. You can use this to resize the component to show the movie at its preferred
  39084. scale.
  39085. If no movie is loaded, the size returned will be 0 x 0.
  39086. */
  39087. void getMovieNormalSize (int& width, int& height) const;
  39088. /** This will position the component within a given area, keeping its aspect
  39089. ratio correct according to the movie's normal size.
  39090. The component will be made as large as it can go within the space, and will
  39091. be aligned according to the justification value if this means there are gaps at
  39092. the top or sides.
  39093. */
  39094. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  39095. const RectanglePlacement& placement);
  39096. /** Starts the movie playing. */
  39097. void play();
  39098. /** Stops the movie playing. */
  39099. void stop();
  39100. /** Returns true if the movie is currently playing. */
  39101. bool isPlaying() const;
  39102. /** Moves the movie's position back to the start. */
  39103. void goToStart();
  39104. /** Sets the movie's position to a given time. */
  39105. void setPosition (const double seconds);
  39106. /** Returns the current play position of the movie. */
  39107. double getPosition() const;
  39108. /** Changes the movie playback rate.
  39109. A value of 1 is normal speed, greater values play it proportionately faster,
  39110. smaller values play it slower.
  39111. */
  39112. void setSpeed (const float newSpeed);
  39113. /** Changes the movie's playback volume.
  39114. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39115. */
  39116. void setMovieVolume (const float newVolume);
  39117. /** Returns the movie's playback volume.
  39118. @returns the volume in the range 0 (silent) to 1.0 (full)
  39119. */
  39120. float getMovieVolume() const;
  39121. /** Tells the movie whether it should loop. */
  39122. void setLooping (const bool shouldLoop);
  39123. /** Returns true if the movie is currently looping.
  39124. @see setLooping
  39125. */
  39126. bool isLooping() const;
  39127. /** True if the native QuickTime controller bar is shown in the window.
  39128. @see loadMovie
  39129. */
  39130. bool isControllerVisible() const;
  39131. /** @internal */
  39132. void paint (Graphics& g);
  39133. juce_UseDebuggingNewOperator
  39134. private:
  39135. File movieFile;
  39136. bool movieLoaded, controllerVisible, looping;
  39137. #if JUCE_WIN32
  39138. /** @internal */
  39139. void parentHierarchyChanged();
  39140. /** @internal */
  39141. void visibilityChanged();
  39142. void createControlIfNeeded();
  39143. bool isControlCreated() const;
  39144. void* internal;
  39145. #else
  39146. void* movie;
  39147. #endif
  39148. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39149. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39150. };
  39151. #endif
  39152. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39153. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39154. #endif
  39155. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39156. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  39157. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39158. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39159. #if JUCE_WIN32 || JUCE_LINUX
  39160. /**
  39161. On Windows only, this component sits in the taskbar tray as a small icon.
  39162. To use it, just create one of these components, but don't attempt to make it
  39163. visible, add it to a parent, or put it on the desktop.
  39164. You can then call setIconImage() to create an icon for it in the taskbar.
  39165. To change the icon's tooltip, you can use setIconTooltip().
  39166. To respond to mouse-events, you can override the normal mouseDown(),
  39167. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  39168. position will not be valid, you can use this to respond to clicks. Traditionally
  39169. you'd use a left-click to show your application's window, and a right-click
  39170. to show a pop-up menu.
  39171. */
  39172. class JUCE_API SystemTrayIconComponent : public Component
  39173. {
  39174. public:
  39175. SystemTrayIconComponent();
  39176. /** Destructor. */
  39177. ~SystemTrayIconComponent();
  39178. /** Changes the image shown in the taskbar.
  39179. */
  39180. void setIconImage (const Image& newImage);
  39181. /** Changes the tooltip that Windows shows above the icon. */
  39182. void setIconTooltip (const String& tooltip);
  39183. #if JUCE_LINUX
  39184. /** @internal */
  39185. void paint (Graphics& g);
  39186. #endif
  39187. juce_UseDebuggingNewOperator
  39188. private:
  39189. SystemTrayIconComponent (const SystemTrayIconComponent&);
  39190. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  39191. };
  39192. #endif
  39193. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39194. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  39195. #endif
  39196. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39197. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  39198. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39199. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39200. #if JUCE_WEB_BROWSER
  39201. class WebBrowserComponentInternal;
  39202. /**
  39203. A component that displays an embedded web browser.
  39204. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  39205. Windows, probably IE.
  39206. */
  39207. class WebBrowserComponent : public Component
  39208. {
  39209. public:
  39210. /** Creates a WebBrowserComponent.
  39211. Once it's created and visible, send the browser to a URL using goToURL().
  39212. */
  39213. WebBrowserComponent();
  39214. /** Destructor. */
  39215. ~WebBrowserComponent();
  39216. /** Sends the browser to a particular URL.
  39217. @param url the URL to go to.
  39218. @param headers an optional set of parameters to put in the HTTP header. If
  39219. you supply this, it should be a set of string in the form
  39220. "HeaderKey: HeaderValue"
  39221. @param postData an optional block of data that will be attached to the HTTP
  39222. POST request
  39223. */
  39224. void goToURL (const String& url,
  39225. const StringArray* headers = 0,
  39226. const MemoryBlock* postData = 0);
  39227. /** Stops the current page loading.
  39228. */
  39229. void stop();
  39230. /** Sends the browser back one page.
  39231. */
  39232. void goBack();
  39233. /** Sends the browser forward one page.
  39234. */
  39235. void goForward();
  39236. /** This callback is called when the browser is about to navigate
  39237. to a new location.
  39238. You can override this method to perform some action when the user
  39239. tries to go to a particular URL. To allow the operation to carry on,
  39240. return true, or return false to stop the navigation happening.
  39241. */
  39242. virtual bool pageAboutToLoad (const String& newURL);
  39243. /** @internal */
  39244. void paint (Graphics& g);
  39245. /** @internal */
  39246. void resized();
  39247. /** @internal */
  39248. void parentHierarchyChanged();
  39249. /** @internal */
  39250. void visibilityChanged();
  39251. juce_UseDebuggingNewOperator
  39252. private:
  39253. WebBrowserComponentInternal* browser;
  39254. bool blankPageShown;
  39255. String lastURL;
  39256. StringArray lastHeaders;
  39257. MemoryBlock lastPostData;
  39258. void reloadLastURL();
  39259. void checkWindowAssociation();
  39260. WebBrowserComponent (const WebBrowserComponent&);
  39261. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  39262. };
  39263. #endif
  39264. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39265. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  39266. #endif
  39267. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39268. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39269. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39270. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39271. class ToggleButton;
  39272. class TextButton;
  39273. class AlertWindow;
  39274. class TextLayout;
  39275. class ScrollBar;
  39276. class BubbleComponent;
  39277. class ComboBox;
  39278. class Button;
  39279. class FilenameComponent;
  39280. class DocumentWindow;
  39281. class ResizableWindow;
  39282. class GroupComponent;
  39283. class MenuBarComponent;
  39284. class DropShadower;
  39285. class GlyphArrangement;
  39286. class PropertyComponent;
  39287. class TableHeaderComponent;
  39288. class Toolbar;
  39289. class ToolbarItemComponent;
  39290. class PopupMenu;
  39291. class ProgressBar;
  39292. class FileBrowserComponent;
  39293. class DirectoryContentsDisplayComponent;
  39294. class FilePreviewComponent;
  39295. /**
  39296. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39297. can be used to apply different 'skins' to the application.
  39298. */
  39299. class JUCE_API LookAndFeel
  39300. {
  39301. public:
  39302. /** Creates the default JUCE look and feel. */
  39303. LookAndFeel();
  39304. /** Destructor. */
  39305. virtual ~LookAndFeel();
  39306. /** Returns the current default look-and-feel for a component to use when it
  39307. hasn't got one explicitly set.
  39308. @see setDefaultLookAndFeel
  39309. */
  39310. static LookAndFeel& getDefaultLookAndFeel() throw();
  39311. /** Changes the default look-and-feel.
  39312. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39313. set to 0, it will revert to using the default one. The
  39314. object passed-in must be deleted by the caller when
  39315. it's no longer needed.
  39316. @see getDefaultLookAndFeel
  39317. */
  39318. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39319. /** Looks for a colour that has been registered with the given colour ID number.
  39320. If a colour has been set for this ID number using setColour(), then it is
  39321. returned. If none has been set, it will just return Colours::black.
  39322. The colour IDs for various purposes are stored as enums in the components that
  39323. they are relevent to - for an example, see Slider::ColourIds,
  39324. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39325. If you're looking up a colour for use in drawing a component, it's usually
  39326. best not to call this directly, but to use the Component::findColour() method
  39327. instead. That will first check whether a suitable colour has been registered
  39328. directly with the component, and will fall-back on calling the component's
  39329. LookAndFeel's findColour() method if none is found.
  39330. @see setColour, Component::findColour, Component::setColour
  39331. */
  39332. const Colour findColour (const int colourId) const throw();
  39333. /** Registers a colour to be used for a particular purpose.
  39334. For more details, see the comments for findColour().
  39335. @see findColour, Component::findColour, Component::setColour
  39336. */
  39337. void setColour (const int colourId, const Colour& colour) throw();
  39338. /** Draws the lozenge-shaped background for a standard button. */
  39339. virtual void drawButtonBackground (Graphics& g,
  39340. Button& button,
  39341. const Colour& backgroundColour,
  39342. bool isMouseOverButton,
  39343. bool isButtonDown);
  39344. /** Draws the text for a TextButton. */
  39345. virtual void drawButtonText (Graphics& g,
  39346. TextButton& button,
  39347. bool isMouseOverButton,
  39348. bool isButtonDown);
  39349. /** Draws the contents of a standard ToggleButton. */
  39350. virtual void drawToggleButton (Graphics& g,
  39351. ToggleButton& button,
  39352. bool isMouseOverButton,
  39353. bool isButtonDown);
  39354. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39355. virtual void drawTickBox (Graphics& g,
  39356. Component& component,
  39357. int x, int y, int w, int h,
  39358. const bool ticked,
  39359. const bool isEnabled,
  39360. const bool isMouseOverButton,
  39361. const bool isButtonDown);
  39362. /** Draws the contents of a message box.
  39363. */
  39364. virtual void drawAlertBox (Graphics& g,
  39365. AlertWindow& alert,
  39366. const Rectangle& textArea,
  39367. TextLayout& textLayout);
  39368. virtual int getAlertBoxWindowFlags();
  39369. virtual int getAlertWindowButtonHeight();
  39370. virtual const Font getAlertWindowFont();
  39371. /** Draws a progress bar.
  39372. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39373. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39374. isn't known). It can use the current time as a basis for playing an animation.
  39375. (Used by progress bars in AlertWindow).
  39376. */
  39377. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39378. int width, int height,
  39379. double progress, const String& textToShow);
  39380. /** Draws one of the buttons on a scrollbar.
  39381. @param g the context to draw into
  39382. @param scrollbar the bar itself
  39383. @param width the width of the button
  39384. @param height the height of the button
  39385. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39386. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39387. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39388. @param isButtonDown whether the mouse button's held down
  39389. */
  39390. virtual void drawScrollbarButton (Graphics& g,
  39391. ScrollBar& scrollbar,
  39392. int width, int height,
  39393. int buttonDirection,
  39394. bool isScrollbarVertical,
  39395. bool isMouseOverButton,
  39396. bool isButtonDown);
  39397. /** Draws the thumb area of a scrollbar.
  39398. @param g the context to draw into
  39399. @param scrollbar the bar itself
  39400. @param x the x position of the left edge of the thumb area to draw in
  39401. @param y the y position of the top edge of the thumb area to draw in
  39402. @param width the width of the thumb area to draw in
  39403. @param height the height of the thumb area to draw in
  39404. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39405. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39406. thumb, or its x position for horizontal bars
  39407. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39408. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39409. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39410. currently dragging the thumb
  39411. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39412. */
  39413. virtual void drawScrollbar (Graphics& g,
  39414. ScrollBar& scrollbar,
  39415. int x, int y,
  39416. int width, int height,
  39417. bool isScrollbarVertical,
  39418. int thumbStartPosition,
  39419. int thumbSize,
  39420. bool isMouseOver,
  39421. bool isMouseDown);
  39422. /** Returns the component effect to use for a scrollbar */
  39423. virtual ImageEffectFilter* getScrollbarEffect();
  39424. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39425. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39426. /** Returns the default thickness to use for a scrollbar. */
  39427. virtual int getDefaultScrollbarWidth();
  39428. /** Returns the length in pixels to use for a scrollbar button. */
  39429. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39430. /** Returns a tick shape for use in yes/no boxes, etc. */
  39431. virtual const Path getTickShape (const float height);
  39432. /** Returns a cross shape for use in yes/no boxes, etc. */
  39433. virtual const Path getCrossShape (const float height);
  39434. /** Draws the + or - box in a treeview. */
  39435. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus);
  39436. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39437. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39438. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39439. virtual Image* getDefaultFolderImage();
  39440. virtual Image* getDefaultDocumentFileImage();
  39441. virtual void createFileChooserHeaderText (const String& title,
  39442. const String& instructions,
  39443. GlyphArrangement& destArrangement,
  39444. int width);
  39445. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39446. const String& filename, Image* icon,
  39447. const String& fileSizeDescription,
  39448. const String& fileTimeDescription,
  39449. const bool isDirectory,
  39450. const bool isItemSelected,
  39451. const int itemIndex);
  39452. virtual Button* createFileBrowserGoUpButton();
  39453. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39454. DirectoryContentsDisplayComponent* fileListComponent,
  39455. FilePreviewComponent* previewComp,
  39456. ComboBox* currentPathBox,
  39457. TextEditor* filenameBox,
  39458. Button* goUpButton);
  39459. virtual void drawBubble (Graphics& g,
  39460. float tipX, float tipY,
  39461. float boxX, float boxY, float boxW, float boxH);
  39462. /** Fills the background of a popup menu component. */
  39463. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39464. /** Draws one of the items in a popup menu. */
  39465. virtual void drawPopupMenuItem (Graphics& g,
  39466. int width, int height,
  39467. const bool isSeparator,
  39468. const bool isActive,
  39469. const bool isHighlighted,
  39470. const bool isTicked,
  39471. const bool hasSubMenu,
  39472. const String& text,
  39473. const String& shortcutKeyText,
  39474. Image* image,
  39475. const Colour* const textColour);
  39476. /** Returns the size and style of font to use in popup menus. */
  39477. virtual const Font getPopupMenuFont();
  39478. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  39479. int width, int height,
  39480. bool isScrollUpArrow);
  39481. /** Finds the best size for an item in a popup menu. */
  39482. virtual void getIdealPopupMenuItemSize (const String& text,
  39483. const bool isSeparator,
  39484. int standardMenuItemHeight,
  39485. int& idealWidth,
  39486. int& idealHeight);
  39487. virtual int getMenuWindowFlags();
  39488. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39489. bool isMouseOverBar,
  39490. MenuBarComponent& menuBar);
  39491. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39492. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39493. virtual void drawMenuBarItem (Graphics& g,
  39494. int width, int height,
  39495. int itemIndex,
  39496. const String& itemText,
  39497. bool isMouseOverItem,
  39498. bool isMenuOpen,
  39499. bool isMouseOverBar,
  39500. MenuBarComponent& menuBar);
  39501. virtual void drawComboBox (Graphics& g, int width, int height,
  39502. const bool isButtonDown,
  39503. int buttonX, int buttonY,
  39504. int buttonW, int buttonH,
  39505. ComboBox& box);
  39506. virtual const Font getComboBoxFont (ComboBox& box);
  39507. virtual Label* createComboBoxTextBox (ComboBox& box);
  39508. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  39509. virtual void drawLabel (Graphics& g, Label& label);
  39510. virtual void drawLinearSlider (Graphics& g,
  39511. int x, int y,
  39512. int width, int height,
  39513. float sliderPos,
  39514. float minSliderPos,
  39515. float maxSliderPos,
  39516. const Slider::SliderStyle style,
  39517. Slider& slider);
  39518. virtual void drawLinearSliderBackground (Graphics& g,
  39519. int x, int y,
  39520. int width, int height,
  39521. float sliderPos,
  39522. float minSliderPos,
  39523. float maxSliderPos,
  39524. const Slider::SliderStyle style,
  39525. Slider& slider);
  39526. virtual void drawLinearSliderThumb (Graphics& g,
  39527. int x, int y,
  39528. int width, int height,
  39529. float sliderPos,
  39530. float minSliderPos,
  39531. float maxSliderPos,
  39532. const Slider::SliderStyle style,
  39533. Slider& slider);
  39534. virtual int getSliderThumbRadius (Slider& slider);
  39535. virtual void drawRotarySlider (Graphics& g,
  39536. int x, int y,
  39537. int width, int height,
  39538. float sliderPosProportional,
  39539. const float rotaryStartAngle,
  39540. const float rotaryEndAngle,
  39541. Slider& slider);
  39542. virtual Button* createSliderButton (const bool isIncrement);
  39543. virtual Label* createSliderTextBox (Slider& slider);
  39544. virtual ImageEffectFilter* getSliderEffect();
  39545. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  39546. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  39547. virtual Button* createFilenameComponentBrowseButton (const String& text);
  39548. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  39549. ComboBox* filenameBox, Button* browseButton);
  39550. virtual void drawCornerResizer (Graphics& g,
  39551. int w, int h,
  39552. bool isMouseOver,
  39553. bool isMouseDragging);
  39554. virtual void drawResizableFrame (Graphics& g,
  39555. int w, int h,
  39556. const BorderSize& borders);
  39557. virtual void drawResizableWindowBorder (Graphics& g,
  39558. int w, int h,
  39559. const BorderSize& border,
  39560. ResizableWindow& window);
  39561. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  39562. Graphics& g, int w, int h,
  39563. int titleSpaceX, int titleSpaceW,
  39564. const Image* icon,
  39565. bool drawTitleTextOnLeft);
  39566. virtual Button* createDocumentWindowButton (int buttonType);
  39567. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39568. int titleBarX, int titleBarY,
  39569. int titleBarW, int titleBarH,
  39570. Button* minimiseButton,
  39571. Button* maximiseButton,
  39572. Button* closeButton,
  39573. bool positionTitleBarButtonsOnLeft);
  39574. virtual int getDefaultMenuBarHeight();
  39575. virtual DropShadower* createDropShadowerForComponent (Component* component);
  39576. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  39577. int w, int h,
  39578. bool isVerticalBar,
  39579. bool isMouseOver,
  39580. bool isMouseDragging);
  39581. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  39582. const String& text,
  39583. const Justification& position,
  39584. GroupComponent& group);
  39585. virtual void createTabButtonShape (Path& p,
  39586. int width, int height,
  39587. int tabIndex,
  39588. const String& text,
  39589. Button& button,
  39590. TabbedButtonBar::Orientation orientation,
  39591. const bool isMouseOver,
  39592. const bool isMouseDown,
  39593. const bool isFrontTab);
  39594. virtual void fillTabButtonShape (Graphics& g,
  39595. const Path& path,
  39596. const Colour& preferredBackgroundColour,
  39597. int tabIndex,
  39598. const String& text,
  39599. Button& button,
  39600. TabbedButtonBar::Orientation orientation,
  39601. const bool isMouseOver,
  39602. const bool isMouseDown,
  39603. const bool isFrontTab);
  39604. virtual void drawTabButtonText (Graphics& g,
  39605. int x, int y, int w, int h,
  39606. const Colour& preferredBackgroundColour,
  39607. int tabIndex,
  39608. const String& text,
  39609. Button& button,
  39610. TabbedButtonBar::Orientation orientation,
  39611. const bool isMouseOver,
  39612. const bool isMouseDown,
  39613. const bool isFrontTab);
  39614. virtual int getTabButtonOverlap (int tabDepth);
  39615. virtual int getTabButtonSpaceAroundImage();
  39616. virtual int getTabButtonBestWidth (int tabIndex,
  39617. const String& text,
  39618. int tabDepth,
  39619. Button& button);
  39620. virtual void drawTabButton (Graphics& g,
  39621. int w, int h,
  39622. const Colour& preferredColour,
  39623. int tabIndex,
  39624. const String& text,
  39625. Button& button,
  39626. TabbedButtonBar::Orientation orientation,
  39627. const bool isMouseOver,
  39628. const bool isMouseDown,
  39629. const bool isFrontTab);
  39630. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  39631. int w, int h,
  39632. TabbedButtonBar& tabBar,
  39633. TabbedButtonBar::Orientation orientation);
  39634. virtual Button* createTabBarExtrasButton();
  39635. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  39636. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  39637. int width, int height,
  39638. bool isMouseOver, bool isMouseDown,
  39639. int columnFlags);
  39640. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  39641. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  39642. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  39643. bool isMouseOver, bool isMouseDown,
  39644. ToolbarItemComponent& component);
  39645. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  39646. const String& text, ToolbarItemComponent& component);
  39647. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  39648. bool isOpen, int width, int height);
  39649. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  39650. PropertyComponent& component);
  39651. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  39652. PropertyComponent& component);
  39653. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  39654. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  39655. /**
  39656. */
  39657. virtual void playAlertSound();
  39658. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  39659. static void drawGlassSphere (Graphics& g,
  39660. const float x, const float y,
  39661. const float diameter,
  39662. const Colour& colour,
  39663. const float outlineThickness) throw();
  39664. static void drawGlassPointer (Graphics& g,
  39665. const float x, const float y,
  39666. const float diameter,
  39667. const Colour& colour, const float outlineThickness,
  39668. const int direction) throw();
  39669. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  39670. static void drawGlassLozenge (Graphics& g,
  39671. const float x, const float y,
  39672. const float width, const float height,
  39673. const Colour& colour,
  39674. const float outlineThickness,
  39675. const float cornerSize,
  39676. const bool flatOnLeft, const bool flatOnRight,
  39677. const bool flatOnTop, const bool flatOnBottom) throw();
  39678. juce_UseDebuggingNewOperator
  39679. protected:
  39680. // xxx the following methods are only here to cause a compiler error, because they've been
  39681. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  39682. // error if you try to build a subclass with the old versions.
  39683. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  39684. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  39685. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  39686. virtual void getTabButtonBestWidth (int, const String&, int) {}
  39687. private:
  39688. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  39689. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  39690. Array <int> colourIds;
  39691. Array <Colour> colours;
  39692. void drawShinyButtonShape (Graphics& g,
  39693. float x, float y, float w, float h, float maxCornerSize,
  39694. const Colour& baseColour,
  39695. const float strokeWidth,
  39696. const bool flatOnLeft,
  39697. const bool flatOnRight,
  39698. const bool flatOnTop,
  39699. const bool flatOnBottom) throw();
  39700. LookAndFeel (const LookAndFeel&);
  39701. const LookAndFeel& operator= (const LookAndFeel&);
  39702. };
  39703. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  39704. /********* End of inlined file: juce_LookAndFeel.h *********/
  39705. #endif
  39706. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39707. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39708. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39709. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39710. /**
  39711. The original Juce look-and-feel.
  39712. */
  39713. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  39714. {
  39715. public:
  39716. /** Creates the default JUCE look and feel. */
  39717. OldSchoolLookAndFeel();
  39718. /** Destructor. */
  39719. virtual ~OldSchoolLookAndFeel();
  39720. /** Draws the lozenge-shaped background for a standard button. */
  39721. virtual void drawButtonBackground (Graphics& g,
  39722. Button& button,
  39723. const Colour& backgroundColour,
  39724. bool isMouseOverButton,
  39725. bool isButtonDown);
  39726. /** Draws the contents of a standard ToggleButton. */
  39727. virtual void drawToggleButton (Graphics& g,
  39728. ToggleButton& button,
  39729. bool isMouseOverButton,
  39730. bool isButtonDown);
  39731. virtual void drawTickBox (Graphics& g,
  39732. Component& component,
  39733. int x, int y, int w, int h,
  39734. const bool ticked,
  39735. const bool isEnabled,
  39736. const bool isMouseOverButton,
  39737. const bool isButtonDown);
  39738. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39739. int width, int height,
  39740. double progress, const String& textToShow);
  39741. virtual void drawScrollbarButton (Graphics& g,
  39742. ScrollBar& scrollbar,
  39743. int width, int height,
  39744. int buttonDirection,
  39745. bool isScrollbarVertical,
  39746. bool isMouseOverButton,
  39747. bool isButtonDown);
  39748. virtual void drawScrollbar (Graphics& g,
  39749. ScrollBar& scrollbar,
  39750. int x, int y,
  39751. int width, int height,
  39752. bool isScrollbarVertical,
  39753. int thumbStartPosition,
  39754. int thumbSize,
  39755. bool isMouseOver,
  39756. bool isMouseDown);
  39757. virtual ImageEffectFilter* getScrollbarEffect();
  39758. virtual void drawTextEditorOutline (Graphics& g,
  39759. int width, int height,
  39760. TextEditor& textEditor);
  39761. /** Fills the background of a popup menu component. */
  39762. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39763. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39764. bool isMouseOverBar,
  39765. MenuBarComponent& menuBar);
  39766. virtual void drawComboBox (Graphics& g, int width, int height,
  39767. const bool isButtonDown,
  39768. int buttonX, int buttonY,
  39769. int buttonW, int buttonH,
  39770. ComboBox& box);
  39771. virtual const Font getComboBoxFont (ComboBox& box);
  39772. virtual void drawLinearSlider (Graphics& g,
  39773. int x, int y,
  39774. int width, int height,
  39775. float sliderPos,
  39776. float minSliderPos,
  39777. float maxSliderPos,
  39778. const Slider::SliderStyle style,
  39779. Slider& slider);
  39780. virtual int getSliderThumbRadius (Slider& slider);
  39781. virtual Button* createSliderButton (const bool isIncrement);
  39782. virtual ImageEffectFilter* getSliderEffect();
  39783. virtual void drawCornerResizer (Graphics& g,
  39784. int w, int h,
  39785. bool isMouseOver,
  39786. bool isMouseDragging);
  39787. virtual Button* createDocumentWindowButton (int buttonType);
  39788. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39789. int titleBarX, int titleBarY,
  39790. int titleBarW, int titleBarH,
  39791. Button* minimiseButton,
  39792. Button* maximiseButton,
  39793. Button* closeButton,
  39794. bool positionTitleBarButtonsOnLeft);
  39795. juce_UseDebuggingNewOperator
  39796. private:
  39797. DropShadowEffect scrollbarShadow;
  39798. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  39799. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  39800. };
  39801. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39802. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39803. #endif
  39804. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39805. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  39806. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39807. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39808. /**
  39809. A class to take care of the logic involved with the loading/saving of some kind
  39810. of document.
  39811. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  39812. functions you need for documents that get saved to a file, so this class attempts
  39813. to abstract most of the boring stuff.
  39814. Your subclass should just implement all the pure virtual methods, and you can
  39815. then use the higher-level public methods to do the load/save dialogs, to warn the user
  39816. about overwriting files, etc.
  39817. The document object keeps track of whether it has changed since it was last saved or
  39818. loaded, so when you change something, call its changed() method. This will set a
  39819. flag so it knows it needs saving, and will also broadcast a change message using the
  39820. ChangeBroadcaster base class.
  39821. @see ChangeBroadcaster
  39822. */
  39823. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  39824. {
  39825. public:
  39826. /** Creates a FileBasedDocument.
  39827. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  39828. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  39829. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  39830. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  39831. */
  39832. FileBasedDocument (const String& fileExtension,
  39833. const String& fileWildCard,
  39834. const String& openFileDialogTitle,
  39835. const String& saveFileDialogTitle);
  39836. /** Destructor. */
  39837. virtual ~FileBasedDocument();
  39838. /** Returns true if the changed() method has been called since the file was
  39839. last saved or loaded.
  39840. @see resetChangedFlag, changed
  39841. */
  39842. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  39843. /** Called to indicate that the document has changed and needs saving.
  39844. This method will also trigger a change message to be sent out using the
  39845. ChangeBroadcaster base class.
  39846. After calling the method, the hasChangedSinceSaved() method will return true, until
  39847. it is reset either by saving to a file or using the resetChangedFlag() method.
  39848. @see hasChangedSinceSaved, resetChangedFlag
  39849. */
  39850. virtual void changed();
  39851. /** Sets the state of the 'changed' flag.
  39852. The 'changed' flag is set to true when the changed() method is called - use this method
  39853. to reset it or to set it without also broadcasting a change message.
  39854. @see changed, hasChangedSinceSaved
  39855. */
  39856. void setChangedFlag (const bool hasChanged);
  39857. /** Tries to open a file.
  39858. If the file opens correctly, the document's file (see the getFile() method) is set
  39859. to this new one; if it fails, the document's file is left unchanged, and optionally
  39860. a message box is shown telling the user there was an error.
  39861. @returns true if the new file loaded successfully
  39862. @see loadDocument, loadFromUserSpecifiedFile
  39863. */
  39864. bool loadFrom (const File& fileToLoadFrom,
  39865. const bool showMessageOnFailure);
  39866. /** Asks the user for a file and tries to load it.
  39867. This will pop up a dialog box using the title, file extension and
  39868. wildcard specified in the document's constructor, and asks the user
  39869. for a file. If they pick one, the loadFrom() method is used to
  39870. try to load it, optionally showing a message if it fails.
  39871. @returns true if a file was loaded; false if the user cancelled or if they
  39872. picked a file which failed to load correctly
  39873. @see loadFrom
  39874. */
  39875. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  39876. /** A set of possible outcomes of one of the save() methods
  39877. */
  39878. enum SaveResult
  39879. {
  39880. savedOk = 0, /**< indicates that a file was saved successfully. */
  39881. userCancelledSave, /**< indicates that the user aborted the save operation. */
  39882. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  39883. };
  39884. /** Tries to save the document to the last file it was saved or loaded from.
  39885. This will always try to write to the file, even if the document isn't flagged as
  39886. having changed.
  39887. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  39888. true, it will prompt the user to pick a file, as if
  39889. saveAsInteractive() was called.
  39890. @param showMessageOnFailure if true it will show a warning message when if the
  39891. save operation fails
  39892. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  39893. */
  39894. SaveResult save (const bool askUserForFileIfNotSpecified,
  39895. const bool showMessageOnFailure);
  39896. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  39897. it if they say yes.
  39898. If you've got a document open and want to close it (e.g. to quit the app), this is the
  39899. method to call.
  39900. If the document doesn't need saving it'll return the value savedOk so
  39901. you can go ahead and delete the document.
  39902. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  39903. return savedOk, so again, you can safely delete the document.
  39904. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  39905. close-document operation.
  39906. And if they click "save changes", it'll try to save and either return savedOk, or
  39907. failedToWriteToFile if there was a problem.
  39908. @see save, saveAs, saveAsInteractive
  39909. */
  39910. SaveResult saveIfNeededAndUserAgrees();
  39911. /** Tries to save the document to a specified file.
  39912. If this succeeds, it'll also change the document's internal file (as returned by
  39913. the getFile() method). If it fails, the file will be left unchanged.
  39914. @param newFile the file to try to write to
  39915. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39916. the user first if they want to overwrite it
  39917. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  39918. use the saveAsInteractive() method to ask the user for a
  39919. filename
  39920. @param showMessageOnFailure if true and the write operation fails, it'll show
  39921. a message box to warn the user
  39922. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  39923. */
  39924. SaveResult saveAs (const File& newFile,
  39925. const bool warnAboutOverwritingExistingFiles,
  39926. const bool askUserForFileIfNotSpecified,
  39927. const bool showMessageOnFailure);
  39928. /** Prompts the user for a filename and tries to save to it.
  39929. This will pop up a dialog box using the title, file extension and
  39930. wildcard specified in the document's constructor, and asks the user
  39931. for a file. If they pick one, the saveAs() method is used to try to save
  39932. to this file.
  39933. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39934. the user first if they want to overwrite it
  39935. @see saveIfNeededAndUserAgrees, save, saveAs
  39936. */
  39937. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  39938. /** Returns the file that this document was last successfully saved or loaded from.
  39939. When the document object is created, this will be set to File::nonexistent.
  39940. It is changed when one of the load or save methods is used, or when setFile()
  39941. is used to explicitly set it.
  39942. */
  39943. const File getFile() const throw() { return documentFile; }
  39944. /** Sets the file that this document thinks it was loaded from.
  39945. This won't actually load anything - it just changes the file stored internally.
  39946. @see getFile
  39947. */
  39948. void setFile (const File& newFile);
  39949. protected:
  39950. /** Overload this to return the title of the document.
  39951. This is used in message boxes, filenames and file choosers, so it should be
  39952. something sensible.
  39953. */
  39954. virtual const String getDocumentTitle() = 0;
  39955. /** This method should try to load your document from the given file.
  39956. If it fails, it should return an error message. If it succeeds, it should return
  39957. an empty string.
  39958. */
  39959. virtual const String loadDocument (const File& file) = 0;
  39960. /** This method should try to write your document to the given file.
  39961. If it fails, it should return an error message. If it succeeds, it should return
  39962. an empty string.
  39963. */
  39964. virtual const String saveDocument (const File& file) = 0;
  39965. /** This is used for dialog boxes to make them open at the last folder you
  39966. were using.
  39967. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39968. the last document that was used - you might want to store this value
  39969. in a static variable, or even in your application's properties. It should
  39970. be a global setting rather than a property of this object.
  39971. This method works very well in conjunction with a RecentlyOpenedFilesList
  39972. object to manage your recent-files list.
  39973. As a default value, it's ok to return File::nonexistent, and the document
  39974. object will use a sensible one instead.
  39975. @see RecentlyOpenedFilesList
  39976. */
  39977. virtual const File getLastDocumentOpened() = 0;
  39978. /** This is used for dialog boxes to make them open at the last folder you
  39979. were using.
  39980. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39981. the last document that was used - you might want to store this value
  39982. in a static variable, or even in your application's properties. It should
  39983. be a global setting rather than a property of this object.
  39984. This method works very well in conjunction with a RecentlyOpenedFilesList
  39985. object to manage your recent-files list.
  39986. @see RecentlyOpenedFilesList
  39987. */
  39988. virtual void setLastDocumentOpened (const File& file) = 0;
  39989. public:
  39990. juce_UseDebuggingNewOperator
  39991. private:
  39992. File documentFile;
  39993. bool changedSinceSave;
  39994. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  39995. FileBasedDocument (const FileBasedDocument&);
  39996. const FileBasedDocument& operator= (const FileBasedDocument&);
  39997. };
  39998. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39999. /********* End of inlined file: juce_FileBasedDocument.h *********/
  40000. #endif
  40001. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40002. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40003. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40004. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40005. /**
  40006. Manages a set of files for use as a list of recently-opened documents.
  40007. This is a handy class for holding your list of recently-opened documents, with
  40008. helpful methods for things like purging any non-existent files, automatically
  40009. adding them to a menu, and making persistence easy.
  40010. @see File, FileBasedDocument
  40011. */
  40012. class JUCE_API RecentlyOpenedFilesList
  40013. {
  40014. public:
  40015. /** Creates an empty list.
  40016. */
  40017. RecentlyOpenedFilesList();
  40018. /** Destructor. */
  40019. ~RecentlyOpenedFilesList();
  40020. /** Sets a limit for the number of files that will be stored in the list.
  40021. When addFile() is called, then if there is no more space in the list, the
  40022. least-recently added file will be dropped.
  40023. @see getMaxNumberOfItems
  40024. */
  40025. void setMaxNumberOfItems (const int newMaxNumber);
  40026. /** Returns the number of items that this list will store.
  40027. @see setMaxNumberOfItems
  40028. */
  40029. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  40030. /** Returns the number of files in the list.
  40031. The most recently added file is always at index 0.
  40032. */
  40033. int getNumFiles() const;
  40034. /** Returns one of the files in the list.
  40035. The most recently added file is always at index 0.
  40036. */
  40037. const File getFile (const int index) const;
  40038. /** Returns an array of all the absolute pathnames in the list.
  40039. */
  40040. const StringArray& getAllFilenames() const throw() { return files; }
  40041. /** Clears all the files from the list. */
  40042. void clear();
  40043. /** Adds a file to the list.
  40044. The file will be added at index 0. If this file is already in the list, it will
  40045. be moved up to index 0, but a file can only appear once in the list.
  40046. If the list already contains the maximum number of items that is permitted, the
  40047. least-recently added file will be dropped from the end.
  40048. */
  40049. void addFile (const File& file);
  40050. /** Checks each of the files in the list, removing any that don't exist.
  40051. You might want to call this after reloading a list of files, or before putting them
  40052. on a menu.
  40053. */
  40054. void removeNonExistentFiles();
  40055. /** Adds entries to a menu, representing each of the files in the list.
  40056. This is handy for creating an "open recent file..." menu in your app. The
  40057. menu items are numbered consecutively starting with the baseItemId value,
  40058. and can either be added as complete pathnames, or just the last part of the
  40059. filename.
  40060. If dontAddNonExistentFiles is true, then each file will be checked and only those
  40061. that exist will be added.
  40062. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  40063. pointers to file objects. Any files that appear in this list will not be added to the
  40064. menu - the reason for this is that you might have a number of files already open, so
  40065. might not want these to be shown in the menu.
  40066. It returns the number of items that were added.
  40067. */
  40068. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  40069. const int baseItemId,
  40070. const bool showFullPaths,
  40071. const bool dontAddNonExistentFiles,
  40072. const File** filesToAvoid = 0);
  40073. /** Returns a string that encapsulates all the files in the list.
  40074. The string that is returned can later be passed into restoreFromString() in
  40075. order to recreate the list. This is handy for persisting your list, e.g. in
  40076. a PropertiesFile object.
  40077. @see restoreFromString
  40078. */
  40079. const String toString() const;
  40080. /** Restores the list from a previously stringified version of the list.
  40081. Pass in a stringified version created with toString() in order to persist/restore
  40082. your list.
  40083. @see toString
  40084. */
  40085. void restoreFromString (const String& stringifiedVersion);
  40086. juce_UseDebuggingNewOperator
  40087. private:
  40088. StringArray files;
  40089. int maxNumberOfItems;
  40090. };
  40091. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40092. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40093. #endif
  40094. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40095. #endif
  40096. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  40097. #endif
  40098. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40099. #endif
  40100. #endif
  40101. /********* End of inlined file: juce_app_includes.h *********/
  40102. #endif
  40103. #if JUCE_MSVC
  40104. #pragma warning (pop)
  40105. #pragma pack (pop)
  40106. #endif
  40107. #if JUCE_MAC
  40108. #pragma align=reset
  40109. #endif
  40110. END_JUCE_NAMESPACE
  40111. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40112. #ifdef JUCE_NAMESPACE
  40113. // this will obviously save a lot of typing, but can be disabled by
  40114. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40115. using namespace JUCE_NAMESPACE;
  40116. /* On the Mac, these symbols are defined in the Mac libraries, so
  40117. these macros make it easier to reference them without writing out
  40118. the namespace every time.
  40119. If you run into difficulties where these macros interfere with the contents
  40120. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40121. the comments in that file for more information.
  40122. */
  40123. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40124. #define Component JUCE_NAMESPACE::Component
  40125. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40126. #define Point JUCE_NAMESPACE::Point
  40127. #define Button JUCE_NAMESPACE::Button
  40128. #endif
  40129. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40130. it easier to use the juce version explicitly.
  40131. If you run into difficulties where this macro interferes with other 3rd party header
  40132. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40133. file for more information.
  40134. */
  40135. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40136. #define Rectangle JUCE_NAMESPACE::Rectangle
  40137. #endif
  40138. #endif
  40139. #endif
  40140. /* Easy autolinking to the right JUCE libraries under win32.
  40141. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40142. including this header file.
  40143. */
  40144. #if JUCE_MSVC
  40145. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40146. /** If you want your application to link to Juce as a DLL instead of
  40147. a static library (on win32), just define the JUCE_DLL macro before
  40148. including juce.h
  40149. */
  40150. #ifdef JUCE_DLL
  40151. #ifdef JUCE_DEBUG
  40152. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40153. #else
  40154. #define AUTOLINKEDLIB "JUCE.lib"
  40155. #endif
  40156. #else
  40157. #ifdef JUCE_DEBUG
  40158. #ifdef _WIN64
  40159. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40160. #else
  40161. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40162. #endif
  40163. #else
  40164. #ifdef _WIN64
  40165. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40166. #else
  40167. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40168. #endif
  40169. #endif
  40170. #endif
  40171. #pragma comment(lib, AUTOLINKEDLIB)
  40172. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40173. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40174. #endif
  40175. // Auto-link the other win32 libs that are needed by library calls..
  40176. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40177. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40178. // Auto-links to various win32 libs that are needed by library calls..
  40179. #pragma comment(lib, "kernel32.lib")
  40180. #pragma comment(lib, "user32.lib")
  40181. #pragma comment(lib, "shell32.lib")
  40182. #pragma comment(lib, "gdi32.lib")
  40183. #pragma comment(lib, "vfw32.lib")
  40184. #pragma comment(lib, "comdlg32.lib")
  40185. #pragma comment(lib, "winmm.lib")
  40186. #pragma comment(lib, "wininet.lib")
  40187. #pragma comment(lib, "ole32.lib")
  40188. #pragma comment(lib, "advapi32.lib")
  40189. #pragma comment(lib, "ws2_32.lib")
  40190. #pragma comment(lib, "comsupp.lib")
  40191. #if JUCE_OPENGL
  40192. #pragma comment(lib, "OpenGL32.Lib")
  40193. #pragma comment(lib, "GlU32.Lib")
  40194. #endif
  40195. #if JUCE_QUICKTIME
  40196. #pragma comment (lib, "QTMLClient.lib")
  40197. #endif
  40198. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40199. #endif
  40200. #endif
  40201. #endif
  40202. /*
  40203. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40204. AppSubClass is the name of a class derived from JUCEApplication.
  40205. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40206. */
  40207. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40208. #define START_JUCE_APPLICATION(AppClass) \
  40209. int main (int argc, char* argv[]) \
  40210. { \
  40211. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40212. }
  40213. #elif JUCE_WIN32
  40214. #ifdef _CONSOLE
  40215. #define START_JUCE_APPLICATION(AppClass) \
  40216. int main (int, char* argv[]) \
  40217. { \
  40218. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40219. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40220. }
  40221. #elif ! defined (_AFXDLL)
  40222. #ifdef _WINDOWS_
  40223. #define START_JUCE_APPLICATION(AppClass) \
  40224. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40225. { \
  40226. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40227. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40228. }
  40229. #else
  40230. #define START_JUCE_APPLICATION(AppClass) \
  40231. int __stdcall WinMain (int, int, const char*, int) \
  40232. { \
  40233. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40234. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40235. }
  40236. #endif
  40237. #endif
  40238. #endif
  40239. #endif // __JUCE_JUCEHEADER__
  40240. /********* End of inlined file: juce.h *********/
  40241. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__