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.

53591 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. /** Disabling this will avoid linking to any UI code. 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. (On mac and windows, this won't generally make much difference to the build).
  165. */
  166. #ifndef JUCE_BUILD_GUI_CLASSES
  167. #define JUCE_BUILD_GUI_CLASSES 1
  168. #endif
  169. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  170. */
  171. #ifndef JUCE_WEB_BROWSER
  172. #define JUCE_WEB_BROWSER 1
  173. #endif
  174. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  175. codebase - you might need to use this if you're linking to some of these libraries
  176. yourself.
  177. */
  178. #ifndef JUCE_INCLUDE_ZLIB_CODE
  179. #define JUCE_INCLUDE_ZLIB_CODE 1
  180. #endif
  181. #ifndef JUCE_INCLUDE_FLAC_CODE
  182. #define JUCE_INCLUDE_FLAC_CODE 1
  183. #endif
  184. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  185. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  186. #endif
  187. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  188. #define JUCE_INCLUDE_PNGLIB_CODE 1
  189. #endif
  190. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  191. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  192. #endif
  193. /** Enable this to add extra memory-leak info to the new and delete operators.
  194. (Currently, this only affects Windows builds in debug mode).
  195. */
  196. #ifndef JUCE_CHECK_MEMORY_LEAKS
  197. #define JUCE_CHECK_MEMORY_LEAKS 1
  198. #endif
  199. /** Enable this to turn on juce's internal catching of exceptions.
  200. Turning it off will avoid any exception catching. With it on, all exceptions
  201. are passed to the JUCEApplication::unhandledException() callback for logging.
  202. */
  203. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  205. #endif
  206. /** If this macro is set, the Juce String class will use unicode as its
  207. internal representation. If it isn't set, it'll use ANSI.
  208. */
  209. #ifndef JUCE_STRINGS_ARE_UNICODE
  210. #define JUCE_STRINGS_ARE_UNICODE 1
  211. #endif
  212. #endif
  213. /********* End of inlined file: juce_Config.h *********/
  214. #ifdef JUCE_NAMESPACE
  215. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  216. #define END_JUCE_NAMESPACE }
  217. #else
  218. #define BEGIN_JUCE_NAMESPACE
  219. #define END_JUCE_NAMESPACE
  220. #endif
  221. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  222. /********* Start of inlined file: juce_PlatformDefs.h *********/
  223. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  224. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  225. /* This file figures out which platform is being built, and defines some macros
  226. that the rest of the code can use for OS-specific compilation.
  227. Macros that will be set here are:
  228. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  229. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  230. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  231. - Either JUCE_INTEL or JUCE_PPC
  232. - Either JUCE_GCC or JUCE_MSVC
  233. On the Mac, it also defines MACOS_10_2_OR_EARLIER if the build is targeting OSX10.2,
  234. and MACOS_10_3_OR_EARLIER if it is targeting either 10.2 or 10.3
  235. It also includes a set of macros for debug console output and assertions.
  236. */
  237. #if (defined (_WIN32) || defined (_WIN64))
  238. #define JUCE_WIN32 1
  239. #else
  240. #ifdef LINUX
  241. #define JUCE_LINUX 1
  242. #else
  243. #define JUCE_MAC 1
  244. #endif
  245. #endif
  246. #if JUCE_WIN32
  247. #ifdef _MSC_VER
  248. #ifdef _WIN64
  249. #define JUCE_64BIT 1
  250. #else
  251. #define JUCE_32BIT 1
  252. #endif
  253. #endif
  254. #ifdef _DEBUG
  255. #define JUCE_DEBUG 1
  256. #endif
  257. /** If defined, this indicates that the processor is little-endian. */
  258. #define JUCE_LITTLE_ENDIAN 1
  259. #define JUCE_INTEL 1
  260. #endif
  261. #if JUCE_MAC
  262. #include <CoreServices/CoreServices.h>
  263. #ifndef NDEBUG
  264. #define JUCE_DEBUG 1
  265. #endif
  266. #ifdef __LITTLE_ENDIAN__
  267. #define JUCE_LITTLE_ENDIAN 1
  268. #else
  269. #define JUCE_BIG_ENDIAN 1
  270. #endif
  271. #if defined (__ppc__) || defined (__ppc64__)
  272. #define JUCE_PPC 1
  273. #else
  274. #define JUCE_INTEL 1
  275. #endif
  276. #ifdef __LP64__
  277. #define JUCE_64BIT 1
  278. #else
  279. #define JUCE_32BIT 1
  280. #endif
  281. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  282. #define MACOS_10_2_OR_EARLIER 1
  283. #endif
  284. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  285. #define MACOS_10_3_OR_EARLIER 1
  286. #endif
  287. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  288. #define MACOS_10_4_OR_EARLIER 1
  289. #endif
  290. #endif
  291. #if JUCE_LINUX
  292. #ifdef _DEBUG
  293. #define JUCE_DEBUG 1
  294. #endif
  295. // Allow override for big-endian Linux platforms
  296. #ifndef JUCE_BIG_ENDIAN
  297. #define JUCE_LITTLE_ENDIAN 1
  298. #endif
  299. #if defined (__LP64__) || defined (_LP64)
  300. #define JUCE_64BIT 1
  301. #else
  302. #define JUCE_32BIT 1
  303. #endif
  304. #define JUCE_INTEL 1
  305. #endif
  306. #ifdef JUCE_FORCE_DEBUG
  307. #undef JUCE_DEBUG
  308. #if JUCE_FORCE_DEBUG
  309. #define JUCE_DEBUG 1
  310. #endif
  311. #endif
  312. // Compiler type macros.
  313. #ifdef __GNUC__
  314. #define JUCE_GCC 1
  315. #elif defined (_MSC_VER)
  316. #define JUCE_MSVC 1
  317. #if _MSC_VER >= 1400
  318. #define JUCE_USE_INTRINSICS 1
  319. #endif
  320. #else
  321. #error unknown compiler
  322. #endif
  323. /** This macro defines the C calling convention used as the standard for Juce calls. */
  324. #if JUCE_MSVC
  325. #define JUCE_CALLTYPE __stdcall
  326. #else
  327. #define JUCE_CALLTYPE
  328. #endif
  329. // Debugging and assertion macros
  330. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  331. #if JUCE_LOG_ASSERTIONS
  332. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  333. #elif defined (JUCE_DEBUG)
  334. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  335. #else
  336. #define juce_LogCurrentAssertion
  337. #endif
  338. #ifdef JUCE_DEBUG
  339. // If debugging is enabled..
  340. /** Writes a string to the standard error stream.
  341. This is only compiled in a debug build.
  342. @see Logger::outputDebugString
  343. */
  344. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  345. /** Printf's a string to the standard error stream.
  346. This is only compiled in a debug build.
  347. @see Logger::outputDebugString
  348. */
  349. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  350. // Assertions..
  351. #if JUCE_WIN32 || DOXYGEN
  352. #if JUCE_USE_INTRINSICS
  353. #pragma intrinsic (__debugbreak)
  354. /** This will try to break the debugger if one is currently hosting this app.
  355. @see jassert()
  356. */
  357. #define juce_breakDebugger __debugbreak();
  358. #elif JUCE_GCC
  359. /** This will try to break the debugger if one is currently hosting this app.
  360. @see jassert()
  361. */
  362. #define juce_breakDebugger asm("int $3");
  363. #else
  364. /** This will try to break the debugger if one is currently hosting this app.
  365. @see jassert()
  366. */
  367. #define juce_breakDebugger { __asm int 3 }
  368. #endif
  369. #elif JUCE_MAC
  370. #define juce_breakDebugger Debugger();
  371. #elif JUCE_LINUX
  372. #define juce_breakDebugger kill (0, SIGTRAP);
  373. #endif
  374. /** This will always cause an assertion failure.
  375. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  376. in juce_Config.h).
  377. @see jassert()
  378. */
  379. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  380. /** Platform-independent assertion macro.
  381. This gets optimised out when not being built with debugging turned on.
  382. Be careful not to call any functions within its arguments that are vital to
  383. the behaviour of the program, because these won't get called in the release
  384. build.
  385. @see jassertfalse
  386. */
  387. #define jassert(expression) { if (! (expression)) jassertfalse }
  388. #else
  389. // If debugging is disabled, these dummy debug and assertion macros are used..
  390. #define DBG(dbgtext)
  391. #define DBG_PRINTF(dbgprintf)
  392. #define jassertfalse { juce_LogCurrentAssertion }
  393. #if JUCE_LOG_ASSERTIONS
  394. #define jassert(expression) { if (! (expression)) jassertfalse }
  395. #else
  396. #define jassert(a) { }
  397. #endif
  398. #endif
  399. #ifndef DOXYGEN
  400. template <bool b> struct JuceStaticAssert;
  401. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  402. #endif
  403. /** A compile-time assertion macro.
  404. If the expression parameter is false, the macro will cause a compile error.
  405. */
  406. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  407. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  408. #define JUCE_TRY try
  409. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  410. object so they can be logged by the application if it wants to.
  411. */
  412. #define JUCE_CATCH_EXCEPTION \
  413. catch (const std::exception& e) \
  414. { \
  415. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  416. } \
  417. catch (...) \
  418. { \
  419. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  420. }
  421. #define JUCE_CATCH_ALL catch (...) {}
  422. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  423. #else
  424. #define JUCE_TRY
  425. #define JUCE_CATCH_EXCEPTION
  426. #define JUCE_CATCH_ALL
  427. #define JUCE_CATCH_ALL_ASSERT
  428. #endif
  429. // Macros for inlining.
  430. #if JUCE_MSVC
  431. /** A platform-independent way of forcing an inline function.
  432. Use the syntax: @code
  433. forcedinline void myfunction (int x)
  434. @endcode
  435. */
  436. #ifdef JUCE_DEBUG
  437. #define forcedinline __forceinline
  438. #else
  439. #define forcedinline inline
  440. #endif
  441. /** A platform-independent way of stopping the compiler inlining a function.
  442. Use the syntax: @code
  443. juce_noinline void myfunction (int x)
  444. @endcode
  445. */
  446. #define juce_noinline
  447. #else
  448. /** A platform-independent way of forcing an inline function.
  449. Use the syntax: @code
  450. forcedinline void myfunction (int x)
  451. @endcode
  452. */
  453. #ifndef JUCE_DEBUG
  454. #define forcedinline inline __attribute__((always_inline))
  455. #else
  456. #define forcedinline inline
  457. #endif
  458. /** A platform-independent way of stopping the compiler inlining a function.
  459. Use the syntax: @code
  460. juce_noinline void myfunction (int x)
  461. @endcode
  462. */
  463. #define juce_noinline __attribute__((noinline))
  464. #endif
  465. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  466. /********* End of inlined file: juce_PlatformDefs.h *********/
  467. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  468. #if JUCE_MSVC
  469. #pragma warning (push)
  470. #pragma warning (disable: 4514 4245 4100)
  471. #endif
  472. #include <cstdlib>
  473. #include <cstdarg>
  474. #include <climits>
  475. #include <cmath>
  476. #include <cwchar>
  477. #include <stdexcept>
  478. #include <typeinfo>
  479. #include <cstring>
  480. #include <cstdio>
  481. #if JUCE_MAC || JUCE_LINUX
  482. #include <pthread.h>
  483. #endif
  484. #if JUCE_USE_INTRINSICS
  485. #include <intrin.h>
  486. #endif
  487. #if JUCE_MAC && ! MACOS_10_3_OR_EARLIER
  488. #include <libkern/OSAtomic.h>
  489. #endif
  490. #if JUCE_LINUX
  491. #include <signal.h>
  492. #endif
  493. #if JUCE_MSVC && JUCE_DEBUG
  494. #include <crtdbg.h>
  495. #endif
  496. #if JUCE_MSVC
  497. #pragma warning (pop)
  498. #endif
  499. // DLL building settings on Win32
  500. #if JUCE_MSVC
  501. #ifdef JUCE_DLL_BUILD
  502. #define JUCE_API __declspec (dllexport)
  503. #pragma warning (disable: 4251)
  504. #elif defined (JUCE_DLL)
  505. #define JUCE_API __declspec (dllimport)
  506. #pragma warning (disable: 4251)
  507. #endif
  508. #endif
  509. #ifndef JUCE_API
  510. /** This macro is added to all juce public class declarations. */
  511. #define JUCE_API
  512. #endif
  513. /** This macro is added to all juce public function declarations. */
  514. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  515. // Now include some basics that are needed by most of the Juce classes...
  516. BEGIN_JUCE_NAMESPACE
  517. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  518. #if JUCE_LOG_ASSERTIONS
  519. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  520. #endif
  521. /********* Start of inlined file: juce_Memory.h *********/
  522. #ifndef __JUCE_MEMORY_JUCEHEADER__
  523. #define __JUCE_MEMORY_JUCEHEADER__
  524. /*
  525. This file defines the various juce_malloc(), juce_free() macros that should be used in
  526. preference to the standard calls.
  527. */
  528. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  529. #ifndef JUCE_DLL
  530. // Win32 debug non-DLL versions..
  531. /** This should be used instead of calling malloc directly. */
  532. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  533. /** This should be used instead of calling calloc directly. */
  534. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  535. /** This should be used instead of calling realloc directly. */
  536. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  537. /** This should be used instead of calling free directly. */
  538. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  539. #else
  540. // Win32 debug DLL versions..
  541. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  542. // way all juce calls in the DLL and in the host API will all use the same allocator.
  543. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  544. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  545. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  546. extern JUCE_API void juce_DebugFree (void* const block);
  547. /** This should be used instead of calling malloc directly. */
  548. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  549. /** This should be used instead of calling calloc directly. */
  550. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  551. /** This should be used instead of calling realloc directly. */
  552. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  553. /** This should be used instead of calling free directly. */
  554. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  555. #endif
  556. #if ! defined (_AFXDLL)
  557. /** This macro can be added to classes to add extra debugging information to the memory
  558. allocated for them, so you can see the type of objects involved when there's a dump
  559. of leaked objects at program shutdown. (Only works on win32 at the moment).
  560. */
  561. #define juce_UseDebuggingNewOperator \
  562. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  563. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  564. static void operator delete (void* p) { juce_free (p); }
  565. #endif
  566. #elif defined (JUCE_DLL)
  567. // Win32 DLL (release) versions..
  568. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  569. // way all juce calls in the DLL and in the host API will all use the same allocator.
  570. extern JUCE_API void* juce_Malloc (const int size);
  571. extern JUCE_API void* juce_Calloc (const int size);
  572. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  573. extern JUCE_API void juce_Free (void* const block);
  574. /** This should be used instead of calling malloc directly. */
  575. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  576. /** This should be used instead of calling calloc directly. */
  577. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  578. /** This should be used instead of calling realloc directly. */
  579. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  580. /** This should be used instead of calling free directly. */
  581. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  582. #define juce_UseDebuggingNewOperator \
  583. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  584. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  585. static void operator delete (void* p) { juce_free (p); }
  586. #else
  587. // Mac, Linux and Win32 (release) versions..
  588. /** This should be used instead of calling malloc directly. */
  589. #define juce_malloc(numBytes) malloc (numBytes)
  590. /** This should be used instead of calling calloc directly. */
  591. #define juce_calloc(numBytes) calloc (1, numBytes)
  592. /** This should be used instead of calling realloc directly. */
  593. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  594. /** This should be used instead of calling free directly. */
  595. #define juce_free(location) free (location)
  596. #endif
  597. /** This macro can be added to classes to add extra debugging information to the memory
  598. allocated for them, so you can see the type of objects involved when there's a dump
  599. of leaked objects at program shutdown. (Only works on win32 at the moment).
  600. Note that if you create a class that inherits from a class that uses this macro,
  601. your class must also use the macro, otherwise you'll probably get compile errors
  602. because of ambiguous new operators.
  603. Most of the JUCE classes use it, so see these for examples of where it should go.
  604. */
  605. #ifndef juce_UseDebuggingNewOperator
  606. #define juce_UseDebuggingNewOperator
  607. #endif
  608. #if JUCE_MSVC
  609. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  610. E.g.
  611. @code
  612. juce_ThreadLocal int myVariable;
  613. @endcode
  614. */
  615. #define juce_ThreadLocal __declspec(thread)
  616. #else
  617. #define juce_ThreadLocal __thread
  618. #endif
  619. /** Clears a block of memory. */
  620. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  621. /** Clears a reference to a local structure. */
  622. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  623. /** A handy macro that calls delete on a pointer if it's non-zero, and
  624. then sets the pointer to null.
  625. */
  626. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  627. #endif // __JUCE_MEMORY_JUCEHEADER__
  628. /********* End of inlined file: juce_Memory.h *********/
  629. /********* Start of inlined file: juce_MathsFunctions.h *********/
  630. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  631. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  632. /*
  633. This file sets up some handy mathematical typdefs and functions.
  634. */
  635. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  636. /** A platform-independent 8-bit signed integer type. */
  637. typedef signed char int8;
  638. /** A platform-independent 8-bit unsigned integer type. */
  639. typedef unsigned char uint8;
  640. /** A platform-independent 16-bit signed integer type. */
  641. typedef signed short int16;
  642. /** A platform-independent 16-bit unsigned integer type. */
  643. typedef unsigned short uint16;
  644. /** A platform-independent 32-bit signed integer type. */
  645. typedef signed int int32;
  646. /** A platform-independent 32-bit unsigned integer type. */
  647. typedef unsigned int uint32;
  648. #if JUCE_MSVC
  649. /** A platform-independent 64-bit integer type. */
  650. typedef __int64 int64;
  651. /** A platform-independent 64-bit unsigned integer type. */
  652. typedef unsigned __int64 uint64;
  653. /** A platform-independent macro for writing 64-bit literals, needed because
  654. different compilers have different syntaxes for this.
  655. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  656. GCC, or 0x1000000000 for MSVC.
  657. */
  658. #define literal64bit(longLiteral) ((__int64) longLiteral)
  659. #else
  660. /** A platform-independent 64-bit integer type. */
  661. typedef long long int64;
  662. /** A platform-independent 64-bit unsigned integer type. */
  663. typedef unsigned long long uint64;
  664. /** A platform-independent macro for writing 64-bit literals, needed because
  665. different compilers have different syntaxes for this.
  666. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  667. GCC, or 0x1000000000 for MSVC.
  668. */
  669. #define literal64bit(longLiteral) (longLiteral##LL)
  670. #endif
  671. #if JUCE_64BIT
  672. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  673. typedef int64 pointer_sized_int;
  674. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  675. typedef uint64 pointer_sized_uint;
  676. #elif _MSC_VER >= 1300
  677. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  678. typedef _W64 int pointer_sized_int;
  679. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  680. typedef _W64 unsigned int pointer_sized_uint;
  681. #else
  682. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  683. typedef int pointer_sized_int;
  684. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  685. typedef unsigned int pointer_sized_uint;
  686. #endif
  687. /** A platform-independent unicode character type. */
  688. typedef wchar_t juce_wchar;
  689. // Some indispensible min/max functions
  690. /** Returns the larger of two values. */
  691. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  692. /** Returns the larger of two values. */
  693. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  694. /** Returns the larger of two values. */
  695. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  696. /** Returns the larger of two values. */
  697. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  698. /** Returns the larger of three values. */
  699. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  700. /** Returns the larger of three values. */
  701. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  702. /** Returns the larger of three values. */
  703. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  704. /** Returns the larger of three values. */
  705. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  706. /** Returns the larger of four values. */
  707. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  708. /** Returns the larger of four values. */
  709. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  710. /** Returns the larger of four values. */
  711. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  712. /** Returns the larger of four values. */
  713. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  714. /** Returns the smaller of two values. */
  715. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  716. /** Returns the smaller of two values. */
  717. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  718. /** Returns the smaller of two values. */
  719. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  720. /** Returns the smaller of two values. */
  721. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  722. /** Returns the smaller of three values. */
  723. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  724. /** Returns the smaller of three values. */
  725. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  726. /** Returns the smaller of three values. */
  727. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  728. /** Returns the smaller of three values. */
  729. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  730. /** Returns the smaller of four values. */
  731. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  732. /** Returns the smaller of four values. */
  733. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  734. /** Returns the smaller of four values. */
  735. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  736. /** Returns the smaller of four values. */
  737. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  738. /** Constrains a value to keep it within a given range.
  739. This will check that the specified value lies between the lower and upper bounds
  740. specified, and if not, will return the nearest value that would be in-range. Effectively,
  741. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  742. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  743. the results will be unpredictable.
  744. @param lowerLimit the minimum value to return
  745. @param upperLimit the maximum value to return
  746. @param valueToConstrain the value to try to return
  747. @returns the closest value to valueToConstrain which lies between lowerLimit
  748. and upperLimit (inclusive)
  749. @see jlimit0To, jmin, jmax
  750. */
  751. template <class Type>
  752. inline Type jlimit (const Type lowerLimit,
  753. const Type upperLimit,
  754. const Type valueToConstrain) throw()
  755. {
  756. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  757. return (valueToConstrain < lowerLimit) ? lowerLimit
  758. : ((valueToConstrain > upperLimit) ? upperLimit
  759. : valueToConstrain);
  760. }
  761. /** Handy function to swap two values over.
  762. */
  763. template <class Type>
  764. inline void swapVariables (Type& variable1, Type& variable2) throw()
  765. {
  766. const Type tempVal = variable1;
  767. variable1 = variable2;
  768. variable2 = tempVal;
  769. }
  770. /** Handy macro for getting the number of elements in a simple const C array.
  771. E.g.
  772. @code
  773. static int myArray[] = { 1, 2, 3 };
  774. int numElements = numElementsInArray (myArray) // returns 3
  775. @endcode
  776. */
  777. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  778. // Some useful maths functions that aren't always present with all compilers and build settings.
  779. #if JUCE_WIN32 || defined (DOXYGEN)
  780. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  781. versions of these functions of various platforms and compilers. */
  782. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  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 float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  786. #elif MACOS_10_2_OR_EARLIER
  787. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  788. versions of these functions of various platforms and compilers. */
  789. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  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 float juce_hypotf (float a, float b) { return (float) hypot (a, b); }
  793. forcedinline float sinf (const float a) { return (float) sin (a); }
  794. forcedinline float cosf (const float a) { return (float) cos (a); }
  795. forcedinline float tanf (const float a) { return (float) tan (a); }
  796. forcedinline float atan2f (const float a, const float b) { return (float) atan2 (a, b); }
  797. forcedinline float sqrtf (const float a) { return (float) sqrt (a); }
  798. forcedinline float logf (const float a) { return (float) log (a); }
  799. forcedinline float powf (const float a, const float b) { return (float) pow (a, b); }
  800. forcedinline float expf (const float a) { return (float) exp (a); }
  801. #else
  802. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  803. versions of these functions of various platforms and compilers. */
  804. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  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 float juce_hypotf (float a, float b) { return hypotf (a, b); }
  808. #endif
  809. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  810. /** A predefined value for Pi, at double-precision.
  811. @see float_Pi
  812. */
  813. const double double_Pi = 3.1415926535897932384626433832795;
  814. /** A predefined value for Pi, at sngle-precision.
  815. @see double_Pi
  816. */
  817. const float float_Pi = 3.14159265358979323846f;
  818. /** The isfinite() method seems to vary greatly between platforms, so this is a
  819. platform-independent macro for it.
  820. */
  821. #if JUCE_LINUX
  822. #define juce_isfinite(v) std::isfinite(v)
  823. #elif JUCE_MAC
  824. #if MACOS_10_2_OR_EARLIER
  825. #define juce_isfinite(v) __isfinite(v)
  826. #elif MACOS_10_3_OR_EARLIER
  827. #ifdef isfinite
  828. #define juce_isfinite(v) isfinite(v)
  829. #else
  830. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  831. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  832. #endif
  833. #else
  834. #define juce_isfinite(v) std::isfinite(v)
  835. #endif
  836. #elif JUCE_WIN32 && ! defined (isfinite)
  837. #define juce_isfinite(v) _finite(v)
  838. #else
  839. #define juce_isfinite(v) isfinite(v)
  840. #endif
  841. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  842. /********* End of inlined file: juce_MathsFunctions.h *********/
  843. /********* Start of inlined file: juce_DataConversions.h *********/
  844. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  845. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  846. #if JUCE_USE_INTRINSICS
  847. #pragma intrinsic (_byteswap_ulong)
  848. #endif
  849. // Endianness conversions..
  850. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  851. forcedinline uint32 swapByteOrder (uint32 n) throw()
  852. {
  853. #if JUCE_MAC
  854. // Mac version
  855. return CFSwapInt32 (n);
  856. #elif JUCE_GCC
  857. // Inpenetrable GCC version..
  858. asm("bswap %%eax" : "=a"(n) : "a"(n));
  859. return n;
  860. #elif JUCE_USE_INTRINSICS
  861. // Win32 intrinsics version..
  862. return _byteswap_ulong (n);
  863. #else
  864. // Win32 version..
  865. __asm {
  866. mov eax, n
  867. bswap eax
  868. mov n, eax
  869. }
  870. return n;
  871. #endif
  872. }
  873. /** Swaps the byte-order of a 16-bit short. */
  874. inline uint16 swapByteOrder (const uint16 n) throw()
  875. {
  876. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  877. // Win32 intrinsics version..
  878. return (uint16) _byteswap_ushort (n);
  879. #else
  880. return (uint16) ((n << 8) | (n >> 8));
  881. #endif
  882. }
  883. inline uint64 swapByteOrder (const uint64 value) throw()
  884. {
  885. #if JUCE_MAC
  886. return CFSwapInt64 (value);
  887. #elif JUCE_USE_INTRINSICS
  888. return _byteswap_uint64 (value);
  889. #else
  890. return (((int64) swapByteOrder ((uint32) value)) << 32)
  891. | swapByteOrder ((uint32) (value >> 32));
  892. #endif
  893. }
  894. #if JUCE_LITTLE_ENDIAN
  895. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  896. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  897. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  898. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  899. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  900. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  901. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  902. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  903. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  904. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  905. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  906. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  907. /** Turns 4 bytes into a little-endian integer. */
  908. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  909. /** Turns 2 bytes into a little-endian integer. */
  910. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  911. /** Turns 4 bytes into a big-endian integer. */
  912. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  913. /** Turns 2 bytes into a big-endian integer. */
  914. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  915. #else
  916. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  917. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  918. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  919. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  920. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  921. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  922. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  923. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  924. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  925. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  926. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  927. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  928. /** Turns 4 bytes into a little-endian integer. */
  929. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  930. /** Turns 2 bytes into a little-endian integer. */
  931. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  932. /** Turns 4 bytes into a big-endian integer. */
  933. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  934. /** Turns 2 bytes into a big-endian integer. */
  935. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  936. #endif
  937. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  938. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  939. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  940. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  941. /** Copies a 24-bit number to 3 little-endian bytes. */
  942. 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); }
  943. /** Copies a 24-bit number to 3 big-endian bytes. */
  944. 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); }
  945. /** Fast floating-point-to-integer conversion.
  946. This is faster than using the normal c++ cast to convert a double to an int, and
  947. it will round the value to the nearest integer, rather than rounding it down
  948. like the normal cast does.
  949. Note that this routine gets its speed at the expense of some accuracy, and when
  950. rounding values whose floating point component is exactly 0.5, odd numbers and
  951. even numbers will be rounded up or down differently. For a more accurate conversion,
  952. see roundDoubleToIntAccurate().
  953. */
  954. inline int roundDoubleToInt (const double value) throw()
  955. {
  956. union { int asInt[2]; double asDouble; } n;
  957. n.asDouble = value + 6755399441055744.0;
  958. #if JUCE_BIG_ENDIAN
  959. return n.asInt [1];
  960. #else
  961. return n.asInt [0];
  962. #endif
  963. }
  964. /** Fast floating-point-to-integer conversion.
  965. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  966. fine for values above zero, but negative numbers are rounded the wrong way.
  967. */
  968. inline int roundDoubleToIntAccurate (const double value) throw()
  969. {
  970. return roundDoubleToInt (value + 1.5e-8);
  971. }
  972. /** Fast floating-point-to-integer conversion.
  973. This is faster than using the normal c++ cast to convert a float to an int, and
  974. it will round the value to the nearest integer, rather than rounding it down
  975. like the normal cast does.
  976. Note that this routine gets its speed at the expense of some accuracy, and when
  977. rounding values whose floating point component is exactly 0.5, odd numbers and
  978. even numbers will be rounded up or down differently.
  979. */
  980. inline int roundFloatToInt (const float value) throw()
  981. {
  982. union { int asInt[2]; double asDouble; } n;
  983. n.asDouble = value + 6755399441055744.0;
  984. #if JUCE_BIG_ENDIAN
  985. return n.asInt [1];
  986. #else
  987. return n.asInt [0];
  988. #endif
  989. }
  990. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  991. /********* End of inlined file: juce_DataConversions.h *********/
  992. /********* Start of inlined file: juce_Logger.h *********/
  993. #ifndef __JUCE_LOGGER_JUCEHEADER__
  994. #define __JUCE_LOGGER_JUCEHEADER__
  995. /********* Start of inlined file: juce_String.h *********/
  996. #ifndef __JUCE_STRING_JUCEHEADER__
  997. #define __JUCE_STRING_JUCEHEADER__
  998. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  999. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1000. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1001. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1002. (in the default system encoding) as its internal representation.
  1003. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1004. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1005. literals in the T("abcd") macro, so that it all works nicely either way round.
  1006. */
  1007. #if JUCE_STRINGS_ARE_UNICODE
  1008. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1009. typedef juce_wchar tchar;
  1010. #define juce_tcharToWideChar(c) (c)
  1011. #else
  1012. #define JUCE_T(stringLiteral) (stringLiteral)
  1013. typedef char tchar;
  1014. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1015. #endif
  1016. #if ! JUCE_DONT_DEFINE_MACROS
  1017. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1018. or unicode.
  1019. If you write your string literals in the form T("xyz"), this will either be compiled
  1020. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1021. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1022. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1023. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1024. the juce/src directory) to avoid defining this macro. See the comments in
  1025. juce_withoutMacros.h for more info.
  1026. */
  1027. #define T(stringLiteral) JUCE_T(stringLiteral)
  1028. #endif
  1029. /**
  1030. A set of methods for manipulating characters and character strings, with
  1031. duplicate methods to handle 8-bit and unicode characters.
  1032. These are defined as wrappers around the basic C string handlers, to provide
  1033. a clean, cross-platform layer, (because various platforms differ in the
  1034. range of C library calls that they provide).
  1035. @see String
  1036. */
  1037. class JUCE_API CharacterFunctions
  1038. {
  1039. public:
  1040. static int length (const char* const s) throw();
  1041. static int length (const juce_wchar* const s) throw();
  1042. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1043. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1044. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1045. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1046. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1047. static void append (char* dest, const char* src) throw();
  1048. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1049. static int compare (const char* const s1, const char* const s2) throw();
  1050. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1051. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1052. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1053. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1054. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1055. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1056. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1057. static const char* find (const char* const haystack, const char* const needle) throw();
  1058. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1059. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1060. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1061. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1062. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1063. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1064. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1065. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1066. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1067. static int getIntValue (const char* const s) throw();
  1068. static int getIntValue (const juce_wchar* s) throw();
  1069. static int64 getInt64Value (const char* s) throw();
  1070. static int64 getInt64Value (const juce_wchar* s) throw();
  1071. static double getDoubleValue (const char* const s) throw();
  1072. static double getDoubleValue (const juce_wchar* const s) throw();
  1073. static char toUpperCase (const char character) throw();
  1074. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1075. static void toUpperCase (char* s) throw();
  1076. static void toUpperCase (juce_wchar* s) throw();
  1077. static bool isUpperCase (const char character) throw();
  1078. static bool isUpperCase (const juce_wchar character) throw();
  1079. static char toLowerCase (const char character) throw();
  1080. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1081. static void toLowerCase (char* s) throw();
  1082. static void toLowerCase (juce_wchar* s) throw();
  1083. static bool isLowerCase (const char character) throw();
  1084. static bool isLowerCase (const juce_wchar character) throw();
  1085. static bool isWhitespace (const char character) throw();
  1086. static bool isWhitespace (const juce_wchar character) throw();
  1087. static bool isDigit (const char character) throw();
  1088. static bool isDigit (const juce_wchar character) throw();
  1089. static bool isLetter (const char character) throw();
  1090. static bool isLetter (const juce_wchar character) throw();
  1091. static bool isLetterOrDigit (const char character) throw();
  1092. static bool isLetterOrDigit (const juce_wchar character) throw();
  1093. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1094. hex digit.
  1095. */
  1096. static int getHexDigitValue (const tchar digit) throw();
  1097. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1098. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1099. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1100. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1101. };
  1102. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1103. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1104. /**
  1105. The JUCE String class!
  1106. Using a reference-counted internal representation, these strings are fast
  1107. and efficient, and there are methods to do just about any operation you'll ever
  1108. dream of.
  1109. @see StringArray, StringPairArray
  1110. */
  1111. class JUCE_API String
  1112. {
  1113. public:
  1114. /** Creates an empty string.
  1115. @see empty
  1116. */
  1117. String() throw();
  1118. /** Creates a copy of another string. */
  1119. String (const String& other) throw();
  1120. /** Creates a string from a zero-terminated text string.
  1121. The string is assumed to be stored in the default system encoding.
  1122. */
  1123. String (const char* const text) throw();
  1124. /** Creates a string from an string of characters.
  1125. This will use up the the first maxChars characters of the string (or
  1126. less if the string is actually shorter)
  1127. */
  1128. String (const char* const text,
  1129. const int maxChars) throw();
  1130. /** Creates a string from a zero-terminated unicode text string. */
  1131. String (const juce_wchar* const unicodeText) throw();
  1132. /** Creates a string from a unicode text string.
  1133. This will use up the the first maxChars characters of the string (or
  1134. less if the string is actually shorter)
  1135. */
  1136. String (const juce_wchar* const unicodeText,
  1137. const int maxChars) throw();
  1138. /** Creates a string from a single character. */
  1139. static const String charToString (const tchar character) throw();
  1140. /** Destructor. */
  1141. ~String() throw();
  1142. /** This is an empty string that can be used whenever one is needed.
  1143. It's better to use this than String() because it explains what's going on
  1144. and is more efficient.
  1145. */
  1146. static const String empty;
  1147. /** Generates a probably-unique 32-bit hashcode from this string. */
  1148. int hashCode() const throw();
  1149. /** Generates a probably-unique 64-bit hashcode from this string. */
  1150. int64 hashCode64() const throw();
  1151. /** Returns the number of characters in the string. */
  1152. int length() const throw();
  1153. // Assignment and concatenation operators..
  1154. /** Replaces this string's contents with another string. */
  1155. const String& operator= (const tchar* const other) throw();
  1156. /** Replaces this string's contents with another string. */
  1157. const String& operator= (const String& other) throw();
  1158. /** Appends another string at the end of this one. */
  1159. const String& operator+= (const tchar* const textToAppend) throw();
  1160. /** Appends another string at the end of this one. */
  1161. const String& operator+= (const String& stringToAppend) throw();
  1162. /** Appends a character at the end of this string. */
  1163. const String& operator+= (const char characterToAppend) throw();
  1164. /** Appends a character at the end of this string. */
  1165. const String& operator+= (const juce_wchar characterToAppend) throw();
  1166. /** Appends a string at the end of this one.
  1167. @param textToAppend the string to add
  1168. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1169. */
  1170. void append (const tchar* const textToAppend,
  1171. const int maxCharsToTake) throw();
  1172. /** Appends a string at the end of this one.
  1173. @returns the concatenated string
  1174. */
  1175. const String operator+ (const String& stringToAppend) const throw();
  1176. /** Appends a string at the end of this one.
  1177. @returns the concatenated string
  1178. */
  1179. const String operator+ (const tchar* const textToAppend) const throw();
  1180. /** Appends a character at the end of this one.
  1181. @returns the concatenated string
  1182. */
  1183. const String operator+ (const tchar characterToAppend) const throw();
  1184. /** Appends a character at the end of this string. */
  1185. String& operator<< (const char n) throw();
  1186. /** Appends a character at the end of this string. */
  1187. String& operator<< (const juce_wchar n) throw();
  1188. /** Appends another string at the end of this one. */
  1189. String& operator<< (const char* const text) throw();
  1190. /** Appends another string at the end of this one. */
  1191. String& operator<< (const juce_wchar* const text) throw();
  1192. /** Appends another string at the end of this one. */
  1193. String& operator<< (const String& text) throw();
  1194. /** Appends a decimal number at the end of this string. */
  1195. String& operator<< (const short number) throw();
  1196. /** Appends a decimal number at the end of this string. */
  1197. String& operator<< (const int number) throw();
  1198. /** Appends a decimal number at the end of this string. */
  1199. String& operator<< (const unsigned int number) throw();
  1200. /** Appends a decimal number at the end of this string. */
  1201. String& operator<< (const float number) throw();
  1202. /** Appends a decimal number at the end of this string. */
  1203. String& operator<< (const double number) throw();
  1204. // Comparison methods..
  1205. /** Returns true if the string contains no characters.
  1206. Note that there's also an isNotEmpty() method to help write readable code.
  1207. */
  1208. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1209. /** Returns true if the string contains at least one character.
  1210. Note that there's also an isEmpty() method to help write readable code.
  1211. */
  1212. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1213. /** Case-sensitive comparison with another string. */
  1214. bool operator== (const String& other) const throw();
  1215. /** Case-sensitive comparison with another string. */
  1216. bool operator== (const tchar* const other) const throw();
  1217. /** Case-sensitive comparison with another string. */
  1218. bool operator!= (const String& other) const throw();
  1219. /** Case-sensitive comparison with another string. */
  1220. bool operator!= (const tchar* const other) const throw();
  1221. /** Case-insensitive comparison with another string. */
  1222. bool equalsIgnoreCase (const String& other) const throw();
  1223. /** Case-insensitive comparison with another string. */
  1224. bool equalsIgnoreCase (const tchar* const other) const throw();
  1225. /** Case-sensitive comparison with another string. */
  1226. bool operator> (const String& other) const throw();
  1227. /** Case-sensitive comparison with another string. */
  1228. bool operator< (const tchar* const other) const throw();
  1229. /** Case-sensitive comparison with another string. */
  1230. bool operator>= (const String& other) const throw();
  1231. /** Case-sensitive comparison with another string. */
  1232. bool operator<= (const tchar* const other) const throw();
  1233. /** Case-sensitive comparison with another string.
  1234. @returns 0 if the two strings are identical; negative if this string
  1235. comes before the other one alphabetically, or positive if it
  1236. comes after it.
  1237. */
  1238. int compare (const tchar* const other) const throw();
  1239. /** Case-insensitive comparison with another string.
  1240. @returns 0 if the two strings are identical; negative if this string
  1241. comes before the other one alphabetically, or positive if it
  1242. comes after it.
  1243. */
  1244. int compareIgnoreCase (const tchar* const other) const throw();
  1245. /** Lexicographic comparison with another string.
  1246. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1247. characters, making it good for sorting human-readable strings.
  1248. @returns 0 if the two strings are identical; negative if this string
  1249. comes before the other one alphabetically, or positive if it
  1250. comes after it.
  1251. */
  1252. int compareLexicographically (const tchar* const other) const throw();
  1253. /** Tests whether the string begins with another string.
  1254. Uses a case-sensitive comparison.
  1255. */
  1256. bool startsWith (const tchar* const text) const throw();
  1257. /** Tests whether the string begins with a particular character.
  1258. Uses a case-sensitive comparison.
  1259. */
  1260. bool startsWithChar (const tchar character) const throw();
  1261. /** Tests whether the string begins with another string.
  1262. Uses a case-insensitive comparison.
  1263. */
  1264. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1265. /** Tests whether the string ends with another string.
  1266. Uses a case-sensitive comparison.
  1267. */
  1268. bool endsWith (const tchar* const text) const throw();
  1269. /** Tests whether the string ends with a particular character.
  1270. Uses a case-sensitive comparison.
  1271. */
  1272. bool endsWithChar (const tchar character) const throw();
  1273. /** Tests whether the string ends with another string.
  1274. Uses a case-insensitive comparison.
  1275. */
  1276. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1277. /** Tests whether the string contains another substring.
  1278. Uses a case-sensitive comparison.
  1279. */
  1280. bool contains (const tchar* const text) const throw();
  1281. /** Tests whether the string contains a particular character.
  1282. Uses a case-sensitive comparison.
  1283. */
  1284. bool containsChar (const tchar character) const throw();
  1285. /** Tests whether the string contains another substring.
  1286. Uses a case-insensitive comparison.
  1287. */
  1288. bool containsIgnoreCase (const tchar* const text) const throw();
  1289. /** Tests whether the string contains another substring as a distict word.
  1290. @returns true if the string contains this word, surrounded by
  1291. non-alphanumeric characters
  1292. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1293. */
  1294. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1295. /** Tests whether the string contains another substring as a distict word.
  1296. @returns true if the string contains this word, surrounded by
  1297. non-alphanumeric characters
  1298. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1299. */
  1300. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1301. /** Finds an instance of another substring if it exists as a distict word.
  1302. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1303. then this will return the index of the start of the substring. If it isn't
  1304. found, then it will return -1
  1305. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1306. */
  1307. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1308. /** Finds an instance of another substring if it exists as a distict word.
  1309. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1310. then this will return the index of the start of the substring. If it isn't
  1311. found, then it will return -1
  1312. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1313. */
  1314. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1315. /** Looks for any of a set of characters in the string.
  1316. Uses a case-sensitive comparison.
  1317. @returns true if the string contains any of the characters from
  1318. the string that is passed in.
  1319. */
  1320. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1321. /** Looks for a set of characters in the string.
  1322. Uses a case-sensitive comparison.
  1323. @returns true if the all the characters in the string are also found in the
  1324. string that is passed in.
  1325. */
  1326. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1327. /** Returns true if the string matches this simple wildcard expression.
  1328. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1329. This isn't a full-blown regex though! The only wildcard characters supported
  1330. are "*" and "?". It's mainly intended for filename pattern matching.
  1331. */
  1332. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1333. // Substring location methods..
  1334. /** Searches for a character inside this string.
  1335. Uses a case-sensitive comparison.
  1336. @returns the index of the first occurrence of the character in this
  1337. string, or -1 if it's not found.
  1338. */
  1339. int indexOfChar (const tchar characterToLookFor) const throw();
  1340. /** Searches for a character inside this string.
  1341. Uses a case-sensitive comparison.
  1342. @param startIndex the index from which the search should proceed
  1343. @param characterToLookFor the character to look for
  1344. @returns the index of the first occurrence of the character in this
  1345. string, or -1 if it's not found.
  1346. */
  1347. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1348. /** Returns the index of the first character that matches one of the characters
  1349. passed-in to this method.
  1350. This scans the string, beginning from the startIndex supplied, and if it finds
  1351. a character that appears in the string charactersToLookFor, it returns its index.
  1352. If none of these characters are found, it returns -1.
  1353. If ignoreCase is true, the comparison will be case-insensitive.
  1354. @see indexOfChar, lastIndexOfAnyOf
  1355. */
  1356. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1357. const int startIndex = 0,
  1358. const bool ignoreCase = false) const throw();
  1359. /** Searches for a substring within this string.
  1360. Uses a case-sensitive comparison.
  1361. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1362. */
  1363. int indexOf (const tchar* const text) const throw();
  1364. /** Searches for a substring within this string.
  1365. Uses a case-sensitive comparison.
  1366. @param startIndex the index from which the search should proceed
  1367. @param textToLookFor the string to search for
  1368. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1369. */
  1370. int indexOf (const int startIndex,
  1371. const tchar* const textToLookFor) const throw();
  1372. /** Searches for a substring within this string.
  1373. Uses a case-insensitive comparison.
  1374. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1375. */
  1376. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1377. /** Searches for a substring within this string.
  1378. Uses a case-insensitive comparison.
  1379. @param startIndex the index from which the search should proceed
  1380. @param textToLookFor the string to search for
  1381. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1382. */
  1383. int indexOfIgnoreCase (const int startIndex,
  1384. const tchar* const textToLookFor) const throw();
  1385. /** Searches for a character inside this string (working backwards from the end of the string).
  1386. Uses a case-sensitive comparison.
  1387. @returns the index of the last occurrence of the character in this
  1388. string, or -1 if it's not found.
  1389. */
  1390. int lastIndexOfChar (const tchar character) const throw();
  1391. /** Searches for a substring inside this string (working backwards from the end of the string).
  1392. Uses a case-sensitive comparison.
  1393. @returns the index of the start of the last occurrence of the
  1394. substring within this string, or -1 if it's not found.
  1395. */
  1396. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1397. /** Searches for a substring inside this string (working backwards from the end of the string).
  1398. Uses a case-insensitive comparison.
  1399. @returns the index of the start of the last occurrence of the
  1400. substring within this string, or -1 if it's not found.
  1401. */
  1402. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1403. /** Returns the index of the last character in this string that matches one of the
  1404. characters passed-in to this method.
  1405. This scans the string backwards, starting from its end, and if it finds
  1406. a character that appears in the string charactersToLookFor, it returns its index.
  1407. If none of these characters are found, it returns -1.
  1408. If ignoreCase is true, the comparison will be case-insensitive.
  1409. @see lastIndexOf, indexOfAnyOf
  1410. */
  1411. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1412. const bool ignoreCase = false) const throw();
  1413. // Substring extraction and manipulation methods..
  1414. /** Returns the character at this index in the string.
  1415. No checks are made to see if the index is within a valid range, so be careful!
  1416. */
  1417. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1418. /** Returns a character from the string such that it can also be altered.
  1419. This can be used as a way of easily changing characters in the string.
  1420. Note that the index passed-in is not checked to see whether it's in-range, so
  1421. be careful when using this.
  1422. */
  1423. tchar& operator[] (const int index) throw();
  1424. /** Returns the final character of the string.
  1425. If the string is empty this will return 0.
  1426. */
  1427. tchar getLastCharacter() const throw();
  1428. /** Returns a subsection of the string.
  1429. If the range specified is beyond the limits of the string, as much as
  1430. possible is returned.
  1431. @param startIndex the index of the start of the substring needed
  1432. @param endIndex all characters from startIndex up to (but not including)
  1433. this index are returned
  1434. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1435. */
  1436. const String substring (int startIndex,
  1437. int endIndex) const throw();
  1438. /** Returns a section of the string, starting from a given position.
  1439. @param startIndex the first character to include. If this is beyond the end
  1440. of the string, an empty string is returned. If it is zero or
  1441. less, the whole string is returned.
  1442. @returns the substring from startIndex up to the end of the string
  1443. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1444. */
  1445. const String substring (const int startIndex) const throw();
  1446. /** Returns a version of this string with a number of characters removed
  1447. from the end.
  1448. @param numberToDrop the number of characters to drop from the end of the
  1449. string. If this is greater than the length of the string,
  1450. an empty string will be returned. If zero or less, the
  1451. original string will be returned.
  1452. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1453. */
  1454. const String dropLastCharacters (const int numberToDrop) const throw();
  1455. /** Returns a section of the string starting from a given substring.
  1456. This will search for the first occurrence of the given substring, and
  1457. return the section of the string starting from the point where this is
  1458. found (optionally not including the substring itself).
  1459. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1460. fromFirstOccurrenceOf ("34", false) would return "56".
  1461. If the substring isn't found, the method will return an empty string.
  1462. If ignoreCase is true, the comparison will be case-insensitive.
  1463. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1464. */
  1465. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1466. const bool includeSubStringInResult,
  1467. const bool ignoreCase) const throw();
  1468. /** Returns a section of the string starting from the last occurrence of a given substring.
  1469. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1470. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1471. return the whole of the original string.
  1472. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1473. */
  1474. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1475. const bool includeSubStringInResult,
  1476. const bool ignoreCase) const throw();
  1477. /** Returns the start of this string, up to the first occurrence of a substring.
  1478. This will search for the first occurrence of a given substring, and then
  1479. return a copy of the string, up to the position of this substring,
  1480. optionally including or excluding the substring itself in the result.
  1481. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1482. upTo ("34", true) would return "1234".
  1483. If the substring isn't found, this will return the whole of the original string.
  1484. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1485. */
  1486. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1487. const bool includeSubStringInResult,
  1488. const bool ignoreCase) const throw();
  1489. /** Returns the start of this string, up to the last occurrence of a substring.
  1490. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1491. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1492. */
  1493. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1494. const bool includeSubStringInResult,
  1495. const bool ignoreCase) const throw();
  1496. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1497. const String trim() const throw();
  1498. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1499. const String trimStart() const throw();
  1500. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1501. const String trimEnd() const throw();
  1502. /** Returns an upper-case version of this string. */
  1503. const String toUpperCase() const throw();
  1504. /** Returns an lower-case version of this string. */
  1505. const String toLowerCase() const throw();
  1506. /** Replaces a sub-section of the string with another string.
  1507. This will return a copy of this string, with a set of characters
  1508. from startIndex to startIndex + numCharsToReplace removed, and with
  1509. a new string inserted in their place.
  1510. Note that this is a const method, and won't alter the string itself.
  1511. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1512. it will be constrained to a valid range.
  1513. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1514. characters will be taken out.
  1515. @param stringToInsert the new string to insert at startIndex after the characters have been
  1516. removed.
  1517. */
  1518. const String replaceSection (int startIndex,
  1519. int numCharactersToReplace,
  1520. const tchar* const stringToInsert) const throw();
  1521. /** Replaces all occurrences of a substring with another string.
  1522. Returns a copy of this string, with any occurrences of stringToReplace
  1523. swapped for stringToInsertInstead.
  1524. Note that this is a const method, and won't alter the string itself.
  1525. */
  1526. const String replace (const tchar* const stringToReplace,
  1527. const tchar* const stringToInsertInstead,
  1528. const bool ignoreCase = false) const throw();
  1529. /** Returns a string with all occurrences of a character replaced with a different one. */
  1530. const String replaceCharacter (const tchar characterToReplace,
  1531. const tchar characterToInsertInstead) const throw();
  1532. /** Replaces a set of characters with another set.
  1533. Returns a string in which each character from charactersToReplace has been replaced
  1534. by the character at the equivalent position in newCharacters (so the two strings
  1535. passed in must be the same length).
  1536. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1537. Note that this is a const method, and won't affect the string itself.
  1538. */
  1539. const String replaceCharacters (const String& charactersToReplace,
  1540. const tchar* const charactersToInsertInstead) const throw();
  1541. /** Returns a version of this string that only retains a fixed set of characters.
  1542. This will return a copy of this string, omitting any characters which are not
  1543. found in the string passed-in.
  1544. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1545. Note that this is a const method, and won't alter the string itself.
  1546. */
  1547. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1548. /** Returns a version of this string with a set of characters removed.
  1549. This will return a copy of this string, omitting any characters which are
  1550. found in the string passed-in.
  1551. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1552. Note that this is a const method, and won't alter the string itself.
  1553. */
  1554. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1555. /** Returns a section from the start of the string that only contains a certain set of characters.
  1556. This returns the leftmost section of the string, up to (and not including) the
  1557. first character that doesn't appear in the string passed in.
  1558. */
  1559. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1560. /** Returns a section from the start of the string that only contains a certain set of characters.
  1561. This returns the leftmost section of the string, up to (and not including) the
  1562. first character that occurs in the string passed in.
  1563. */
  1564. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1565. /** Checks whether the string might be in quotation marks.
  1566. @returns true if the string begins with a quote character (either a double or single quote).
  1567. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1568. @see unquoted, quoted
  1569. */
  1570. bool isQuotedString() const throw();
  1571. /** Removes quotation marks from around the string, (if there are any).
  1572. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1573. at the ends of the string are not affected. If there aren't any quotes, the original string
  1574. is returned.
  1575. Note that this is a const method, and won't alter the string itself.
  1576. @see isQuotedString, quoted
  1577. */
  1578. const String unquoted() const throw();
  1579. /** Adds quotation marks around a string.
  1580. This will return a copy of the string with a quote at the start and end, (but won't
  1581. add the quote if there's already one there, so it's safe to call this on strings that
  1582. may already have quotes around them).
  1583. Note that this is a const method, and won't alter the string itself.
  1584. @param quoteCharacter the character to add at the start and end
  1585. @see isQuotedString, unquoted
  1586. */
  1587. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1588. /** Writes text into this string, using printf style-arguments.
  1589. This will replace the contents of the string with the output of this
  1590. formatted printf.
  1591. Note that using the %s token with a juce string is probably a bad idea, as
  1592. this may expect differect encodings on different platforms.
  1593. @see formatted
  1594. */
  1595. void printf (const tchar* const format, ...) throw();
  1596. /** Returns a string, created using arguments in the style of printf.
  1597. This will return a string which is the result of a sprintf using the
  1598. arguments passed-in.
  1599. Note that using the %s token with a juce string is probably a bad idea, as
  1600. this may expect differect encodings on different platforms.
  1601. @see printf, vprintf
  1602. */
  1603. static const String formatted (const tchar* const format, ...) throw();
  1604. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1605. This will replace the contents of the string with the output of this
  1606. formatted printf. Used by other methods, this is public in case it's
  1607. useful for other purposes where you want to pass a va_list through directly.
  1608. Note that using the %s token with a juce string is probably a bad idea, as
  1609. this may expect differect encodings on different platforms.
  1610. @see printf, formatted
  1611. */
  1612. void vprintf (const tchar* const format, va_list& args) throw();
  1613. /** Creates a string which is a version of a string repeated and joined together.
  1614. @param stringToRepeat the string to repeat
  1615. @param numberOfTimesToRepeat how many times to repeat it
  1616. */
  1617. static const String repeatedString (const tchar* const stringToRepeat,
  1618. int numberOfTimesToRepeat) throw();
  1619. /** Creates a string from data in an unknown format.
  1620. This looks at some binary data and tries to guess whether it's Unicode
  1621. or 8-bit characters, then returns a string that represents it correctly.
  1622. Should be able to handle Unicode endianness correctly, by looking at
  1623. the first two bytes.
  1624. */
  1625. static const String createStringFromData (const void* const data,
  1626. const int size) throw();
  1627. // Numeric conversions..
  1628. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1629. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1630. */
  1631. explicit String (const int decimalInteger) throw();
  1632. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1633. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1634. */
  1635. explicit String (const unsigned int decimalInteger) throw();
  1636. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1637. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1638. */
  1639. explicit String (const short decimalInteger) throw();
  1640. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1641. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1642. */
  1643. explicit String (const unsigned short decimalInteger) throw();
  1644. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1645. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1646. */
  1647. explicit String (const int64 largeIntegerValue) throw();
  1648. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1649. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1650. */
  1651. explicit String (const uint64 largeIntegerValue) throw();
  1652. /** Creates a string representing this floating-point number.
  1653. @param floatValue the value to convert to a string
  1654. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1655. decimal places, and will not use exponent notation. If 0 or
  1656. less, it will use exponent notation if necessary.
  1657. @see getDoubleValue, getIntValue
  1658. */
  1659. explicit String (const float floatValue,
  1660. const int numberOfDecimalPlaces = 0) throw();
  1661. /** Creates a string representing this floating-point number.
  1662. @param doubleValue the value to convert to a string
  1663. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1664. decimal places, and will not use exponent notation. If 0 or
  1665. less, it will use exponent notation if necessary.
  1666. @see getFloatValue, getIntValue
  1667. */
  1668. explicit String (const double doubleValue,
  1669. const int numberOfDecimalPlaces = 0) throw();
  1670. /** Parses this string to find its numerical value (up to 32 bits in size).
  1671. @returns the value of the string as a 32 bit signed base-10 integer.
  1672. @see getTrailingIntValue, getHexValue32, getHexValue64
  1673. */
  1674. int getIntValue() const throw();
  1675. /** Parses this string to find its numerical value (up to 64 bits in size).
  1676. @returns the value of the string as a 64 bit signed base-10 integer.
  1677. */
  1678. int64 getLargeIntValue() const throw();
  1679. /** Parses a decimal number from the end of the string.
  1680. This will look for a value at the end of the string.
  1681. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1682. Negative numbers are not handled, so "xyz-5" returns 5.
  1683. @see getIntValue
  1684. */
  1685. int getTrailingIntValue() const throw();
  1686. /** Parses this string as a floating point number.
  1687. @returns the value of the string as a 32-bit floating point value.
  1688. @see getDoubleValue
  1689. */
  1690. float getFloatValue() const throw();
  1691. /** Parses this string as a floating point number.
  1692. @returns the value of the string as a 64-bit floating point value.
  1693. @see getFloatValue
  1694. */
  1695. double getDoubleValue() const throw();
  1696. /** Parses the string as a hexadecimal number.
  1697. Non-hexadecimal characters in the string are ignored.
  1698. If the string contains too many characters, then the lowest significant
  1699. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1700. @returns a 32-bit number which is the value of the string in hex.
  1701. */
  1702. int getHexValue32() const throw();
  1703. /** Parses the string as a hexadecimal number.
  1704. Non-hexadecimal characters in the string are ignored.
  1705. If the string contains too many characters, then the lowest significant
  1706. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1707. @returns a 64-bit number which is the value of the string in hex.
  1708. */
  1709. int64 getHexValue64() const throw();
  1710. /** Creates a string representing this 32-bit value in hexadecimal. */
  1711. static const String toHexString (const int number) throw();
  1712. /** Creates a string representing this 64-bit value in hexadecimal. */
  1713. static const String toHexString (const int64 number) throw();
  1714. /** Creates a string representing this 16-bit value in hexadecimal. */
  1715. static const String toHexString (const short number) throw();
  1716. /** Creates a string containing a hex dump of a block of binary data.
  1717. @param data the binary data to use as input
  1718. @param size how many bytes of data to use
  1719. @param groupSize how many bytes are grouped together before inserting a
  1720. space into the output. e.g. group size 0 has no spaces,
  1721. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1722. like "bea1 c2ff".
  1723. */
  1724. static const String toHexString (const unsigned char* data,
  1725. const int size,
  1726. const int groupSize = 1) throw();
  1727. // Casting to character arrays..
  1728. #if JUCE_STRINGS_ARE_UNICODE
  1729. /** Returns a version of this string using the default 8-bit system encoding.
  1730. Because it returns a reference to the string's internal data, the pointer
  1731. that is returned must not be stored anywhere, as it can be deleted whenever the
  1732. string changes.
  1733. */
  1734. operator const char*() const throw();
  1735. /** Returns a unicode version of this string.
  1736. Because it returns a reference to the string's internal data, the pointer
  1737. that is returned must not be stored anywhere, as it can be deleted whenever the
  1738. string changes.
  1739. */
  1740. inline operator const juce_wchar*() const throw() { return text->text; }
  1741. #else
  1742. /** Returns a version of this string using the default 8-bit system encoding.
  1743. Because it returns a reference to the string's internal data, the pointer
  1744. that is returned must not be stored anywhere, as it can be deleted whenever the
  1745. string changes.
  1746. */
  1747. inline operator const char*() const throw() { return text->text; }
  1748. /** Returns a unicode version of this string.
  1749. Because it returns a reference to the string's internal data, the pointer
  1750. that is returned must not be stored anywhere, as it can be deleted whenever the
  1751. string changes.
  1752. */
  1753. operator const juce_wchar*() const throw();
  1754. #endif
  1755. /** Copies the string to a buffer.
  1756. @param destBuffer the place to copy it to
  1757. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1758. not including the tailing zero, so this shouldn't be
  1759. larger than the size of your destination buffer - 1
  1760. */
  1761. void copyToBuffer (char* const destBuffer,
  1762. const int maxCharsToCopy) const throw();
  1763. /** Copies the string to a unicode buffer.
  1764. @param destBuffer the place to copy it to
  1765. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1766. not including the tailing zero, so this shouldn't be
  1767. larger than the size of your destination buffer - 1
  1768. */
  1769. void copyToBuffer (juce_wchar* const destBuffer,
  1770. const int maxCharsToCopy) const throw();
  1771. /** Copies the string to a buffer as UTF-8 characters.
  1772. Returns the number of bytes copied to the buffer, including the terminating null
  1773. character.
  1774. @param destBuffer the place to copy it to; if this is a null pointer,
  1775. the method just returns the number of bytes required
  1776. (including the terminating null character).
  1777. */
  1778. int copyToUTF8 (uint8* const destBuffer) const throw();
  1779. /** Returns a pointer to a UTF-8 version of this string.
  1780. Because it returns a reference to the string's internal data, the pointer
  1781. that is returned must not be stored anywhere, as it can be deleted whenever the
  1782. string changes.
  1783. */
  1784. const char* toUTF8() const throw();
  1785. /** Creates a String from a UTF-8 encoded buffer.
  1786. If the size is < 0, it'll keep reading until it hits a zero.
  1787. */
  1788. static const String fromUTF8 (const uint8* const utf8buffer,
  1789. int bufferSizeBytes = -1) throw();
  1790. /** Increases the string's internally allocated storage.
  1791. Although the string's contents won't be affected by this call, it will
  1792. increase the amount of memory allocated internally for the string to grow into.
  1793. If you're about to make a large number of calls to methods such
  1794. as += or <<, it's more efficient to preallocate enough extra space
  1795. beforehand, so that these methods won't have to keep resizing the string
  1796. to append the extra characters.
  1797. @param numCharsNeeded the number of characters to allocate storage for. If this
  1798. value is less than the currently allocated size, it will
  1799. have no effect.
  1800. */
  1801. void preallocateStorage (const int numCharsNeeded) throw();
  1802. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1803. private:
  1804. struct InternalRefCountedStringHolder
  1805. {
  1806. int refCount;
  1807. int allocatedNumChars;
  1808. #if JUCE_STRINGS_ARE_UNICODE
  1809. wchar_t text[1];
  1810. #else
  1811. char text[1];
  1812. #endif
  1813. };
  1814. InternalRefCountedStringHolder* text;
  1815. static InternalRefCountedStringHolder emptyString;
  1816. // internal constructor that preallocates a certain amount of memory
  1817. String (const int numChars, const int dummyVariable) throw();
  1818. void deleteInternal() throw();
  1819. void createInternal (const int numChars) throw();
  1820. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1821. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1822. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1823. void dupeInternalIfMultiplyReferenced() throw();
  1824. };
  1825. /** Global operator to allow a String to be appended to a string literal.
  1826. This allows the use of expressions such as "abc" + String (x)
  1827. @see String
  1828. */
  1829. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1830. const String& string2) throw();
  1831. /** Global operator to allow a String to be appended to a string literal.
  1832. This allows the use of expressions such as "abc" + String (x)
  1833. @see String
  1834. */
  1835. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1836. const String& string2) throw();
  1837. #endif // __JUCE_STRING_JUCEHEADER__
  1838. /********* End of inlined file: juce_String.h *********/
  1839. /**
  1840. Acts as an application-wide logging class.
  1841. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1842. method and this will then be used by all calls to writeToLog.
  1843. The logger class also contains methods for writing messages to the debugger's
  1844. output stream.
  1845. @see FileLogger
  1846. */
  1847. class JUCE_API Logger
  1848. {
  1849. public:
  1850. /** Destructor. */
  1851. virtual ~Logger();
  1852. /** Sets the current logging class to use.
  1853. Note that the object passed in won't be deleted when no longer needed.
  1854. A null pointer can be passed-in to disable any logging.
  1855. If deleteOldLogger is set to true, the existing logger will be
  1856. deleted (if there is one).
  1857. */
  1858. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1859. const bool deleteOldLogger = false);
  1860. /** Writes a string to the current logger.
  1861. This will pass the string to the logger's logMessage() method if a logger
  1862. has been set.
  1863. @see logMessage
  1864. */
  1865. static void JUCE_CALLTYPE writeToLog (const String& message);
  1866. /** Writes a message to the standard error stream.
  1867. This can be called directly, or by using the DBG() macro in
  1868. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1869. */
  1870. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1871. /** Writes a message to the standard error stream.
  1872. This can be called directly, or by using the DBG_PRINTF() macro in
  1873. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1874. */
  1875. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1876. protected:
  1877. Logger();
  1878. /** This is overloaded by subclasses to implement custom logging behaviour.
  1879. @see setCurrentLogger
  1880. */
  1881. virtual void logMessage (const String& message) = 0;
  1882. };
  1883. #endif // __JUCE_LOGGER_JUCEHEADER__
  1884. /********* End of inlined file: juce_Logger.h *********/
  1885. END_JUCE_NAMESPACE
  1886. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1887. /********* End of inlined file: juce_StandardHeader.h *********/
  1888. BEGIN_JUCE_NAMESPACE
  1889. #if JUCE_MSVC
  1890. // this is set explicitly in case the app is using a different packing size.
  1891. #pragma pack (push, 8)
  1892. #pragma warning (push)
  1893. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1894. #endif
  1895. #if JUCE_MAC
  1896. #pragma align=natural
  1897. #endif
  1898. #define JUCE_PUBLIC_INCLUDES
  1899. // this is where all the class header files get brought in..
  1900. /********* Start of inlined file: juce_core_includes.h *********/
  1901. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1902. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1903. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  1904. /********* Start of inlined file: juce_Singleton.h *********/
  1905. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  1906. #define __JUCE_SINGLETON_JUCEHEADER__
  1907. /********* Start of inlined file: juce_ScopedLock.h *********/
  1908. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  1909. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  1910. /********* Start of inlined file: juce_CriticalSection.h *********/
  1911. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  1912. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  1913. /**
  1914. Prevents multiple threads from accessing shared objects at the same time.
  1915. @see ScopedLock, Thread, InterProcessLock
  1916. */
  1917. class JUCE_API CriticalSection
  1918. {
  1919. public:
  1920. /**
  1921. Creates a CriticalSection object
  1922. */
  1923. CriticalSection() throw();
  1924. /** Destroys a CriticalSection object.
  1925. If the critical section is deleted whilst locked, its subsequent behaviour
  1926. is unpredictable.
  1927. */
  1928. ~CriticalSection() throw();
  1929. /** Locks this critical section.
  1930. If the lock is currently held by another thread, this will wait until it
  1931. becomes free.
  1932. If the lock is already held by the caller thread, the method returns immediately.
  1933. @see exit, ScopedLock
  1934. */
  1935. void enter() const throw();
  1936. /** Attempts to lock this critical section without blocking.
  1937. This method behaves identically to CriticalSection::enter, except that the caller thread
  1938. does not wait if the lock is currently held by another thread but returns false immediately.
  1939. @returns false if the lock is currently held by another thread, true otherwise.
  1940. @see enter
  1941. */
  1942. bool tryEnter() const throw();
  1943. /** Releases the lock.
  1944. If the caller thread hasn't got the lock, this can have unpredictable results.
  1945. If the enter() method has been called multiple times by the thread, each
  1946. call must be matched by a call to exit() before other threads will be allowed
  1947. to take over the lock.
  1948. @see enter, ScopedLock
  1949. */
  1950. void exit() const throw();
  1951. juce_UseDebuggingNewOperator
  1952. private:
  1953. #if JUCE_WIN32
  1954. #if JUCE_64BIT
  1955. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  1956. // block of memory here that's big enough to be used internally as a windows critical
  1957. // section object.
  1958. uint8 internal [44];
  1959. #else
  1960. uint8 internal [24];
  1961. #endif
  1962. #else
  1963. mutable pthread_mutex_t internal;
  1964. #endif
  1965. CriticalSection (const CriticalSection&);
  1966. const CriticalSection& operator= (const CriticalSection&);
  1967. };
  1968. /**
  1969. A class that can be used in place of a real CriticalSection object.
  1970. This is currently used by some templated array classes, and should get
  1971. optimised out by the compiler.
  1972. @see Array, OwnedArray, ReferenceCountedArray
  1973. */
  1974. class JUCE_API DummyCriticalSection
  1975. {
  1976. public:
  1977. forcedinline DummyCriticalSection() throw() {}
  1978. forcedinline ~DummyCriticalSection() throw() {}
  1979. forcedinline void enter() const throw() {}
  1980. forcedinline void exit() const throw() {}
  1981. };
  1982. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  1983. /********* End of inlined file: juce_CriticalSection.h *********/
  1984. /**
  1985. Automatically locks and unlocks a CriticalSection object.
  1986. Use one of these as a local variable to control access to a CriticalSection.
  1987. e.g. @code
  1988. CriticalSection myCriticalSection;
  1989. for (;;)
  1990. {
  1991. const ScopedLock myScopedLock (myCriticalSection);
  1992. // myCriticalSection is now locked
  1993. ...do some stuff...
  1994. // myCriticalSection gets unlocked here.
  1995. }
  1996. @endcode
  1997. @see CriticalSection, ScopedUnlock
  1998. */
  1999. class JUCE_API ScopedLock
  2000. {
  2001. public:
  2002. /** Creates a ScopedLock.
  2003. As soon as it is created, this will lock the CriticalSection, and
  2004. when the ScopedLock object is deleted, the CriticalSection will
  2005. be unlocked.
  2006. Make sure this object is created and deleted by the same thread,
  2007. otherwise there are no guarantees what will happen! Best just to use it
  2008. as a local stack object, rather than creating one with the new() operator.
  2009. */
  2010. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  2011. /** Destructor.
  2012. The CriticalSection will be unlocked when the destructor is called.
  2013. Make sure this object is created and deleted by the same thread,
  2014. otherwise there are no guarantees what will happen!
  2015. */
  2016. inline ~ScopedLock() throw() { lock_.exit(); }
  2017. private:
  2018. const CriticalSection& lock_;
  2019. ScopedLock (const ScopedLock&);
  2020. const ScopedLock& operator= (const ScopedLock&);
  2021. };
  2022. /**
  2023. Automatically unlocks and re-locks a CriticalSection object.
  2024. This is the reverse of a ScopedLock object - instead of locking the critical
  2025. section for the lifetime of this object, it unlocks it.
  2026. Make sure you don't try to unlock critical sections that aren't actually locked!
  2027. e.g. @code
  2028. CriticalSection myCriticalSection;
  2029. for (;;)
  2030. {
  2031. const ScopedLock myScopedLock (myCriticalSection);
  2032. // myCriticalSection is now locked
  2033. ... do some stuff with it locked ..
  2034. while (xyz)
  2035. {
  2036. ... do some stuff with it locked ..
  2037. const ScopedUnlock unlocker (myCriticalSection);
  2038. // myCriticalSection is now unlocked for the remainder of this block,
  2039. // and re-locked at the end.
  2040. ...do some stuff with it unlocked ...
  2041. }
  2042. // myCriticalSection gets unlocked here.
  2043. }
  2044. @endcode
  2045. @see CriticalSection, ScopedLock
  2046. */
  2047. class ScopedUnlock
  2048. {
  2049. public:
  2050. /** Creates a ScopedUnlock.
  2051. As soon as it is created, this will unlock the CriticalSection, and
  2052. when the ScopedLock object is deleted, the CriticalSection will
  2053. be re-locked.
  2054. Make sure this object is created and deleted by the same thread,
  2055. otherwise there are no guarantees what will happen! Best just to use it
  2056. as a local stack object, rather than creating one with the new() operator.
  2057. */
  2058. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  2059. /** Destructor.
  2060. The CriticalSection will be unlocked when the destructor is called.
  2061. Make sure this object is created and deleted by the same thread,
  2062. otherwise there are no guarantees what will happen!
  2063. */
  2064. inline ~ScopedUnlock() throw() { lock_.enter(); }
  2065. private:
  2066. const CriticalSection& lock_;
  2067. ScopedUnlock (const ScopedLock&);
  2068. const ScopedUnlock& operator= (const ScopedUnlock&);
  2069. };
  2070. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  2071. /********* End of inlined file: juce_ScopedLock.h *********/
  2072. /**
  2073. Macro to declare member variables and methods for a singleton class.
  2074. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  2075. to the class's definition.
  2076. If allowOnlyOneInstance == true, it won't allow the object to be created
  2077. more than once in the process's lifetime.
  2078. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  2079. implementation code.
  2080. Clients can then call the static MyClass::getInstance() to get a pointer to the
  2081. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  2082. is currently extant
  2083. it's a very good idea to also add the call clearSingletonInstance() to the
  2084. destructor of the class, in case it is deleted by other means than deleteInstance()
  2085. e.g. @code
  2086. class MySingleton
  2087. {
  2088. public:
  2089. MySingleton()
  2090. {
  2091. }
  2092. ~MySingleton()
  2093. {
  2094. // this ensures that no dangling pointers are left when the
  2095. // singleton is deleted.
  2096. clearSingletonInstance();
  2097. }
  2098. juce_DeclareSingleton (MySingleton, false)
  2099. };
  2100. juce_ImplementSingleton (MySingleton)
  2101. // example of usage:
  2102. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  2103. ...
  2104. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  2105. @endcode
  2106. If you know that your object will only be created and deleted by a single thread, you
  2107. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  2108. of this one.
  2109. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  2110. */
  2111. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  2112. \
  2113. static classname* _singletonInstance; \
  2114. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  2115. \
  2116. static classname* getInstance() \
  2117. { \
  2118. if (_singletonInstance == 0) \
  2119. {\
  2120. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  2121. \
  2122. if (_singletonInstance == 0) \
  2123. { \
  2124. static bool alreadyInside = false; \
  2125. static bool createdOnceAlready = false; \
  2126. \
  2127. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  2128. jassert (! problem); \
  2129. if (! problem) \
  2130. { \
  2131. createdOnceAlready = true; \
  2132. alreadyInside = true; \
  2133. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  2134. alreadyInside = false; \
  2135. \
  2136. _singletonInstance = newObject; \
  2137. } \
  2138. } \
  2139. } \
  2140. \
  2141. return _singletonInstance; \
  2142. } \
  2143. \
  2144. static inline classname* getInstanceWithoutCreating() throw() \
  2145. { \
  2146. return _singletonInstance; \
  2147. } \
  2148. \
  2149. static void deleteInstance() \
  2150. { \
  2151. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  2152. if (_singletonInstance != 0) \
  2153. { \
  2154. classname* const old = _singletonInstance; \
  2155. _singletonInstance = 0; \
  2156. delete old; \
  2157. } \
  2158. } \
  2159. \
  2160. void clearSingletonInstance() throw() \
  2161. { \
  2162. if (_singletonInstance == this) \
  2163. _singletonInstance = 0; \
  2164. }
  2165. /** This is a counterpart to the juce_DeclareSingleton macro.
  2166. After adding the juce_DeclareSingleton to the class definition, this macro has
  2167. to be used in the cpp file.
  2168. */
  2169. #define juce_ImplementSingleton(classname) \
  2170. \
  2171. classname* classname::_singletonInstance = 0; \
  2172. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  2173. /**
  2174. Macro to declare member variables and methods for a singleton class.
  2175. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  2176. section to make access to it thread-safe. If you know that your object will
  2177. only ever be created or deleted by a single thread, then this is a
  2178. more efficient version to use.
  2179. See the documentation for juce_DeclareSingleton for more information about
  2180. how to use it, the only difference being that you have to use
  2181. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  2182. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  2183. */
  2184. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  2185. \
  2186. static classname* _singletonInstance; \
  2187. \
  2188. static classname* getInstance() \
  2189. { \
  2190. if (_singletonInstance == 0) \
  2191. { \
  2192. static bool alreadyInside = false; \
  2193. static bool createdOnceAlready = false; \
  2194. \
  2195. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  2196. jassert (! problem); \
  2197. if (! problem) \
  2198. { \
  2199. createdOnceAlready = true; \
  2200. alreadyInside = true; \
  2201. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  2202. alreadyInside = false; \
  2203. \
  2204. _singletonInstance = newObject; \
  2205. } \
  2206. } \
  2207. \
  2208. return _singletonInstance; \
  2209. } \
  2210. \
  2211. static inline classname* getInstanceWithoutCreating() throw() \
  2212. { \
  2213. return _singletonInstance; \
  2214. } \
  2215. \
  2216. static void deleteInstance() \
  2217. { \
  2218. if (_singletonInstance != 0) \
  2219. { \
  2220. classname* const old = _singletonInstance; \
  2221. _singletonInstance = 0; \
  2222. delete old; \
  2223. } \
  2224. } \
  2225. \
  2226. void clearSingletonInstance() throw() \
  2227. { \
  2228. if (_singletonInstance == this) \
  2229. _singletonInstance = 0; \
  2230. }
  2231. /**
  2232. Macro to declare member variables and methods for a singleton class.
  2233. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  2234. for recursion or repeated instantiation. It's intended for use as a lightweight
  2235. version of a singleton, where you're using it in very straightforward
  2236. circumstances and don't need the extra checking.
  2237. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  2238. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  2239. See the documentation for juce_DeclareSingleton for more information about
  2240. how to use it, the only difference being that you have to use
  2241. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  2242. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  2243. */
  2244. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  2245. \
  2246. static classname* _singletonInstance; \
  2247. \
  2248. static classname* getInstance() \
  2249. { \
  2250. if (_singletonInstance == 0) \
  2251. _singletonInstance = new classname(); \
  2252. \
  2253. return _singletonInstance; \
  2254. } \
  2255. \
  2256. static inline classname* getInstanceWithoutCreating() throw() \
  2257. { \
  2258. return _singletonInstance; \
  2259. } \
  2260. \
  2261. static void deleteInstance() \
  2262. { \
  2263. if (_singletonInstance != 0) \
  2264. { \
  2265. classname* const old = _singletonInstance; \
  2266. _singletonInstance = 0; \
  2267. delete old; \
  2268. } \
  2269. } \
  2270. \
  2271. void clearSingletonInstance() throw() \
  2272. { \
  2273. if (_singletonInstance == this) \
  2274. _singletonInstance = 0; \
  2275. }
  2276. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  2277. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  2278. to the class definition, this macro has to be used somewhere in the cpp file.
  2279. */
  2280. #define juce_ImplementSingleton_SingleThreaded(classname) \
  2281. \
  2282. classname* classname::_singletonInstance = 0;
  2283. #endif // __JUCE_SINGLETON_JUCEHEADER__
  2284. /********* End of inlined file: juce_Singleton.h *********/
  2285. #endif
  2286. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  2287. /********* Start of inlined file: juce_SystemStats.h *********/
  2288. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  2289. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  2290. /**
  2291. Contains methods for finding out about the current hardware and OS configuration.
  2292. */
  2293. class JUCE_API SystemStats
  2294. {
  2295. public:
  2296. /** Returns the current version of JUCE,
  2297. (just in case you didn't already know at compile-time.)
  2298. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  2299. */
  2300. static const String getJUCEVersion() throw();
  2301. /** The set of possible results of the getOperatingSystemType() method.
  2302. */
  2303. enum OperatingSystemType
  2304. {
  2305. UnknownOS = 0,
  2306. MacOSX = 0x1000,
  2307. Linux = 0x2000,
  2308. Win95 = 0x4001,
  2309. Win98 = 0x4002,
  2310. WinNT351 = 0x4103,
  2311. WinNT40 = 0x4104,
  2312. Win2000 = 0x4105,
  2313. WinXP = 0x4106,
  2314. WinVista = 0x4107,
  2315. Windows = 0x4000, /**< To test whether any version of Windows is running,
  2316. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  2317. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  2318. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  2319. };
  2320. /** Returns the type of operating system we're running on.
  2321. @returns one of the values from the OperatingSystemType enum.
  2322. @see getOperatingSystemName
  2323. */
  2324. static OperatingSystemType getOperatingSystemType() throw();
  2325. /** Returns the name of the type of operating system we're running on.
  2326. @returns a string describing the OS type.
  2327. @see getOperatingSystemType
  2328. */
  2329. static const String getOperatingSystemName() throw();
  2330. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  2331. */
  2332. static bool isOperatingSystem64Bit() throw();
  2333. // CPU and memory information..
  2334. /** Returns the approximate CPU speed.
  2335. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  2336. what year you're reading this...)
  2337. */
  2338. static int getCpuSpeedInMegaherz() throw();
  2339. /** Returns a string to indicate the CPU vendor.
  2340. Might not be known on some systems.
  2341. */
  2342. static const String getCpuVendor() throw();
  2343. /** Checks whether Intel MMX instructions are available. */
  2344. static bool hasMMX() throw();
  2345. /** Checks whether Intel SSE instructions are available. */
  2346. static bool hasSSE() throw();
  2347. /** Checks whether Intel SSE2 instructions are available. */
  2348. static bool hasSSE2() throw();
  2349. /** Checks whether AMD 3DNOW instructions are available. */
  2350. static bool has3DNow() throw();
  2351. /** Returns the number of CPUs.
  2352. */
  2353. static int getNumCpus() throw();
  2354. /** Returns a clock-cycle tick counter, if available.
  2355. If the machine can do it, this will return a tick-count
  2356. where each tick is one cpu clock cycle - used for profiling
  2357. code.
  2358. @returns the tick count, or zero if not available.
  2359. */
  2360. static int64 getClockCycleCounter() throw();
  2361. /** Finds out how much RAM is in the machine.
  2362. @returns the approximate number of megabytes of memory, or zero if
  2363. something goes wrong when finding out.
  2364. */
  2365. static int getMemorySizeInMegabytes() throw();
  2366. /** Returns the system page-size.
  2367. This is only used by programmers with beards.
  2368. */
  2369. static int getPageSize() throw();
  2370. /** Returns a list of MAC addresses found on this machine.
  2371. @param addresses an array into which the MAC addresses should be copied
  2372. @param maxNum the number of elements in this array
  2373. @param littleEndian the endianness of the numbers to return. Note that
  2374. the default values of this parameter are different on
  2375. Mac/PC to avoid breaking old software that was written
  2376. before this parameter was added (when the two systems
  2377. defaulted to using different endiannesses). In newer
  2378. software you probably want to specify an explicit value
  2379. for this.
  2380. @returns the number of MAC addresses that were found
  2381. */
  2382. static int getMACAddresses (int64* addresses, int maxNum,
  2383. #if JUCE_MAC
  2384. const bool littleEndian = true) throw();
  2385. #else
  2386. const bool littleEndian = false) throw();
  2387. #endif
  2388. // not-for-public-use platform-specific method gets called at startup to initialise things.
  2389. static void initialiseStats() throw();
  2390. };
  2391. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  2392. /********* End of inlined file: juce_SystemStats.h *********/
  2393. #endif
  2394. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  2395. #endif
  2396. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  2397. #endif
  2398. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  2399. /********* Start of inlined file: juce_Atomic.h *********/
  2400. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  2401. #define __JUCE_ATOMIC_JUCEHEADER__
  2402. // Atomic increment/decrement operations..
  2403. #if JUCE_MAC && ! DOXYGEN
  2404. #if ! MACOS_10_3_OR_EARLIER
  2405. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  2406. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  2407. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  2408. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  2409. #else
  2410. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  2411. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  2412. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  2413. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  2414. #endif
  2415. #elif JUCE_GCC
  2416. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  2417. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  2418. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  2419. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  2420. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  2421. #else
  2422. /** Increments an integer in a thread-safe way. */
  2423. forcedinline void atomicIncrement (int& variable) throw()
  2424. {
  2425. __asm__ __volatile__ (
  2426. #if JUCE_64BIT
  2427. "lock incl (%%rax)"
  2428. :
  2429. : "a" (&variable)
  2430. : "cc", "memory");
  2431. #else
  2432. "lock incl %0"
  2433. : "=m" (variable)
  2434. : "m" (variable));
  2435. #endif
  2436. }
  2437. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2438. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  2439. {
  2440. int result;
  2441. __asm__ __volatile__ (
  2442. #if JUCE_64BIT
  2443. "lock xaddl %%ebx, (%%rax) \n\
  2444. incl %%ebx"
  2445. : "=b" (result)
  2446. : "a" (&variable), "b" (1)
  2447. : "cc", "memory");
  2448. #else
  2449. "lock xaddl %%eax, (%%ecx) \n\
  2450. incl %%eax"
  2451. : "=a" (result)
  2452. : "c" (&variable), "a" (1)
  2453. : "memory");
  2454. #endif
  2455. return result;
  2456. }
  2457. /** Decrememts an integer in a thread-safe way. */
  2458. forcedinline void atomicDecrement (int& variable) throw()
  2459. {
  2460. __asm__ __volatile__ (
  2461. #if JUCE_64BIT
  2462. "lock decl (%%rax)"
  2463. :
  2464. : "a" (&variable)
  2465. : "cc", "memory");
  2466. #else
  2467. "lock decl %0"
  2468. : "=m" (variable)
  2469. : "m" (variable));
  2470. #endif
  2471. }
  2472. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2473. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  2474. {
  2475. int result;
  2476. __asm__ __volatile__ (
  2477. #if JUCE_64BIT
  2478. "lock xaddl %%ebx, (%%rax) \n\
  2479. decl %%ebx"
  2480. : "=b" (result)
  2481. : "a" (&variable), "b" (-1)
  2482. : "cc", "memory");
  2483. #else
  2484. "lock xaddl %%eax, (%%ecx) \n\
  2485. decl %%eax"
  2486. : "=a" (result)
  2487. : "c" (&variable), "a" (-1)
  2488. : "memory");
  2489. #endif
  2490. return result;
  2491. }
  2492. #endif
  2493. #elif JUCE_USE_INTRINSICS
  2494. #pragma intrinsic (_InterlockedIncrement)
  2495. #pragma intrinsic (_InterlockedDecrement)
  2496. /** Increments an integer in a thread-safe way. */
  2497. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2498. {
  2499. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2500. }
  2501. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2502. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2503. {
  2504. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2505. }
  2506. /** Decrememts an integer in a thread-safe way. */
  2507. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2508. {
  2509. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2510. }
  2511. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2512. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2513. {
  2514. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2515. }
  2516. #else
  2517. /** Increments an integer in a thread-safe way. */
  2518. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2519. {
  2520. __asm {
  2521. mov ecx, dword ptr [variable]
  2522. lock inc dword ptr [ecx]
  2523. }
  2524. }
  2525. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2526. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2527. {
  2528. int result;
  2529. __asm {
  2530. mov ecx, dword ptr [variable]
  2531. mov eax, 1
  2532. lock xadd dword ptr [ecx], eax
  2533. inc eax
  2534. mov result, eax
  2535. }
  2536. return result;
  2537. }
  2538. /** Decrememts an integer in a thread-safe way. */
  2539. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2540. {
  2541. __asm {
  2542. mov ecx, dword ptr [variable]
  2543. lock dec dword ptr [ecx]
  2544. }
  2545. }
  2546. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2547. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2548. {
  2549. int result;
  2550. __asm {
  2551. mov ecx, dword ptr [variable]
  2552. mov eax, -1
  2553. lock xadd dword ptr [ecx], eax
  2554. dec eax
  2555. mov result, eax
  2556. }
  2557. return result;
  2558. }
  2559. #endif
  2560. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2561. /********* End of inlined file: juce_Atomic.h *********/
  2562. #endif
  2563. #ifndef __JUCE_LOGGER_JUCEHEADER__
  2564. #endif
  2565. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2566. /********* Start of inlined file: juce_FileLogger.h *********/
  2567. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2568. #define __JUCE_FILELOGGER_JUCEHEADER__
  2569. /********* Start of inlined file: juce_File.h *********/
  2570. #ifndef __JUCE_FILE_JUCEHEADER__
  2571. #define __JUCE_FILE_JUCEHEADER__
  2572. /********* Start of inlined file: juce_OwnedArray.h *********/
  2573. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2574. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2575. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2576. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2577. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2578. /** The default size of chunk in which arrays increase their storage.
  2579. Used by ArrayAllocationBase and its subclasses.
  2580. */
  2581. const int juceDefaultArrayGranularity = 8;
  2582. /**
  2583. Implements some basic array storage allocation functions.
  2584. This class isn't really for public use - it's used by the other
  2585. array classes, but might come in handy for some purposes.
  2586. @see Array, OwnedArray, ReferenceCountedArray
  2587. */
  2588. template <class ElementType>
  2589. class ArrayAllocationBase
  2590. {
  2591. protected:
  2592. /** Creates an empty array.
  2593. @param granularity_ this is the size of increment by which the internal storage
  2594. will be increased.
  2595. */
  2596. ArrayAllocationBase (const int granularity_) throw()
  2597. : elements (0),
  2598. numAllocated (0),
  2599. granularity (granularity_)
  2600. {
  2601. }
  2602. /** Destructor. */
  2603. ~ArrayAllocationBase() throw()
  2604. {
  2605. delete[] elements;
  2606. }
  2607. /** Changes the amount of storage allocated.
  2608. This will retain any data currently held in the array, and either add or
  2609. remove extra space at the end.
  2610. @param numElements the number of elements that are needed
  2611. */
  2612. void setAllocatedSize (const int numElements) throw()
  2613. {
  2614. if (numAllocated != numElements)
  2615. {
  2616. if (numElements > 0)
  2617. {
  2618. ElementType* const newElements = new ElementType [numElements];
  2619. const int itemsToRetain = jmin (numElements, numAllocated);
  2620. for (int i = 0; i < itemsToRetain; ++i)
  2621. newElements[i] = elements[i];
  2622. delete[] elements;
  2623. elements = newElements;
  2624. }
  2625. else if (elements != 0)
  2626. {
  2627. delete[] elements;
  2628. elements = 0;
  2629. }
  2630. numAllocated = numElements;
  2631. }
  2632. }
  2633. /** Increases the amount of storage allocated if it is less than a given amount.
  2634. This will retain any data currently held in the array, but will add
  2635. extra space at the end to make sure there it's at least as big as the size
  2636. passed in. If it's already bigger, no action is taken.
  2637. @param minNumElements the minimum number of elements that are needed
  2638. */
  2639. void ensureAllocatedSize (int minNumElements) throw()
  2640. {
  2641. if (minNumElements > numAllocated)
  2642. {
  2643. // for arrays with small granularity that get big, start
  2644. // increasing the size in bigger jumps
  2645. if (minNumElements > (granularity << 6))
  2646. {
  2647. minNumElements += (minNumElements / granularity);
  2648. if (minNumElements > (granularity << 8))
  2649. minNumElements += granularity << 6;
  2650. else
  2651. minNumElements += granularity << 5;
  2652. }
  2653. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2654. }
  2655. }
  2656. ElementType* elements;
  2657. int numAllocated, granularity;
  2658. private:
  2659. ArrayAllocationBase (const ArrayAllocationBase&);
  2660. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2661. };
  2662. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2663. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2664. /********* Start of inlined file: juce_ElementComparator.h *********/
  2665. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2666. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2667. /**
  2668. Sorts a range of elements in an array.
  2669. The comparator object that is passed-in must define a public method with the following
  2670. signature:
  2671. @code
  2672. int compareElements (ElementType first, ElementType second);
  2673. @endcode
  2674. ..and this method must return:
  2675. - a value of < 0 if the first comes before the second
  2676. - a value of 0 if the two objects are equivalent
  2677. - a value of > 0 if the second comes before the first
  2678. To improve performance, the compareElements() method can be declared as static or const.
  2679. @param comparator an object which defines a compareElements() method
  2680. @param array the array to sort
  2681. @param firstElement the index of the first element of the range to be sorted
  2682. @param lastElement the index of the last element in the range that needs
  2683. sorting (this is inclusive)
  2684. @param retainOrderOfEquivalentItems if true, the order of items that the
  2685. comparator deems the same will be maintained - this will be
  2686. a slower algorithm than if they are allowed to be moved around.
  2687. @see sortArrayRetainingOrder
  2688. */
  2689. template <class ElementType, class ElementComparator>
  2690. static void sortArray (ElementComparator& comparator,
  2691. ElementType* const array,
  2692. int firstElement,
  2693. int lastElement,
  2694. const bool retainOrderOfEquivalentItems)
  2695. {
  2696. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2697. // avoids getting warning messages about the parameter being unused
  2698. if (lastElement > firstElement)
  2699. {
  2700. if (retainOrderOfEquivalentItems)
  2701. {
  2702. for (int i = firstElement; i < lastElement; ++i)
  2703. {
  2704. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2705. {
  2706. const ElementType temp = array [i];
  2707. array [i] = array[i + 1];
  2708. array [i + 1] = temp;
  2709. if (i > firstElement)
  2710. i -= 2;
  2711. }
  2712. }
  2713. }
  2714. else
  2715. {
  2716. int fromStack[30], toStack[30];
  2717. int stackIndex = 0;
  2718. for (;;)
  2719. {
  2720. const int size = (lastElement - firstElement) + 1;
  2721. if (size <= 8)
  2722. {
  2723. int j = lastElement;
  2724. int maxIndex;
  2725. while (j > firstElement)
  2726. {
  2727. maxIndex = firstElement;
  2728. for (int k = firstElement + 1; k <= j; ++k)
  2729. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2730. maxIndex = k;
  2731. const ElementType temp = array [maxIndex];
  2732. array [maxIndex] = array[j];
  2733. array [j] = temp;
  2734. --j;
  2735. }
  2736. }
  2737. else
  2738. {
  2739. const int mid = firstElement + (size >> 1);
  2740. ElementType temp = array [mid];
  2741. array [mid] = array [firstElement];
  2742. array [firstElement] = temp;
  2743. int i = firstElement;
  2744. int j = lastElement + 1;
  2745. for (;;)
  2746. {
  2747. while (++i <= lastElement
  2748. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2749. {}
  2750. while (--j > firstElement
  2751. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2752. {}
  2753. if (j < i)
  2754. break;
  2755. temp = array[i];
  2756. array[i] = array[j];
  2757. array[j] = temp;
  2758. }
  2759. temp = array [firstElement];
  2760. array [firstElement] = array[j];
  2761. array [j] = temp;
  2762. if (j - 1 - firstElement >= lastElement - i)
  2763. {
  2764. if (firstElement + 1 < j)
  2765. {
  2766. fromStack [stackIndex] = firstElement;
  2767. toStack [stackIndex] = j - 1;
  2768. ++stackIndex;
  2769. }
  2770. if (i < lastElement)
  2771. {
  2772. firstElement = i;
  2773. continue;
  2774. }
  2775. }
  2776. else
  2777. {
  2778. if (i < lastElement)
  2779. {
  2780. fromStack [stackIndex] = i;
  2781. toStack [stackIndex] = lastElement;
  2782. ++stackIndex;
  2783. }
  2784. if (firstElement + 1 < j)
  2785. {
  2786. lastElement = j - 1;
  2787. continue;
  2788. }
  2789. }
  2790. }
  2791. if (--stackIndex < 0)
  2792. break;
  2793. jassert (stackIndex < numElementsInArray (fromStack));
  2794. firstElement = fromStack [stackIndex];
  2795. lastElement = toStack [stackIndex];
  2796. }
  2797. }
  2798. }
  2799. }
  2800. /**
  2801. Searches a sorted array of elements, looking for the index at which a specified value
  2802. should be inserted for it to be in the correct order.
  2803. The comparator object that is passed-in must define a public method with the following
  2804. signature:
  2805. @code
  2806. int compareElements (ElementType first, ElementType second);
  2807. @endcode
  2808. ..and this method must return:
  2809. - a value of < 0 if the first comes before the second
  2810. - a value of 0 if the two objects are equivalent
  2811. - a value of > 0 if the second comes before the first
  2812. To improve performance, the compareElements() method can be declared as static or const.
  2813. @param comparator an object which defines a compareElements() method
  2814. @param array the array to search
  2815. @param newElement the value that is going to be inserted
  2816. @param firstElement the index of the first element to search
  2817. @param lastElement the index of the last element in the range (this is non-inclusive)
  2818. */
  2819. template <class ElementType, class ElementComparator>
  2820. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2821. ElementType* const array,
  2822. const ElementType newElement,
  2823. int firstElement,
  2824. int lastElement)
  2825. {
  2826. jassert (firstElement <= lastElement);
  2827. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2828. // avoids getting warning messages about the parameter being unused
  2829. while (firstElement < lastElement)
  2830. {
  2831. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2832. {
  2833. ++firstElement;
  2834. break;
  2835. }
  2836. else
  2837. {
  2838. const int halfway = (firstElement + lastElement) >> 1;
  2839. if (halfway == firstElement)
  2840. {
  2841. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2842. ++firstElement;
  2843. break;
  2844. }
  2845. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2846. {
  2847. firstElement = halfway;
  2848. }
  2849. else
  2850. {
  2851. lastElement = halfway;
  2852. }
  2853. }
  2854. }
  2855. return firstElement;
  2856. }
  2857. /**
  2858. A simple ElementComparator class that can be used to sort an array of
  2859. integer primitive objects.
  2860. Example: @code
  2861. Array <int> myArray;
  2862. IntegerElementComparator<int> sorter;
  2863. myArray.sort (sorter);
  2864. @endcode
  2865. For floating point values, see the FloatElementComparator class instead.
  2866. @see FloatElementComparator, ElementComparator
  2867. */
  2868. template <class ElementType>
  2869. class IntegerElementComparator
  2870. {
  2871. public:
  2872. static int compareElements (const ElementType first,
  2873. const ElementType second) throw()
  2874. {
  2875. return first - second;
  2876. }
  2877. };
  2878. /**
  2879. A simple ElementComparator class that can be used to sort an array of numeric
  2880. double or floating point primitive objects.
  2881. Example: @code
  2882. Array <double> myArray;
  2883. FloatElementComparator<double> sorter;
  2884. myArray.sort (sorter);
  2885. @endcode
  2886. For integer values, see the IntegerElementComparator class instead.
  2887. @see IntegerElementComparator, ElementComparator
  2888. */
  2889. template <class ElementType>
  2890. class FloatElementComparator
  2891. {
  2892. public:
  2893. static int compareElements (const ElementType first,
  2894. const ElementType second) throw()
  2895. {
  2896. return (first < second) ? -1
  2897. : ((first == second) ? 0
  2898. : 1);
  2899. }
  2900. };
  2901. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2902. /********* End of inlined file: juce_ElementComparator.h *********/
  2903. /** An array designed for holding objects.
  2904. This holds a list of pointers to objects, and will automatically
  2905. delete the objects when they are removed from the array, or when the
  2906. array is itself deleted.
  2907. Declare it in the form: OwnedArray<MyObjectClass>
  2908. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2909. After adding objects, they are 'owned' by the array and will be deleted when
  2910. removed or replaced.
  2911. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2912. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2913. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2914. */
  2915. template <class ObjectClass,
  2916. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2917. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2918. {
  2919. public:
  2920. /** Creates an empty array.
  2921. @param granularity this is the size of increment by which the internal storage
  2922. used by the array will grow. Only change it from the default if you know the
  2923. array is going to be very big and needs to be able to grow efficiently.
  2924. @see ArrayAllocationBase
  2925. */
  2926. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2927. : ArrayAllocationBase <ObjectClass*> (granularity),
  2928. numUsed (0)
  2929. {
  2930. }
  2931. /** Deletes the array and also deletes any objects inside it.
  2932. To get rid of the array without deleting its objects, use its
  2933. clear (false) method before deleting it.
  2934. */
  2935. ~OwnedArray()
  2936. {
  2937. clear (true);
  2938. }
  2939. /** Clears the array, optionally deleting the objects inside it first. */
  2940. void clear (const bool deleteObjects = true)
  2941. {
  2942. lock.enter();
  2943. if (deleteObjects)
  2944. {
  2945. while (numUsed > 0)
  2946. delete this->elements [--numUsed];
  2947. }
  2948. this->setAllocatedSize (0);
  2949. numUsed = 0;
  2950. lock.exit();
  2951. }
  2952. /** Returns the number of items currently in the array.
  2953. @see operator[]
  2954. */
  2955. inline int size() const throw()
  2956. {
  2957. return numUsed;
  2958. }
  2959. /** Returns a pointer to the object at this index in the array.
  2960. If the index is out-of-range, this will return a null pointer, (and
  2961. it could be null anyway, because it's ok for the array to hold null
  2962. pointers as well as objects).
  2963. @see getUnchecked
  2964. */
  2965. inline ObjectClass* operator[] (const int index) const throw()
  2966. {
  2967. lock.enter();
  2968. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2969. ? this->elements [index]
  2970. : (ObjectClass*) 0;
  2971. lock.exit();
  2972. return result;
  2973. }
  2974. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2975. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2976. it can be used when you're sure the index if always going to be legal.
  2977. */
  2978. inline ObjectClass* getUnchecked (const int index) const throw()
  2979. {
  2980. lock.enter();
  2981. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2982. ObjectClass* const result = this->elements [index];
  2983. lock.exit();
  2984. return result;
  2985. }
  2986. /** Returns a pointer to the first object in the array.
  2987. This will return a null pointer if the array's empty.
  2988. @see getLast
  2989. */
  2990. inline ObjectClass* getFirst() const throw()
  2991. {
  2992. lock.enter();
  2993. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2994. : (ObjectClass*) 0;
  2995. lock.exit();
  2996. return result;
  2997. }
  2998. /** Returns a pointer to the last object in the array.
  2999. This will return a null pointer if the array's empty.
  3000. @see getFirst
  3001. */
  3002. inline ObjectClass* getLast() const throw()
  3003. {
  3004. lock.enter();
  3005. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  3006. : (ObjectClass*) 0;
  3007. lock.exit();
  3008. return result;
  3009. }
  3010. /** Finds the index of an object which might be in the array.
  3011. @param objectToLookFor the object to look for
  3012. @returns the index at which the object was found, or -1 if it's not found
  3013. */
  3014. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  3015. {
  3016. int result = -1;
  3017. lock.enter();
  3018. ObjectClass* const* e = this->elements;
  3019. for (int i = numUsed; --i >= 0;)
  3020. {
  3021. if (objectToLookFor == *e)
  3022. {
  3023. result = (int) (e - this->elements);
  3024. break;
  3025. }
  3026. ++e;
  3027. }
  3028. lock.exit();
  3029. return result;
  3030. }
  3031. /** Returns true if the array contains a specified object.
  3032. @param objectToLookFor the object to look for
  3033. @returns true if the object is in the array
  3034. */
  3035. bool contains (const ObjectClass* const objectToLookFor) const throw()
  3036. {
  3037. lock.enter();
  3038. ObjectClass* const* e = this->elements;
  3039. int i = numUsed;
  3040. while (i >= 4)
  3041. {
  3042. if (objectToLookFor == *e
  3043. || objectToLookFor == *++e
  3044. || objectToLookFor == *++e
  3045. || objectToLookFor == *++e)
  3046. {
  3047. lock.exit();
  3048. return true;
  3049. }
  3050. i -= 4;
  3051. ++e;
  3052. }
  3053. while (i > 0)
  3054. {
  3055. if (objectToLookFor == *e)
  3056. {
  3057. lock.exit();
  3058. return true;
  3059. }
  3060. --i;
  3061. ++e;
  3062. }
  3063. lock.exit();
  3064. return false;
  3065. }
  3066. /** Appends a new object to the end of the array.
  3067. Note that the this object will be deleted by the OwnedArray when it
  3068. is removed, so be careful not to delete it somewhere else.
  3069. Also be careful not to add the same object to the array more than once,
  3070. as this will obviously cause deletion of dangling pointers.
  3071. @param newObject the new object to add to the array
  3072. @see set, insert, addIfNotAlreadyThere, addSorted
  3073. */
  3074. void add (const ObjectClass* const newObject) throw()
  3075. {
  3076. lock.enter();
  3077. this->ensureAllocatedSize (numUsed + 1);
  3078. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  3079. lock.exit();
  3080. }
  3081. /** Inserts a new object into the array at the given index.
  3082. Note that the this object will be deleted by the OwnedArray when it
  3083. is removed, so be careful not to delete it somewhere else.
  3084. If the index is less than 0 or greater than the size of the array, the
  3085. element will be added to the end of the array.
  3086. Otherwise, it will be inserted into the array, moving all the later elements
  3087. along to make room.
  3088. Be careful not to add the same object to the array more than once,
  3089. as this will obviously cause deletion of dangling pointers.
  3090. @param indexToInsertAt the index at which the new element should be inserted
  3091. @param newObject the new object to add to the array
  3092. @see add, addSorted, addIfNotAlreadyThere, set
  3093. */
  3094. void insert (int indexToInsertAt,
  3095. const ObjectClass* const newObject) throw()
  3096. {
  3097. if (indexToInsertAt >= 0)
  3098. {
  3099. lock.enter();
  3100. if (indexToInsertAt > numUsed)
  3101. indexToInsertAt = numUsed;
  3102. this->ensureAllocatedSize (numUsed + 1);
  3103. ObjectClass** const e = this->elements + indexToInsertAt;
  3104. const int numToMove = numUsed - indexToInsertAt;
  3105. if (numToMove > 0)
  3106. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  3107. *e = const_cast <ObjectClass*> (newObject);
  3108. ++numUsed;
  3109. lock.exit();
  3110. }
  3111. else
  3112. {
  3113. add (newObject);
  3114. }
  3115. }
  3116. /** Appends a new object at the end of the array as long as the array doesn't
  3117. already contain it.
  3118. If the array already contains a matching object, nothing will be done.
  3119. @param newObject the new object to add to the array
  3120. */
  3121. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  3122. {
  3123. lock.enter();
  3124. if (! contains (newObject))
  3125. add (newObject);
  3126. lock.exit();
  3127. }
  3128. /** Replaces an object in the array with a different one.
  3129. If the index is less than zero, this method does nothing.
  3130. If the index is beyond the end of the array, the new object is added to the end of the array.
  3131. Be careful not to add the same object to the array more than once,
  3132. as this will obviously cause deletion of dangling pointers.
  3133. @param indexToChange the index whose value you want to change
  3134. @param newObject the new value to set for this index.
  3135. @param deleteOldElement whether to delete the object that's being replaced with the new one
  3136. @see add, insert, remove
  3137. */
  3138. void set (const int indexToChange,
  3139. const ObjectClass* const newObject,
  3140. const bool deleteOldElement = true)
  3141. {
  3142. if (indexToChange >= 0)
  3143. {
  3144. ObjectClass* toDelete = 0;
  3145. lock.enter();
  3146. if (indexToChange < numUsed)
  3147. {
  3148. if (deleteOldElement)
  3149. toDelete = this->elements [indexToChange];
  3150. if (toDelete == newObject)
  3151. toDelete = 0;
  3152. else
  3153. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  3154. }
  3155. else
  3156. {
  3157. this->ensureAllocatedSize (numUsed + 1);
  3158. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  3159. }
  3160. lock.exit();
  3161. delete toDelete;
  3162. }
  3163. }
  3164. /** Inserts a new object into the array assuming that the array is sorted.
  3165. This will use a comparator to find the position at which the new object
  3166. should go. If the array isn't sorted, the behaviour of this
  3167. method will be unpredictable.
  3168. @param comparator the comparator to use to compare the elements - see the sort method
  3169. for details about this object's structure
  3170. @param newObject the new object to insert to the array
  3171. @see add, sort, indexOfSorted
  3172. */
  3173. template <class ElementComparator>
  3174. void addSorted (ElementComparator& comparator,
  3175. ObjectClass* const newObject) throw()
  3176. {
  3177. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3178. // avoids getting warning messages about the parameter being unused
  3179. lock.enter();
  3180. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  3181. lock.exit();
  3182. }
  3183. /** Finds the index of an object in the array, assuming that the array is sorted.
  3184. This will use a comparator to do a binary-chop to find the index of the given
  3185. element, if it exists. If the array isn't sorted, the behaviour of this
  3186. method will be unpredictable.
  3187. @param comparator the comparator to use to compare the elements - see the sort()
  3188. method for details about the form this object should take
  3189. @param objectToLookFor the object to search for
  3190. @returns the index of the element, or -1 if it's not found
  3191. @see addSorted, sort
  3192. */
  3193. template <class ElementComparator>
  3194. int indexOfSorted (ElementComparator& comparator,
  3195. const ObjectClass* const objectToLookFor) const throw()
  3196. {
  3197. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3198. // avoids getting warning messages about the parameter being unused
  3199. lock.enter();
  3200. int start = 0;
  3201. int end = numUsed;
  3202. for (;;)
  3203. {
  3204. if (start >= end)
  3205. {
  3206. lock.exit();
  3207. return -1;
  3208. }
  3209. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  3210. {
  3211. lock.exit();
  3212. return start;
  3213. }
  3214. else
  3215. {
  3216. const int halfway = (start + end) >> 1;
  3217. if (halfway == start)
  3218. {
  3219. lock.exit();
  3220. return -1;
  3221. }
  3222. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  3223. start = halfway;
  3224. else
  3225. end = halfway;
  3226. }
  3227. }
  3228. }
  3229. /** Removes an object from the array.
  3230. This will remove the object at a given index (optionally also
  3231. deleting it) and move back all the subsequent objects to close the gap.
  3232. If the index passed in is out-of-range, nothing will happen.
  3233. @param indexToRemove the index of the element to remove
  3234. @param deleteObject whether to delete the object that is removed
  3235. @see removeObject, removeRange
  3236. */
  3237. void remove (const int indexToRemove,
  3238. const bool deleteObject = true)
  3239. {
  3240. lock.enter();
  3241. ObjectClass* toDelete = 0;
  3242. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3243. {
  3244. ObjectClass** const e = this->elements + indexToRemove;
  3245. if (deleteObject)
  3246. toDelete = *e;
  3247. --numUsed;
  3248. const int numToShift = numUsed - indexToRemove;
  3249. if (numToShift > 0)
  3250. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  3251. if ((numUsed << 1) < this->numAllocated)
  3252. minimiseStorageOverheads();
  3253. }
  3254. lock.exit();
  3255. delete toDelete;
  3256. }
  3257. /** Removes a specified object from the array.
  3258. If the item isn't found, no action is taken.
  3259. @param objectToRemove the object to try to remove
  3260. @param deleteObject whether to delete the object (if it's found)
  3261. @see remove, removeRange
  3262. */
  3263. void removeObject (const ObjectClass* const objectToRemove,
  3264. const bool deleteObject = true)
  3265. {
  3266. lock.enter();
  3267. ObjectClass** e = this->elements;
  3268. for (int i = numUsed; --i >= 0;)
  3269. {
  3270. if (objectToRemove == *e)
  3271. {
  3272. remove ((int) (e - this->elements), deleteObject);
  3273. break;
  3274. }
  3275. ++e;
  3276. }
  3277. lock.exit();
  3278. }
  3279. /** Removes a range of objects from the array.
  3280. This will remove a set of objects, starting from the given index,
  3281. and move any subsequent elements down to close the gap.
  3282. If the range extends beyond the bounds of the array, it will
  3283. be safely clipped to the size of the array.
  3284. @param startIndex the index of the first object to remove
  3285. @param numberToRemove how many objects should be removed
  3286. @param deleteObjects whether to delete the objects that get removed
  3287. @see remove, removeObject
  3288. */
  3289. void removeRange (int startIndex,
  3290. const int numberToRemove,
  3291. const bool deleteObjects = true)
  3292. {
  3293. lock.enter();
  3294. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3295. startIndex = jlimit (0, numUsed, startIndex);
  3296. if (endIndex > startIndex)
  3297. {
  3298. if (deleteObjects)
  3299. {
  3300. for (int i = startIndex; i < endIndex; ++i)
  3301. {
  3302. delete this->elements [i];
  3303. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  3304. }
  3305. }
  3306. const int rangeSize = endIndex - startIndex;
  3307. ObjectClass** e = this->elements + startIndex;
  3308. int numToShift = numUsed - endIndex;
  3309. numUsed -= rangeSize;
  3310. while (--numToShift >= 0)
  3311. {
  3312. *e = e [rangeSize];
  3313. ++e;
  3314. }
  3315. if ((numUsed << 1) < this->numAllocated)
  3316. minimiseStorageOverheads();
  3317. }
  3318. lock.exit();
  3319. }
  3320. /** Removes the last n objects from the array.
  3321. @param howManyToRemove how many objects to remove from the end of the array
  3322. @param deleteObjects whether to also delete the objects that are removed
  3323. @see remove, removeObject, removeRange
  3324. */
  3325. void removeLast (int howManyToRemove = 1,
  3326. const bool deleteObjects = true)
  3327. {
  3328. lock.enter();
  3329. if (howManyToRemove >= numUsed)
  3330. {
  3331. clear (deleteObjects);
  3332. }
  3333. else
  3334. {
  3335. while (--howManyToRemove >= 0)
  3336. remove (numUsed - 1, deleteObjects);
  3337. }
  3338. lock.exit();
  3339. }
  3340. /** Swaps a pair of objects in the array.
  3341. If either of the indexes passed in is out-of-range, nothing will happen,
  3342. otherwise the two objects at these positions will be exchanged.
  3343. */
  3344. void swap (const int index1,
  3345. const int index2) throw()
  3346. {
  3347. lock.enter();
  3348. if (((unsigned int) index1) < (unsigned int) numUsed
  3349. && ((unsigned int) index2) < (unsigned int) numUsed)
  3350. {
  3351. swapVariables (this->elements [index1],
  3352. this->elements [index2]);
  3353. }
  3354. lock.exit();
  3355. }
  3356. /** Moves one of the objects to a different position.
  3357. This will move the object to a specified index, shuffling along
  3358. any intervening elements as required.
  3359. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3360. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3361. @param currentIndex the index of the object to be moved. If this isn't a
  3362. valid index, then nothing will be done
  3363. @param newIndex the index at which you'd like this object to end up. If this
  3364. is less than zero, it will be moved to the end of the array
  3365. */
  3366. void move (const int currentIndex,
  3367. int newIndex) throw()
  3368. {
  3369. if (currentIndex != newIndex)
  3370. {
  3371. lock.enter();
  3372. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3373. {
  3374. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3375. newIndex = numUsed - 1;
  3376. ObjectClass* const value = this->elements [currentIndex];
  3377. if (newIndex > currentIndex)
  3378. {
  3379. memmove (this->elements + currentIndex,
  3380. this->elements + currentIndex + 1,
  3381. (newIndex - currentIndex) * sizeof (ObjectClass*));
  3382. }
  3383. else
  3384. {
  3385. memmove (this->elements + newIndex + 1,
  3386. this->elements + newIndex,
  3387. (currentIndex - newIndex) * sizeof (ObjectClass*));
  3388. }
  3389. this->elements [newIndex] = value;
  3390. }
  3391. lock.exit();
  3392. }
  3393. }
  3394. /** This swaps the contents of this array with those of another array.
  3395. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3396. because it just swaps their internal pointers.
  3397. */
  3398. template <class OtherArrayType>
  3399. void swapWithArray (OtherArrayType& otherArray) throw()
  3400. {
  3401. lock.enter();
  3402. otherArray.lock.enter();
  3403. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3404. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  3405. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3406. otherArray.lock.exit();
  3407. lock.exit();
  3408. }
  3409. /** Reduces the amount of storage being used by the array.
  3410. Arrays typically allocate slightly more storage than they need, and after
  3411. removing elements, they may have quite a lot of unused space allocated.
  3412. This method will reduce the amount of allocated storage to a minimum.
  3413. */
  3414. void minimiseStorageOverheads() throw()
  3415. {
  3416. lock.enter();
  3417. if (numUsed == 0)
  3418. {
  3419. this->setAllocatedSize (0);
  3420. }
  3421. else
  3422. {
  3423. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3424. if (newAllocation < this->numAllocated)
  3425. this->setAllocatedSize (newAllocation);
  3426. }
  3427. lock.exit();
  3428. }
  3429. /** Increases the array's internal storage to hold a minimum number of elements.
  3430. Calling this before adding a large known number of elements means that
  3431. the array won't have to keep dynamically resizing itself as the elements
  3432. are added, and it'll therefore be more efficient.
  3433. */
  3434. void ensureStorageAllocated (const int minNumElements) throw()
  3435. {
  3436. this->ensureAllocatedSize (minNumElements);
  3437. }
  3438. /** Sorts the elements in the array.
  3439. This will use a comparator object to sort the elements into order. The object
  3440. passed must have a method of the form:
  3441. @code
  3442. int compareElements (ElementType first, ElementType second);
  3443. @endcode
  3444. ..and this method must return:
  3445. - a value of < 0 if the first comes before the second
  3446. - a value of 0 if the two objects are equivalent
  3447. - a value of > 0 if the second comes before the first
  3448. To improve performance, the compareElements() method can be declared as static or const.
  3449. @param comparator the comparator to use for comparing elements.
  3450. @param retainOrderOfEquivalentItems if this is true, then items
  3451. which the comparator says are equivalent will be
  3452. kept in the order in which they currently appear
  3453. in the array. This is slower to perform, but may
  3454. be important in some cases. If it's false, a faster
  3455. algorithm is used, but equivalent elements may be
  3456. rearranged.
  3457. @see sortArray, indexOfSorted
  3458. */
  3459. template <class ElementComparator>
  3460. void sort (ElementComparator& comparator,
  3461. const bool retainOrderOfEquivalentItems = false) const throw()
  3462. {
  3463. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3464. // avoids getting warning messages about the parameter being unused
  3465. lock.enter();
  3466. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3467. lock.exit();
  3468. }
  3469. /** Locks the array's CriticalSection.
  3470. Of course if the type of section used is a DummyCriticalSection, this won't
  3471. have any effect.
  3472. @see unlockArray
  3473. */
  3474. void lockArray() const throw()
  3475. {
  3476. lock.enter();
  3477. }
  3478. /** Unlocks the array's CriticalSection.
  3479. Of course if the type of section used is a DummyCriticalSection, this won't
  3480. have any effect.
  3481. @see lockArray
  3482. */
  3483. void unlockArray() const throw()
  3484. {
  3485. lock.exit();
  3486. }
  3487. juce_UseDebuggingNewOperator
  3488. private:
  3489. int numUsed;
  3490. TypeOfCriticalSectionToUse lock;
  3491. // disallow copy constructor and assignment
  3492. OwnedArray (const OwnedArray&);
  3493. const OwnedArray& operator= (const OwnedArray&);
  3494. };
  3495. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3496. /********* End of inlined file: juce_OwnedArray.h *********/
  3497. /********* Start of inlined file: juce_Time.h *********/
  3498. #ifndef __JUCE_TIME_JUCEHEADER__
  3499. #define __JUCE_TIME_JUCEHEADER__
  3500. /********* Start of inlined file: juce_RelativeTime.h *********/
  3501. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3502. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3503. /** A relative measure of time.
  3504. The time is stored as a number of seconds, at double-precision floating
  3505. point accuracy, and may be positive or negative.
  3506. If you need an absolute time, (i.e. a date + time), see the Time class.
  3507. */
  3508. class JUCE_API RelativeTime
  3509. {
  3510. public:
  3511. /** Creates a RelativeTime.
  3512. @param seconds the number of seconds, which may be +ve or -ve.
  3513. @see milliseconds, minutes, hours, days, weeks
  3514. */
  3515. explicit RelativeTime (const double seconds = 0.0) throw();
  3516. /** Copies another relative time. */
  3517. RelativeTime (const RelativeTime& other) throw();
  3518. /** Copies another relative time. */
  3519. const RelativeTime& operator= (const RelativeTime& other) throw();
  3520. /** Destructor. */
  3521. ~RelativeTime() throw();
  3522. /** Creates a new RelativeTime object representing a number of milliseconds.
  3523. @see minutes, hours, days, weeks
  3524. */
  3525. static const RelativeTime milliseconds (const int milliseconds) throw();
  3526. /** Creates a new RelativeTime object representing a number of milliseconds.
  3527. @see minutes, hours, days, weeks
  3528. */
  3529. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3530. /** Creates a new RelativeTime object representing a number of minutes.
  3531. @see milliseconds, hours, days, weeks
  3532. */
  3533. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3534. /** Creates a new RelativeTime object representing a number of hours.
  3535. @see milliseconds, minutes, days, weeks
  3536. */
  3537. static const RelativeTime hours (const double numberOfHours) throw();
  3538. /** Creates a new RelativeTime object representing a number of days.
  3539. @see milliseconds, minutes, hours, weeks
  3540. */
  3541. static const RelativeTime days (const double numberOfDays) throw();
  3542. /** Creates a new RelativeTime object representing a number of weeks.
  3543. @see milliseconds, minutes, hours, days
  3544. */
  3545. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3546. /** Returns the number of milliseconds this time represents.
  3547. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3548. */
  3549. int64 inMilliseconds() const throw();
  3550. /** Returns the number of seconds this time represents.
  3551. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3552. */
  3553. double inSeconds() const throw() { return seconds; }
  3554. /** Returns the number of minutes this time represents.
  3555. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3556. */
  3557. double inMinutes() const throw();
  3558. /** Returns the number of hours this time represents.
  3559. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3560. */
  3561. double inHours() const throw();
  3562. /** Returns the number of days this time represents.
  3563. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3564. */
  3565. double inDays() const throw();
  3566. /** Returns the number of weeks this time represents.
  3567. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3568. */
  3569. double inWeeks() const throw();
  3570. /** Returns a readable textual description of the time.
  3571. The exact format of the string returned will depend on
  3572. the magnitude of the time - e.g.
  3573. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3574. so that only the two most significant units are printed.
  3575. The returnValueForZeroTime value is the result that is returned if the
  3576. length is zero. Depending on your application you might want to use this
  3577. to return something more relevant like "empty" or "0 secs", etc.
  3578. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3579. */
  3580. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3581. /** Compares two RelativeTimes. */
  3582. bool operator== (const RelativeTime& other) const throw();
  3583. /** Compares two RelativeTimes. */
  3584. bool operator!= (const RelativeTime& other) const throw();
  3585. /** Compares two RelativeTimes. */
  3586. bool operator> (const RelativeTime& other) const throw();
  3587. /** Compares two RelativeTimes. */
  3588. bool operator< (const RelativeTime& other) const throw();
  3589. /** Compares two RelativeTimes. */
  3590. bool operator>= (const RelativeTime& other) const throw();
  3591. /** Compares two RelativeTimes. */
  3592. bool operator<= (const RelativeTime& other) const throw();
  3593. /** Adds another RelativeTime to this one and returns the result. */
  3594. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3595. /** Subtracts another RelativeTime from this one and returns the result. */
  3596. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3597. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3598. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3599. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3600. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3601. /** Adds another RelativeTime to this one. */
  3602. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3603. /** Subtracts another RelativeTime from this one. */
  3604. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3605. /** Adds a number of seconds to this time. */
  3606. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3607. /** Subtracts a number of seconds from this time. */
  3608. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3609. juce_UseDebuggingNewOperator
  3610. private:
  3611. double seconds;
  3612. };
  3613. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3614. /********* End of inlined file: juce_RelativeTime.h *********/
  3615. /**
  3616. Holds an absolute date and time.
  3617. Internally, the time is stored at millisecond precision.
  3618. @see RelativeTime
  3619. */
  3620. class JUCE_API Time
  3621. {
  3622. public:
  3623. /** Creates a Time object.
  3624. This default constructor creates a time of 1st January 1970, (which is
  3625. represented internally as 0ms).
  3626. To create a time object representing the current time, use getCurrentTime().
  3627. @see getCurrentTime
  3628. */
  3629. Time() throw();
  3630. /** Creates a copy of another Time object. */
  3631. Time (const Time& other) throw();
  3632. /** Creates a time based on a number of milliseconds.
  3633. The internal millisecond count is set to 0 (1st January 1970). To create a
  3634. time object set to the current time, use getCurrentTime().
  3635. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3636. 'epoch' (midnight Jan 1st 1970).
  3637. @see getCurrentTime, currentTimeMillis
  3638. */
  3639. Time (const int64 millisecondsSinceEpoch) throw();
  3640. /** Creates a time from a set of date components.
  3641. The timezone is assumed to be whatever the system is using as its locale.
  3642. @param year the year, in 4-digit format, e.g. 2004
  3643. @param month the month, in the range 0 to 11
  3644. @param day the day of the month, in the range 1 to 31
  3645. @param hours hours in 24-hour clock format, 0 to 23
  3646. @param minutes minutes 0 to 59
  3647. @param seconds seconds 0 to 59
  3648. @param milliseconds milliseconds 0 to 999
  3649. @param useLocalTime if true, encode using the current machine's local time; if
  3650. false, it will always work in GMT.
  3651. */
  3652. Time (const int year,
  3653. const int month,
  3654. const int day,
  3655. const int hours,
  3656. const int minutes,
  3657. const int seconds = 0,
  3658. const int milliseconds = 0,
  3659. const bool useLocalTime = true) throw();
  3660. /** Destructor. */
  3661. ~Time() throw();
  3662. /** Copies this time from another one. */
  3663. const Time& operator= (const Time& other) throw();
  3664. /** Returns a Time object that is set to the current system time.
  3665. @see currentTimeMillis
  3666. */
  3667. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3668. /** Returns the time as a number of milliseconds.
  3669. @returns the number of milliseconds this Time object represents, since
  3670. midnight jan 1st 1970.
  3671. @see getMilliseconds
  3672. */
  3673. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3674. /** Returns the year.
  3675. A 4-digit format is used, e.g. 2004.
  3676. */
  3677. int getYear() const throw();
  3678. /** Returns the number of the month.
  3679. The value returned is in the range 0 to 11.
  3680. @see getMonthName
  3681. */
  3682. int getMonth() const throw();
  3683. /** Returns the name of the month.
  3684. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3685. it'll return the long form, e.g. "January"
  3686. @see getMonth
  3687. */
  3688. const String getMonthName (const bool threeLetterVersion) const throw();
  3689. /** Returns the day of the month.
  3690. The value returned is in the range 1 to 31.
  3691. */
  3692. int getDayOfMonth() const throw();
  3693. /** Returns the number of the day of the week.
  3694. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3695. */
  3696. int getDayOfWeek() const throw();
  3697. /** Returns the name of the weekday.
  3698. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3699. false, it'll return the full version, e.g. "Tuesday".
  3700. */
  3701. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3702. /** Returns the number of hours since midnight.
  3703. This is in 24-hour clock format, in the range 0 to 23.
  3704. @see getHoursInAmPmFormat, isAfternoon
  3705. */
  3706. int getHours() const throw();
  3707. /** Returns true if the time is in the afternoon.
  3708. So it returns true for "PM", false for "AM".
  3709. @see getHoursInAmPmFormat, getHours
  3710. */
  3711. bool isAfternoon() const throw();
  3712. /** Returns the hours in 12-hour clock format.
  3713. This will return a value 1 to 12 - use isAfternoon() to find out
  3714. whether this is in the afternoon or morning.
  3715. @see getHours, isAfternoon
  3716. */
  3717. int getHoursInAmPmFormat() const throw();
  3718. /** Returns the number of minutes, 0 to 59. */
  3719. int getMinutes() const throw();
  3720. /** Returns the number of seconds, 0 to 59. */
  3721. int getSeconds() const throw();
  3722. /** Returns the number of milliseconds, 0 to 999.
  3723. Unlike toMilliseconds(), this just returns the position within the
  3724. current second rather than the total number since the epoch.
  3725. @see toMilliseconds
  3726. */
  3727. int getMilliseconds() const throw();
  3728. /** Returns true if the local timezone uses a daylight saving correction. */
  3729. bool isDaylightSavingTime() const throw();
  3730. /** Returns a 3-character string to indicate the local timezone. */
  3731. const String getTimeZone() const throw();
  3732. /** Quick way of getting a string version of a date and time.
  3733. For a more powerful way of formatting the date and time, see the formatted() method.
  3734. @param includeDate whether to include the date in the string
  3735. @param includeTime whether to include the time in the string
  3736. @param includeSeconds if the time is being included, this provides an option not to include
  3737. the seconds in it
  3738. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3739. hour notation.
  3740. @see formatted
  3741. */
  3742. const String toString (const bool includeDate,
  3743. const bool includeTime,
  3744. const bool includeSeconds = true,
  3745. const bool use24HourClock = false) const throw();
  3746. /** Converts this date/time to a string with a user-defined format.
  3747. This uses the C strftime() function to format this time as a string. To save you
  3748. looking it up, these are the escape codes that strftime uses (other codes might
  3749. work on some platforms and not others, but these are the common ones):
  3750. %a is replaced by the locale's abbreviated weekday name.
  3751. %A is replaced by the locale's full weekday name.
  3752. %b is replaced by the locale's abbreviated month name.
  3753. %B is replaced by the locale's full month name.
  3754. %c is replaced by the locale's appropriate date and time representation.
  3755. %d is replaced by the day of the month as a decimal number [01,31].
  3756. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3757. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3758. %j is replaced by the day of the year as a decimal number [001,366].
  3759. %m is replaced by the month as a decimal number [01,12].
  3760. %M is replaced by the minute as a decimal number [00,59].
  3761. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3762. %S is replaced by the second as a decimal number [00,61].
  3763. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3764. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3765. %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.
  3766. %x is replaced by the locale's appropriate date representation.
  3767. %X is replaced by the locale's appropriate time representation.
  3768. %y is replaced by the year without century as a decimal number [00,99].
  3769. %Y is replaced by the year with century as a decimal number.
  3770. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3771. %% is replaced by %.
  3772. @see toString
  3773. */
  3774. const String formatted (const tchar* const format) const throw();
  3775. /** Adds a RelativeTime to this time and returns the result. */
  3776. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3777. /** Subtracts a RelativeTime from this time and returns the result. */
  3778. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3779. /** Returns the relative time difference between this time and another one. */
  3780. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3781. /** Compares two Time objects. */
  3782. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3783. /** Compares two Time objects. */
  3784. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3785. /** Compares two Time objects. */
  3786. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3787. /** Compares two Time objects. */
  3788. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3789. /** Compares two Time objects. */
  3790. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3791. /** Compares two Time objects. */
  3792. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3793. /** Tries to set the computer's clock.
  3794. @returns true if this succeeds, although depending on the system, the
  3795. application might not have sufficient privileges to do this.
  3796. */
  3797. bool setSystemTimeToThisTime() const throw();
  3798. /** Returns the name of a day of the week.
  3799. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3800. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3801. false, it'll return the full version, e.g. "Tuesday".
  3802. */
  3803. static const String getWeekdayName (int dayNumber,
  3804. const bool threeLetterVersion) throw();
  3805. /** Returns the name of one of the months.
  3806. @param monthNumber the month, 0 to 11
  3807. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3808. it'll return the long form, e.g. "January"
  3809. */
  3810. static const String getMonthName (int monthNumber,
  3811. const bool threeLetterVersion) throw();
  3812. // Static methods for getting system timers directly..
  3813. /** Returns the current system time.
  3814. Returns the number of milliseconds since midnight jan 1st 1970.
  3815. Should be accurate to within a few millisecs, depending on platform,
  3816. hardware, etc.
  3817. */
  3818. static int64 currentTimeMillis() throw();
  3819. /** Returns the number of millisecs since system startup.
  3820. Should be accurate to within a few millisecs, depending on platform,
  3821. hardware, etc.
  3822. @see getApproximateMillisecondCounter
  3823. */
  3824. static uint32 getMillisecondCounter() throw();
  3825. /** Returns the number of millisecs since system startup.
  3826. Same as getMillisecondCounter(), but returns a more accurate value, using
  3827. the high-res timer.
  3828. @see getMillisecondCounter
  3829. */
  3830. static double getMillisecondCounterHiRes() throw();
  3831. /** Waits until the getMillisecondCounter() reaches a given value.
  3832. This will make the thread sleep as efficiently as it can while it's waiting.
  3833. */
  3834. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3835. /** Less-accurate but faster version of getMillisecondCounter().
  3836. This will return the last value that getMillisecondCounter() returned, so doesn't
  3837. need to make a system call, but is less accurate - it shouldn't be more than
  3838. 100ms away from the correct time, though, so is still accurate enough for a
  3839. lot of purposes.
  3840. @see getMillisecondCounter
  3841. */
  3842. static uint32 getApproximateMillisecondCounter() throw();
  3843. // High-resolution timers..
  3844. /** Returns the current high-resolution counter's tick-count.
  3845. This is a similar idea to getMillisecondCounter(), but with a higher
  3846. resolution.
  3847. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3848. secondsToHighResolutionTicks
  3849. */
  3850. static int64 getHighResolutionTicks() throw();
  3851. /** Returns the resolution of the high-resolution counter in ticks per second.
  3852. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3853. secondsToHighResolutionTicks
  3854. */
  3855. static int64 getHighResolutionTicksPerSecond() throw();
  3856. /** Converts a number of high-resolution ticks into seconds.
  3857. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3858. secondsToHighResolutionTicks
  3859. */
  3860. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3861. /** Converts a number seconds into high-resolution ticks.
  3862. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3863. highResolutionTicksToSeconds
  3864. */
  3865. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3866. private:
  3867. int64 millisSinceEpoch;
  3868. };
  3869. #endif // __JUCE_TIME_JUCEHEADER__
  3870. /********* End of inlined file: juce_Time.h *********/
  3871. /********* Start of inlined file: juce_StringArray.h *********/
  3872. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3873. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3874. /********* Start of inlined file: juce_VoidArray.h *********/
  3875. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3876. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3877. /********* Start of inlined file: juce_Array.h *********/
  3878. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3879. #define __JUCE_ARRAY_JUCEHEADER__
  3880. /**
  3881. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3882. Examples of arrays are: Array<int> or Array<MyClass*>
  3883. Note that when holding pointers to objects, the array doesn't take any ownership
  3884. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3885. If you're using a class or struct as the element type, it must be
  3886. capable of being copied or moved with a straightforward memcpy, rather than
  3887. needing construction and destruction code.
  3888. For holding lists of strings, use the specialised class StringArray.
  3889. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3890. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3891. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3892. */
  3893. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3894. class Array : private ArrayAllocationBase <ElementType>
  3895. {
  3896. public:
  3897. /** Creates an empty array.
  3898. @param granularity this is the size of increment by which the internal storage
  3899. used by the array will grow. Only change it from the default if you know the
  3900. array is going to be very big and needs to be able to grow efficiently.
  3901. @see ArrayAllocationBase
  3902. */
  3903. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3904. : ArrayAllocationBase <ElementType> (granularity),
  3905. numUsed (0)
  3906. {
  3907. }
  3908. /** Creates a copy of another array.
  3909. @param other the array to copy
  3910. */
  3911. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3912. : ArrayAllocationBase <ElementType> (other.granularity)
  3913. {
  3914. other.lockArray();
  3915. numUsed = other.numUsed;
  3916. this->setAllocatedSize (other.numUsed);
  3917. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3918. other.unlockArray();
  3919. }
  3920. /** Initalises from a null-terminated C array of values.
  3921. @param values the array to copy from
  3922. */
  3923. Array (const ElementType* values) throw()
  3924. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3925. numUsed (0)
  3926. {
  3927. while (*values != 0)
  3928. add (*values++);
  3929. }
  3930. /** Initalises from a C array of values.
  3931. @param values the array to copy from
  3932. @param numValues the number of values in the array
  3933. */
  3934. Array (const ElementType* values, int numValues) throw()
  3935. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3936. numUsed (numValues)
  3937. {
  3938. this->setAllocatedSize (numValues);
  3939. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3940. }
  3941. /** Destructor. */
  3942. ~Array() throw()
  3943. {
  3944. }
  3945. /** Copies another array.
  3946. @param other the array to copy
  3947. */
  3948. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3949. {
  3950. if (this != &other)
  3951. {
  3952. other.lockArray();
  3953. lock.enter();
  3954. this->granularity = other.granularity;
  3955. this->ensureAllocatedSize (other.size());
  3956. numUsed = other.numUsed;
  3957. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3958. minimiseStorageOverheads();
  3959. lock.exit();
  3960. other.unlockArray();
  3961. }
  3962. return *this;
  3963. }
  3964. /** Compares this array to another one.
  3965. Two arrays are considered equal if they both contain the same set of
  3966. elements, in the same order.
  3967. @param other the other array to compare with
  3968. */
  3969. template <class OtherArrayType>
  3970. bool operator== (const OtherArrayType& other) const throw()
  3971. {
  3972. lock.enter();
  3973. if (this->numUsed != other.numUsed)
  3974. {
  3975. lock.exit();
  3976. return false;
  3977. }
  3978. for (int i = numUsed; --i >= 0;)
  3979. {
  3980. if (this->elements [i] != other.elements [i])
  3981. {
  3982. lock.exit();
  3983. return false;
  3984. }
  3985. }
  3986. lock.exit();
  3987. return true;
  3988. }
  3989. /** Compares this array to another one.
  3990. Two arrays are considered equal if they both contain the same set of
  3991. elements, in the same order.
  3992. @param other the other array to compare with
  3993. */
  3994. template <class OtherArrayType>
  3995. bool operator!= (const OtherArrayType& other) const throw()
  3996. {
  3997. return ! operator== (other);
  3998. }
  3999. /** Removes all elements from the array.
  4000. This will remove all the elements, and free any storage that the array is
  4001. using. To clear the array without freeing the storage, use the clearQuick()
  4002. method instead.
  4003. @see clearQuick
  4004. */
  4005. void clear() throw()
  4006. {
  4007. lock.enter();
  4008. this->setAllocatedSize (0);
  4009. numUsed = 0;
  4010. lock.exit();
  4011. }
  4012. /** Removes all elements from the array without freeing the array's allocated storage.
  4013. @see clear
  4014. */
  4015. void clearQuick() throw()
  4016. {
  4017. lock.enter();
  4018. numUsed = 0;
  4019. lock.exit();
  4020. }
  4021. /** Returns the current number of elements in the array.
  4022. */
  4023. inline int size() const throw()
  4024. {
  4025. return numUsed;
  4026. }
  4027. /** Returns one of the elements in the array.
  4028. If the index passed in is beyond the range of valid elements, this
  4029. will return zero.
  4030. If you're certain that the index will always be a valid element, you
  4031. can call getUnchecked() instead, which is faster.
  4032. @param index the index of the element being requested (0 is the first element in the array)
  4033. @see getUnchecked, getFirst, getLast
  4034. */
  4035. inline ElementType operator[] (const int index) const throw()
  4036. {
  4037. lock.enter();
  4038. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  4039. ? this->elements [index]
  4040. : ElementType();
  4041. lock.exit();
  4042. return result;
  4043. }
  4044. /** Returns one of the elements in the array, without checking the index passed in.
  4045. Unlike the operator[] method, this will try to return an element without
  4046. checking that the index is within the bounds of the array, so should only
  4047. be used when you're confident that it will always be a valid index.
  4048. @param index the index of the element being requested (0 is the first element in the array)
  4049. @see operator[], getFirst, getLast
  4050. */
  4051. inline ElementType getUnchecked (const int index) const throw()
  4052. {
  4053. lock.enter();
  4054. jassert (((unsigned int) index) < (unsigned int) numUsed);
  4055. const ElementType result = this->elements [index];
  4056. lock.exit();
  4057. return result;
  4058. }
  4059. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  4060. This is like getUnchecked, but returns a direct reference to the element, so that
  4061. you can alter it directly. Obviously this can be dangerous, so only use it when
  4062. absolutely necessary.
  4063. @param index the index of the element being requested (0 is the first element in the array)
  4064. @see operator[], getFirst, getLast
  4065. */
  4066. inline ElementType& getReference (const int index) const throw()
  4067. {
  4068. lock.enter();
  4069. jassert (((unsigned int) index) < (unsigned int) numUsed);
  4070. ElementType& result = this->elements [index];
  4071. lock.exit();
  4072. return result;
  4073. }
  4074. /** Returns the first element in the array, or 0 if the array is empty.
  4075. @see operator[], getUnchecked, getLast
  4076. */
  4077. inline ElementType getFirst() const throw()
  4078. {
  4079. lock.enter();
  4080. const ElementType result = (numUsed > 0) ? this->elements [0]
  4081. : ElementType();
  4082. lock.exit();
  4083. return result;
  4084. }
  4085. /** Returns the last element in the array, or 0 if the array is empty.
  4086. @see operator[], getUnchecked, getFirst
  4087. */
  4088. inline ElementType getLast() const throw()
  4089. {
  4090. lock.enter();
  4091. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  4092. : ElementType();
  4093. lock.exit();
  4094. return result;
  4095. }
  4096. /** Finds the index of the first element which matches the value passed in.
  4097. This will search the array for the given object, and return the index
  4098. of its first occurrence. If the object isn't found, the method will return -1.
  4099. @param elementToLookFor the value or object to look for
  4100. @returns the index of the object, or -1 if it's not found
  4101. */
  4102. int indexOf (const ElementType elementToLookFor) const throw()
  4103. {
  4104. int result = -1;
  4105. lock.enter();
  4106. const ElementType* e = this->elements;
  4107. for (int i = numUsed; --i >= 0;)
  4108. {
  4109. if (elementToLookFor == *e)
  4110. {
  4111. result = (int) (e - this->elements);
  4112. break;
  4113. }
  4114. ++e;
  4115. }
  4116. lock.exit();
  4117. return result;
  4118. }
  4119. /** Returns true if the array contains at least one occurrence of an object.
  4120. @param elementToLookFor the value or object to look for
  4121. @returns true if the item is found
  4122. */
  4123. bool contains (const ElementType elementToLookFor) const throw()
  4124. {
  4125. lock.enter();
  4126. const ElementType* e = this->elements;
  4127. int num = numUsed;
  4128. while (num >= 4)
  4129. {
  4130. if (*e == elementToLookFor
  4131. || *++e == elementToLookFor
  4132. || *++e == elementToLookFor
  4133. || *++e == elementToLookFor)
  4134. {
  4135. lock.exit();
  4136. return true;
  4137. }
  4138. num -= 4;
  4139. ++e;
  4140. }
  4141. while (num > 0)
  4142. {
  4143. if (elementToLookFor == *e)
  4144. {
  4145. lock.exit();
  4146. return true;
  4147. }
  4148. --num;
  4149. ++e;
  4150. }
  4151. lock.exit();
  4152. return false;
  4153. }
  4154. /** Appends a new element at the end of the array.
  4155. @param newElement the new object to add to the array
  4156. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  4157. */
  4158. void add (const ElementType newElement) throw()
  4159. {
  4160. lock.enter();
  4161. this->ensureAllocatedSize (numUsed + 1);
  4162. this->elements [numUsed++] = newElement;
  4163. lock.exit();
  4164. }
  4165. /** Inserts a new element into the array at a given position.
  4166. If the index is less than 0 or greater than the size of the array, the
  4167. element will be added to the end of the array.
  4168. Otherwise, it will be inserted into the array, moving all the later elements
  4169. along to make room.
  4170. @param indexToInsertAt the index at which the new element should be
  4171. inserted (pass in -1 to add it to the end)
  4172. @param newElement the new object to add to the array
  4173. @see add, addSorted, set
  4174. */
  4175. void insert (int indexToInsertAt, const ElementType newElement) throw()
  4176. {
  4177. lock.enter();
  4178. this->ensureAllocatedSize (numUsed + 1);
  4179. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  4180. {
  4181. ElementType* const insertPos = this->elements + indexToInsertAt;
  4182. const int numberToMove = numUsed - indexToInsertAt;
  4183. if (numberToMove > 0)
  4184. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  4185. *insertPos = newElement;
  4186. ++numUsed;
  4187. }
  4188. else
  4189. {
  4190. this->elements [numUsed++] = newElement;
  4191. }
  4192. lock.exit();
  4193. }
  4194. /** Inserts multiple copies of an element into the array at a given position.
  4195. If the index is less than 0 or greater than the size of the array, the
  4196. element will be added to the end of the array.
  4197. Otherwise, it will be inserted into the array, moving all the later elements
  4198. along to make room.
  4199. @param indexToInsertAt the index at which the new element should be inserted
  4200. @param newElement the new object to add to the array
  4201. @param numberOfTimesToInsertIt how many copies of the value to insert
  4202. @see insert, add, addSorted, set
  4203. */
  4204. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  4205. int numberOfTimesToInsertIt) throw()
  4206. {
  4207. if (numberOfTimesToInsertIt > 0)
  4208. {
  4209. lock.enter();
  4210. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  4211. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  4212. {
  4213. ElementType* insertPos = this->elements + indexToInsertAt;
  4214. const int numberToMove = numUsed - indexToInsertAt;
  4215. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  4216. numUsed += numberOfTimesToInsertIt;
  4217. while (--numberOfTimesToInsertIt >= 0)
  4218. *insertPos++ = newElement;
  4219. }
  4220. else
  4221. {
  4222. while (--numberOfTimesToInsertIt >= 0)
  4223. this->elements [numUsed++] = newElement;
  4224. }
  4225. lock.exit();
  4226. }
  4227. }
  4228. /** Inserts an array of values into this array at a given position.
  4229. If the index is less than 0 or greater than the size of the array, the
  4230. new elements will be added to the end of the array.
  4231. Otherwise, they will be inserted into the array, moving all the later elements
  4232. along to make room.
  4233. @param indexToInsertAt the index at which the first new element should be inserted
  4234. @param newElements the new values to add to the array
  4235. @param numberOfElements how many items are in the array
  4236. @see insert, add, addSorted, set
  4237. */
  4238. void insertArray (int indexToInsertAt,
  4239. const ElementType* newElements,
  4240. int numberOfElements) throw()
  4241. {
  4242. if (numberOfElements > 0)
  4243. {
  4244. lock.enter();
  4245. this->ensureAllocatedSize (numUsed + numberOfElements);
  4246. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  4247. {
  4248. ElementType* insertPos = this->elements + indexToInsertAt;
  4249. const int numberToMove = numUsed - indexToInsertAt;
  4250. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  4251. numUsed += numberOfElements;
  4252. while (--numberOfElements >= 0)
  4253. *insertPos++ = *newElements++;
  4254. }
  4255. else
  4256. {
  4257. while (--numberOfElements >= 0)
  4258. this->elements [numUsed++] = *newElements++;
  4259. }
  4260. lock.exit();
  4261. }
  4262. }
  4263. /** Appends a new element at the end of the array as long as the array doesn't
  4264. already contain it.
  4265. If the array already contains an element that matches the one passed in, nothing
  4266. will be done.
  4267. @param newElement the new object to add to the array
  4268. */
  4269. void addIfNotAlreadyThere (const ElementType newElement) throw()
  4270. {
  4271. lock.enter();
  4272. if (! contains (newElement))
  4273. add (newElement);
  4274. lock.exit();
  4275. }
  4276. /** Replaces an element with a new value.
  4277. If the index is less than zero, this method does nothing.
  4278. If the index is beyond the end of the array, the item is added to the end of the array.
  4279. @param indexToChange the index whose value you want to change
  4280. @param newValue the new value to set for this index.
  4281. @see add, insert
  4282. */
  4283. void set (const int indexToChange,
  4284. const ElementType newValue) throw()
  4285. {
  4286. jassert (indexToChange >= 0);
  4287. if (indexToChange >= 0)
  4288. {
  4289. lock.enter();
  4290. if (indexToChange < numUsed)
  4291. {
  4292. this->elements [indexToChange] = newValue;
  4293. }
  4294. else
  4295. {
  4296. this->ensureAllocatedSize (numUsed + 1);
  4297. this->elements [numUsed++] = newValue;
  4298. }
  4299. lock.exit();
  4300. }
  4301. }
  4302. /** Replaces an element with a new value without doing any bounds-checking.
  4303. This just sets a value directly in the array's internal storage, so you'd
  4304. better make sure it's in range!
  4305. @param indexToChange the index whose value you want to change
  4306. @param newValue the new value to set for this index.
  4307. @see set, getUnchecked
  4308. */
  4309. void setUnchecked (const int indexToChange,
  4310. const ElementType newValue) throw()
  4311. {
  4312. lock.enter();
  4313. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  4314. this->elements [indexToChange] = newValue;
  4315. lock.exit();
  4316. }
  4317. /** Adds elements from an array to the end of this array.
  4318. @param elementsToAdd the array of elements to add
  4319. @param numElementsToAdd how many elements are in this other array
  4320. @see add
  4321. */
  4322. void addArray (const ElementType* elementsToAdd,
  4323. int numElementsToAdd) throw()
  4324. {
  4325. lock.enter();
  4326. if (numElementsToAdd > 0)
  4327. {
  4328. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  4329. while (--numElementsToAdd >= 0)
  4330. this->elements [numUsed++] = *elementsToAdd++;
  4331. }
  4332. lock.exit();
  4333. }
  4334. /** This swaps the contents of this array with those of another array.
  4335. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  4336. because it just swaps their internal pointers.
  4337. */
  4338. template <class OtherArrayType>
  4339. void swapWithArray (OtherArrayType& otherArray) throw()
  4340. {
  4341. lock.enter();
  4342. otherArray.lock.enter();
  4343. swapVariables <int> (this->numUsed, otherArray.numUsed);
  4344. swapVariables <ElementType*> (this->elements, otherArray.elements);
  4345. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  4346. otherArray.lock.exit();
  4347. lock.exit();
  4348. }
  4349. /** Adds elements from another array to the end of this array.
  4350. @param arrayToAddFrom the array from which to copy the elements
  4351. @param startIndex the first element of the other array to start copying from
  4352. @param numElementsToAdd how many elements to add from the other array. If this
  4353. value is negative or greater than the number of available elements,
  4354. all available elements will be copied.
  4355. @see add
  4356. */
  4357. template <class OtherArrayType>
  4358. void addArray (const OtherArrayType& arrayToAddFrom,
  4359. int startIndex = 0,
  4360. int numElementsToAdd = -1) throw()
  4361. {
  4362. arrayToAddFrom.lockArray();
  4363. lock.enter();
  4364. jassert (this != &arrayToAddFrom);
  4365. if (startIndex < 0)
  4366. {
  4367. jassertfalse
  4368. startIndex = 0;
  4369. }
  4370. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  4371. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  4372. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  4373. lock.exit();
  4374. arrayToAddFrom.unlockArray();
  4375. }
  4376. /** Inserts a new element into the array, assuming that the array is sorted.
  4377. This will use a comparator to find the position at which the new element
  4378. should go. If the array isn't sorted, the behaviour of this
  4379. method will be unpredictable.
  4380. @param comparator the comparator to use to compare the elements - see the sort()
  4381. method for details about the form this object should take
  4382. @param newElement the new element to insert to the array
  4383. @see add, sort
  4384. */
  4385. template <class ElementComparator>
  4386. void addSorted (ElementComparator& comparator,
  4387. const ElementType newElement) throw()
  4388. {
  4389. lock.enter();
  4390. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  4391. lock.exit();
  4392. }
  4393. /** Finds the index of an element in the array, assuming that the array is sorted.
  4394. This will use a comparator to do a binary-chop to find the index of the given
  4395. element, if it exists. If the array isn't sorted, the behaviour of this
  4396. method will be unpredictable.
  4397. @param comparator the comparator to use to compare the elements - see the sort()
  4398. method for details about the form this object should take
  4399. @param elementToLookFor the element to search for
  4400. @returns the index of the element, or -1 if it's not found
  4401. @see addSorted, sort
  4402. */
  4403. template <class ElementComparator>
  4404. int indexOfSorted (ElementComparator& comparator,
  4405. const ElementType elementToLookFor) const throw()
  4406. {
  4407. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4408. // avoids getting warning messages about the parameter being unused
  4409. lock.enter();
  4410. int start = 0;
  4411. int end = numUsed;
  4412. for (;;)
  4413. {
  4414. if (start >= end)
  4415. {
  4416. lock.exit();
  4417. return -1;
  4418. }
  4419. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4420. {
  4421. lock.exit();
  4422. return start;
  4423. }
  4424. else
  4425. {
  4426. const int halfway = (start + end) >> 1;
  4427. if (halfway == start)
  4428. {
  4429. lock.exit();
  4430. return -1;
  4431. }
  4432. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4433. start = halfway;
  4434. else
  4435. end = halfway;
  4436. }
  4437. }
  4438. }
  4439. /** Removes an element from the array.
  4440. This will remove the element at a given index, and move back
  4441. all the subsequent elements to close the gap.
  4442. If the index passed in is out-of-range, nothing will happen.
  4443. @param indexToRemove the index of the element to remove
  4444. @returns the element that has been removed
  4445. @see removeValue, removeRange
  4446. */
  4447. ElementType remove (const int indexToRemove) throw()
  4448. {
  4449. lock.enter();
  4450. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4451. {
  4452. --numUsed;
  4453. ElementType* const e = this->elements + indexToRemove;
  4454. ElementType const removed = *e;
  4455. const int numberToShift = numUsed - indexToRemove;
  4456. if (numberToShift > 0)
  4457. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4458. if ((numUsed << 1) < this->numAllocated)
  4459. minimiseStorageOverheads();
  4460. lock.exit();
  4461. return removed;
  4462. }
  4463. else
  4464. {
  4465. lock.exit();
  4466. return ElementType();
  4467. }
  4468. }
  4469. /** Removes an item from the array.
  4470. This will remove the first occurrence of the given element from the array.
  4471. If the item isn't found, no action is taken.
  4472. @param valueToRemove the object to try to remove
  4473. @see remove, removeRange
  4474. */
  4475. void removeValue (const ElementType valueToRemove) throw()
  4476. {
  4477. lock.enter();
  4478. ElementType* e = this->elements;
  4479. for (int i = numUsed; --i >= 0;)
  4480. {
  4481. if (valueToRemove == *e)
  4482. {
  4483. remove ((int) (e - this->elements));
  4484. break;
  4485. }
  4486. ++e;
  4487. }
  4488. lock.exit();
  4489. }
  4490. /** Removes a range of elements from the array.
  4491. This will remove a set of elements, starting from the given index,
  4492. and move subsequent elements down to close the gap.
  4493. If the range extends beyond the bounds of the array, it will
  4494. be safely clipped to the size of the array.
  4495. @param startIndex the index of the first element to remove
  4496. @param numberToRemove how many elements should be removed
  4497. @see remove, removeValue
  4498. */
  4499. void removeRange (int startIndex,
  4500. const int numberToRemove) throw()
  4501. {
  4502. lock.enter();
  4503. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4504. startIndex = jlimit (0, numUsed, startIndex);
  4505. if (endIndex > startIndex)
  4506. {
  4507. const int rangeSize = endIndex - startIndex;
  4508. ElementType* e = this->elements + startIndex;
  4509. int numToShift = numUsed - endIndex;
  4510. numUsed -= rangeSize;
  4511. while (--numToShift >= 0)
  4512. {
  4513. *e = e [rangeSize];
  4514. ++e;
  4515. }
  4516. if ((numUsed << 1) < this->numAllocated)
  4517. minimiseStorageOverheads();
  4518. }
  4519. lock.exit();
  4520. }
  4521. /** Removes the last n elements from the array.
  4522. @param howManyToRemove how many elements to remove from the end of the array
  4523. @see remove, removeValue, removeRange
  4524. */
  4525. void removeLast (const int howManyToRemove = 1) throw()
  4526. {
  4527. lock.enter();
  4528. numUsed = jmax (0, numUsed - howManyToRemove);
  4529. if ((numUsed << 1) < this->numAllocated)
  4530. minimiseStorageOverheads();
  4531. lock.exit();
  4532. }
  4533. /** Removes any elements which are also in another array.
  4534. @param otherArray the other array in which to look for elements to remove
  4535. @see removeValuesNotIn, remove, removeValue, removeRange
  4536. */
  4537. template <class OtherArrayType>
  4538. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4539. {
  4540. otherArray.lockArray();
  4541. lock.enter();
  4542. if (this == &otherArray)
  4543. {
  4544. clear();
  4545. }
  4546. else
  4547. {
  4548. if (otherArray.size() > 0)
  4549. {
  4550. for (int i = numUsed; --i >= 0;)
  4551. if (otherArray.contains (this->elements [i]))
  4552. remove (i);
  4553. }
  4554. }
  4555. lock.exit();
  4556. otherArray.unlockArray();
  4557. }
  4558. /** Removes any elements which are not found in another array.
  4559. Only elements which occur in this other array will be retained.
  4560. @param otherArray the array in which to look for elements NOT to remove
  4561. @see removeValuesIn, remove, removeValue, removeRange
  4562. */
  4563. template <class OtherArrayType>
  4564. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4565. {
  4566. otherArray.lockArray();
  4567. lock.enter();
  4568. if (this != &otherArray)
  4569. {
  4570. if (otherArray.size() <= 0)
  4571. {
  4572. clear();
  4573. }
  4574. else
  4575. {
  4576. for (int i = numUsed; --i >= 0;)
  4577. if (! otherArray.contains (this->elements [i]))
  4578. remove (i);
  4579. }
  4580. }
  4581. lock.exit();
  4582. otherArray.unlockArray();
  4583. }
  4584. /** Swaps over two elements in the array.
  4585. This swaps over the elements found at the two indexes passed in.
  4586. If either index is out-of-range, this method will do nothing.
  4587. @param index1 index of one of the elements to swap
  4588. @param index2 index of the other element to swap
  4589. */
  4590. void swap (const int index1,
  4591. const int index2) throw()
  4592. {
  4593. lock.enter();
  4594. if (((unsigned int) index1) < (unsigned int) numUsed
  4595. && ((unsigned int) index2) < (unsigned int) numUsed)
  4596. {
  4597. swapVariables (this->elements [index1],
  4598. this->elements [index2]);
  4599. }
  4600. lock.exit();
  4601. }
  4602. /** Moves one of the values to a different position.
  4603. This will move the value to a specified index, shuffling along
  4604. any intervening elements as required.
  4605. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4606. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4607. @param currentIndex the index of the value to be moved. If this isn't a
  4608. valid index, then nothing will be done
  4609. @param newIndex the index at which you'd like this value to end up. If this
  4610. is less than zero, the value will be moved to the end
  4611. of the array
  4612. */
  4613. void move (const int currentIndex,
  4614. int newIndex) throw()
  4615. {
  4616. if (currentIndex != newIndex)
  4617. {
  4618. lock.enter();
  4619. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4620. {
  4621. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4622. newIndex = numUsed - 1;
  4623. const ElementType value = this->elements [currentIndex];
  4624. if (newIndex > currentIndex)
  4625. {
  4626. memmove (this->elements + currentIndex,
  4627. this->elements + currentIndex + 1,
  4628. (newIndex - currentIndex) * sizeof (ElementType));
  4629. }
  4630. else
  4631. {
  4632. memmove (this->elements + newIndex + 1,
  4633. this->elements + newIndex,
  4634. (currentIndex - newIndex) * sizeof (ElementType));
  4635. }
  4636. this->elements [newIndex] = value;
  4637. }
  4638. lock.exit();
  4639. }
  4640. }
  4641. /** Reduces the amount of storage being used by the array.
  4642. Arrays typically allocate slightly more storage than they need, and after
  4643. removing elements, they may have quite a lot of unused space allocated.
  4644. This method will reduce the amount of allocated storage to a minimum.
  4645. */
  4646. void minimiseStorageOverheads() throw()
  4647. {
  4648. lock.enter();
  4649. if (numUsed == 0)
  4650. {
  4651. this->setAllocatedSize (0);
  4652. }
  4653. else
  4654. {
  4655. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4656. if (newAllocation < this->numAllocated)
  4657. this->setAllocatedSize (newAllocation);
  4658. }
  4659. lock.exit();
  4660. }
  4661. /** Increases the array's internal storage to hold a minimum number of elements.
  4662. Calling this before adding a large known number of elements means that
  4663. the array won't have to keep dynamically resizing itself as the elements
  4664. are added, and it'll therefore be more efficient.
  4665. */
  4666. void ensureStorageAllocated (const int minNumElements) throw()
  4667. {
  4668. this->ensureAllocatedSize (minNumElements);
  4669. }
  4670. /** Sorts the elements in the array.
  4671. This will use a comparator object to sort the elements into order. The object
  4672. passed must have a method of the form:
  4673. @code
  4674. int compareElements (ElementType first, ElementType second);
  4675. @endcode
  4676. ..and this method must return:
  4677. - a value of < 0 if the first comes before the second
  4678. - a value of 0 if the two objects are equivalent
  4679. - a value of > 0 if the second comes before the first
  4680. To improve performance, the compareElements() method can be declared as static or const.
  4681. @param comparator the comparator to use for comparing elements.
  4682. @param retainOrderOfEquivalentItems if this is true, then items
  4683. which the comparator says are equivalent will be
  4684. kept in the order in which they currently appear
  4685. in the array. This is slower to perform, but may
  4686. be important in some cases. If it's false, a faster
  4687. algorithm is used, but equivalent elements may be
  4688. rearranged.
  4689. @see addSorted, indexOfSorted, sortArray
  4690. */
  4691. template <class ElementComparator>
  4692. void sort (ElementComparator& comparator,
  4693. const bool retainOrderOfEquivalentItems = false) const throw()
  4694. {
  4695. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4696. // avoids getting warning messages about the parameter being unused
  4697. lock.enter();
  4698. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4699. lock.exit();
  4700. }
  4701. /** Locks the array's CriticalSection.
  4702. Of course if the type of section used is a DummyCriticalSection, this won't
  4703. have any effect.
  4704. @see unlockArray
  4705. */
  4706. void lockArray() const throw()
  4707. {
  4708. lock.enter();
  4709. }
  4710. /** Unlocks the array's CriticalSection.
  4711. Of course if the type of section used is a DummyCriticalSection, this won't
  4712. have any effect.
  4713. @see lockArray
  4714. */
  4715. void unlockArray() const throw()
  4716. {
  4717. lock.exit();
  4718. }
  4719. juce_UseDebuggingNewOperator
  4720. private:
  4721. int numUsed;
  4722. TypeOfCriticalSectionToUse lock;
  4723. };
  4724. #endif // __JUCE_ARRAY_JUCEHEADER__
  4725. /********* End of inlined file: juce_Array.h *********/
  4726. /**
  4727. A typedef for an Array of void*'s.
  4728. VoidArrays are used in various places throughout the library instead of
  4729. more strongly-typed arrays, to keep code-size low.
  4730. */
  4731. typedef Array <void*> VoidArray;
  4732. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4733. /********* End of inlined file: juce_VoidArray.h *********/
  4734. #ifndef DOXYGEN
  4735. // (used in StringArray::appendNumbersToDuplicates)
  4736. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4737. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4738. #endif
  4739. /**
  4740. A special array for holding a list of strings.
  4741. @see String, StringPairArray
  4742. */
  4743. class JUCE_API StringArray
  4744. {
  4745. public:
  4746. /** Creates an empty string array */
  4747. StringArray() throw();
  4748. /** Creates a copy of another string array */
  4749. StringArray (const StringArray& other) throw();
  4750. /** Creates a copy of an array of string literals.
  4751. @param strings an array of strings to add. Null pointers in the array will be
  4752. treated as empty strings
  4753. @param numberOfStrings how many items there are in the array
  4754. */
  4755. StringArray (const juce_wchar** const strings,
  4756. const int numberOfStrings) throw();
  4757. /** Creates a copy of an array of string literals.
  4758. @param strings an array of strings to add. Null pointers in the array will be
  4759. treated as empty strings
  4760. @param numberOfStrings how many items there are in the array
  4761. */
  4762. StringArray (const char** const strings,
  4763. const int numberOfStrings) throw();
  4764. /** Creates a copy of a null-terminated array of string literals.
  4765. Each item from the array passed-in is added, until it encounters a null pointer,
  4766. at which point it stops.
  4767. */
  4768. StringArray (const juce_wchar** const strings) throw();
  4769. /** Creates a copy of a null-terminated array of string literals.
  4770. Each item from the array passed-in is added, until it encounters a null pointer,
  4771. at which point it stops.
  4772. */
  4773. StringArray (const char** const strings) throw();
  4774. /** Destructor. */
  4775. virtual ~StringArray() throw();
  4776. /** Copies the contents of another string array into this one */
  4777. const StringArray& operator= (const StringArray& other) throw();
  4778. /** Compares two arrays.
  4779. Comparisons are case-sensitive.
  4780. @returns true only if the other array contains exactly the same strings in the same order
  4781. */
  4782. bool operator== (const StringArray& other) const throw();
  4783. /** Compares two arrays.
  4784. Comparisons are case-sensitive.
  4785. @returns false if the other array contains exactly the same strings in the same order
  4786. */
  4787. bool operator!= (const StringArray& other) const throw();
  4788. /** Returns the number of strings in the array */
  4789. inline int size() const throw() { return strings.size(); };
  4790. /** Returns one of the strings from the array.
  4791. If the index is out-of-range, an empty string is returned.
  4792. Obviously the reference returned shouldn't be stored for later use, as the
  4793. string it refers to may disappear when the array changes.
  4794. */
  4795. const String& operator[] (const int index) const throw();
  4796. /** Searches for a string in the array.
  4797. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4798. @returns true if the string is found inside the array
  4799. */
  4800. bool contains (const String& stringToLookFor,
  4801. const bool ignoreCase = false) const throw();
  4802. /** Searches for a string in the array.
  4803. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4804. @param stringToLookFor the string to try to find
  4805. @param ignoreCase whether the comparison should be case-insensitive
  4806. @param startIndex the first index to start searching from
  4807. @returns the index of the first occurrence of the string in this array,
  4808. or -1 if it isn't found.
  4809. */
  4810. int indexOf (const String& stringToLookFor,
  4811. const bool ignoreCase = false,
  4812. int startIndex = 0) const throw();
  4813. /** Appends a string at the end of the array. */
  4814. void add (const String& stringToAdd) throw();
  4815. /** Inserts a string into the array.
  4816. This will insert a string into the array at the given index, moving
  4817. up the other elements to make room for it.
  4818. If the index is less than zero or greater than the size of the array,
  4819. the new string will be added to the end of the array.
  4820. */
  4821. void insert (const int index,
  4822. const String& stringToAdd) throw();
  4823. /** Adds a string to the array as long as it's not already in there.
  4824. The search can optionally be case-insensitive.
  4825. */
  4826. void addIfNotAlreadyThere (const String& stringToAdd,
  4827. const bool ignoreCase = false) throw();
  4828. /** Replaces one of the strings in the array with another one.
  4829. If the index is higher than the array's size, the new string will be
  4830. added to the end of the array; if it's less than zero nothing happens.
  4831. */
  4832. void set (const int index,
  4833. const String& newString) throw();
  4834. /** Appends some strings from another array to the end of this one.
  4835. @param other the array to add
  4836. @param startIndex the first element of the other array to add
  4837. @param numElementsToAdd the maximum number of elements to add (if this is
  4838. less than zero, they are all added)
  4839. */
  4840. void addArray (const StringArray& other,
  4841. int startIndex = 0,
  4842. int numElementsToAdd = -1) throw();
  4843. /** Breaks up a string into tokens and adds them to this array.
  4844. This will tokenise the given string using whitespace characters as the
  4845. token delimiters, and will add these tokens to the end of the array.
  4846. @returns the number of tokens added
  4847. */
  4848. int addTokens (const tchar* const stringToTokenise,
  4849. const bool preserveQuotedStrings) throw();
  4850. /** Breaks up a string into tokens and adds them to this array.
  4851. This will tokenise the given string (using the string passed in to define the
  4852. token delimiters), and will add these tokens to the end of the array.
  4853. @param stringToTokenise the string to tokenise
  4854. @param breakCharacters a string of characters, any of which will be considered
  4855. to be a token delimiter.
  4856. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4857. which are treated as quotes. Any text occurring
  4858. between quotes is not broken up into tokens.
  4859. @returns the number of tokens added
  4860. */
  4861. int addTokens (const tchar* const stringToTokenise,
  4862. const tchar* breakCharacters,
  4863. const tchar* quoteCharacters) throw();
  4864. /** Breaks up a string into lines and adds them to this array.
  4865. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4866. to the array. Line-break characters are omitted from the strings that are added to
  4867. the array.
  4868. */
  4869. int addLines (const tchar* stringToBreakUp) throw();
  4870. /** Removes all elements from the array. */
  4871. void clear() throw();
  4872. /** Removes a string from the array.
  4873. If the index is out-of-range, no action will be taken.
  4874. */
  4875. void remove (const int index) throw();
  4876. /** Finds a string in the array and removes it.
  4877. This will remove the first occurrence of the given string from the array. The
  4878. comparison may be case-insensitive depending on the ignoreCase parameter.
  4879. */
  4880. void removeString (const String& stringToRemove,
  4881. const bool ignoreCase = false) throw();
  4882. /** Removes any duplicated elements from the array.
  4883. If any string appears in the array more than once, only the first occurrence of
  4884. it will be retained.
  4885. @param ignoreCase whether to use a case-insensitive comparison
  4886. */
  4887. void removeDuplicates (const bool ignoreCase) throw();
  4888. /** Removes empty strings from the array.
  4889. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4890. characters will also be removed
  4891. */
  4892. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4893. /** Moves one of the strings to a different position.
  4894. This will move the string to a specified index, shuffling along
  4895. any intervening elements as required.
  4896. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4897. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4898. @param currentIndex the index of the value to be moved. If this isn't a
  4899. valid index, then nothing will be done
  4900. @param newIndex the index at which you'd like this value to end up. If this
  4901. is less than zero, the value will be moved to the end
  4902. of the array
  4903. */
  4904. void move (const int currentIndex, int newIndex) throw();
  4905. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4906. void trim() throw();
  4907. /** Adds numbers to the strings in the array, to make each string unique.
  4908. This will add numbers to the ends of groups of similar strings.
  4909. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4910. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4911. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4912. also has a number appended to it.
  4913. @param preNumberString when adding a number, this string is added before the number
  4914. @param postNumberString this string is appended after any numbers that are added
  4915. */
  4916. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4917. const bool appendNumberToFirstInstance,
  4918. const tchar* const preNumberString = defaultPreNumberString,
  4919. const tchar* const postNumberString = defaultPostNumberString) throw();
  4920. /** Joins the strings in the array together into one string.
  4921. This will join a range of elements from the array into a string, separating
  4922. them with a given string.
  4923. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4924. @param separatorString the string to insert between all the strings
  4925. @param startIndex the first element to join
  4926. @param numberOfElements how many elements to join together. If this is less
  4927. than zero, all available elements will be used.
  4928. */
  4929. const String joinIntoString (const String& separatorString,
  4930. int startIndex = 0,
  4931. int numberOfElements = -1) const throw();
  4932. /** Sorts the array into alphabetical order.
  4933. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4934. */
  4935. void sort (const bool ignoreCase) throw();
  4936. /** Reduces the amount of storage being used by the array.
  4937. Arrays typically allocate slightly more storage than they need, and after
  4938. removing elements, they may have quite a lot of unused space allocated.
  4939. This method will reduce the amount of allocated storage to a minimum.
  4940. */
  4941. void minimiseStorageOverheads() throw();
  4942. juce_UseDebuggingNewOperator
  4943. private:
  4944. VoidArray strings;
  4945. };
  4946. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4947. /********* End of inlined file: juce_StringArray.h *********/
  4948. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4949. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4950. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4951. /**
  4952. A class to hold a resizable block of raw data.
  4953. */
  4954. class JUCE_API MemoryBlock
  4955. {
  4956. public:
  4957. /** Create an uninitialised block with 0 size. */
  4958. MemoryBlock() throw();
  4959. /** Creates a memory block with a given initial size.
  4960. @param initialSize the size of block to create
  4961. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4962. */
  4963. MemoryBlock (const int initialSize,
  4964. const bool initialiseToZero = false) throw();
  4965. /** Creates a copy of another memory block. */
  4966. MemoryBlock (const MemoryBlock& other) throw();
  4967. /** Creates a memory block using a copy of a block of data.
  4968. @param dataToInitialiseFrom some data to copy into this block
  4969. @param sizeInBytes how much space to use
  4970. */
  4971. MemoryBlock (const void* const dataToInitialiseFrom,
  4972. const int sizeInBytes) throw();
  4973. /** Destructor. */
  4974. ~MemoryBlock() throw();
  4975. /** Copies another memory block onto this one.
  4976. This block will be resized and copied to exactly match the other one.
  4977. */
  4978. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4979. /** Compares two memory blocks.
  4980. @returns true only if the two blocks are the same size and have identical contents.
  4981. */
  4982. bool operator== (const MemoryBlock& other) const throw();
  4983. /** Compares two memory blocks.
  4984. @returns true if the two blocks are different sizes or have different contents.
  4985. */
  4986. bool operator!= (const MemoryBlock& other) const throw();
  4987. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4988. Note that the pointer returned will probably become invalid when the
  4989. block is resized.
  4990. */
  4991. template <class DataType>
  4992. operator DataType*() const throw() { return (DataType*) data; }
  4993. /** Returns a void pointer to the data.
  4994. Note that the pointer returned will probably become invalid when the
  4995. block is resized.
  4996. */
  4997. void* getData() const throw() { return data; }
  4998. /** Returns a byte from the memory block.
  4999. This returns a reference, so you can also use it to set a byte.
  5000. */
  5001. char& operator[] (const int offset) const throw() { return data [offset]; }
  5002. /** Returns the block's current allocated size, in bytes. */
  5003. int getSize() const throw() { return size; }
  5004. /** Resizes the memory block.
  5005. This will try to keep as much of the block's current content as it can,
  5006. and can optionally be made to clear any new space that gets allocated at
  5007. the end of the block.
  5008. @param newSize the new desired size for the block
  5009. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  5010. whether to clear the new section or just leave it
  5011. uninitialised
  5012. @see ensureSize
  5013. */
  5014. void setSize (const int newSize,
  5015. const bool initialiseNewSpaceToZero = false) throw();
  5016. /** Increases the block's size only if it's smaller than a given size.
  5017. @param minimumSize if the block is already bigger than this size, no action
  5018. will be taken; otherwise it will be increased to this size
  5019. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  5020. whether to clear the new section or just leave it
  5021. uninitialised
  5022. @see setSize
  5023. */
  5024. void ensureSize (const int minimumSize,
  5025. const bool initialiseNewSpaceToZero = false) throw();
  5026. /** Fills the entire memory block with a repeated byte value.
  5027. This is handy for clearing a block of memory to zero.
  5028. */
  5029. void fillWith (const uint8 valueToUse) throw();
  5030. /** Adds another block of data to the end of this one.
  5031. This block's size will be increased accordingly.
  5032. */
  5033. void append (const void* const data,
  5034. const int numBytes) throw();
  5035. /** Copies data into this MemoryBlock from a memory address.
  5036. @param srcData the memory location of the data to copy into this block
  5037. @param destinationOffset the offset in this block at which the data being copied should begin
  5038. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  5039. it will be clipped so not to do anything nasty)
  5040. */
  5041. void copyFrom (const void* srcData,
  5042. int destinationOffset,
  5043. int numBytes) throw();
  5044. /** Copies data from this MemoryBlock to a memory address.
  5045. @param destData the memory location to write to
  5046. @param sourceOffset the offset within this block from which the copied data will be read
  5047. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  5048. zeros will be used for that portion of the data)
  5049. */
  5050. void copyTo (void* destData,
  5051. int sourceOffset,
  5052. int numBytes) const throw();
  5053. /** Chops out a section of the block.
  5054. This will remove a section of the memory block and close the gap around it,
  5055. shifting any subsequent data downwards and reducing the size of the block.
  5056. If the range specified goes beyond the size of the block, it will be clipped.
  5057. */
  5058. void removeSection (int startByte, int numBytesToRemove) throw();
  5059. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  5060. characters in the system's default encoding. */
  5061. const String toString() const throw();
  5062. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  5063. The block will be resized to the number of valid bytes read from the string.
  5064. Non-hex characters in the string will be ignored.
  5065. @see String::toHexString()
  5066. */
  5067. void loadFromHexString (const String& sourceHexString) throw();
  5068. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  5069. void setBitRange (int bitRangeStart,
  5070. int numBits,
  5071. int binaryNumberToApply) throw();
  5072. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  5073. int getBitRange (int bitRangeStart,
  5074. int numBitsToRead) const throw();
  5075. /** Returns a string of characters that represent the binary contents of this block.
  5076. Uses a 64-bit encoding system to allow binary data to be turned into a string
  5077. of simple non-extended characters, e.g. for storage in XML.
  5078. @see fromBase64Encoding
  5079. */
  5080. const String toBase64Encoding() const throw();
  5081. /** Takes a string of encoded characters and turns it into binary data.
  5082. The string passed in must have been created by to64BitEncoding(), and this
  5083. block will be resized to recreate the original data block.
  5084. @see toBase64Encoding
  5085. */
  5086. bool fromBase64Encoding (const String& encodedString) throw();
  5087. juce_UseDebuggingNewOperator
  5088. private:
  5089. char* data;
  5090. int size;
  5091. };
  5092. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  5093. /********* End of inlined file: juce_MemoryBlock.h *********/
  5094. class FileInputStream;
  5095. class FileOutputStream;
  5096. /**
  5097. Represents a local file or directory.
  5098. This class encapsulates the absolute pathname of a file or directory, and
  5099. has methods for finding out about the file and changing its properties.
  5100. To read or write to the file, there are methods for returning an input or
  5101. output stream.
  5102. @see FileInputStream, FileOutputStream
  5103. */
  5104. class JUCE_API File
  5105. {
  5106. public:
  5107. /** Creates an (invalid) file object.
  5108. The file is initially set to an empty path, so getFullPath() will return
  5109. an empty string, and comparing the file to File::nonexistent will return
  5110. true.
  5111. You can use its operator= method to point it at a proper file.
  5112. */
  5113. File() throw() {}
  5114. /** Creates a file from an absolute path.
  5115. If the path supplied is a relative path, it is taken to be relative
  5116. to the current working directory (see File::getCurrentWorkingDirectory()),
  5117. but this isn't a recommended way of creating a file, because you
  5118. never know what the CWD is going to be.
  5119. On the Mac/Linux, the path can include "~" notation for referring to
  5120. user home directories.
  5121. */
  5122. File (const String& path) throw();
  5123. /** Creates a copy of another file object. */
  5124. File (const File& other) throw();
  5125. /** Destructor. */
  5126. ~File() throw() {}
  5127. /** Sets the file based on an absolute pathname.
  5128. If the path supplied is a relative path, it is taken to be relative
  5129. to the current working directory (see File::getCurrentWorkingDirectory()),
  5130. but this isn't a recommended way of creating a file, because you
  5131. never know what the CWD is going to be.
  5132. On the Mac/Linux, the path can include "~" notation for referring to
  5133. user home directories.
  5134. */
  5135. const File& operator= (const String& newFilePath) throw();
  5136. /** Copies from another file object. */
  5137. const File& operator= (const File& otherFile) throw();
  5138. /** This static constant is used for referring to an 'invalid' file. */
  5139. static const File nonexistent;
  5140. /** Checks whether the file actually exists.
  5141. @returns true if the file exists, either as a file or a directory.
  5142. @see existsAsFile, isDirectory
  5143. */
  5144. bool exists() const throw();
  5145. /** Checks whether the file exists and is a file rather than a directory.
  5146. @returns true only if this is a real file, false if it's a directory
  5147. or doesn't exist
  5148. @see exists, isDirectory
  5149. */
  5150. bool existsAsFile() const throw();
  5151. /** Checks whether the file is a directory that exists.
  5152. @returns true only if the file is a directory which actually exists, so
  5153. false if it's a file or doesn't exist at all
  5154. @see exists, existsAsFile
  5155. */
  5156. bool isDirectory() const throw();
  5157. /** Returns the size of the file in bytes.
  5158. @returns the number of bytes in the file, or 0 if it doesn't exist.
  5159. */
  5160. int64 getSize() const throw();
  5161. /** Utility function to convert a file size in bytes to a neat string description.
  5162. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  5163. 2000000 would produce "2 MB", etc.
  5164. */
  5165. static const String descriptionOfSizeInBytes (const int64 bytes);
  5166. /** Returns the complete, absolute path of this file.
  5167. This includes the filename and all its parent folders. On Windows it'll
  5168. also include the drive letter prefix; on Mac or Linux it'll be a complete
  5169. path starting from the root folder.
  5170. If you just want the file's name, you should use getFileName() or
  5171. getFileNameWithoutExtension().
  5172. @see getFileName, getRelativePathFrom
  5173. */
  5174. const String& getFullPathName() const throw() { return fullPath; }
  5175. /** Returns the last section of the pathname.
  5176. Returns just the final part of the path - e.g. if the whole path
  5177. is "/moose/fish/foo.txt" this will return "foo.txt".
  5178. For a directory, it returns the final part of the path - e.g. for the
  5179. directory "/moose/fish" it'll return "fish".
  5180. If the filename begins with a dot, it'll return the whole filename, e.g. for
  5181. "/moose/.fish", it'll return ".fish"
  5182. @see getFullPathName, getFileNameWithoutExtension
  5183. */
  5184. const String getFileName() const throw();
  5185. /** Creates a relative path that refers to a file relatively to a given directory.
  5186. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  5187. would return "../../foo.txt".
  5188. If it's not possible to navigate from one file to the other, an absolute
  5189. path is returned. If the paths are invalid, an empty string may also be
  5190. returned.
  5191. @param directoryToBeRelativeTo the directory which the resultant string will
  5192. be relative to. If this is actually a file rather than
  5193. a directory, its parent directory will be used instead.
  5194. If it doesn't exist, it's assumed to be a directory.
  5195. @see getChildFile, isAbsolutePath
  5196. */
  5197. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  5198. /** Returns the file's extension.
  5199. Returns the file extension of this file, also including the dot.
  5200. e.g. "/moose/fish/foo.txt" would return ".txt"
  5201. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  5202. */
  5203. const String getFileExtension() const throw();
  5204. /** Checks whether the file has a given extension.
  5205. @param extensionToTest the extension to look for - it doesn't matter whether or
  5206. not this string has a dot at the start, so ".wav" and "wav"
  5207. will have the same effect. The comparison used is
  5208. case-insensitve.
  5209. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  5210. */
  5211. bool hasFileExtension (const String& extensionToTest) const throw();
  5212. /** Returns a version of this file with a different file extension.
  5213. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  5214. @param newExtension the new extension, either with or without a dot at the start (this
  5215. doesn't make any difference). To get remove a file's extension altogether,
  5216. pass an empty string into this function.
  5217. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  5218. */
  5219. const File withFileExtension (const String& newExtension) const throw();
  5220. /** Returns the last part of the filename, without its file extension.
  5221. e.g. for "/moose/fish/foo.txt" this will return "foo".
  5222. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  5223. */
  5224. const String getFileNameWithoutExtension() const throw();
  5225. /** Returns a 32-bit hash-code that identifies this file.
  5226. This is based on the filename. Obviously it's possible, although unlikely, that
  5227. two files will have the same hash-code.
  5228. */
  5229. int hashCode() const throw();
  5230. /** Returns a 64-bit hash-code that identifies this file.
  5231. This is based on the filename. Obviously it's possible, although unlikely, that
  5232. two files will have the same hash-code.
  5233. */
  5234. int64 hashCode64() const throw();
  5235. /** Returns a file based on a relative path.
  5236. This will find a child file or directory of the current object.
  5237. e.g.
  5238. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  5239. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  5240. If the string is actually an absolute path, it will be treated as such, e.g.
  5241. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  5242. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  5243. */
  5244. const File getChildFile (String relativePath) const throw();
  5245. /** Returns a file which is in the same directory as this one.
  5246. This is equivalent to getParentDirectory().getChildFile (name).
  5247. @see getChildFile, getParentDirectory
  5248. */
  5249. const File getSiblingFile (const String& siblingFileName) const throw();
  5250. /** Returns the directory that contains this file or directory.
  5251. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  5252. */
  5253. const File getParentDirectory() const throw();
  5254. /** Checks whether a file is somewhere inside a directory.
  5255. Returns true if this file is somewhere inside a subdirectory of the directory
  5256. that is passed in. Neither file actually has to exist, because the function
  5257. just checks the paths for similarities.
  5258. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  5259. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  5260. */
  5261. bool isAChildOf (const File& potentialParentDirectory) const throw();
  5262. /** Chooses a filename relative to this one that doesn't already exist.
  5263. If this file is a directory, this will return a child file of this
  5264. directory that doesn't exist, by adding numbers to a prefix and suffix until
  5265. it finds one that isn't already there.
  5266. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  5267. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  5268. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  5269. @param prefix the string to use for the filename before the number
  5270. @param suffix the string to add to the filename after the number
  5271. @param putNumbersInBrackets if true, this will create filenames in the
  5272. format "prefix(number)suffix", if false, it will leave the
  5273. brackets out.
  5274. */
  5275. const File getNonexistentChildFile (const String& prefix,
  5276. const String& suffix,
  5277. bool putNumbersInBrackets = true) const throw();
  5278. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  5279. If this file doesn't exist, this will just return itself, otherwise it
  5280. will return an appropriate sibling that doesn't exist, e.g. if a file
  5281. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  5282. @param putNumbersInBrackets whether to add brackets around the numbers that
  5283. get appended to the new filename.
  5284. */
  5285. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  5286. /** Compares the pathnames for two files. */
  5287. bool operator== (const File& otherFile) const throw();
  5288. /** Compares the pathnames for two files. */
  5289. bool operator!= (const File& otherFile) const throw();
  5290. /** Checks whether a file can be created or written to.
  5291. @returns true if it's possible to create and write to this file. If the file
  5292. doesn't already exist, this will check its parent directory to
  5293. see if writing is allowed.
  5294. @see setReadOnly
  5295. */
  5296. bool hasWriteAccess() const throw();
  5297. /** Changes the write-permission of a file or directory.
  5298. @param shouldBeReadOnly whether to add or remove write-permission
  5299. @param applyRecursively if the file is a directory and this is true, it will
  5300. recurse through all the subfolders changing the permissions
  5301. of all files
  5302. @returns true if it manages to change the file's permissions.
  5303. @see hasWriteAccess
  5304. */
  5305. bool setReadOnly (const bool shouldBeReadOnly,
  5306. const bool applyRecursively = false) const throw();
  5307. /** Returns true if this file is a hidden or system file.
  5308. The criteria for deciding whether a file is hidden are platform-dependent.
  5309. */
  5310. bool isHidden() const throw();
  5311. /** Returns the last modification time of this file.
  5312. @returns the time, or an invalid time if the file doesn't exist.
  5313. @see setLastModificationTime, getLastAccessTime, getCreationTime
  5314. */
  5315. const Time getLastModificationTime() const throw();
  5316. /** Returns the last time this file was accessed.
  5317. @returns the time, or an invalid time if the file doesn't exist.
  5318. @see setLastAccessTime, getLastModificationTime, getCreationTime
  5319. */
  5320. const Time getLastAccessTime() const throw();
  5321. /** Returns the time that this file was created.
  5322. @returns the time, or an invalid time if the file doesn't exist.
  5323. @see getLastModificationTime, getLastAccessTime
  5324. */
  5325. const Time getCreationTime() const throw();
  5326. /** Changes the modification time for this file.
  5327. @param newTime the time to apply to the file
  5328. @returns true if it manages to change the file's time.
  5329. @see getLastModificationTime, setLastAccessTime, setCreationTime
  5330. */
  5331. bool setLastModificationTime (const Time& newTime) const throw();
  5332. /** Changes the last-access time for this file.
  5333. @param newTime the time to apply to the file
  5334. @returns true if it manages to change the file's time.
  5335. @see getLastAccessTime, setLastModificationTime, setCreationTime
  5336. */
  5337. bool setLastAccessTime (const Time& newTime) const throw();
  5338. /** Changes the creation date for this file.
  5339. @param newTime the time to apply to the file
  5340. @returns true if it manages to change the file's time.
  5341. @see getCreationTime, setLastModificationTime, setLastAccessTime
  5342. */
  5343. bool setCreationTime (const Time& newTime) const throw();
  5344. /** Creates an empty file if it doesn't already exist.
  5345. If the file that this object refers to doesn't exist, this will create a file
  5346. of zero size.
  5347. If it already exists or is a directory, this method will do nothing.
  5348. @returns true if the file has been created (or if it already existed).
  5349. @see createDirectory
  5350. */
  5351. bool create() const throw();
  5352. /** Creates a new directory for this filename.
  5353. This will try to create the file as a directory, and fill also create
  5354. any parent directories it needs in order to complete the operation.
  5355. @returns true if the directory has been created successfully, (or if it
  5356. already existed beforehand).
  5357. @see create
  5358. */
  5359. bool createDirectory() const throw();
  5360. /** Deletes a file.
  5361. If this file is actually a directory, it may not be deleted correctly if it
  5362. contains files. See deleteRecursively() as a better way of deleting directories.
  5363. @returns true if the file has been successfully deleted (or if it didn't exist to
  5364. begin with).
  5365. @see deleteRecursively
  5366. */
  5367. bool deleteFile() const throw();
  5368. /** Deletes a file or directory and all its subdirectories.
  5369. If this file is a directory, this will try to delete it and all its subfolders. If
  5370. it's just a file, it will just try to delete the file.
  5371. @returns true if the file and all its subfolders have been successfully deleted
  5372. (or if it didn't exist to begin with).
  5373. @see deleteFile
  5374. */
  5375. bool deleteRecursively() const throw();
  5376. /** Moves or renames a file.
  5377. Tries to move a file to a different location.
  5378. If the target file already exists, this will attempt to delete it first, and
  5379. will fail if this can't be done.
  5380. Note that the destination file isn't the directory to put it in, it's the actual
  5381. filename that you want the new file to have.
  5382. @returns true if the operation succeeds
  5383. */
  5384. bool moveFileTo (const File& targetLocation) const throw();
  5385. /** Copies a file.
  5386. Tries to copy a file to a different location.
  5387. If the target file already exists, this will attempt to delete it first, and
  5388. will fail if this can't be done.
  5389. @returns true if the operation succeeds
  5390. */
  5391. bool copyFileTo (const File& targetLocation) const throw();
  5392. /** Copies a directory.
  5393. Tries to copy an entire directory, recursively.
  5394. If this file isn't a directory or if any target files can't be created, this
  5395. will return false.
  5396. @param newDirectory the directory that this one should be copied to. Note that this
  5397. is the name of the actual directory to create, not the directory
  5398. into which the new one should be placed, so there must be enough
  5399. write privileges to create it if it doesn't exist. Any files inside
  5400. it will be overwritten by similarly named ones that are copied.
  5401. */
  5402. bool copyDirectoryTo (const File& newDirectory) const throw();
  5403. /** Used in file searching, to specify whether to return files, directories, or both.
  5404. */
  5405. enum TypesOfFileToFind
  5406. {
  5407. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5408. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5409. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5410. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5411. };
  5412. /** Searches inside a directory for files matching a wildcard pattern.
  5413. Assuming that this file is a directory, this method will search it
  5414. for either files or subdirectories whose names match a filename pattern.
  5415. @param results an array to which File objects will be added for the
  5416. files that the search comes up with
  5417. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5418. return files, directories, or both. If the ignoreHiddenFiles flag
  5419. is also added to this value, hidden files won't be returned
  5420. @param searchRecursively if true, all subdirectories will be recursed into to do
  5421. an exhaustive search
  5422. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5423. @returns the number of results that have been found
  5424. @see getNumberOfChildFiles, DirectoryIterator
  5425. */
  5426. int findChildFiles (OwnedArray<File>& results,
  5427. const int whatToLookFor,
  5428. const bool searchRecursively,
  5429. const String& wildCardPattern = JUCE_T("*")) const throw();
  5430. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5431. Assuming that this file is a directory, this method will search it
  5432. for either files or subdirectories whose names match a filename pattern,
  5433. and will return the number of matches found.
  5434. This isn't a recursive call, and will only search this directory, not
  5435. its children.
  5436. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5437. count files, directories, or both. If the ignoreHiddenFiles flag
  5438. is also added to this value, hidden files won't be counted
  5439. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5440. @returns the number of matches found
  5441. @see findChildFiles, DirectoryIterator
  5442. */
  5443. int getNumberOfChildFiles (const int whatToLookFor,
  5444. const String& wildCardPattern = JUCE_T("*")) const throw();
  5445. /** Creates a stream to read from this file.
  5446. @returns a stream that will read from this file (initially positioned at the
  5447. start of the file), or 0 if the file can't be opened for some reason
  5448. @see createOutputStream, loadFileAsData
  5449. */
  5450. FileInputStream* createInputStream() const throw();
  5451. /** Creates a stream to write to this file.
  5452. If the file exists, the stream that is returned will be positioned ready for
  5453. writing at the end of the file, so you might want to use deleteFile() first
  5454. to write to an empty file.
  5455. @returns a stream that will write to this file (initially positioned at the
  5456. end of the file), or 0 if the file can't be opened for some reason
  5457. @see createInputStream, printf, appendData, appendText
  5458. */
  5459. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5460. /** Loads a file's contents into memory as a block of binary data.
  5461. Of course, trying to load a very large file into memory will blow up, so
  5462. it's better to check first.
  5463. @param result the data block to which the file's contents should be appended - note
  5464. that if the memory block might already contain some data, you
  5465. might want to clear it first
  5466. @returns true if the file could all be read into memory
  5467. */
  5468. bool loadFileAsData (MemoryBlock& result) const throw();
  5469. /** Reads a file into memory as a string.
  5470. Attempts to load the entire file as a zero-terminated string.
  5471. This makes use of InputStream::readEntireStreamAsString, which should
  5472. automatically cope with unicode/acsii file formats.
  5473. */
  5474. const String loadFileAsString() const throw();
  5475. /** Writes text to the end of the file.
  5476. This will try to do a printf to the file.
  5477. @returns false if it can't write to the file for some reason
  5478. */
  5479. bool printf (const tchar* format, ...) const throw();
  5480. /** Appends a block of binary data to the end of the file.
  5481. This will try to write the given buffer to the end of the file.
  5482. @returns false if it can't write to the file for some reason
  5483. */
  5484. bool appendData (const void* const dataToAppend,
  5485. const int numberOfBytes) const throw();
  5486. /** Replaces this file's contents with a given block of data.
  5487. This will delete the file and replace it with the given data.
  5488. A nice feature of this method is that it's safe - instead of deleting
  5489. the file first and then re-writing it, it creates a new temporary file,
  5490. writes the data to that, and then moves the new file to replace the existing
  5491. file. This means that if the power gets pulled out or something crashes,
  5492. you're a lot less likely to end up with an empty file..
  5493. Returns true if the operation succeeds, or false if it fails.
  5494. @see appendText
  5495. */
  5496. bool replaceWithData (const void* const dataToWrite,
  5497. const int numberOfBytes) const throw();
  5498. /** Appends a string to the end of the file.
  5499. This will try to append a text string to the file, as either 16-bit unicode
  5500. or 8-bit characters in the default system encoding.
  5501. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5502. the endianness of the file.
  5503. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5504. @see replaceWithText
  5505. */
  5506. bool appendText (const String& textToAppend,
  5507. const bool asUnicode = false,
  5508. const bool writeUnicodeHeaderBytes = false) const throw();
  5509. /** Replaces this file's contents with a given text string.
  5510. This will delete the file and replace it with the given text.
  5511. A nice feature of this method is that it's safe - instead of deleting
  5512. the file first and then re-writing it, it creates a new temporary file,
  5513. writes the text to that, and then moves the new file to replace the existing
  5514. file. This means that if the power gets pulled out or something crashes,
  5515. you're a lot less likely to end up with an empty file..
  5516. For an explanation of the parameters here, see the appendText() method.
  5517. Returns true if the operation succeeds, or false if it fails.
  5518. @see appendText
  5519. */
  5520. bool replaceWithText (const String& textToWrite,
  5521. const bool asUnicode = false,
  5522. const bool writeUnicodeHeaderBytes = false) const throw();
  5523. /** Creates a set of files to represent each file root.
  5524. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5525. to which ones are available. On the Mac/Linux, this will probably
  5526. just add a single entry for "/".
  5527. */
  5528. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5529. /** Finds the name of the drive on which this file lives.
  5530. @returns the volume label of the drive, or an empty string if this isn't possible
  5531. */
  5532. const String getVolumeLabel() const throw();
  5533. /** Returns the serial number of the volume on which this file lives.
  5534. @returns the serial number, or zero if there's a problem doing this
  5535. */
  5536. int getVolumeSerialNumber() const throw();
  5537. /** Returns the number of bytes free on the drive that this file lives on.
  5538. @returns the number of bytes free, or 0 if there's a problem finding this out
  5539. */
  5540. int64 getBytesFreeOnVolume() const throw();
  5541. /** Returns true if this file is on a CD or DVD drive. */
  5542. bool isOnCDRomDrive() const throw();
  5543. /** Returns true if this file is on a hard disk.
  5544. This will fail if it's a network drive, but will still be true for
  5545. removable hard-disks.
  5546. */
  5547. bool isOnHardDisk() const throw();
  5548. /** Returns true if this file is on a removable disk drive.
  5549. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5550. */
  5551. bool isOnRemovableDrive() const throw();
  5552. /** Launches the file as a process.
  5553. - if the file is executable, this will run it.
  5554. - if it's a document of some kind, it will launch the document with its
  5555. default viewer application.
  5556. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5557. */
  5558. bool startAsProcess (const String& parameters = String::empty) const throw();
  5559. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5560. */
  5561. enum SpecialLocationType
  5562. {
  5563. /** The user's home folder. This is the same as using File ("~"). */
  5564. userHomeDirectory,
  5565. /** The user's default documents folder. On Windows, this might be the user's
  5566. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5567. doesn't tend to have one of these, so it might just return their home folder.
  5568. */
  5569. userDocumentsDirectory,
  5570. /** The folder that contains the user's desktop objects. */
  5571. userDesktopDirectory,
  5572. /** The folder in which applications store their persistent user-specific settings.
  5573. On Windows, this might be "\Documents and Settings\username\Application Data".
  5574. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5575. always create your own sub-folder to put them in, to avoid making a mess.
  5576. */
  5577. userApplicationDataDirectory,
  5578. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5579. of the computer, rather than just the current user.
  5580. On the Mac it'll be "/Library", on Windows, it could be something like
  5581. "\Documents and Settings\All Users\Application Data".
  5582. Depending on the setup, this folder may be read-only.
  5583. */
  5584. commonApplicationDataDirectory,
  5585. /** The folder that should be used for temporary files.
  5586. Always delete them when you're finished, to keep the user's computer tidy!
  5587. */
  5588. tempDirectory,
  5589. /** Returns this application's executable file.
  5590. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5591. host app.
  5592. On the mac this will return the unix binary, not the package folder - see
  5593. currentApplicationFile for that.
  5594. */
  5595. currentExecutableFile,
  5596. /** Returns this application's location.
  5597. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5598. host app.
  5599. On the mac this will return the package folder (if it's in one), not the unix binary
  5600. that's inside it - compare with currentExecutableFile.
  5601. */
  5602. currentApplicationFile,
  5603. /** The directory in which applications normally get installed.
  5604. So on windows, this would be something like "c:\program files", on the
  5605. Mac "/Applications", or "/usr" on linux.
  5606. */
  5607. globalApplicationsDirectory,
  5608. /** The most likely place where a user might store their music files.
  5609. */
  5610. userMusicDirectory,
  5611. /** The most likely place where a user might store their movie files.
  5612. */
  5613. userMoviesDirectory,
  5614. };
  5615. /** Finds the location of a special type of file or directory, such as a home folder or
  5616. documents folder.
  5617. @see SpecialLocationType
  5618. */
  5619. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5620. /** Returns a temporary file in the system's temp directory.
  5621. This will try to return the name of a non-existent temp file.
  5622. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5623. */
  5624. static const File createTempFile (const String& fileNameEnding) throw();
  5625. /** Returns the current working directory.
  5626. @see setAsCurrentWorkingDirectory
  5627. */
  5628. static const File getCurrentWorkingDirectory() throw();
  5629. /** Sets the current working directory to be this file.
  5630. For this to work the file must point to a valid directory.
  5631. @returns true if the current directory has been changed.
  5632. @see getCurrentWorkingDirectory
  5633. */
  5634. bool setAsCurrentWorkingDirectory() const throw();
  5635. /** The system-specific file separator character.
  5636. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5637. */
  5638. static const tchar separator;
  5639. /** The system-specific file separator character, as a string.
  5640. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5641. */
  5642. static const tchar* separatorString;
  5643. /** Removes illegal characters from a filename.
  5644. This will return a copy of the given string after removing characters
  5645. that are not allowed in a legal filename, and possibly shortening the
  5646. string if it's too long.
  5647. Because this will remove slashes, don't use it on an absolute pathname.
  5648. @see createLegalPathName
  5649. */
  5650. static const String createLegalFileName (const String& fileNameToFix) throw();
  5651. /** Removes illegal characters from a pathname.
  5652. Similar to createLegalFileName(), but this won't remove slashes, so can
  5653. be used on a complete pathname.
  5654. @see createLegalFileName
  5655. */
  5656. static const String createLegalPathName (const String& pathNameToFix) throw();
  5657. /** Indicates whether filenames are case-sensitive on the current operating system.
  5658. */
  5659. static bool areFileNamesCaseSensitive();
  5660. /** Returns true if the string seems to be a fully-specified absolute path.
  5661. */
  5662. static bool isAbsolutePath (const String& path) throw();
  5663. juce_UseDebuggingNewOperator
  5664. private:
  5665. String fullPath;
  5666. // internal way of contructing a file without checking the path
  5667. friend class DirectoryIterator;
  5668. File (const String&, int) throw();
  5669. const String getPathUpToLastSlash() const throw();
  5670. };
  5671. #endif // __JUCE_FILE_JUCEHEADER__
  5672. /********* End of inlined file: juce_File.h *********/
  5673. /**
  5674. A simple implemenation of a Logger that writes to a file.
  5675. @see Logger
  5676. */
  5677. class JUCE_API FileLogger : public Logger
  5678. {
  5679. public:
  5680. /** Creates a FileLogger for a given file.
  5681. @param fileToWriteTo the file that to use - new messages will be appended
  5682. to the file. If the file doesn't exist, it will be created,
  5683. along with any parent directories that are needed.
  5684. @param welcomeMessage when opened, the logger will write a header to the log, along
  5685. with the current date and time, and this welcome message
  5686. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5687. but is larger than this number of bytes, then the start of the
  5688. file will be truncated to keep the size down. This prevents a log
  5689. file getting ridiculously large over time. The file will be truncated
  5690. at a new-line boundary. If this value is less than zero, no size limit
  5691. will be imposed; if it's zero, the file will always be deleted. Note that
  5692. the size is only checked once when this object is created - any logging
  5693. that is done later will be appended without any checking
  5694. */
  5695. FileLogger (const File& fileToWriteTo,
  5696. const String& welcomeMessage,
  5697. const int maxInitialFileSizeBytes = 128 * 1024);
  5698. /** Destructor. */
  5699. ~FileLogger();
  5700. void logMessage (const String& message);
  5701. /** Helper function to create a log file in the correct place for this platform.
  5702. On Windows this will return a logger with a path such as:
  5703. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5704. On the Mac it'll create something like:
  5705. ~/Library/Logs/[logFileName]
  5706. The method might return 0 if the file can't be created for some reason.
  5707. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5708. it's best to use the something like the name of your application here.
  5709. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5710. call it "log.txt" because if it goes in a directory with logs
  5711. from other applications (as it will do on the Mac) then no-one
  5712. will know which one is yours!
  5713. @param welcomeMessage a message that will be written to the log when it's opened.
  5714. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5715. */
  5716. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5717. const String& logFileName,
  5718. const String& welcomeMessage,
  5719. const int maxInitialFileSizeBytes = 128 * 1024);
  5720. juce_UseDebuggingNewOperator
  5721. private:
  5722. File logFile;
  5723. CriticalSection logLock;
  5724. FileOutputStream* logStream;
  5725. void trimFileSize (int maxFileSizeBytes) const;
  5726. FileLogger (const FileLogger&);
  5727. const FileLogger& operator= (const FileLogger&);
  5728. };
  5729. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5730. /********* End of inlined file: juce_FileLogger.h *********/
  5731. #endif
  5732. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5733. /********* Start of inlined file: juce_Random.h *********/
  5734. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5735. #define __JUCE_RANDOM_JUCEHEADER__
  5736. /**
  5737. A simple pseudo-random number generator.
  5738. */
  5739. class JUCE_API Random
  5740. {
  5741. public:
  5742. /** Creates a Random object based on a seed value.
  5743. For a given seed value, the subsequent numbers generated by this object
  5744. will be predictable, so a good idea is to set this value based
  5745. on the time, e.g.
  5746. new Random (Time::currentTimeMillis())
  5747. */
  5748. Random (const int64 seedValue) throw();
  5749. /** Destructor. */
  5750. ~Random() throw();
  5751. /** Returns the next random 32 bit integer.
  5752. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5753. */
  5754. int nextInt() throw();
  5755. /** Returns the next random number, limited to a given range.
  5756. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5757. */
  5758. int nextInt (const int maxValue) throw();
  5759. /** Returns the next 64-bit random number.
  5760. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5761. */
  5762. int64 nextInt64() throw();
  5763. /** Returns the next random floating-point number.
  5764. @returns a random value in the range 0 to 1.0
  5765. */
  5766. float nextFloat() throw();
  5767. /** Returns the next random floating-point number.
  5768. @returns a random value in the range 0 to 1.0
  5769. */
  5770. double nextDouble() throw();
  5771. /** Returns the next random boolean value.
  5772. */
  5773. bool nextBool() throw();
  5774. /** To avoid the overhead of having to create a new Random object whenever
  5775. you need a number, this is a shared application-wide object that
  5776. can be used.
  5777. It's not thread-safe though, so threads should use their own Random object.
  5778. */
  5779. static Random& getSystemRandom() throw();
  5780. /** Resets this Random object to a given seed value. */
  5781. void setSeed (const int64 newSeed) throw();
  5782. juce_UseDebuggingNewOperator
  5783. private:
  5784. int64 seed;
  5785. };
  5786. #endif // __JUCE_RANDOM_JUCEHEADER__
  5787. /********* End of inlined file: juce_Random.h *********/
  5788. #endif
  5789. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5790. /********* Start of inlined file: juce_Initialisation.h *********/
  5791. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5792. #define __JUCE_INITIALISATION_JUCEHEADER__
  5793. /** Initialises Juce's GUI classes.
  5794. If you're embedding Juce into an application that uses its own event-loop rather
  5795. than using the START_JUCE_APPLICATION macro, call this function before making any
  5796. Juce calls, to make sure things are initialised correctly.
  5797. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5798. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5799. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5800. */
  5801. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5802. /** Clears up any static data being used by Juce's GUI classes.
  5803. If you're embedding Juce into an application that uses its own event-loop rather
  5804. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5805. code to clean up any juce objects that might be lying around.
  5806. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5807. */
  5808. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5809. /** Initialises the core parts of Juce.
  5810. If you're embedding Juce into either a command-line program, call this function
  5811. at the start of your main() function to make sure that Juce is initialised correctly.
  5812. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5813. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5814. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5815. */
  5816. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5817. /** Clears up any static data being used by Juce's non-gui core classes.
  5818. If you're embedding Juce into either a command-line program, call this function
  5819. at the end of your main() function if you want to make sure any Juce objects are
  5820. cleaned up correctly.
  5821. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5822. */
  5823. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5824. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5825. /********* End of inlined file: juce_Initialisation.h *********/
  5826. #endif
  5827. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  5828. #endif
  5829. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5830. #endif
  5831. #ifndef __JUCE_TIME_JUCEHEADER__
  5832. #endif
  5833. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  5834. #endif
  5835. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5836. #endif
  5837. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5838. /********* Start of inlined file: juce_PropertySet.h *********/
  5839. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5840. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5841. /********* Start of inlined file: juce_StringPairArray.h *********/
  5842. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5843. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5844. /**
  5845. A container for holding a set of strings which are keyed by another string.
  5846. @see StringArray
  5847. */
  5848. class JUCE_API StringPairArray
  5849. {
  5850. public:
  5851. /** Creates an empty array */
  5852. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  5853. /** Creates a copy of another array */
  5854. StringPairArray (const StringPairArray& other) throw();
  5855. /** Destructor. */
  5856. ~StringPairArray() throw();
  5857. /** Copies the contents of another string array into this one */
  5858. const StringPairArray& operator= (const StringPairArray& other) throw();
  5859. /** Compares two arrays.
  5860. Comparisons are case-sensitive.
  5861. @returns true only if the other array contains exactly the same strings with the same keys
  5862. */
  5863. bool operator== (const StringPairArray& other) const throw();
  5864. /** Compares two arrays.
  5865. Comparisons are case-sensitive.
  5866. @returns false if the other array contains exactly the same strings with the same keys
  5867. */
  5868. bool operator!= (const StringPairArray& other) const throw();
  5869. /** Finds the value corresponding to a key string.
  5870. If no such key is found, this will just return an empty string. To check whether
  5871. a given key actually exists (because it might actually be paired with an empty string), use
  5872. the getAllKeys() method to obtain a list.
  5873. Obviously the reference returned shouldn't be stored for later use, as the
  5874. string it refers to may disappear when the array changes.
  5875. @see getValue
  5876. */
  5877. const String& operator[] (const String& key) const throw();
  5878. /** Finds the value corresponding to a key string.
  5879. If no such key is found, this will just return the value provided as a default.
  5880. @see operator[]
  5881. */
  5882. const String getValue (const String& key, const String& defaultReturnValue) const;
  5883. /** Returns a list of all keys in the array. */
  5884. const StringArray& getAllKeys() const throw() { return keys; }
  5885. /** Returns a list of all values in the array. */
  5886. const StringArray& getAllValues() const throw() { return values; }
  5887. /** Returns the number of strings in the array */
  5888. inline int size() const throw() { return keys.size(); };
  5889. /** Adds or amends a key/value pair.
  5890. If a value already exists with this key, its value will be overwritten,
  5891. otherwise the key/value pair will be added to the array.
  5892. */
  5893. void set (const String& key,
  5894. const String& value) throw();
  5895. /** Adds the items from another array to this one.
  5896. This is equivalent to using set() to add each of the pairs from the other array.
  5897. */
  5898. void addArray (const StringPairArray& other);
  5899. /** Removes all elements from the array. */
  5900. void clear() throw();
  5901. /** Removes a string from the array based on its key.
  5902. If the key isn't found, nothing will happen.
  5903. */
  5904. void remove (const String& key) throw();
  5905. /** Removes a string from the array based on its index.
  5906. If the index is out-of-range, no action will be taken.
  5907. */
  5908. void remove (const int index) throw();
  5909. /** Reduces the amount of storage being used by the array.
  5910. Arrays typically allocate slightly more storage than they need, and after
  5911. removing elements, they may have quite a lot of unused space allocated.
  5912. This method will reduce the amount of allocated storage to a minimum.
  5913. */
  5914. void minimiseStorageOverheads() throw();
  5915. juce_UseDebuggingNewOperator
  5916. private:
  5917. StringArray keys, values;
  5918. bool ignoreCase;
  5919. };
  5920. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5921. /********* End of inlined file: juce_StringPairArray.h *********/
  5922. /********* Start of inlined file: juce_XmlElement.h *********/
  5923. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5924. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5925. /********* Start of inlined file: juce_OutputStream.h *********/
  5926. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  5927. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  5928. /********* Start of inlined file: juce_InputStream.h *********/
  5929. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  5930. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  5931. /** The base class for streams that read data.
  5932. Input and output streams are used throughout the library - subclasses can override
  5933. some or all of the virtual functions to implement their behaviour.
  5934. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  5935. */
  5936. class JUCE_API InputStream
  5937. {
  5938. public:
  5939. /** Destructor. */
  5940. virtual ~InputStream() {}
  5941. /** Returns the total number of bytes available for reading in this stream.
  5942. Note that this is the number of bytes available from the start of the
  5943. stream, not from the current position.
  5944. If the size of the stream isn't actually known, this may return -1.
  5945. */
  5946. virtual int64 getTotalLength() = 0;
  5947. /** Returns true if the stream has no more data to read. */
  5948. virtual bool isExhausted() = 0;
  5949. /** Reads a set of bytes from the stream into a memory buffer.
  5950. This is the only read method that subclasses actually need to implement, as the
  5951. InputStream base class implements the other read methods in terms of this one (although
  5952. it's often more efficient for subclasses to implement them directly).
  5953. @param destBuffer the destination buffer for the data
  5954. @param maxBytesToRead the maximum number of bytes to read - make sure the
  5955. memory block passed in is big enough to contain this
  5956. many bytes.
  5957. @returns the actual number of bytes that were read, which may be less than
  5958. maxBytesToRead if the stream is exhausted before it gets that far
  5959. */
  5960. virtual int read (void* destBuffer,
  5961. int maxBytesToRead) = 0;
  5962. /** Reads a byte from the stream.
  5963. If the stream is exhausted, this will return zero.
  5964. @see OutputStream::writeByte
  5965. */
  5966. virtual char readByte();
  5967. /** Reads a boolean from the stream.
  5968. The bool is encoded as a single byte - 1 for true, 0 for false.
  5969. If the stream is exhausted, this will return false.
  5970. @see OutputStream::writeBool
  5971. */
  5972. virtual bool readBool();
  5973. /** Reads two bytes from the stream as a little-endian 16-bit value.
  5974. If the next two bytes read are byte1 and byte2, this returns
  5975. (byte1 | (byte2 << 8)).
  5976. If the stream is exhausted partway through reading the bytes, this will return zero.
  5977. @see OutputStream::writeShort, readShortBigEndian
  5978. */
  5979. virtual short readShort();
  5980. /** Reads two bytes from the stream as a little-endian 16-bit value.
  5981. If the next two bytes read are byte1 and byte2, this returns
  5982. (byte2 | (byte1 << 8)).
  5983. If the stream is exhausted partway through reading the bytes, this will return zero.
  5984. @see OutputStream::writeShortBigEndian, readShort
  5985. */
  5986. virtual short readShortBigEndian();
  5987. /** Reads four bytes from the stream as a little-endian 32-bit value.
  5988. If the next four bytes are byte1 to byte4, this returns
  5989. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  5990. If the stream is exhausted partway through reading the bytes, this will return zero.
  5991. @see OutputStream::writeInt, readIntBigEndian
  5992. */
  5993. virtual int readInt();
  5994. /** Reads four bytes from the stream as a big-endian 32-bit value.
  5995. If the next four bytes are byte1 to byte4, this returns
  5996. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  5997. If the stream is exhausted partway through reading the bytes, this will return zero.
  5998. @see OutputStream::writeIntBigEndian, readInt
  5999. */
  6000. virtual int readIntBigEndian();
  6001. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6002. If the next eight bytes are byte1 to byte8, this returns
  6003. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6004. If the stream is exhausted partway through reading the bytes, this will return zero.
  6005. @see OutputStream::writeInt64, readInt64BigEndian
  6006. */
  6007. virtual int64 readInt64();
  6008. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6009. If the next eight bytes are byte1 to byte8, this returns
  6010. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6011. If the stream is exhausted partway through reading the bytes, this will return zero.
  6012. @see OutputStream::writeInt64BigEndian, readInt64
  6013. */
  6014. virtual int64 readInt64BigEndian();
  6015. /** Reads four bytes as a 32-bit floating point value.
  6016. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6017. If the stream is exhausted partway through reading the bytes, this will return zero.
  6018. @see OutputStream::writeFloat, readDouble
  6019. */
  6020. virtual float readFloat();
  6021. /** Reads four bytes as a 32-bit floating point value.
  6022. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6023. If the stream is exhausted partway through reading the bytes, this will return zero.
  6024. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6025. */
  6026. virtual float readFloatBigEndian();
  6027. /** Reads eight bytes as a 64-bit floating point value.
  6028. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6029. If the stream is exhausted partway through reading the bytes, this will return zero.
  6030. @see OutputStream::writeDouble, readFloat
  6031. */
  6032. virtual double readDouble();
  6033. /** Reads eight bytes as a 64-bit floating point value.
  6034. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6035. If the stream is exhausted partway through reading the bytes, this will return zero.
  6036. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6037. */
  6038. virtual double readDoubleBigEndian();
  6039. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6040. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6041. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6042. @see OutputStream::writeCompressedInt()
  6043. */
  6044. virtual int readCompressedInt();
  6045. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6046. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6047. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6048. After this call, the stream's position will be left pointing to the character
  6049. following the line-feed, but the linefeeds aren't included in the string that
  6050. is returned.
  6051. */
  6052. virtual const String readNextLine();
  6053. /** Reads a zero-terminated string from the stream.
  6054. This will read characters from the stream until it hits a zero character or
  6055. end-of-stream.
  6056. @see OutputStream::writeString, readEntireStreamAsString
  6057. */
  6058. virtual const String readString();
  6059. /** Tries to read the whole stream and turn it into a string.
  6060. This will read from the stream's current position until the end-of-stream, and
  6061. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6062. */
  6063. virtual const String readEntireStreamAsString();
  6064. /** Reads from the stream and appends the data to a MemoryBlock.
  6065. @param destBlock the block to append the data onto
  6066. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6067. of bytes that will be read - if it's negative, data
  6068. will be read until the stream is exhausted.
  6069. @returns the number of bytes that were added to the memory block
  6070. */
  6071. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6072. int maxNumBytesToRead = -1);
  6073. /** Returns the offset of the next byte that will be read from the stream.
  6074. @see setPosition
  6075. */
  6076. virtual int64 getPosition() = 0;
  6077. /** Tries to move the current read position of the stream.
  6078. The position is an absolute number of bytes from the stream's start.
  6079. Some streams might not be able to do this, in which case they should do
  6080. nothing and return false. Others might be able to manage it by resetting
  6081. themselves and skipping to the correct position, although this is
  6082. obviously a bit slow.
  6083. @returns true if the stream manages to reposition itself correctly
  6084. @see getPosition
  6085. */
  6086. virtual bool setPosition (int64 newPosition) = 0;
  6087. /** Reads and discards a number of bytes from the stream.
  6088. Some input streams might implement this efficiently, but the base
  6089. class will just keep reading data until the requisite number of bytes
  6090. have been done.
  6091. */
  6092. virtual void skipNextBytes (int64 numBytesToSkip);
  6093. juce_UseDebuggingNewOperator
  6094. protected:
  6095. InputStream() throw() {}
  6096. };
  6097. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6098. /********* End of inlined file: juce_InputStream.h *********/
  6099. /**
  6100. The base class for streams that write data to some kind of destination.
  6101. Input and output streams are used throughout the library - subclasses can override
  6102. some or all of the virtual functions to implement their behaviour.
  6103. @see InputStream, MemoryOutputStream, FileOutputStream
  6104. */
  6105. class JUCE_API OutputStream
  6106. {
  6107. public:
  6108. /** Destructor.
  6109. Some subclasses might want to do things like call flush() during their
  6110. destructors.
  6111. */
  6112. virtual ~OutputStream();
  6113. /** If the stream is using a buffer, this will ensure it gets written
  6114. out to the destination. */
  6115. virtual void flush() = 0;
  6116. /** Tries to move the stream's output position.
  6117. Not all streams will be able to seek to a new position - this will return
  6118. false if it fails to work.
  6119. @see getPosition
  6120. */
  6121. virtual bool setPosition (int64 newPosition) = 0;
  6122. /** Returns the stream's current position.
  6123. @see setPosition
  6124. */
  6125. virtual int64 getPosition() = 0;
  6126. /** Writes a block of data to the stream.
  6127. When creating a subclass of OutputStream, this is the only write method
  6128. that needs to be overloaded - the base class has methods for writing other
  6129. types of data which use this to do the work.
  6130. @returns false if the write operation fails for some reason
  6131. */
  6132. virtual bool write (const void* dataToWrite,
  6133. int howManyBytes) = 0;
  6134. /** Writes a single byte to the stream.
  6135. @see InputStream::readByte
  6136. */
  6137. virtual void writeByte (char byte);
  6138. /** Writes a boolean to the stream.
  6139. This is encoded as a byte - either 1 or 0.
  6140. @see InputStream::readBool
  6141. */
  6142. virtual void writeBool (bool boolValue);
  6143. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6144. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6145. @see InputStream::readShort
  6146. */
  6147. virtual void writeShort (short value);
  6148. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6149. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6150. @see InputStream::readShortBigEndian
  6151. */
  6152. virtual void writeShortBigEndian (short value);
  6153. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6154. @see InputStream::readInt
  6155. */
  6156. virtual void writeInt (int value);
  6157. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6158. @see InputStream::readIntBigEndian
  6159. */
  6160. virtual void writeIntBigEndian (int value);
  6161. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6162. @see InputStream::readInt64
  6163. */
  6164. virtual void writeInt64 (int64 value);
  6165. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6166. @see InputStream::readInt64BigEndian
  6167. */
  6168. virtual void writeInt64BigEndian (int64 value);
  6169. /** Writes a 32-bit floating point value to the stream.
  6170. The binary 32-bit encoding of the float is written as a little-endian int.
  6171. @see InputStream::readFloat
  6172. */
  6173. virtual void writeFloat (float value);
  6174. /** Writes a 32-bit floating point value to the stream.
  6175. The binary 32-bit encoding of the float is written as a big-endian int.
  6176. @see InputStream::readFloatBigEndian
  6177. */
  6178. virtual void writeFloatBigEndian (float value);
  6179. /** Writes a 64-bit floating point value to the stream.
  6180. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6181. @see InputStream::readDouble
  6182. */
  6183. virtual void writeDouble (double value);
  6184. /** Writes a 64-bit floating point value to the stream.
  6185. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6186. @see InputStream::readDoubleBigEndian
  6187. */
  6188. virtual void writeDoubleBigEndian (double value);
  6189. /** Writes a condensed encoding of a 32-bit integer.
  6190. If you're storing a lot of integers which are unlikely to have very large values,
  6191. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6192. under 0xffff only 3 bytes, etc.
  6193. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6194. @see InputStream::readCompressedInt
  6195. */
  6196. virtual void writeCompressedInt (int value);
  6197. /** Stores a string in the stream.
  6198. This isn't the method to use if you're trying to append text to the end of a
  6199. text-file! It's intended for storing a string for later retrieval
  6200. by InputStream::readString.
  6201. For appending text to a file, instead use writeText, printf, or operator<<
  6202. @see InputStream::readString, writeText, printf, operator<<
  6203. */
  6204. virtual void writeString (const String& text);
  6205. /** Writes a string of text to the stream.
  6206. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6207. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6208. should only be done at the start of a file).
  6209. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6210. */
  6211. virtual void writeText (const String& text,
  6212. const bool asUnicode,
  6213. const bool writeUnicodeHeaderBytes);
  6214. /** Writes a string of text to the stream.
  6215. @see writeText
  6216. */
  6217. virtual void printf (const char* format, ...);
  6218. /** Reads data from an input stream and writes it to this stream.
  6219. @param source the stream to read from
  6220. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6221. less than zero, it will keep reading until the input
  6222. is exhausted)
  6223. */
  6224. virtual int writeFromInputStream (InputStream& source,
  6225. int maxNumBytesToWrite);
  6226. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6227. virtual OutputStream& operator<< (const int number);
  6228. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6229. virtual OutputStream& operator<< (const double number);
  6230. /** Writes a character to the stream. */
  6231. virtual OutputStream& operator<< (const char character);
  6232. /** Writes a null-terminated string to the stream. */
  6233. virtual OutputStream& operator<< (const char* const text);
  6234. /** Writes a null-terminated unicode text string to the stream, converting it
  6235. to 8-bit characters in the default system encoding. */
  6236. virtual OutputStream& operator<< (const juce_wchar* const text);
  6237. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6238. virtual OutputStream& operator<< (const String& text);
  6239. juce_UseDebuggingNewOperator
  6240. protected:
  6241. OutputStream() throw();
  6242. };
  6243. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6244. /********* End of inlined file: juce_OutputStream.h *********/
  6245. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6246. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6247. will be the name of a pointer to each child element.
  6248. E.g. @code
  6249. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6250. forEachXmlChildElement (*myParentXml, child)
  6251. {
  6252. if (child->hasTagName ("FOO"))
  6253. doSomethingWithXmlElement (child);
  6254. }
  6255. @endcode
  6256. @see forEachXmlChildElementWithTagName
  6257. */
  6258. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6259. \
  6260. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6261. childElementVariableName != 0; \
  6262. childElementVariableName = childElementVariableName->getNextElement())
  6263. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6264. which have a specified tag.
  6265. This does the same job as the forEachXmlChildElement macro, but only for those
  6266. elements that have a particular tag name.
  6267. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6268. will be the name of a pointer to each child element. The requiredTagName is the
  6269. tag name to match.
  6270. E.g. @code
  6271. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6272. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6273. {
  6274. // the child object is now guaranteed to be a <MYTAG> element..
  6275. doSomethingWithMYTAGElement (child);
  6276. }
  6277. @endcode
  6278. @see forEachXmlChildElement
  6279. */
  6280. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6281. \
  6282. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6283. childElementVariableName != 0; \
  6284. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6285. /** Used to build a tree of elements representing an XML document.
  6286. An XML document can be parsed into a tree of XmlElements, each of which
  6287. represents an XML tag structure, and which may itself contain other
  6288. nested elements.
  6289. An XmlElement can also be converted back into a text document, and has
  6290. lots of useful methods for manipulating its attributes and sub-elements,
  6291. so XmlElements can actually be used as a handy general-purpose data
  6292. structure.
  6293. Here's an example of parsing some elements: @code
  6294. // check we're looking at the right kind of document..
  6295. if (myElement->hasTagName ("ANIMALS"))
  6296. {
  6297. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6298. forEachXmlChildElement (*myElement, e)
  6299. {
  6300. if (e->hasTagName ("GIRAFFE"))
  6301. {
  6302. // found a giraffe, so use some of its attributes..
  6303. String giraffeName = e->getStringAttribute ("name");
  6304. int giraffeAge = e->getIntAttribute ("age");
  6305. bool isFriendly = e->getBoolAttribute ("friendly");
  6306. }
  6307. }
  6308. }
  6309. @endcode
  6310. And here's an example of how to create an XML document from scratch: @code
  6311. // create an outer node called "ANIMALS"
  6312. XmlElement animalsList ("ANIMALS");
  6313. for (int i = 0; i < numAnimals; ++i)
  6314. {
  6315. // create an inner element..
  6316. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6317. giraffe->setAttribute ("name", "nigel");
  6318. giraffe->setAttribute ("age", 10);
  6319. giraffe->setAttribute ("friendly", true);
  6320. // ..and add our new element to the parent node
  6321. animalsList.addChildElement (giraffe);
  6322. }
  6323. // now we can turn the whole thing into a text document..
  6324. String myXmlDoc = animalsList.createDocument (String::empty);
  6325. @endcode
  6326. @see XmlDocument
  6327. */
  6328. class JUCE_API XmlElement
  6329. {
  6330. public:
  6331. /** Creates an XmlElement with this tag name. */
  6332. XmlElement (const String& tagName) throw();
  6333. /** Creates a (deep) copy of another element. */
  6334. XmlElement (const XmlElement& other) throw();
  6335. /** Creates a (deep) copy of another element. */
  6336. const XmlElement& operator= (const XmlElement& other) throw();
  6337. /** Deleting an XmlElement will also delete all its child elements. */
  6338. ~XmlElement() throw();
  6339. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6340. The elements are only considered equivalent if they contain the same attiributes
  6341. with the same values, and have the same sub-nodes.
  6342. @param other the other element to compare to
  6343. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6344. same attributes in a different order will be
  6345. considered the same; if false, the attributes must
  6346. be in the same order as well
  6347. */
  6348. bool isEquivalentTo (const XmlElement* const other,
  6349. const bool ignoreOrderOfAttributes) const throw();
  6350. /** Returns an XML text document that represents this element.
  6351. The string returned can be parsed to recreate the same XmlElement that
  6352. was used to create it.
  6353. @param dtdToUse the DTD to add to the document
  6354. @param allOnOneLine if true, this means that the document will not contain any
  6355. linefeeds, so it'll be smaller but not very easy to read.
  6356. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6357. document
  6358. @param encodingType the character encoding format string to put into the xml
  6359. header
  6360. @param lineWrapLength the line length that will be used before items get placed on
  6361. a new line. This isn't an absolute maximum length, it just
  6362. determines how lists of attributes get broken up
  6363. @see writeToFile
  6364. */
  6365. const String createDocument (const String& dtdToUse,
  6366. const bool allOnOneLine = false,
  6367. const bool includeXmlHeader = true,
  6368. const tchar* const encodingType = JUCE_T("UTF-8"),
  6369. const int lineWrapLength = 60) const throw();
  6370. /** Writes the element to a file as an XML document.
  6371. To improve safety in case something goes wrong while writing the file, this
  6372. will actually write the document to a new temporary file in the same
  6373. directory as the destination file, and if this succeeds, it will rename this
  6374. new file as the destination file (overwriting any existing file that was there).
  6375. @param destinationFile the file to write to. If this already exists, it will be
  6376. overwritten.
  6377. @param dtdToUse the DTD to add to the document
  6378. @param encodingType the character encoding format string to put into the xml
  6379. header
  6380. @param lineWrapLength the line length that will be used before items get placed on
  6381. a new line. This isn't an absolute maximum length, it just
  6382. determines how lists of attributes get broken up
  6383. @returns true if the file is written successfully; false if something goes wrong
  6384. in the process
  6385. @see createDocument
  6386. */
  6387. bool writeToFile (const File& destinationFile,
  6388. const String& dtdToUse,
  6389. const tchar* const encodingType = JUCE_T("UTF-8"),
  6390. const int lineWrapLength = 60) const throw();
  6391. /** Returns this element's tag type name.
  6392. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6393. "MOOSE".
  6394. @see hasTagName
  6395. */
  6396. inline const String& getTagName() const throw() { return tagName; }
  6397. /** Tests whether this element has a particular tag name.
  6398. @param possibleTagName the tag name you're comparing it with
  6399. @see getTagName
  6400. */
  6401. bool hasTagName (const tchar* const possibleTagName) const throw();
  6402. /** Returns the number of XML attributes this element contains.
  6403. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6404. return 2.
  6405. */
  6406. int getNumAttributes() const throw();
  6407. /** Returns the name of one of the elements attributes.
  6408. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6409. getAttributeName(1) would return "antlers".
  6410. @see getAttributeValue, getStringAttribute
  6411. */
  6412. const String& getAttributeName (const int attributeIndex) const throw();
  6413. /** Returns the value of one of the elements attributes.
  6414. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6415. getAttributeName(1) would return "2".
  6416. @see getAttributeName, getStringAttribute
  6417. */
  6418. const String& getAttributeValue (const int attributeIndex) const throw();
  6419. // Attribute-handling methods..
  6420. /** Checks whether the element contains an attribute with a certain name. */
  6421. bool hasAttribute (const tchar* const attributeName) const throw();
  6422. /** Returns the value of a named attribute.
  6423. @param attributeName the name of the attribute to look up
  6424. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6425. with this name
  6426. */
  6427. const String getStringAttribute (const tchar* const attributeName,
  6428. const tchar* const defaultReturnValue = 0) const throw();
  6429. /** Compares the value of a named attribute with a value passed-in.
  6430. @param attributeName the name of the attribute to look up
  6431. @param stringToCompareAgainst the value to compare it with
  6432. @param ignoreCase whether the comparison should be case-insensitive
  6433. @returns true if the value of the attribute is the same as the string passed-in;
  6434. false if it's different (or if no such attribute exists)
  6435. */
  6436. bool compareAttribute (const tchar* const attributeName,
  6437. const tchar* const stringToCompareAgainst,
  6438. const bool ignoreCase = false) const throw();
  6439. /** Returns the value of a named attribute as an integer.
  6440. This will try to find the attribute and convert it to an integer (using
  6441. the String::getIntValue() method).
  6442. @param attributeName the name of the attribute to look up
  6443. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6444. with this name
  6445. @see setAttribute (const tchar* const, int)
  6446. */
  6447. int getIntAttribute (const tchar* const attributeName,
  6448. const int defaultReturnValue = 0) const throw();
  6449. /** Returns the value of a named attribute as floating-point.
  6450. This will try to find the attribute and convert it to an integer (using
  6451. the String::getDoubleValue() method).
  6452. @param attributeName the name of the attribute to look up
  6453. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6454. with this name
  6455. @see setAttribute (const tchar* const, double)
  6456. */
  6457. double getDoubleAttribute (const tchar* const attributeName,
  6458. const double defaultReturnValue = 0.0) const throw();
  6459. /** Returns the value of a named attribute as a boolean.
  6460. This will try to find the attribute and interpret it as a boolean. To do this,
  6461. it'll return true if the value is "1", "true", "y", etc, or false for other
  6462. values.
  6463. @param attributeName the name of the attribute to look up
  6464. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6465. with this name
  6466. */
  6467. bool getBoolAttribute (const tchar* const attributeName,
  6468. const bool defaultReturnValue = false) const throw();
  6469. /** Adds a named attribute to the element.
  6470. If the element already contains an attribute with this name, it's value will
  6471. be updated to the new value. If there's no such attribute yet, a new one will
  6472. be added.
  6473. Note that there are other setAttribute() methods that take integers,
  6474. doubles, etc. to make it easy to store numbers.
  6475. @param attributeName the name of the attribute to set
  6476. @param newValue the value to set it to
  6477. @see removeAttribute
  6478. */
  6479. void setAttribute (const tchar* const attributeName,
  6480. const String& newValue) throw();
  6481. /** Adds a named attribute to the element.
  6482. If the element already contains an attribute with this name, it's value will
  6483. be updated to the new value. If there's no such attribute yet, a new one will
  6484. be added.
  6485. Note that there are other setAttribute() methods that take integers,
  6486. doubles, etc. to make it easy to store numbers.
  6487. @param attributeName the name of the attribute to set
  6488. @param newValue the value to set it to
  6489. */
  6490. void setAttribute (const tchar* const attributeName,
  6491. const tchar* const newValue) throw();
  6492. /** Adds a named attribute to the element, setting it to an integer value.
  6493. If the element already contains an attribute with this name, it's value will
  6494. be updated to the new value. If there's no such attribute yet, a new one will
  6495. be added.
  6496. Note that there are other setAttribute() methods that take integers,
  6497. doubles, etc. to make it easy to store numbers.
  6498. @param attributeName the name of the attribute to set
  6499. @param newValue the value to set it to
  6500. */
  6501. void setAttribute (const tchar* const attributeName,
  6502. const int newValue) throw();
  6503. /** Adds a named attribute to the element, setting it to a floating-point value.
  6504. If the element already contains an attribute with this name, it's value will
  6505. be updated to the new value. If there's no such attribute yet, a new one will
  6506. be added.
  6507. Note that there are other setAttribute() methods that take integers,
  6508. doubles, etc. to make it easy to store numbers.
  6509. @param attributeName the name of the attribute to set
  6510. @param newValue the value to set it to
  6511. */
  6512. void setAttribute (const tchar* const attributeName,
  6513. const double newValue) throw();
  6514. /** Removes a named attribute from the element.
  6515. @param attributeName the name of the attribute to remove
  6516. @see removeAllAttributes
  6517. */
  6518. void removeAttribute (const tchar* const attributeName) throw();
  6519. /** Removes all attributes from this element.
  6520. */
  6521. void removeAllAttributes() throw();
  6522. // Child element methods..
  6523. /** Returns the first of this element's sub-elements.
  6524. see getNextElement() for an example of how to iterate the sub-elements.
  6525. @see forEachXmlChildElement
  6526. */
  6527. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6528. /** Returns the next of this element's siblings.
  6529. This can be used for iterating an element's sub-elements, e.g.
  6530. @code
  6531. XmlElement* child = myXmlDocument->getFirstChildElement();
  6532. while (child != 0)
  6533. {
  6534. ...do stuff with this child..
  6535. child = child->getNextElement();
  6536. }
  6537. @endcode
  6538. Note that when iterating the child elements, some of them might be
  6539. text elements as well as XML tags - use isTextElement() to work this
  6540. out.
  6541. Also, it's much easier and neater to use this method indirectly via the
  6542. forEachXmlChildElement macro.
  6543. @returns the sibling element that follows this one, or zero if this is the last
  6544. element in its parent
  6545. @see getNextElement, isTextElement, forEachXmlChildElement
  6546. */
  6547. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6548. /** Returns the next of this element's siblings which has the specified tag
  6549. name.
  6550. This is like getNextElement(), but will scan through the list until it
  6551. finds an element with the given tag name.
  6552. @see getNextElement, forEachXmlChildElementWithTagName
  6553. */
  6554. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6555. /** Returns the number of sub-elements in this element.
  6556. @see getChildElement
  6557. */
  6558. int getNumChildElements() const throw();
  6559. /** Returns the sub-element at a certain index.
  6560. It's not very efficient to iterate the sub-elements by index - see
  6561. getNextElement() for an example of how best to iterate.
  6562. @returns the n'th child of this element, or 0 if the index is out-of-range
  6563. @see getNextElement, isTextElement, getChildByName
  6564. */
  6565. XmlElement* getChildElement (const int index) const throw();
  6566. /** Returns the first sub-element with a given tag-name.
  6567. @param tagNameToLookFor the tag name of the element you want to find
  6568. @returns the first element with this tag name, or 0 if none is found
  6569. @see getNextElement, isTextElement, getChildElement
  6570. */
  6571. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6572. /** Appends an element to this element's list of children.
  6573. Child elements are deleted automatically when their parent is deleted, so
  6574. make sure the object that you pass in will not be deleted by anything else,
  6575. and make sure it's not already the child of another element.
  6576. @see getFirstChildElement, getNextElement, getNumChildElements,
  6577. getChildElement, removeChildElement
  6578. */
  6579. void addChildElement (XmlElement* const newChildElement) throw();
  6580. /** Inserts an element into this element's list of children.
  6581. Child elements are deleted automatically when their parent is deleted, so
  6582. make sure the object that you pass in will not be deleted by anything else,
  6583. and make sure it's not already the child of another element.
  6584. @param newChildNode the element to add
  6585. @param indexToInsertAt the index at which to insert the new element - if this is
  6586. below zero, it will be added to the end of the list
  6587. @see addChildElement, insertChildElement
  6588. */
  6589. void insertChildElement (XmlElement* const newChildNode,
  6590. int indexToInsertAt) throw();
  6591. /** Replaces one of this element's children with another node.
  6592. If the current element passed-in isn't actually a child of this element,
  6593. this will return false and the new one won't be added. Otherwise, the
  6594. existing element will be deleted, replaced with the new one, and it
  6595. will return true.
  6596. */
  6597. bool replaceChildElement (XmlElement* const currentChildElement,
  6598. XmlElement* const newChildNode) throw();
  6599. /** Removes a child element.
  6600. @param childToRemove the child to look for and remove
  6601. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6602. just remove it
  6603. */
  6604. void removeChildElement (XmlElement* const childToRemove,
  6605. const bool shouldDeleteTheChild) throw();
  6606. /** Deletes all the child elements in the element.
  6607. @see removeChildElement, deleteAllChildElementsWithTagName
  6608. */
  6609. void deleteAllChildElements() throw();
  6610. /** Deletes all the child elements with a given tag name.
  6611. @see removeChildElement
  6612. */
  6613. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6614. /** Returns true if the given element is a child of this one. */
  6615. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6616. /** Recursively searches all sub-elements to find one that contains the specified
  6617. child element.
  6618. */
  6619. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6620. /** Sorts the child elements using a comparator.
  6621. This will use a comparator object to sort the elements into order. The object
  6622. passed must have a method of the form:
  6623. @code
  6624. int compareElements (const XmlElement* first, const XmlElement* second);
  6625. @endcode
  6626. ..and this method must return:
  6627. - a value of < 0 if the first comes before the second
  6628. - a value of 0 if the two objects are equivalent
  6629. - a value of > 0 if the second comes before the first
  6630. To improve performance, the compareElements() method can be declared as static or const.
  6631. @param comparator the comparator to use for comparing elements.
  6632. @param retainOrderOfEquivalentItems if this is true, then items
  6633. which the comparator says are equivalent will be
  6634. kept in the order in which they currently appear
  6635. in the array. This is slower to perform, but may
  6636. be important in some cases. If it's false, a faster
  6637. algorithm is used, but equivalent elements may be
  6638. rearranged.
  6639. */
  6640. template <class ElementComparator>
  6641. void sortChildElements (ElementComparator& comparator,
  6642. const bool retainOrderOfEquivalentItems = false) throw()
  6643. {
  6644. const int num = getNumChildElements();
  6645. if (num > 1)
  6646. {
  6647. XmlElement** const elems = getChildElementsAsArray (num);
  6648. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  6649. reorderChildElements (elems, num);
  6650. delete[] elems;
  6651. }
  6652. }
  6653. /** Returns true if this element is a section of text.
  6654. Elements can either be an XML tag element or a secton of text, so this
  6655. is used to find out what kind of element this one is.
  6656. @see getAllText, addTextElement, deleteAllTextElements
  6657. */
  6658. bool isTextElement() const throw();
  6659. /** Returns the text for a text element.
  6660. Note that if you have an element like this:
  6661. @code<xyz>hello</xyz>@endcode
  6662. then calling getText on the "xyz" element won't return "hello", because that is
  6663. actually stored in a special text sub-element inside the xyz element. To get the
  6664. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6665. use getAllSubText() to do this automatically.
  6666. @see isTextElement, getAllSubText, getChildElementAllSubText
  6667. */
  6668. const String getText() const throw();
  6669. /** Sets the text in a text element.
  6670. Note that this is only a valid call if this element is a text element. If it's
  6671. not, then no action will be performed.
  6672. */
  6673. void setText (const String& newText) throw();
  6674. /** Returns all the text from this element's child nodes.
  6675. This iterates all the child elements and when it finds text elements,
  6676. it concatenates their text into a big string which it returns.
  6677. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6678. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6679. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6680. */
  6681. const String getAllSubText() const throw();
  6682. /** Returns all the sub-text of a named child element.
  6683. If there is a child element with the given tag name, this will return
  6684. all of its sub-text (by calling getAllSubText() on it). If there is
  6685. no such child element, this will return the default string passed-in.
  6686. @see getAllSubText
  6687. */
  6688. const String getChildElementAllSubText (const tchar* const childTagName,
  6689. const String& defaultReturnValue) const throw();
  6690. /** Appends a section of text to this element.
  6691. @see isTextElement, getText, getAllSubText
  6692. */
  6693. void addTextElement (const String& text) throw();
  6694. /** Removes all the text elements from this element.
  6695. @see isTextElement, getText, getAllSubText, addTextElement
  6696. */
  6697. void deleteAllTextElements() throw();
  6698. /** Creates a text element that can be added to a parent element.
  6699. */
  6700. static XmlElement* createTextElement (const String& text) throw();
  6701. juce_UseDebuggingNewOperator
  6702. private:
  6703. friend class XmlDocument;
  6704. String tagName;
  6705. XmlElement* firstChildElement;
  6706. XmlElement* nextElement;
  6707. struct XmlAttributeNode
  6708. {
  6709. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6710. XmlAttributeNode (const String& name, const String& value) throw();
  6711. String name, value;
  6712. XmlAttributeNode* next;
  6713. };
  6714. XmlAttributeNode* attributes;
  6715. XmlElement (int) throw(); // for internal use
  6716. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6717. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6718. void writeElementAsText (OutputStream& out,
  6719. const int indentationLevel,
  6720. const int lineWrapLength) const throw();
  6721. XmlElement** getChildElementsAsArray (const int) const throw();
  6722. void reorderChildElements (XmlElement** const, const int) throw();
  6723. };
  6724. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6725. /********* End of inlined file: juce_XmlElement.h *********/
  6726. /**
  6727. A set of named property values, which can be strings, integers, floating point, etc.
  6728. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6729. to load and save types other than strings.
  6730. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6731. messages and saves/loads the list from a file.
  6732. */
  6733. class JUCE_API PropertySet
  6734. {
  6735. public:
  6736. /** Creates an empty PropertySet.
  6737. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6738. case-insensitive way
  6739. */
  6740. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6741. /** Creates a copy of another PropertySet.
  6742. */
  6743. PropertySet (const PropertySet& other) throw();
  6744. /** Copies another PropertySet over this one.
  6745. */
  6746. const PropertySet& operator= (const PropertySet& other) throw();
  6747. /** Destructor. */
  6748. virtual ~PropertySet();
  6749. /** Returns one of the properties as a string.
  6750. If the value isn't found in this set, then this will look for it in a fallback
  6751. property set (if you've specified one with the setFallbackPropertySet() method),
  6752. and if it can't find one there, it'll return the default value passed-in.
  6753. @param keyName the name of the property to retrieve
  6754. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6755. */
  6756. const String getValue (const String& keyName,
  6757. const String& defaultReturnValue = String::empty) const throw();
  6758. /** Returns one of the properties as an integer.
  6759. If the value isn't found in this set, then this will look for it in a fallback
  6760. property set (if you've specified one with the setFallbackPropertySet() method),
  6761. and if it can't find one there, it'll return the default value passed-in.
  6762. @param keyName the name of the property to retrieve
  6763. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6764. */
  6765. int getIntValue (const String& keyName,
  6766. const int defaultReturnValue = 0) const throw();
  6767. /** Returns one of the properties as an double.
  6768. If the value isn't found in this set, then this will look for it in a fallback
  6769. property set (if you've specified one with the setFallbackPropertySet() method),
  6770. and if it can't find one there, it'll return the default value passed-in.
  6771. @param keyName the name of the property to retrieve
  6772. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6773. */
  6774. double getDoubleValue (const String& keyName,
  6775. const double defaultReturnValue = 0.0) const throw();
  6776. /** Returns one of the properties as an boolean.
  6777. The result will be true if the string found for this key name can be parsed as a non-zero
  6778. integer.
  6779. If the value isn't found in this set, then this will look for it in a fallback
  6780. property set (if you've specified one with the setFallbackPropertySet() method),
  6781. and if it can't find one there, it'll return the default value passed-in.
  6782. @param keyName the name of the property to retrieve
  6783. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6784. */
  6785. bool getBoolValue (const String& keyName,
  6786. const bool defaultReturnValue = false) const throw();
  6787. /** Returns one of the properties as an XML element.
  6788. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  6789. key isn't found, or if the entry contains an string that isn't valid XML.
  6790. If the value isn't found in this set, then this will look for it in a fallback
  6791. property set (if you've specified one with the setFallbackPropertySet() method),
  6792. and if it can't find one there, it'll return the default value passed-in.
  6793. @param keyName the name of the property to retrieve
  6794. */
  6795. XmlElement* getXmlValue (const String& keyName) const;
  6796. /** Sets a named property as a string.
  6797. @param keyName the name of the property to set. (This mustn't be an empty string)
  6798. @param value the new value to set it to
  6799. */
  6800. void setValue (const String& keyName, const String& value) throw();
  6801. /** Sets a named property as a string.
  6802. @param keyName the name of the property to set. (This mustn't be an empty string)
  6803. @param value the new value to set it to
  6804. */
  6805. void setValue (const String& keyName, const tchar* const value) throw();
  6806. /** Sets a named property to an integer.
  6807. @param keyName the name of the property to set. (This mustn't be an empty string)
  6808. @param value the new value to set it to
  6809. */
  6810. void setValue (const String& keyName, const int value) throw();
  6811. /** Sets a named property to a double.
  6812. @param keyName the name of the property to set. (This mustn't be an empty string)
  6813. @param value the new value to set it to
  6814. */
  6815. void setValue (const String& keyName, const double value) throw();
  6816. /** Sets a named property to a boolean.
  6817. @param keyName the name of the property to set. (This mustn't be an empty string)
  6818. @param value the new value to set it to
  6819. */
  6820. void setValue (const String& keyName, const bool value) throw();
  6821. /** Sets a named property to an XML element.
  6822. @param keyName the name of the property to set. (This mustn't be an empty string)
  6823. @param xml the new element to set it to. If this is zero, the value will be set to
  6824. an empty string
  6825. @see getXmlValue
  6826. */
  6827. void setValue (const String& keyName, const XmlElement* const xml);
  6828. /** Deletes a property.
  6829. @param keyName the name of the property to delete. (This mustn't be an empty string)
  6830. */
  6831. void removeValue (const String& keyName) throw();
  6832. /** Returns true if the properies include the given key. */
  6833. bool containsKey (const String& keyName) const throw();
  6834. /** Removes all values. */
  6835. void clear();
  6836. /** Returns the keys/value pair array containing all the properties. */
  6837. StringPairArray& getAllProperties() throw() { return properties; }
  6838. /** Returns the lock used when reading or writing to this set */
  6839. const CriticalSection& getLock() const throw() { return lock; }
  6840. /** Returns an XML element which encapsulates all the items in this property set.
  6841. The string parameter is the tag name that should be used for the node.
  6842. @see restoreFromXml
  6843. */
  6844. XmlElement* createXml (const String& nodeName) const throw();
  6845. /** Reloads a set of properties that were previously stored as XML.
  6846. The node passed in must have been created by the createXml() method.
  6847. @see createXml
  6848. */
  6849. void restoreFromXml (const XmlElement& xml) throw();
  6850. /** Sets up a second PopertySet that will be used to look up any values that aren't
  6851. set in this one.
  6852. If you set this up to be a pointer to a second property set, then whenever one
  6853. of the getValue() methods fails to find an entry in this set, it will look up that
  6854. value in the fallback set, and if it finds it, it will return that.
  6855. Make sure that you don't delete the fallback set while it's still being used by
  6856. another set! To remove the fallback set, just call this method with a null pointer.
  6857. @see getFallbackPropertySet
  6858. */
  6859. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  6860. /** Returns the fallback property set.
  6861. @see setFallbackPropertySet
  6862. */
  6863. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  6864. juce_UseDebuggingNewOperator
  6865. protected:
  6866. /** Subclasses can override this to be told when one of the properies has been changed.
  6867. */
  6868. virtual void propertyChanged();
  6869. private:
  6870. StringPairArray properties;
  6871. PropertySet* fallbackProperties;
  6872. CriticalSection lock;
  6873. bool ignoreCaseOfKeys;
  6874. };
  6875. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  6876. /********* End of inlined file: juce_PropertySet.h *********/
  6877. #endif
  6878. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  6879. #endif
  6880. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6881. #endif
  6882. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6883. #endif
  6884. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6885. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  6886. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6887. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6888. /**
  6889. Adds reference-counting to an object.
  6890. To add reference-counting to a class, derive it from this class, and
  6891. use the ReferenceCountedObjectPtr class to point to it.
  6892. e.g. @code
  6893. class MyClass : public ReferenceCountedObject
  6894. {
  6895. void foo();
  6896. // This is a neat way of declaring a typedef for a pointer class,
  6897. // rather than typing out the full templated name each time..
  6898. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  6899. };
  6900. MyClass::Ptr p = new MyClass();
  6901. MyClass::Ptr p2 = p;
  6902. p = 0;
  6903. p2->foo();
  6904. @endcode
  6905. Once a new ReferenceCountedObject has been assigned to a pointer, be
  6906. careful not to delete the object manually.
  6907. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  6908. */
  6909. class JUCE_API ReferenceCountedObject
  6910. {
  6911. public:
  6912. /** Increments the object's reference count.
  6913. This is done automatically by the smart pointer, but is public just
  6914. in case it's needed for nefarious purposes.
  6915. */
  6916. inline void incReferenceCount() throw()
  6917. {
  6918. atomicIncrement (refCounts);
  6919. jassert (refCounts > 0);
  6920. }
  6921. /** Decreases the object's reference count.
  6922. If the count gets to zero, the object will be deleted.
  6923. */
  6924. inline void decReferenceCount() throw()
  6925. {
  6926. jassert (refCounts > 0);
  6927. if (atomicDecrementAndReturn (refCounts) == 0)
  6928. delete this;
  6929. }
  6930. /** Returns the object's current reference count. */
  6931. inline int getReferenceCount() const throw()
  6932. {
  6933. return refCounts;
  6934. }
  6935. protected:
  6936. /** Creates the reference-counted object (with an initial ref count of zero). */
  6937. ReferenceCountedObject()
  6938. : refCounts (0)
  6939. {
  6940. }
  6941. /** Destructor. */
  6942. virtual ~ReferenceCountedObject()
  6943. {
  6944. // it's dangerous to delete an object that's still referenced by something else!
  6945. jassert (refCounts == 0);
  6946. }
  6947. private:
  6948. int refCounts;
  6949. };
  6950. /**
  6951. Used to point to an object of type ReferenceCountedObject.
  6952. It's wise to use a typedef instead of typing out the templated name
  6953. each time - e.g.
  6954. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  6955. @see ReferenceCountedObject, ReferenceCountedObjectArray
  6956. */
  6957. template <class ReferenceCountedObjectClass>
  6958. class ReferenceCountedObjectPtr
  6959. {
  6960. public:
  6961. /** Creates a pointer to a null object. */
  6962. inline ReferenceCountedObjectPtr() throw()
  6963. : referencedObject (0)
  6964. {
  6965. }
  6966. /** Creates a pointer to an object.
  6967. This will increment the object's reference-count if it is non-null.
  6968. */
  6969. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  6970. : referencedObject (refCountedObject)
  6971. {
  6972. if (refCountedObject != 0)
  6973. refCountedObject->incReferenceCount();
  6974. }
  6975. /** Copies another pointer.
  6976. This will increment the object's reference-count (if it is non-null).
  6977. */
  6978. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  6979. : referencedObject (other.referencedObject)
  6980. {
  6981. if (referencedObject != 0)
  6982. referencedObject->incReferenceCount();
  6983. }
  6984. /** Changes this pointer to point at a different object.
  6985. The reference count of the old object is decremented, and it might be
  6986. deleted if it hits zero. The new object's count is incremented.
  6987. */
  6988. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  6989. {
  6990. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  6991. if (newObject != referencedObject)
  6992. {
  6993. if (newObject != 0)
  6994. newObject->incReferenceCount();
  6995. ReferenceCountedObjectClass* const oldObject = referencedObject;
  6996. referencedObject = newObject;
  6997. if (oldObject != 0)
  6998. oldObject->decReferenceCount();
  6999. }
  7000. return *this;
  7001. }
  7002. /** Changes this pointer to point at a different object.
  7003. The reference count of the old object is decremented, and it might be
  7004. deleted if it hits zero. The new object's count is incremented.
  7005. */
  7006. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7007. {
  7008. if (referencedObject != newObject)
  7009. {
  7010. if (newObject != 0)
  7011. newObject->incReferenceCount();
  7012. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7013. referencedObject = newObject;
  7014. if (oldObject != 0)
  7015. oldObject->decReferenceCount();
  7016. }
  7017. return *this;
  7018. }
  7019. /** Destructor.
  7020. This will decrement the object's reference-count, and may delete it if it
  7021. gets to zero.
  7022. */
  7023. inline ~ReferenceCountedObjectPtr()
  7024. {
  7025. if (referencedObject != 0)
  7026. referencedObject->decReferenceCount();
  7027. }
  7028. /** Returns the object that this pointer references.
  7029. The pointer returned may be zero, of course.
  7030. */
  7031. inline operator ReferenceCountedObjectClass*() const throw()
  7032. {
  7033. return referencedObject;
  7034. }
  7035. /** Returns true if this pointer refers to the given object. */
  7036. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7037. {
  7038. return referencedObject == object;
  7039. }
  7040. /** Returns true if this pointer doesn't refer to the given object. */
  7041. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7042. {
  7043. return referencedObject != object;
  7044. }
  7045. // the -> operator is called on the referenced object
  7046. inline ReferenceCountedObjectClass* operator->() const throw()
  7047. {
  7048. return referencedObject;
  7049. }
  7050. private:
  7051. ReferenceCountedObjectClass* referencedObject;
  7052. };
  7053. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7054. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7055. #endif
  7056. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  7057. /********* Start of inlined file: juce_SparseSet.h *********/
  7058. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  7059. #define __JUCE_SPARSESET_JUCEHEADER__
  7060. /**
  7061. Holds a set of primitive values, storing them as a set of ranges.
  7062. This container acts like a simple BitArray, but can efficiently hold large
  7063. continguous ranges of values. It's quite a specialised class, mostly useful
  7064. for things like keeping the set of selected rows in a listbox.
  7065. The type used as a template paramter must be an integer type, such as int, short,
  7066. int64, etc.
  7067. */
  7068. template <class Type>
  7069. class SparseSet
  7070. {
  7071. public:
  7072. /** Creates a new empty set. */
  7073. SparseSet() throw()
  7074. {
  7075. }
  7076. /** Creates a copy of another SparseSet. */
  7077. SparseSet (const SparseSet<Type>& other) throw()
  7078. : values (other.values)
  7079. {
  7080. }
  7081. /** Destructor. */
  7082. ~SparseSet() throw()
  7083. {
  7084. }
  7085. /** Clears the set. */
  7086. void clear() throw()
  7087. {
  7088. values.clear();
  7089. }
  7090. /** Checks whether the set is empty.
  7091. This is much quicker than using (size() == 0).
  7092. */
  7093. bool isEmpty() const throw()
  7094. {
  7095. return values.size() == 0;
  7096. }
  7097. /** Returns the number of values in the set.
  7098. Because of the way the data is stored, this method can take longer if there
  7099. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  7100. are any items.
  7101. */
  7102. Type size() const throw()
  7103. {
  7104. Type num = 0;
  7105. for (int i = 0; i < values.size(); i += 2)
  7106. num += values[i + 1] - values[i];
  7107. return num;
  7108. }
  7109. /** Returns one of the values in the set.
  7110. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  7111. @returns the value at this index, or 0 if it's out-of-range
  7112. */
  7113. Type operator[] (int index) const throw()
  7114. {
  7115. for (int i = 0; i < values.size(); i += 2)
  7116. {
  7117. const Type s = values.getUnchecked(i);
  7118. const Type e = values.getUnchecked(i + 1);
  7119. if (index < e - s)
  7120. return s + index;
  7121. index -= e - s;
  7122. }
  7123. return (Type) 0;
  7124. }
  7125. /** Checks whether a particular value is in the set. */
  7126. bool contains (const Type valueToLookFor) const throw()
  7127. {
  7128. bool on = false;
  7129. for (int i = 0; i < values.size(); ++i)
  7130. {
  7131. if (values.getUnchecked(i) > valueToLookFor)
  7132. return on;
  7133. on = ! on;
  7134. }
  7135. return false;
  7136. }
  7137. /** Returns the number of contiguous blocks of values.
  7138. @see getRange
  7139. */
  7140. int getNumRanges() const throw()
  7141. {
  7142. return values.size() >> 1;
  7143. }
  7144. /** Returns one of the contiguous ranges of values stored.
  7145. @param rangeIndex the index of the range to look up, between 0
  7146. and (getNumRanges() - 1)
  7147. @param startValue on return, the value at the start of the range
  7148. @param numValues on return, the number of values in the range
  7149. @see getTotalRange
  7150. */
  7151. bool getRange (const int rangeIndex,
  7152. Type& startValue,
  7153. Type& numValues) const throw()
  7154. {
  7155. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  7156. {
  7157. startValue = values [rangeIndex << 1];
  7158. numValues = values [(rangeIndex << 1) + 1] - startValue;
  7159. return true;
  7160. }
  7161. return false;
  7162. }
  7163. /** Returns the lowest and highest values in the set.
  7164. @see getRange
  7165. */
  7166. bool getTotalRange (Type& lowestValue,
  7167. Type& highestValue) const throw()
  7168. {
  7169. if (values.size() > 0)
  7170. {
  7171. lowestValue = values.getUnchecked (0);
  7172. highestValue = values.getUnchecked (values.size() - 1);
  7173. return true;
  7174. }
  7175. return false;
  7176. }
  7177. /** Adds a range of contiguous values to the set.
  7178. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  7179. @param firstValue the start of the range of values to add
  7180. @param numValuesToAdd how many values to add
  7181. */
  7182. void addRange (const Type firstValue,
  7183. const Type numValuesToAdd) throw()
  7184. {
  7185. jassert (numValuesToAdd >= 0);
  7186. if (numValuesToAdd > 0)
  7187. {
  7188. removeRange (firstValue, numValuesToAdd);
  7189. IntegerElementComparator<Type> sorter;
  7190. values.addSorted (sorter, firstValue);
  7191. values.addSorted (sorter, firstValue + numValuesToAdd);
  7192. simplify();
  7193. }
  7194. }
  7195. /** Removes a range of values from the set.
  7196. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  7197. @param firstValue the start of the range of values to remove
  7198. @param numValuesToRemove how many values to remove
  7199. */
  7200. void removeRange (const Type firstValue,
  7201. const Type numValuesToRemove) throw()
  7202. {
  7203. jassert (numValuesToRemove >= 0);
  7204. if (numValuesToRemove > 0
  7205. && firstValue < values.getLast())
  7206. {
  7207. const bool onAtStart = contains (firstValue - 1);
  7208. Type lastValue = firstValue + numValuesToRemove;
  7209. if (lastValue < firstValue) // possible if the signed arithmetic wraps around
  7210. lastValue = values.getLast();
  7211. const bool onAtEnd = contains (lastValue);
  7212. for (int i = values.size(); --i >= 0;)
  7213. {
  7214. if (values.getUnchecked(i) >= firstValue
  7215. && values.getUnchecked(i) <= lastValue)
  7216. {
  7217. values.remove (i);
  7218. }
  7219. }
  7220. IntegerElementComparator<Type> sorter;
  7221. if (onAtStart)
  7222. values.addSorted (sorter, firstValue);
  7223. if (onAtEnd)
  7224. values.addSorted (sorter, lastValue);
  7225. simplify();
  7226. }
  7227. }
  7228. /** Does an XOR of the values in a given range. */
  7229. void invertRange (const Type firstValue,
  7230. const Type numValues)
  7231. {
  7232. SparseSet newItems;
  7233. newItems.addRange (firstValue, numValues);
  7234. int i;
  7235. for (i = getNumRanges(); --i >= 0;)
  7236. {
  7237. const int start = values [i << 1];
  7238. const int end = values [(i << 1) + 1];
  7239. newItems.removeRange (start, end);
  7240. }
  7241. removeRange (firstValue, numValues);
  7242. for (i = newItems.getNumRanges(); --i >= 0;)
  7243. {
  7244. const int start = newItems.values [i << 1];
  7245. const int end = newItems.values [(i << 1) + 1];
  7246. addRange (start, end);
  7247. }
  7248. }
  7249. /** Checks whether any part of a given range overlaps any part of this one. */
  7250. bool overlapsRange (const Type firstValue,
  7251. const Type numValues) throw()
  7252. {
  7253. jassert (numValues >= 0);
  7254. if (numValues > 0)
  7255. {
  7256. for (int i = getNumRanges(); --i >= 0;)
  7257. {
  7258. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  7259. return false;
  7260. if (firstValue + numValues > values.getUnchecked (i << 1))
  7261. return true;
  7262. }
  7263. }
  7264. return false;
  7265. }
  7266. /** Checks whether the whole of a given range is contained within this one. */
  7267. bool containsRange (const Type firstValue,
  7268. const Type numValues) throw()
  7269. {
  7270. jassert (numValues >= 0);
  7271. if (numValues > 0)
  7272. {
  7273. for (int i = getNumRanges(); --i >= 0;)
  7274. {
  7275. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  7276. return false;
  7277. if (firstValue >= values.getUnchecked (i << 1)
  7278. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  7279. return true;
  7280. }
  7281. }
  7282. return false;
  7283. }
  7284. bool operator== (const SparseSet<Type>& other) throw()
  7285. {
  7286. return values == other.values;
  7287. }
  7288. bool operator!= (const SparseSet<Type>& other) throw()
  7289. {
  7290. return values != other.values;
  7291. }
  7292. juce_UseDebuggingNewOperator
  7293. private:
  7294. // alternating start/end values of ranges of values that are present.
  7295. Array<Type> values;
  7296. void simplify() throw()
  7297. {
  7298. jassert ((values.size() & 1) == 0);
  7299. for (int i = values.size(); --i > 0;)
  7300. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  7301. values.removeRange (i - 1, 2);
  7302. }
  7303. };
  7304. #endif // __JUCE_SPARSESET_JUCEHEADER__
  7305. /********* End of inlined file: juce_SparseSet.h *********/
  7306. #endif
  7307. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7308. #endif
  7309. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7310. /********* Start of inlined file: juce_SortedSet.h *********/
  7311. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7312. #define __JUCE_SORTEDSET_JUCEHEADER__
  7313. #if JUCE_MSVC
  7314. #pragma warning (push)
  7315. #pragma warning (disable: 4512)
  7316. #endif
  7317. /**
  7318. Holds a set of unique primitive objects, such as ints or doubles.
  7319. A set can only hold one item with a given value, so if for example it's a
  7320. set of integers, attempting to add the same integer twice will do nothing
  7321. the second time.
  7322. Internally, the list of items is kept sorted (which means that whatever
  7323. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7324. to determine the order), and searching the set for known values is very fast
  7325. because it uses a binary-chop method.
  7326. Note that if you're using a class or struct as the element type, it must be
  7327. capable of being copied or moved with a straightforward memcpy, rather than
  7328. needing construction and destruction code.
  7329. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7330. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7331. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7332. */
  7333. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7334. class SortedSet : private ArrayAllocationBase <ElementType>
  7335. {
  7336. public:
  7337. /** Creates an empty set.
  7338. @param granularity this is the size of increment by which the internal storage
  7339. used by the array will grow. Only change it from the default if you know the
  7340. array is going to be very big and needs to be able to grow efficiently.
  7341. @see ArrayAllocationBase
  7342. */
  7343. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7344. : ArrayAllocationBase <ElementType> (granularity),
  7345. numUsed (0)
  7346. {
  7347. }
  7348. /** Creates a copy of another set.
  7349. @param other the set to copy
  7350. */
  7351. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7352. : ArrayAllocationBase <ElementType> (other.granularity)
  7353. {
  7354. other.lockSet();
  7355. numUsed = other.numUsed;
  7356. setAllocatedSize (other.numUsed);
  7357. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7358. other.unlockSet();
  7359. }
  7360. /** Destructor. */
  7361. ~SortedSet() throw()
  7362. {
  7363. }
  7364. /** Copies another set over this one.
  7365. @param other the set to copy
  7366. */
  7367. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7368. {
  7369. if (this != &other)
  7370. {
  7371. other.lockSet();
  7372. lock.enter();
  7373. this->granularity = other.granularity;
  7374. ensureAllocatedSize (other.size());
  7375. numUsed = other.numUsed;
  7376. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7377. minimiseStorageOverheads();
  7378. lock.exit();
  7379. other.unlockSet();
  7380. }
  7381. return *this;
  7382. }
  7383. /** Compares this set to another one.
  7384. Two sets are considered equal if they both contain the same set of
  7385. elements.
  7386. @param other the other set to compare with
  7387. */
  7388. bool operator== (const SortedSet<ElementType>& other) const throw()
  7389. {
  7390. lock.enter();
  7391. if (numUsed != other.numUsed)
  7392. {
  7393. lock.exit();
  7394. return false;
  7395. }
  7396. for (int i = numUsed; --i >= 0;)
  7397. {
  7398. if (this->elements [i] != other.elements [i])
  7399. {
  7400. lock.exit();
  7401. return false;
  7402. }
  7403. }
  7404. lock.exit();
  7405. return true;
  7406. }
  7407. /** Compares this set to another one.
  7408. Two sets are considered equal if they both contain the same set of
  7409. elements.
  7410. @param other the other set to compare with
  7411. */
  7412. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7413. {
  7414. return ! operator== (other);
  7415. }
  7416. /** Removes all elements from the set.
  7417. This will remove all the elements, and free any storage that the set is
  7418. using. To clear it without freeing the storage, use the clearQuick()
  7419. method instead.
  7420. @see clearQuick
  7421. */
  7422. void clear() throw()
  7423. {
  7424. lock.enter();
  7425. this->setAllocatedSize (0);
  7426. numUsed = 0;
  7427. lock.exit();
  7428. }
  7429. /** Removes all elements from the set without freeing the array's allocated storage.
  7430. @see clear
  7431. */
  7432. void clearQuick() throw()
  7433. {
  7434. lock.enter();
  7435. numUsed = 0;
  7436. lock.exit();
  7437. }
  7438. /** Returns the current number of elements in the set.
  7439. */
  7440. inline int size() const throw()
  7441. {
  7442. return numUsed;
  7443. }
  7444. /** Returns one of the elements in the set.
  7445. If the index passed in is beyond the range of valid elements, this
  7446. will return zero.
  7447. If you're certain that the index will always be a valid element, you
  7448. can call getUnchecked() instead, which is faster.
  7449. @param index the index of the element being requested (0 is the first element in the set)
  7450. @see getUnchecked, getFirst, getLast
  7451. */
  7452. inline ElementType operator[] (const int index) const throw()
  7453. {
  7454. lock.enter();
  7455. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  7456. ? this->elements [index]
  7457. : (ElementType) 0;
  7458. lock.exit();
  7459. return result;
  7460. }
  7461. /** Returns one of the elements in the set, without checking the index passed in.
  7462. Unlike the operator[] method, this will try to return an element without
  7463. checking that the index is within the bounds of the set, so should only
  7464. be used when you're confident that it will always be a valid index.
  7465. @param index the index of the element being requested (0 is the first element in the set)
  7466. @see operator[], getFirst, getLast
  7467. */
  7468. inline ElementType getUnchecked (const int index) const throw()
  7469. {
  7470. lock.enter();
  7471. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7472. const ElementType result = this->elements [index];
  7473. lock.exit();
  7474. return result;
  7475. }
  7476. /** Returns the first element in the set, or 0 if the set is empty.
  7477. @see operator[], getUnchecked, getLast
  7478. */
  7479. inline ElementType getFirst() const throw()
  7480. {
  7481. lock.enter();
  7482. const ElementType result = (numUsed > 0) ? this->elements [0]
  7483. : (ElementType) 0;
  7484. lock.exit();
  7485. return result;
  7486. }
  7487. /** Returns the last element in the set, or 0 if the set is empty.
  7488. @see operator[], getUnchecked, getFirst
  7489. */
  7490. inline ElementType getLast() const throw()
  7491. {
  7492. lock.enter();
  7493. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  7494. : (ElementType) 0;
  7495. lock.exit();
  7496. return result;
  7497. }
  7498. /** Finds the index of the first element which matches the value passed in.
  7499. This will search the set for the given object, and return the index
  7500. of its first occurrence. If the object isn't found, the method will return -1.
  7501. @param elementToLookFor the value or object to look for
  7502. @returns the index of the object, or -1 if it's not found
  7503. */
  7504. int indexOf (const ElementType elementToLookFor) const throw()
  7505. {
  7506. lock.enter();
  7507. int start = 0;
  7508. int end = numUsed;
  7509. for (;;)
  7510. {
  7511. if (start >= end)
  7512. {
  7513. lock.exit();
  7514. return -1;
  7515. }
  7516. else if (elementToLookFor == this->elements [start])
  7517. {
  7518. lock.exit();
  7519. return start;
  7520. }
  7521. else
  7522. {
  7523. const int halfway = (start + end) >> 1;
  7524. if (halfway == start)
  7525. {
  7526. lock.exit();
  7527. return -1;
  7528. }
  7529. else if (elementToLookFor >= this->elements [halfway])
  7530. start = halfway;
  7531. else
  7532. end = halfway;
  7533. }
  7534. }
  7535. }
  7536. /** Returns true if the set contains at least one occurrence of an object.
  7537. @param elementToLookFor the value or object to look for
  7538. @returns true if the item is found
  7539. */
  7540. bool contains (const ElementType elementToLookFor) const throw()
  7541. {
  7542. lock.enter();
  7543. int start = 0;
  7544. int end = numUsed;
  7545. for (;;)
  7546. {
  7547. if (start >= end)
  7548. {
  7549. lock.exit();
  7550. return false;
  7551. }
  7552. else if (elementToLookFor == this->elements [start])
  7553. {
  7554. lock.exit();
  7555. return true;
  7556. }
  7557. else
  7558. {
  7559. const int halfway = (start + end) >> 1;
  7560. if (halfway == start)
  7561. {
  7562. lock.exit();
  7563. return false;
  7564. }
  7565. else if (elementToLookFor >= this->elements [halfway])
  7566. start = halfway;
  7567. else
  7568. end = halfway;
  7569. }
  7570. }
  7571. }
  7572. /** Adds a new element to the set, (as long as it's not already in there).
  7573. @param newElement the new object to add to the set
  7574. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  7575. */
  7576. void add (const ElementType newElement) throw()
  7577. {
  7578. lock.enter();
  7579. int start = 0;
  7580. int end = numUsed;
  7581. for (;;)
  7582. {
  7583. if (start >= end)
  7584. {
  7585. jassert (start <= end);
  7586. insertInternal (start, newElement);
  7587. break;
  7588. }
  7589. else if (newElement == this->elements [start])
  7590. {
  7591. break;
  7592. }
  7593. else
  7594. {
  7595. const int halfway = (start + end) >> 1;
  7596. if (halfway == start)
  7597. {
  7598. if (newElement >= this->elements [halfway])
  7599. insertInternal (start + 1, newElement);
  7600. else
  7601. insertInternal (start, newElement);
  7602. break;
  7603. }
  7604. else if (newElement >= this->elements [halfway])
  7605. start = halfway;
  7606. else
  7607. end = halfway;
  7608. }
  7609. }
  7610. lock.exit();
  7611. }
  7612. /** Adds elements from an array to this set.
  7613. @param elementsToAdd the array of elements to add
  7614. @param numElementsToAdd how many elements are in this other array
  7615. @see add
  7616. */
  7617. void addArray (const ElementType* elementsToAdd,
  7618. int numElementsToAdd) throw()
  7619. {
  7620. lock.enter();
  7621. while (--numElementsToAdd >= 0)
  7622. add (*elementsToAdd++);
  7623. lock.exit();
  7624. }
  7625. /** Adds elements from another set to this one.
  7626. @param setToAddFrom the set from which to copy the elements
  7627. @param startIndex the first element of the other set to start copying from
  7628. @param numElementsToAdd how many elements to add from the other set. If this
  7629. value is negative or greater than the number of available elements,
  7630. all available elements will be copied.
  7631. @see add
  7632. */
  7633. template <class OtherSetType>
  7634. void addSet (const OtherSetType& setToAddFrom,
  7635. int startIndex = 0,
  7636. int numElementsToAdd = -1) throw()
  7637. {
  7638. setToAddFrom.lockSet();
  7639. lock.enter();
  7640. jassert (this != &setToAddFrom);
  7641. if (this != &setToAddFrom)
  7642. {
  7643. if (startIndex < 0)
  7644. {
  7645. jassertfalse
  7646. startIndex = 0;
  7647. }
  7648. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  7649. numElementsToAdd = setToAddFrom.size() - startIndex;
  7650. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  7651. }
  7652. lock.exit();
  7653. setToAddFrom.unlockSet();
  7654. }
  7655. /** Removes an element from the set.
  7656. This will remove the element at a given index.
  7657. If the index passed in is out-of-range, nothing will happen.
  7658. @param indexToRemove the index of the element to remove
  7659. @returns the element that has been removed
  7660. @see removeValue, removeRange
  7661. */
  7662. ElementType remove (const int indexToRemove) throw()
  7663. {
  7664. lock.enter();
  7665. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7666. {
  7667. --numUsed;
  7668. ElementType* const e = this->elements + indexToRemove;
  7669. ElementType const removed = *e;
  7670. const int numberToShift = numUsed - indexToRemove;
  7671. if (numberToShift > 0)
  7672. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  7673. if ((numUsed << 1) < this->numAllocated)
  7674. minimiseStorageOverheads();
  7675. lock.exit();
  7676. return removed;
  7677. }
  7678. else
  7679. {
  7680. lock.exit();
  7681. return 0;
  7682. }
  7683. }
  7684. /** Removes an item from the set.
  7685. This will remove the given element from the set, if it's there.
  7686. @param valueToRemove the object to try to remove
  7687. @see remove, removeRange
  7688. */
  7689. void removeValue (const ElementType valueToRemove) throw()
  7690. {
  7691. lock.enter();
  7692. remove (indexOf (valueToRemove));
  7693. lock.exit();
  7694. }
  7695. /** Removes any elements which are also in another set.
  7696. @param otherSet the other set in which to look for elements to remove
  7697. @see removeValuesNotIn, remove, removeValue, removeRange
  7698. */
  7699. template <class OtherSetType>
  7700. void removeValuesIn (const OtherSetType& otherSet) throw()
  7701. {
  7702. otherSet.lockSet();
  7703. lock.enter();
  7704. if (this == &otherSet)
  7705. {
  7706. clear();
  7707. }
  7708. else
  7709. {
  7710. if (otherSet.size() > 0)
  7711. {
  7712. for (int i = numUsed; --i >= 0;)
  7713. if (otherSet.contains (this->elements [i]))
  7714. remove (i);
  7715. }
  7716. }
  7717. lock.exit();
  7718. otherSet.unlockSet();
  7719. }
  7720. /** Removes any elements which are not found in another set.
  7721. Only elements which occur in this other set will be retained.
  7722. @param otherSet the set in which to look for elements NOT to remove
  7723. @see removeValuesIn, remove, removeValue, removeRange
  7724. */
  7725. template <class OtherSetType>
  7726. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  7727. {
  7728. otherSet.lockSet();
  7729. lock.enter();
  7730. if (this != &otherSet)
  7731. {
  7732. if (otherSet.size() <= 0)
  7733. {
  7734. clear();
  7735. }
  7736. else
  7737. {
  7738. for (int i = numUsed; --i >= 0;)
  7739. if (! otherSet.contains (this->elements [i]))
  7740. remove (i);
  7741. }
  7742. }
  7743. lock.exit();
  7744. otherSet.lockSet();
  7745. }
  7746. /** Reduces the amount of storage being used by the set.
  7747. Sets typically allocate slightly more storage than they need, and after
  7748. removing elements, they may have quite a lot of unused space allocated.
  7749. This method will reduce the amount of allocated storage to a minimum.
  7750. */
  7751. void minimiseStorageOverheads() throw()
  7752. {
  7753. lock.enter();
  7754. if (numUsed == 0)
  7755. {
  7756. this->setAllocatedSize (0);
  7757. }
  7758. else
  7759. {
  7760. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  7761. if (newAllocation < this->numAllocated)
  7762. this->setAllocatedSize (newAllocation);
  7763. }
  7764. lock.exit();
  7765. }
  7766. /** Locks the set's CriticalSection.
  7767. Of course if the type of section used is a DummyCriticalSection, this won't
  7768. have any effect.
  7769. @see unlockSet
  7770. */
  7771. void lockSet() const throw()
  7772. {
  7773. lock.enter();
  7774. }
  7775. /** Unlocks the set's CriticalSection.
  7776. Of course if the type of section used is a DummyCriticalSection, this won't
  7777. have any effect.
  7778. @see lockSet
  7779. */
  7780. void unlockSet() const throw()
  7781. {
  7782. lock.exit();
  7783. }
  7784. juce_UseDebuggingNewOperator
  7785. private:
  7786. int numUsed;
  7787. TypeOfCriticalSectionToUse lock;
  7788. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  7789. {
  7790. this->ensureAllocatedSize (numUsed + 1);
  7791. ElementType* const insertPos = this->elements + indexToInsertAt;
  7792. const int numberToMove = numUsed - indexToInsertAt;
  7793. if (numberToMove > 0)
  7794. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  7795. *insertPos = newElement;
  7796. ++numUsed;
  7797. }
  7798. };
  7799. #if JUCE_MSVC
  7800. #pragma warning (pop)
  7801. #endif
  7802. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  7803. /********* End of inlined file: juce_SortedSet.h *********/
  7804. #endif
  7805. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  7806. /********* Start of inlined file: juce_BitArray.h *********/
  7807. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  7808. #define __JUCE_BITARRAY_JUCEHEADER__
  7809. class MemoryBlock;
  7810. /**
  7811. An array of on/off bits, also usable to store large binary integers.
  7812. A BitArray acts like an arbitrarily large integer whose bits can be set or
  7813. cleared, and some basic mathematical operations can be done on the number as
  7814. a whole.
  7815. */
  7816. class JUCE_API BitArray
  7817. {
  7818. public:
  7819. /** Creates an empty BitArray */
  7820. BitArray() throw();
  7821. /** Creates a BitArray containing an integer value in its low bits.
  7822. The low 32 bits of the array are initialised with this value.
  7823. */
  7824. BitArray (const unsigned int value) throw();
  7825. /** Creates a BitArray containing an integer value in its low bits.
  7826. The low 32 bits of the array are initialised with the absolute value
  7827. passed in, and its sign is set to reflect the sign of the number.
  7828. */
  7829. BitArray (const int value) throw();
  7830. /** Creates a BitArray containing an integer value in its low bits.
  7831. The low 64 bits of the array are initialised with the absolute value
  7832. passed in, and its sign is set to reflect the sign of the number.
  7833. */
  7834. BitArray (int64 value) throw();
  7835. /** Creates a copy of another BitArray. */
  7836. BitArray (const BitArray& other) throw();
  7837. /** Destructor. */
  7838. ~BitArray() throw();
  7839. /** Copies another BitArray onto this one. */
  7840. const BitArray& operator= (const BitArray& other) throw();
  7841. /** Two arrays are the same if the same bits are set. */
  7842. bool operator== (const BitArray& other) const throw();
  7843. /** Two arrays are the same if the same bits are set. */
  7844. bool operator!= (const BitArray& other) const throw();
  7845. /** Clears all bits in the BitArray to 0. */
  7846. void clear() throw();
  7847. /** Clears a particular bit in the array. */
  7848. void clearBit (const int bitNumber) throw();
  7849. /** Sets a specified bit to 1.
  7850. If the bit number is high, this will grow the array to accomodate it.
  7851. */
  7852. void setBit (const int bitNumber) throw();
  7853. /** Sets or clears a specified bit. */
  7854. void setBit (const int bitNumber,
  7855. const bool shouldBeSet) throw();
  7856. /** Sets a range of bits to be either on or off.
  7857. @param startBit the first bit to change
  7858. @param numBits the number of bits to change
  7859. @param shouldBeSet whether to turn these bits on or off
  7860. */
  7861. void setRange (int startBit,
  7862. int numBits,
  7863. const bool shouldBeSet) throw();
  7864. /** Inserts a bit an a given position, shifting up any bits above it. */
  7865. void insertBit (const int bitNumber,
  7866. const bool shouldBeSet) throw();
  7867. /** Returns the value of a specified bit in the array.
  7868. If the index is out-of-range, the result will be false.
  7869. */
  7870. bool operator[] (const int bit) const throw();
  7871. /** Returns true if no bits are set. */
  7872. bool isEmpty() const throw();
  7873. /** Returns a range of bits in the array as an integer value.
  7874. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  7875. Asking for more than 32 bits isn't allowed (obviously).
  7876. */
  7877. int getBitRangeAsInt (int startBit, int numBits) const throw();
  7878. /** Sets a range of bits in the array based on an integer value.
  7879. Copies the given integer into the array, starting at startBit,
  7880. and only using up to numBits of the available bits.
  7881. */
  7882. void setBitRangeAsInt (int startBit, int numBits,
  7883. unsigned int valueToSet) throw();
  7884. /** Performs a bitwise OR with another BitArray.
  7885. The result ends up in this array.
  7886. */
  7887. void orWith (const BitArray& other) throw();
  7888. /** Performs a bitwise AND with another BitArray.
  7889. The result ends up in this array.
  7890. */
  7891. void andWith (const BitArray& other) throw();
  7892. /** Performs a bitwise XOR with another BitArray.
  7893. The result ends up in this array.
  7894. */
  7895. void xorWith (const BitArray& other) throw();
  7896. /** Adds another BitArray's value to this one.
  7897. Treating the two arrays as large positive integers, this
  7898. adds them up and puts the result in this array.
  7899. */
  7900. void add (const BitArray& other) throw();
  7901. /** Subtracts another BitArray's value from this one.
  7902. Treating the two arrays as large positive integers, this
  7903. subtracts them and puts the result in this array.
  7904. Note that if the result should be negative, this won't be
  7905. handled correctly.
  7906. */
  7907. void subtract (const BitArray& other) throw();
  7908. /** Multiplies another BitArray's value with this one.
  7909. Treating the two arrays as large positive integers, this
  7910. multiplies them and puts the result in this array.
  7911. */
  7912. void multiplyBy (const BitArray& other) throw();
  7913. /** Divides another BitArray's value into this one and also produces a remainder.
  7914. Treating the two arrays as large positive integers, this
  7915. divides this value by the other, leaving the quotient in this
  7916. array, and the remainder is copied into the other BitArray passed in.
  7917. */
  7918. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  7919. /** Returns the largest value that will divide both this value and the one
  7920. passed-in.
  7921. */
  7922. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  7923. /** Performs a modulo operation on this value.
  7924. The result is stored in this value.
  7925. */
  7926. void modulo (const BitArray& divisor) throw();
  7927. /** Performs a combined exponent and modulo operation.
  7928. This BitArray's value becomes (this ^ exponent) % modulus.
  7929. */
  7930. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  7931. /** Performs an inverse modulo on the value.
  7932. i.e. the result is (this ^ -1) mod (modulus).
  7933. */
  7934. void inverseModulo (const BitArray& modulus) throw();
  7935. /** Shifts a section of bits left or right.
  7936. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  7937. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  7938. */
  7939. void shiftBits (int howManyBitsLeft,
  7940. int startBit = 0) throw();
  7941. /** Does a signed comparison of two BitArrays.
  7942. Return values are:
  7943. - 0 if the numbers are the same
  7944. - < 0 if this number is smaller than the other
  7945. - > 0 if this number is bigger than the other
  7946. */
  7947. int compare (const BitArray& other) const throw();
  7948. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  7949. Return values are:
  7950. - 0 if the numbers are the same
  7951. - < 0 if this number is smaller than the other
  7952. - > 0 if this number is bigger than the other
  7953. */
  7954. int compareAbsolute (const BitArray& other) const throw();
  7955. /** Returns true if the value is less than zero.
  7956. @see setNegative, negate
  7957. */
  7958. bool isNegative() const throw();
  7959. /** Changes the sign of the number to be positive or negative.
  7960. @see isNegative, negate
  7961. */
  7962. void setNegative (const bool shouldBeNegative) throw();
  7963. /** Inverts the sign of the number.
  7964. @see isNegative, setNegative
  7965. */
  7966. void negate() throw();
  7967. /** Counts the total number of set bits in the array. */
  7968. int countNumberOfSetBits() const throw();
  7969. /** Looks for the index of the next set bit after a given starting point.
  7970. searches from startIndex (inclusive) upwards for the first set bit,
  7971. and returns its index.
  7972. If no set bits are found, it returns -1.
  7973. */
  7974. int findNextSetBit (int startIndex = 0) const throw();
  7975. /** Looks for the index of the next clear bit after a given starting point.
  7976. searches from startIndex (inclusive) upwards for the first clear bit,
  7977. and returns its index.
  7978. */
  7979. int findNextClearBit (int startIndex = 0) const throw();
  7980. /** Returns the index of the highest set bit in the array.
  7981. If the array is empty, this will return -1.
  7982. */
  7983. int getHighestBit() const throw();
  7984. /** Sets a range of bits to random values. */
  7985. void fillBitsRandomly (int startBit, int numBits) throw();
  7986. /** Turns this value into a random number less than the given value. */
  7987. void createRandomNumber (const BitArray& maximumValue) throw();
  7988. /** Converts the array to a number string.
  7989. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  7990. */
  7991. const String toString (const int base) const throw();
  7992. /** Converts a number string to an array.
  7993. Any non-valid characters will be ignored.
  7994. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  7995. */
  7996. void parseString (const String& text,
  7997. const int base) throw();
  7998. /** Turns the array into a block of binary data.
  7999. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  8000. of the array, and so on.
  8001. @see loadFromMemoryBlock
  8002. */
  8003. const MemoryBlock toMemoryBlock() const throw();
  8004. /** Copies a block of raw data onto this array.
  8005. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  8006. of the array, and so on.
  8007. @see toMemoryBlock
  8008. */
  8009. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  8010. juce_UseDebuggingNewOperator
  8011. private:
  8012. void ensureSize (const int numVals) throw();
  8013. unsigned int* values;
  8014. int numValues, highestBit;
  8015. bool negative;
  8016. };
  8017. #endif // __JUCE_BITARRAY_JUCEHEADER__
  8018. /********* End of inlined file: juce_BitArray.h *********/
  8019. #endif
  8020. #ifndef __JUCE_ARRAY_JUCEHEADER__
  8021. #endif
  8022. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  8023. #endif
  8024. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8025. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  8026. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8027. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8028. /**
  8029. Holds a list of objects derived from ReferenceCountedObject.
  8030. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  8031. and takes care of incrementing and decrementing their ref counts when they
  8032. are added and removed from the array.
  8033. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  8034. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8035. @see Array, OwnedArray, StringArray
  8036. */
  8037. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8038. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  8039. {
  8040. public:
  8041. /** Creates an empty array.
  8042. @param granularity this is the size of increment by which the internal storage
  8043. used by the array will grow. Only change it from the default if you know the
  8044. array is going to be very big and needs to be able to grow efficiently.
  8045. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  8046. */
  8047. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  8048. : ArrayAllocationBase <ObjectClass*> (granularity),
  8049. numUsed (0)
  8050. {
  8051. }
  8052. /** Creates a copy of another array */
  8053. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  8054. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  8055. numUsed (other.numUsed)
  8056. {
  8057. other.lockArray();
  8058. this->setAllocatedSize (numUsed);
  8059. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  8060. for (int i = numUsed; --i >= 0;)
  8061. if (this->elements[i] != 0)
  8062. this->elements[i]->incReferenceCount();
  8063. other.unlockArray();
  8064. }
  8065. /** Copies another array into this one.
  8066. Any existing objects in this array will first be released.
  8067. */
  8068. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  8069. {
  8070. if (this != &other)
  8071. {
  8072. other.lockArray();
  8073. lock.enter();
  8074. clear();
  8075. this->granularity = other.granularity;
  8076. this->ensureAllocatedSize (other.numUsed);
  8077. numUsed = other.numUsed;
  8078. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  8079. minimiseStorageOverheads();
  8080. for (int i = numUsed; --i >= 0;)
  8081. if (this->elements[i] != 0)
  8082. this->elements[i]->incReferenceCount();
  8083. lock.exit();
  8084. other.unlockArray();
  8085. }
  8086. return *this;
  8087. }
  8088. /** Destructor.
  8089. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  8090. */
  8091. ~ReferenceCountedArray()
  8092. {
  8093. clear();
  8094. }
  8095. /** Removes all objects from the array.
  8096. Any objects in the array that are not referenced from elsewhere will be deleted.
  8097. */
  8098. void clear()
  8099. {
  8100. lock.enter();
  8101. while (numUsed > 0)
  8102. if (this->elements [--numUsed] != 0)
  8103. this->elements [numUsed]->decReferenceCount();
  8104. jassert (numUsed == 0);
  8105. this->setAllocatedSize (0);
  8106. lock.exit();
  8107. }
  8108. /** Returns the current number of objects in the array. */
  8109. inline int size() const throw()
  8110. {
  8111. return numUsed;
  8112. }
  8113. /** Returns a pointer to the object at this index in the array.
  8114. If the index is out-of-range, this will return a null pointer, (and
  8115. it could be null anyway, because it's ok for the array to hold null
  8116. pointers as well as objects).
  8117. @see getUnchecked
  8118. */
  8119. inline ObjectClass* operator[] (const int index) const throw()
  8120. {
  8121. lock.enter();
  8122. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  8123. ? this->elements [index]
  8124. : (ObjectClass*) 0;
  8125. lock.exit();
  8126. return result;
  8127. }
  8128. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  8129. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  8130. it can be used when you're sure the index if always going to be legal.
  8131. */
  8132. inline ObjectClass* getUnchecked (const int index) const throw()
  8133. {
  8134. lock.enter();
  8135. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8136. ObjectClass* const result = this->elements [index];
  8137. lock.exit();
  8138. return result;
  8139. }
  8140. /** Returns a pointer to the first object in the array.
  8141. This will return a null pointer if the array's empty.
  8142. @see getLast
  8143. */
  8144. inline ObjectClass* getFirst() const throw()
  8145. {
  8146. lock.enter();
  8147. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  8148. : (ObjectClass*) 0;
  8149. lock.exit();
  8150. return result;
  8151. }
  8152. /** Returns a pointer to the last object in the array.
  8153. This will return a null pointer if the array's empty.
  8154. @see getFirst
  8155. */
  8156. inline ObjectClass* getLast() const throw()
  8157. {
  8158. lock.enter();
  8159. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  8160. : (ObjectClass*) 0;
  8161. lock.exit();
  8162. return result;
  8163. }
  8164. /** Finds the index of the first occurrence of an object in the array.
  8165. @param objectToLookFor the object to look for
  8166. @returns the index at which the object was found, or -1 if it's not found
  8167. */
  8168. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  8169. {
  8170. int result = -1;
  8171. lock.enter();
  8172. ObjectClass** e = this->elements;
  8173. for (int i = numUsed; --i >= 0;)
  8174. {
  8175. if (objectToLookFor == *e)
  8176. {
  8177. result = (int) (e - this->elements);
  8178. break;
  8179. }
  8180. ++e;
  8181. }
  8182. lock.exit();
  8183. return result;
  8184. }
  8185. /** Returns true if the array contains a specified object.
  8186. @param objectToLookFor the object to look for
  8187. @returns true if the object is in the array
  8188. */
  8189. bool contains (const ObjectClass* const objectToLookFor) const throw()
  8190. {
  8191. lock.enter();
  8192. ObjectClass** e = this->elements;
  8193. for (int i = numUsed; --i >= 0;)
  8194. {
  8195. if (objectToLookFor == *e)
  8196. {
  8197. lock.exit();
  8198. return true;
  8199. }
  8200. ++e;
  8201. }
  8202. lock.exit();
  8203. return false;
  8204. }
  8205. /** Appends a new object to the end of the array.
  8206. This will increase the new object's reference count.
  8207. @param newObject the new object to add to the array
  8208. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  8209. */
  8210. void add (ObjectClass* const newObject) throw()
  8211. {
  8212. lock.enter();
  8213. this->ensureAllocatedSize (numUsed + 1);
  8214. this->elements [numUsed++] = newObject;
  8215. if (newObject != 0)
  8216. newObject->incReferenceCount();
  8217. lock.exit();
  8218. }
  8219. /** Inserts a new object into the array at the given index.
  8220. If the index is less than 0 or greater than the size of the array, the
  8221. element will be added to the end of the array.
  8222. Otherwise, it will be inserted into the array, moving all the later elements
  8223. along to make room.
  8224. This will increase the new object's reference count.
  8225. @param indexToInsertAt the index at which the new element should be inserted
  8226. @param newObject the new object to add to the array
  8227. @see add, addSorted, addIfNotAlreadyThere, set
  8228. */
  8229. void insert (int indexToInsertAt,
  8230. ObjectClass* const newObject) throw()
  8231. {
  8232. if (indexToInsertAt >= 0)
  8233. {
  8234. lock.enter();
  8235. if (indexToInsertAt > numUsed)
  8236. indexToInsertAt = numUsed;
  8237. this->ensureAllocatedSize (numUsed + 1);
  8238. ObjectClass** const e = this->elements + indexToInsertAt;
  8239. const int numToMove = numUsed - indexToInsertAt;
  8240. if (numToMove > 0)
  8241. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8242. *e = newObject;
  8243. if (newObject != 0)
  8244. newObject->incReferenceCount();
  8245. ++numUsed;
  8246. lock.exit();
  8247. }
  8248. else
  8249. {
  8250. add (newObject);
  8251. }
  8252. }
  8253. /** Appends a new object at the end of the array as long as the array doesn't
  8254. already contain it.
  8255. If the array already contains a matching object, nothing will be done.
  8256. @param newObject the new object to add to the array
  8257. */
  8258. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8259. {
  8260. lock.enter();
  8261. if (! contains (newObject))
  8262. add (newObject);
  8263. lock.exit();
  8264. }
  8265. /** Replaces an object in the array with a different one.
  8266. If the index is less than zero, this method does nothing.
  8267. If the index is beyond the end of the array, the new object is added to the end of the array.
  8268. The object being added has its reference count increased, and if it's replacing
  8269. another object, then that one has its reference count decreased, and may be deleted.
  8270. @param indexToChange the index whose value you want to change
  8271. @param newObject the new value to set for this index.
  8272. @see add, insert, remove
  8273. */
  8274. void set (const int indexToChange,
  8275. ObjectClass* const newObject)
  8276. {
  8277. if (indexToChange >= 0)
  8278. {
  8279. lock.enter();
  8280. if (newObject != 0)
  8281. newObject->incReferenceCount();
  8282. if (indexToChange < numUsed)
  8283. {
  8284. if (this->elements [indexToChange] != 0)
  8285. this->elements [indexToChange]->decReferenceCount();
  8286. this->elements [indexToChange] = newObject;
  8287. }
  8288. else
  8289. {
  8290. this->ensureAllocatedSize (numUsed + 1);
  8291. this->elements [numUsed++] = newObject;
  8292. }
  8293. lock.exit();
  8294. }
  8295. }
  8296. /** Adds elements from another array to the end of this array.
  8297. @param arrayToAddFrom the array from which to copy the elements
  8298. @param startIndex the first element of the other array to start copying from
  8299. @param numElementsToAdd how many elements to add from the other array. If this
  8300. value is negative or greater than the number of available elements,
  8301. all available elements will be copied.
  8302. @see add
  8303. */
  8304. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8305. int startIndex = 0,
  8306. int numElementsToAdd = -1) throw()
  8307. {
  8308. arrayToAddFrom.lockArray();
  8309. lock.enter();
  8310. if (startIndex < 0)
  8311. {
  8312. jassertfalse
  8313. startIndex = 0;
  8314. }
  8315. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8316. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8317. if (numElementsToAdd > 0)
  8318. {
  8319. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  8320. while (--numElementsToAdd >= 0)
  8321. add (arrayToAddFrom.getUnchecked (startIndex++));
  8322. }
  8323. lock.exit();
  8324. arrayToAddFrom.unlockArray();
  8325. }
  8326. /** Inserts a new object into the array assuming that the array is sorted.
  8327. This will use a comparator to find the position at which the new object
  8328. should go. If the array isn't sorted, the behaviour of this
  8329. method will be unpredictable.
  8330. @param comparator the comparator object to use to compare the elements - see the
  8331. sort() method for details about this object's form
  8332. @param newObject the new object to insert to the array
  8333. @see add, sort
  8334. */
  8335. template <class ElementComparator>
  8336. void addSorted (ElementComparator& comparator,
  8337. ObjectClass* newObject) throw()
  8338. {
  8339. lock.enter();
  8340. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  8341. lock.exit();
  8342. }
  8343. /** Removes an object from the array.
  8344. This will remove the object at a given index and move back all the
  8345. subsequent objects to close the gap.
  8346. If the index passed in is out-of-range, nothing will happen.
  8347. The object that is removed will have its reference count decreased,
  8348. and may be deleted if not referenced from elsewhere.
  8349. @param indexToRemove the index of the element to remove
  8350. @see removeObject, removeRange
  8351. */
  8352. void remove (const int indexToRemove)
  8353. {
  8354. lock.enter();
  8355. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8356. {
  8357. ObjectClass** const e = this->elements + indexToRemove;
  8358. if (*e != 0)
  8359. (*e)->decReferenceCount();
  8360. --numUsed;
  8361. const int numberToShift = numUsed - indexToRemove;
  8362. if (numberToShift > 0)
  8363. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8364. if ((numUsed << 1) < this->numAllocated)
  8365. minimiseStorageOverheads();
  8366. }
  8367. lock.exit();
  8368. }
  8369. /** Removes the first occurrence of a specified object from the array.
  8370. If the item isn't found, no action is taken. If it is found, it is
  8371. removed and has its reference count decreased.
  8372. @param objectToRemove the object to try to remove
  8373. @see remove, removeRange
  8374. */
  8375. void removeObject (ObjectClass* const objectToRemove)
  8376. {
  8377. lock.enter();
  8378. remove (indexOf (objectToRemove));
  8379. lock.exit();
  8380. }
  8381. /** Removes a range of objects from the array.
  8382. This will remove a set of objects, starting from the given index,
  8383. and move any subsequent elements down to close the gap.
  8384. If the range extends beyond the bounds of the array, it will
  8385. be safely clipped to the size of the array.
  8386. The objects that are removed will have their reference counts decreased,
  8387. and may be deleted if not referenced from elsewhere.
  8388. @param startIndex the index of the first object to remove
  8389. @param numberToRemove how many objects should be removed
  8390. @see remove, removeObject
  8391. */
  8392. void removeRange (const int startIndex,
  8393. const int numberToRemove)
  8394. {
  8395. lock.enter();
  8396. const int start = jlimit (0, numUsed, startIndex);
  8397. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8398. if (end > start)
  8399. {
  8400. int i;
  8401. for (i = start; i < end; ++i)
  8402. {
  8403. if (this->elements[i] != 0)
  8404. {
  8405. this->elements[i]->decReferenceCount();
  8406. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8407. }
  8408. }
  8409. const int rangeSize = end - start;
  8410. ObjectClass** e = this->elements + start;
  8411. i = numUsed - end;
  8412. numUsed -= rangeSize;
  8413. while (--i >= 0)
  8414. {
  8415. *e = e [rangeSize];
  8416. ++e;
  8417. }
  8418. if ((numUsed << 1) < this->numAllocated)
  8419. minimiseStorageOverheads();
  8420. }
  8421. lock.exit();
  8422. }
  8423. /** Removes the last n objects from the array.
  8424. The objects that are removed will have their reference counts decreased,
  8425. and may be deleted if not referenced from elsewhere.
  8426. @param howManyToRemove how many objects to remove from the end of the array
  8427. @see remove, removeObject, removeRange
  8428. */
  8429. void removeLast (int howManyToRemove = 1)
  8430. {
  8431. lock.enter();
  8432. if (howManyToRemove > numUsed)
  8433. howManyToRemove = numUsed;
  8434. while (--howManyToRemove >= 0)
  8435. remove (numUsed - 1);
  8436. lock.exit();
  8437. }
  8438. /** Swaps a pair of objects in the array.
  8439. If either of the indexes passed in is out-of-range, nothing will happen,
  8440. otherwise the two objects at these positions will be exchanged.
  8441. */
  8442. void swap (const int index1,
  8443. const int index2) throw()
  8444. {
  8445. lock.enter();
  8446. if (((unsigned int) index1) < (unsigned int) numUsed
  8447. && ((unsigned int) index2) < (unsigned int) numUsed)
  8448. {
  8449. swapVariables (this->elements [index1],
  8450. this->elements [index2]);
  8451. }
  8452. lock.exit();
  8453. }
  8454. /** Moves one of the objects to a different position.
  8455. This will move the object to a specified index, shuffling along
  8456. any intervening elements as required.
  8457. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8458. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8459. @param currentIndex the index of the object to be moved. If this isn't a
  8460. valid index, then nothing will be done
  8461. @param newIndex the index at which you'd like this object to end up. If this
  8462. is less than zero, it will be moved to the end of the array
  8463. */
  8464. void move (const int currentIndex,
  8465. int newIndex) throw()
  8466. {
  8467. if (currentIndex != newIndex)
  8468. {
  8469. lock.enter();
  8470. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8471. {
  8472. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8473. newIndex = numUsed - 1;
  8474. ObjectClass* const value = this->elements [currentIndex];
  8475. if (newIndex > currentIndex)
  8476. {
  8477. memmove (this->elements + currentIndex,
  8478. this->elements + currentIndex + 1,
  8479. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8480. }
  8481. else
  8482. {
  8483. memmove (this->elements + newIndex + 1,
  8484. this->elements + newIndex,
  8485. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8486. }
  8487. this->elements [newIndex] = value;
  8488. }
  8489. lock.exit();
  8490. }
  8491. }
  8492. /** Compares this array to another one.
  8493. @returns true only if the other array contains the same objects in the same order
  8494. */
  8495. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8496. {
  8497. other.lockArray();
  8498. lock.enter();
  8499. bool result = numUsed == other.numUsed;
  8500. if (result)
  8501. {
  8502. for (int i = numUsed; --i >= 0;)
  8503. {
  8504. if (this->elements [i] != other.elements [i])
  8505. {
  8506. result = false;
  8507. break;
  8508. }
  8509. }
  8510. }
  8511. lock.exit();
  8512. other.unlockArray();
  8513. return result;
  8514. }
  8515. /** Compares this array to another one.
  8516. @see operator==
  8517. */
  8518. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8519. {
  8520. return ! operator== (other);
  8521. }
  8522. /** Sorts the elements in the array.
  8523. This will use a comparator object to sort the elements into order. The object
  8524. passed must have a method of the form:
  8525. @code
  8526. int compareElements (ElementType first, ElementType second);
  8527. @endcode
  8528. ..and this method must return:
  8529. - a value of < 0 if the first comes before the second
  8530. - a value of 0 if the two objects are equivalent
  8531. - a value of > 0 if the second comes before the first
  8532. To improve performance, the compareElements() method can be declared as static or const.
  8533. @param comparator the comparator to use for comparing elements.
  8534. @param retainOrderOfEquivalentItems if this is true, then items
  8535. which the comparator says are equivalent will be
  8536. kept in the order in which they currently appear
  8537. in the array. This is slower to perform, but may
  8538. be important in some cases. If it's false, a faster
  8539. algorithm is used, but equivalent elements may be
  8540. rearranged.
  8541. @see sortArray
  8542. */
  8543. template <class ElementComparator>
  8544. void sort (ElementComparator& comparator,
  8545. const bool retainOrderOfEquivalentItems = false) const throw()
  8546. {
  8547. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8548. // avoids getting warning messages about the parameter being unused
  8549. lock.enter();
  8550. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  8551. lock.exit();
  8552. }
  8553. /** Reduces the amount of storage being used by the array.
  8554. Arrays typically allocate slightly more storage than they need, and after
  8555. removing elements, they may have quite a lot of unused space allocated.
  8556. This method will reduce the amount of allocated storage to a minimum.
  8557. */
  8558. void minimiseStorageOverheads() throw()
  8559. {
  8560. lock.enter();
  8561. if (numUsed == 0)
  8562. {
  8563. this->setAllocatedSize (0);
  8564. }
  8565. else
  8566. {
  8567. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8568. if (newAllocation < this->numAllocated)
  8569. this->setAllocatedSize (newAllocation);
  8570. }
  8571. lock.exit();
  8572. }
  8573. /** Locks the array's CriticalSection.
  8574. Of course if the type of section used is a DummyCriticalSection, this won't
  8575. have any effect.
  8576. @see unlockArray
  8577. */
  8578. void lockArray() const throw()
  8579. {
  8580. lock.enter();
  8581. }
  8582. /** Unlocks the array's CriticalSection.
  8583. Of course if the type of section used is a DummyCriticalSection, this won't
  8584. have any effect.
  8585. @see lockArray
  8586. */
  8587. void unlockArray() const throw()
  8588. {
  8589. lock.exit();
  8590. }
  8591. juce_UseDebuggingNewOperator
  8592. private:
  8593. int numUsed;
  8594. TypeOfCriticalSectionToUse lock;
  8595. };
  8596. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8597. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  8598. #endif
  8599. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  8600. #endif
  8601. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  8602. #endif
  8603. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8604. /********* Start of inlined file: juce_FileInputStream.h *********/
  8605. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8606. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8607. /**
  8608. An input stream that reads from a local file.
  8609. @see InputStream, FileOutputStream, File::createInputStream
  8610. */
  8611. class JUCE_API FileInputStream : public InputStream
  8612. {
  8613. public:
  8614. /** Creates a FileInputStream.
  8615. @param fileToRead the file to read from - if the file can't be accessed for some
  8616. reason, then the stream will just contain no data
  8617. */
  8618. FileInputStream (const File& fileToRead);
  8619. /** Destructor. */
  8620. ~FileInputStream();
  8621. const File& getFile() const throw() { return file; }
  8622. int64 getTotalLength();
  8623. int read (void* destBuffer, int maxBytesToRead);
  8624. bool isExhausted();
  8625. int64 getPosition();
  8626. bool setPosition (int64 pos);
  8627. juce_UseDebuggingNewOperator
  8628. private:
  8629. File file;
  8630. void* fileHandle;
  8631. int64 currentPosition, totalSize;
  8632. bool needToSeek;
  8633. };
  8634. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8635. /********* End of inlined file: juce_FileInputStream.h *********/
  8636. #endif
  8637. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8638. /********* Start of inlined file: juce_FileOutputStream.h *********/
  8639. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8640. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8641. /**
  8642. An output stream that writes into a local file.
  8643. @see OutputStream, FileInputStream, File::createOutputStream
  8644. */
  8645. class JUCE_API FileOutputStream : public OutputStream
  8646. {
  8647. public:
  8648. /** Creates a FileOutputStream.
  8649. If the file doesn't exist, it will first be created. If the file can't be
  8650. created or opened, the failedToOpen() method will return
  8651. true.
  8652. If the file already exists when opened, the stream's write-postion will
  8653. be set to the end of the file. To overwrite an existing file,
  8654. use File::deleteFile() before opening the stream, or use setPosition(0)
  8655. after it's opened (although this won't truncate the file).
  8656. It's better to use File::createOutputStream() to create one of these, rather
  8657. than using the class directly.
  8658. */
  8659. FileOutputStream (const File& fileToWriteTo,
  8660. const int bufferSizeToUse = 16384);
  8661. /** Destructor. */
  8662. ~FileOutputStream();
  8663. /** Returns the file that this stream is writing to.
  8664. */
  8665. const File& getFile() const throw() { return file; }
  8666. /** Returns true if the stream couldn't be opened for some reason.
  8667. */
  8668. bool failedToOpen() const throw() { return fileHandle == 0; }
  8669. void flush();
  8670. int64 getPosition();
  8671. bool setPosition (int64 pos);
  8672. bool write (const void* data, int numBytes);
  8673. juce_UseDebuggingNewOperator
  8674. private:
  8675. File file;
  8676. void* fileHandle;
  8677. int64 currentPosition;
  8678. int bufferSize, bytesInBuffer;
  8679. char* buffer;
  8680. };
  8681. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8682. /********* End of inlined file: juce_FileOutputStream.h *********/
  8683. #endif
  8684. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8685. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  8686. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8687. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8688. /**
  8689. Searches through a the files in a directory, returning each file that is found.
  8690. A DirectoryIterator will search through a directory and its subdirectories using
  8691. a wildcard filepattern match.
  8692. If you may be finding a large number of files, this is better than
  8693. using File::findChildFiles() because it doesn't block while it finds them
  8694. all, and this is more memory-efficient.
  8695. It can also guess how far it's got using a wildly inaccurate algorithm.
  8696. */
  8697. class JUCE_API DirectoryIterator
  8698. {
  8699. public:
  8700. /** Creates a DirectoryIterator for a given directory.
  8701. After creating one of these, call its next() method to get the
  8702. first file - e.g. @code
  8703. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  8704. while (iter.next())
  8705. {
  8706. File theFileItFound (iter.getFile());
  8707. ... etc
  8708. }
  8709. @endcode
  8710. @param directory the directory to search in
  8711. @param isRecursive whether all the subdirectories should also be searched
  8712. @param wildCard the file pattern to match
  8713. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  8714. whether to look for files, directories, or both.
  8715. */
  8716. DirectoryIterator (const File& directory,
  8717. bool isRecursive,
  8718. const String& wildCard = JUCE_T("*"),
  8719. const int whatToLookFor = File::findFiles) throw();
  8720. /** Destructor. */
  8721. ~DirectoryIterator() throw();
  8722. /** Call this to move the iterator along to the next file.
  8723. @returns true if a file was found (you can then use getFile() to see what it was) - or
  8724. false if there are no more matching files.
  8725. */
  8726. bool next() throw();
  8727. /** Returns the file that the iterator is currently pointing at.
  8728. The result of this call is only valid after a call to next() has returned true.
  8729. */
  8730. const File getFile() const throw();
  8731. /** Returns a guess of how far through the search the iterator has got.
  8732. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  8733. very accurate.
  8734. */
  8735. float getEstimatedProgress() const throw();
  8736. juce_UseDebuggingNewOperator
  8737. private:
  8738. OwnedArray <File> filesFound;
  8739. OwnedArray <File> dirsFound;
  8740. String wildCard;
  8741. int index;
  8742. const int whatToLookFor;
  8743. DirectoryIterator* subIterator;
  8744. DirectoryIterator (const DirectoryIterator&);
  8745. const DirectoryIterator& operator= (const DirectoryIterator&);
  8746. };
  8747. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8748. /********* End of inlined file: juce_DirectoryIterator.h *********/
  8749. #endif
  8750. #ifndef __JUCE_FILE_JUCEHEADER__
  8751. #endif
  8752. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8753. /********* Start of inlined file: juce_FileSearchPath.h *********/
  8754. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8755. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  8756. /**
  8757. Encapsulates a set of folders that make up a search path.
  8758. @see File
  8759. */
  8760. class JUCE_API FileSearchPath
  8761. {
  8762. public:
  8763. /** Creates an empty search path. */
  8764. FileSearchPath();
  8765. /** Creates a search path from a string of pathnames.
  8766. The path can be semicolon- or comma-separated, e.g.
  8767. "/foo/bar;/foo/moose;/fish/moose"
  8768. The separate folders are tokenised and added to the search path.
  8769. */
  8770. FileSearchPath (const String& path);
  8771. /** Creates a copy of another search path. */
  8772. FileSearchPath (const FileSearchPath& other);
  8773. /** Destructor. */
  8774. ~FileSearchPath();
  8775. /** Uses a string containing a list of pathnames to re-initialise this list.
  8776. This search path is cleared and the semicolon- or comma-separated folders
  8777. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  8778. */
  8779. const FileSearchPath& operator= (const String& path);
  8780. /** Returns the number of folders in this search path.
  8781. @see operator[]
  8782. */
  8783. int getNumPaths() const;
  8784. /** Returns one of the folders in this search path.
  8785. The file returned isn't guaranteed to actually be a valid directory.
  8786. @see getNumPaths
  8787. */
  8788. const File operator[] (const int index) const;
  8789. /** Returns the search path as a semicolon-separated list of directories. */
  8790. const String toString() const;
  8791. /** Adds a new directory to the search path.
  8792. The new directory is added to the end of the list if the insertIndex parameter is
  8793. less than zero, otherwise it is inserted at the given index.
  8794. */
  8795. void add (const File& directoryToAdd,
  8796. const int insertIndex = -1);
  8797. /** Adds a new directory to the search path if it's not already in there. */
  8798. void addIfNotAlreadyThere (const File& directoryToAdd);
  8799. /** Removes a directory from the search path. */
  8800. void remove (const int indexToRemove);
  8801. /** Merges another search path into this one.
  8802. This will remove any duplicate directories.
  8803. */
  8804. void addPath (const FileSearchPath& other);
  8805. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  8806. If the search is intended to be recursive, there's no point having nested folders in the search
  8807. path, because they'll just get searched twice and you'll get duplicate results.
  8808. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  8809. */
  8810. void removeRedundantPaths();
  8811. /** Removes any directories that don't actually exist. */
  8812. void removeNonExistentPaths();
  8813. /** Searches the path for a wildcard.
  8814. This will search all the directories in the search path in order, adding any
  8815. matching files to the results array.
  8816. @param results an array to append the results to
  8817. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  8818. return files, directories, or both.
  8819. @param searchRecursively whether to recursively search the subdirectories too
  8820. @param wildCardPattern a pattern to match against the filenames
  8821. @returns the number of files added to the array
  8822. @see File::findChildFiles
  8823. */
  8824. int findChildFiles (OwnedArray<File>& results,
  8825. const int whatToLookFor,
  8826. const bool searchRecursively,
  8827. const String& wildCardPattern = JUCE_T("*")) const;
  8828. /** Finds out whether a file is inside one of the path's directories.
  8829. This will return true if the specified file is a child of one of the
  8830. directories specified by this path. Note that this doesn't actually do any
  8831. searching or check that the files exist - it just looks at the pathnames
  8832. to work out whether the file would be inside a directory.
  8833. @param fileToCheck the file to look for
  8834. @param checkRecursively if true, then this will return true if the file is inside a
  8835. subfolder of one of the path's directories (at any depth). If false
  8836. it will only return true if the file is actually a direct child
  8837. of one of the directories.
  8838. @see File::isAChildOf
  8839. */
  8840. bool isFileInPath (const File& fileToCheck,
  8841. const bool checkRecursively) const;
  8842. juce_UseDebuggingNewOperator
  8843. private:
  8844. StringArray directories;
  8845. void init (const String& path);
  8846. };
  8847. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  8848. /********* End of inlined file: juce_FileSearchPath.h *********/
  8849. #endif
  8850. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8851. /********* Start of inlined file: juce_NamedPipe.h *********/
  8852. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8853. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  8854. /**
  8855. A cross-process pipe that can have data written to and read from it.
  8856. Two or more processes can use these for inter-process communication.
  8857. @see InterprocessConnection
  8858. */
  8859. class JUCE_API NamedPipe
  8860. {
  8861. public:
  8862. /** Creates a NamedPipe. */
  8863. NamedPipe();
  8864. /** Destructor. */
  8865. ~NamedPipe();
  8866. /** Tries to open a pipe that already exists.
  8867. Returns true if it succeeds.
  8868. */
  8869. bool openExisting (const String& pipeName);
  8870. /** Tries to create a new pipe.
  8871. Returns true if it succeeds.
  8872. */
  8873. bool createNewPipe (const String& pipeName);
  8874. /** Closes the pipe, if it's open. */
  8875. void close();
  8876. /** True if the pipe is currently open. */
  8877. bool isOpen() const throw();
  8878. /** Returns the last name that was used to try to open this pipe. */
  8879. const String getName() const throw();
  8880. /** Reads data from the pipe.
  8881. This will block until another thread has written enough data into the pipe to fill
  8882. the number of bytes specified, or until another thread calls the cancelPendingReads()
  8883. method.
  8884. If the operation fails, it returns -1, otherwise, it will return the number of
  8885. bytes read.
  8886. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  8887. this is a maximum timeout for reading from the pipe.
  8888. */
  8889. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  8890. /** Writes some data to the pipe.
  8891. If the operation fails, it returns -1, otherwise, it will return the number of
  8892. bytes written.
  8893. */
  8894. int write (const void* sourceBuffer, int numBytesToWrite,
  8895. int timeOutMilliseconds = 2000);
  8896. /** If any threads are currently blocked on a read operation, this tells them to abort.
  8897. */
  8898. void cancelPendingReads();
  8899. juce_UseDebuggingNewOperator
  8900. private:
  8901. void* internal;
  8902. String currentPipeName;
  8903. NamedPipe (const NamedPipe&);
  8904. const NamedPipe& operator= (const NamedPipe&);
  8905. bool openInternal (const String& pipeName, const bool createPipe);
  8906. };
  8907. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  8908. /********* End of inlined file: juce_NamedPipe.h *********/
  8909. #endif
  8910. #ifndef __JUCE_MD5_JUCEHEADER__
  8911. /********* Start of inlined file: juce_MD5.h *********/
  8912. #ifndef __JUCE_MD5_JUCEHEADER__
  8913. #define __JUCE_MD5_JUCEHEADER__
  8914. /**
  8915. MD5 checksum class.
  8916. Create one of these with a block of source data or a string, and it calculates the
  8917. MD5 checksum of that data.
  8918. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  8919. */
  8920. class JUCE_API MD5
  8921. {
  8922. public:
  8923. /** Creates a null MD5 object. */
  8924. MD5();
  8925. /** Creates a copy of another MD5. */
  8926. MD5 (const MD5& other);
  8927. /** Copies another MD5. */
  8928. const MD5& operator= (const MD5& other);
  8929. /** Creates a checksum for a block of binary data. */
  8930. MD5 (const MemoryBlock& data);
  8931. /** Creates a checksum for a block of binary data. */
  8932. MD5 (const char* data, const int numBytes);
  8933. /** Creates a checksum for a string. */
  8934. MD5 (const String& text);
  8935. /** Creates a checksum for the input from a stream.
  8936. This will read up to the given number of bytes from the stream, and produce the
  8937. checksum of that. If the number of bytes to read is negative, it'll read
  8938. until the stream is exhausted.
  8939. */
  8940. MD5 (InputStream& input, int numBytesToRead = -1);
  8941. /** Creates a checksum for a file. */
  8942. MD5 (const File& file);
  8943. /** Destructor. */
  8944. ~MD5();
  8945. /** Returns the checksum as a 16-byte block of data. */
  8946. const MemoryBlock getRawChecksumData() const;
  8947. /** Returns the checksum as a 32-digit hex string. */
  8948. const String toHexString() const;
  8949. /** Compares this to another MD5. */
  8950. bool operator== (const MD5& other) const;
  8951. /** Compares this to another MD5. */
  8952. bool operator!= (const MD5& other) const;
  8953. juce_UseDebuggingNewOperator
  8954. private:
  8955. uint8 result [16];
  8956. struct ProcessContext
  8957. {
  8958. uint8 buffer [64];
  8959. uint32 state [4];
  8960. uint32 count [2];
  8961. ProcessContext();
  8962. void processBlock (const uint8* const data, int dataSize);
  8963. void transform (const uint8* const buffer);
  8964. void finish (uint8* const result);
  8965. };
  8966. void processStream (InputStream& input, int numBytesToRead);
  8967. };
  8968. #endif // __JUCE_MD5_JUCEHEADER__
  8969. /********* End of inlined file: juce_MD5.h *********/
  8970. #endif
  8971. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8972. /********* Start of inlined file: juce_BlowFish.h *********/
  8973. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8974. #define __JUCE_BLOWFISH_JUCEHEADER__
  8975. /**
  8976. BlowFish encryption class.
  8977. */
  8978. class JUCE_API BlowFish
  8979. {
  8980. public:
  8981. /** Creates an object that can encode/decode based on the specified key.
  8982. The key data can be up to 72 bytes long.
  8983. */
  8984. BlowFish (const uint8* keyData, int keyBytes);
  8985. /** Creates a copy of another blowfish object. */
  8986. BlowFish (const BlowFish& other);
  8987. /** Copies another blowfish object. */
  8988. const BlowFish& operator= (const BlowFish& other);
  8989. /** Destructor. */
  8990. ~BlowFish();
  8991. /** Encrypts a pair of 32-bit integers. */
  8992. void encrypt (uint32& data1, uint32& data2) const;
  8993. /** Decrypts a pair of 32-bit integers. */
  8994. void decrypt (uint32& data1, uint32& data2) const;
  8995. juce_UseDebuggingNewOperator
  8996. private:
  8997. uint32 p[18];
  8998. uint32* s[4];
  8999. uint32 F (uint32 x) const;
  9000. };
  9001. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  9002. /********* End of inlined file: juce_BlowFish.h *********/
  9003. #endif
  9004. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9005. /********* Start of inlined file: juce_RSAKey.h *********/
  9006. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9007. #define __JUCE_RSAKEY_JUCEHEADER__
  9008. /**
  9009. RSA public/private key-pair encryption class.
  9010. An object of this type makes up one half of a public/private RSA key pair. Use the
  9011. createKeyPair() method to create a matching pair for encoding/decoding.
  9012. */
  9013. class JUCE_API RSAKey
  9014. {
  9015. public:
  9016. /** Creates a null key object.
  9017. Initialise a pair of objects for use with the createKeyPair() method.
  9018. */
  9019. RSAKey() throw();
  9020. /** Loads a key from an encoded string representation.
  9021. This reloads a key from a string created by the toString() method.
  9022. */
  9023. RSAKey (const String& stringRepresentation) throw();
  9024. /** Destructor. */
  9025. ~RSAKey() throw();
  9026. /** Turns the key into a string representation.
  9027. This can be reloaded using the constructor that takes a string.
  9028. */
  9029. const String toString() const throw();
  9030. /** Encodes or decodes a value.
  9031. Call this on the public key object to encode some data, then use the matching
  9032. private key object to decode it.
  9033. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9034. */
  9035. bool applyToValue (BitArray& value) const throw();
  9036. /** Creates a public/private key-pair.
  9037. Each key will perform one-way encryption that can only be reversed by
  9038. using the other key.
  9039. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9040. sizes are more secure, but this method will take longer to execute.
  9041. */
  9042. static void createKeyPair (RSAKey& publicKey,
  9043. RSAKey& privateKey,
  9044. const int numBits) throw();
  9045. juce_UseDebuggingNewOperator
  9046. protected:
  9047. BitArray part1, part2;
  9048. };
  9049. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9050. /********* End of inlined file: juce_RSAKey.h *********/
  9051. #endif
  9052. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9053. /********* Start of inlined file: juce_Primes.h *********/
  9054. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9055. #define __JUCE_PRIMES_JUCEHEADER__
  9056. /**
  9057. Prime number creation class.
  9058. This class contains static methods for generating and testing prime numbers.
  9059. @see BitArray
  9060. */
  9061. class JUCE_API Primes
  9062. {
  9063. public:
  9064. /** Creates a random prime number with a given bit-length.
  9065. The certainty parameter specifies how many iterations to use when testing
  9066. for primality. A safe value might be anything over about 20-30.
  9067. */
  9068. static const BitArray createProbablePrime (int bitLength,
  9069. int certainty) throw();
  9070. /** Tests a number to see if it's prime.
  9071. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9072. whether the number is prime.
  9073. The certainty parameter specifies how many iterations to use when testing - a
  9074. safe value might be anything over about 20-30.
  9075. */
  9076. static bool isProbablyPrime (const BitArray& number,
  9077. int certainty) throw();
  9078. };
  9079. #endif // __JUCE_PRIMES_JUCEHEADER__
  9080. /********* End of inlined file: juce_Primes.h *********/
  9081. #endif
  9082. #ifndef __JUCE_URL_JUCEHEADER__
  9083. /********* Start of inlined file: juce_URL.h *********/
  9084. #ifndef __JUCE_URL_JUCEHEADER__
  9085. #define __JUCE_URL_JUCEHEADER__
  9086. /**
  9087. Represents a URL and has a bunch of useful functions to manipulate it.
  9088. This class can be used to launch URLs in browsers, and also to create
  9089. InputStreams that can read from remote http or ftp sources.
  9090. */
  9091. class JUCE_API URL
  9092. {
  9093. public:
  9094. /** Creates an empty URL. */
  9095. URL() throw();
  9096. /** Creates a URL from a string. */
  9097. URL (const String& url);
  9098. /** Creates a copy of another URL. */
  9099. URL (const URL& other);
  9100. /** Destructor. */
  9101. ~URL() throw();
  9102. /** Copies this URL from another one. */
  9103. const URL& operator= (const URL& other);
  9104. /** Returns a string version of the URL.
  9105. If includeGetParameters is true and any parameters have been set with the
  9106. withParameter() method, then the string will have these appended on the
  9107. end and url-encoded.
  9108. */
  9109. const String toString (const bool includeGetParameters) const;
  9110. /** True if it seems to be valid. */
  9111. bool isWellFormed() const;
  9112. /** Returns a copy of this URL, with a GET parameter added to the end.
  9113. Any control characters in the value will be encoded.
  9114. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  9115. would produce a new url whose toString(true) method would return
  9116. "www.fish.com?amount=some+fish".
  9117. */
  9118. const URL withParameter (const String& parameterName,
  9119. const String& parameterValue) const;
  9120. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  9121. When performing a POST where one of your parameters is a binary file, this
  9122. lets you specify the file.
  9123. Note that the filename is stored, but the file itself won't actually be read
  9124. until this URL is later used to create a network input stream.
  9125. */
  9126. const URL withFileToUpload (const String& parameterName,
  9127. const File& fileToUpload,
  9128. const String& mimeType) const;
  9129. /** Returns a set of all the parameters encoded into the url.
  9130. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  9131. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  9132. The values returned will have been cleaned up to remove any escape characters.
  9133. @see getNamedParameter, withParameter
  9134. */
  9135. const StringPairArray& getParameters() const throw();
  9136. /** Returns the set of files that should be uploaded as part of a POST operation.
  9137. This is the set of files that were added to the URL with the withFileToUpload()
  9138. method.
  9139. */
  9140. const StringPairArray& getFilesToUpload() const throw();
  9141. /** Returns the set of mime types associated with each of the upload files.
  9142. */
  9143. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  9144. /** Tries to launch the system's default browser to open the URL.
  9145. Returns true if this seems to have worked.
  9146. */
  9147. bool launchInDefaultBrowser() const;
  9148. /** Takes a guess as to whether a string might be a valid website address.
  9149. This isn't foolproof!
  9150. */
  9151. static bool isProbablyAWebsiteURL (const String& possibleURL);
  9152. /** Takes a guess as to whether a string might be a valid email address.
  9153. This isn't foolproof!
  9154. */
  9155. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  9156. /** This callback function can be used by the createInputStream() method.
  9157. It allows your app to receive progress updates during a lengthy POST operation. If you
  9158. want to continue the operation, this should return true, or false to abort.
  9159. */
  9160. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  9161. /** Attempts to open a stream that can read from this URL.
  9162. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  9163. the paramters, otherwise it'll encode them into the
  9164. URL and do a 'GET'.
  9165. @param progressCallback if this is non-zero, it lets you supply a callback function
  9166. to keep track of the operation's progress. This can be useful
  9167. for lengthy POST operations, so that you can provide user feedback.
  9168. @param progressCallbackContext if a callback is specified, this value will be passed to
  9169. the function
  9170. @param extraHeaders if not empty, this string is appended onto the headers that
  9171. are used for the request. It must therefore be a valid set of HTML
  9172. header directives, separated by newlines.
  9173. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  9174. a negative number, it will be infinite. Otherwise it specifies a
  9175. time in milliseconds.
  9176. */
  9177. InputStream* createInputStream (const bool usePostCommand,
  9178. OpenStreamProgressCallback* const progressCallback = 0,
  9179. void* const progressCallbackContext = 0,
  9180. const String& extraHeaders = String::empty,
  9181. const int connectionTimeOutMs = 0) const;
  9182. /** Tries to download the entire contents of this URL into a binary data block.
  9183. If it succeeds, this will return true and append the data it read onto the end
  9184. of the memory block.
  9185. @param destData the memory block to append the new data to
  9186. @param usePostCommand whether to use a POST command to get the data (uses
  9187. a GET command if this is false)
  9188. @see readEntireTextStream, readEntireXmlStream
  9189. */
  9190. bool readEntireBinaryStream (MemoryBlock& destData,
  9191. const bool usePostCommand = false) const;
  9192. /** Tries to download the entire contents of this URL as a string.
  9193. If it fails, this will return an empty string, otherwise it will return the
  9194. contents of the downloaded file. If you need to distinguish between a read
  9195. operation that fails and one that returns an empty string, you'll need to use
  9196. a different method, such as readEntireBinaryStream().
  9197. @param usePostCommand whether to use a POST command to get the data (uses
  9198. a GET command if this is false)
  9199. @see readEntireBinaryStream, readEntireXmlStream
  9200. */
  9201. const String readEntireTextStream (const bool usePostCommand = false) const;
  9202. /** Tries to download the entire contents of this URL and parse it as XML.
  9203. If it fails, or if the text that it reads can't be parsed as XML, this will
  9204. return 0.
  9205. When it returns a valid XmlElement object, the caller is responsibile for deleting
  9206. this object when no longer needed.
  9207. @param usePostCommand whether to use a POST command to get the data (uses
  9208. a GET command if this is false)
  9209. @see readEntireBinaryStream, readEntireTextStream
  9210. */
  9211. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  9212. /** Adds escape sequences to a string to encode any characters that aren't
  9213. legal in a URL.
  9214. E.g. any spaces will be replaced with "%20".
  9215. This is the opposite of removeEscapeChars().
  9216. If isParameter is true, it means that the string is going to be used
  9217. as a parameter, so it also encodes '$' and ',' (which would otherwise
  9218. be legal in a URL.
  9219. @see removeEscapeChars
  9220. */
  9221. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  9222. const bool isParameter);
  9223. /** Replaces any escape character sequences in a string with their original
  9224. character codes.
  9225. E.g. any instances of "%20" will be replaced by a space.
  9226. This is the opposite of addEscapeChars().
  9227. @see addEscapeChars
  9228. */
  9229. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  9230. juce_UseDebuggingNewOperator
  9231. private:
  9232. String url;
  9233. StringPairArray parameters, filesToUpload, mimeTypes;
  9234. };
  9235. #endif // __JUCE_URL_JUCEHEADER__
  9236. /********* End of inlined file: juce_URL.h *********/
  9237. #endif
  9238. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9239. /********* Start of inlined file: juce_Socket.h *********/
  9240. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9241. #define __JUCE_SOCKET_JUCEHEADER__
  9242. /**
  9243. A wrapper for a streaming (TCP) socket.
  9244. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9245. sockets, you could also try the InterprocessConnection class.
  9246. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9247. */
  9248. class JUCE_API StreamingSocket
  9249. {
  9250. public:
  9251. /** Creates an uninitialised socket.
  9252. To connect it, use the connect() method, after which you can read() or write()
  9253. to it.
  9254. To wait for other sockets to connect to this one, the createListener() method
  9255. enters "listener" mode, and can be used to spawn new sockets for each connection
  9256. that comes along.
  9257. */
  9258. StreamingSocket();
  9259. /** Destructor. */
  9260. ~StreamingSocket();
  9261. /** Binds the socket to the specified local port.
  9262. @returns true on success; false may indicate that another socket is already bound
  9263. on the same port
  9264. */
  9265. bool bindToPort (const int localPortNumber);
  9266. /** Tries to connect the socket to hostname:port.
  9267. If timeOutMillisecs is 0, then this method will block until the operating system
  9268. rejects the connection (which could take a long time).
  9269. @returns true if it succeeds.
  9270. @see isConnected
  9271. */
  9272. bool connect (const String& remoteHostname,
  9273. const int remotePortNumber,
  9274. const int timeOutMillisecs = 3000);
  9275. /** True if the socket is currently connected. */
  9276. bool isConnected() const throw() { return connected; }
  9277. /** Closes the connection. */
  9278. void close();
  9279. /** Returns the name of the currently connected host. */
  9280. const String& getHostName() const throw() { return hostName; }
  9281. /** Returns the port number that's currently open. */
  9282. int getPort() const throw() { return portNumber; }
  9283. /** True if the socket is connected to this machine rather than over the network. */
  9284. bool isLocal() const throw();
  9285. /** Waits until the socket is ready for reading or writing.
  9286. If readyForReading is true, it will wait until the socket is ready for
  9287. reading; if false, it will wait until it's ready for writing.
  9288. If the timeout is < 0, it will wait forever, or else will give up after
  9289. the specified time.
  9290. If the socket is ready on return, this returns 1. If it times-out before
  9291. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9292. */
  9293. int waitUntilReady (const bool readyForReading,
  9294. const int timeoutMsecs) const;
  9295. /** Reads bytes from the socket (blocking).
  9296. Note that this method will block unless you have checked the socket is ready
  9297. for reading before calling it (see the waitUntilReady() method).
  9298. @returns the number of bytes read, or -1 if there was an error.
  9299. */
  9300. int read (void* destBuffer, const int maxBytesToRead);
  9301. /** Writes bytes to the socket from a buffer.
  9302. Note that this method will block unless you have checked the socket is ready
  9303. for writing before calling it (see the waitUntilReady() method).
  9304. @returns the number of bytes written, or -1 if there was an error.
  9305. */
  9306. int write (const void* sourceBuffer, const int numBytesToWrite);
  9307. /** Puts this socket into "listener" mode.
  9308. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9309. which will spawn new sockets for each new connection, so that these can
  9310. be handled in parallel by other threads.
  9311. This returns true if it manages to open the socket successfully.
  9312. @see waitForNextConnection
  9313. */
  9314. bool createListener (const int portNumber);
  9315. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9316. socket.
  9317. The object that gets returned will be owned by the caller.
  9318. This method can only be called after using createListener().
  9319. @see createListener
  9320. */
  9321. StreamingSocket* waitForNextConnection() const;
  9322. juce_UseDebuggingNewOperator
  9323. private:
  9324. String hostName;
  9325. int volatile portNumber, handle;
  9326. bool connected, isListener;
  9327. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9328. StreamingSocket (const StreamingSocket&);
  9329. const StreamingSocket& operator= (const StreamingSocket&);
  9330. };
  9331. /**
  9332. A wrapper for a datagram (UDP) socket.
  9333. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9334. sockets, you could also try the InterprocessConnection class.
  9335. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9336. */
  9337. class JUCE_API DatagramSocket
  9338. {
  9339. public:
  9340. /**
  9341. Creates an (uninitialised) datagram socket.
  9342. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9343. the port number is assigned by the operating system.
  9344. To use the socket for sending, call the connect() method. This will not immediately
  9345. make a connection, but will save the destination you've provided. After this, you can
  9346. call read() or write().
  9347. To wait for other sockets to connect to this one, call waitForNextConnection().
  9348. */
  9349. DatagramSocket (const int localPortNumber);
  9350. /** Destructor. */
  9351. ~DatagramSocket();
  9352. /** Binds the socket to the specified local port.
  9353. @returns true on success; false may indicate that another socket is already bound
  9354. on the same port
  9355. */
  9356. bool bindToPort (const int localPortNumber);
  9357. /** Tries to connect the socket to hostname:port.
  9358. If timeOutMillisecs is 0, then this method will block until the operating system
  9359. rejects the connection (which could take a long time).
  9360. @returns true if it succeeds.
  9361. @see isConnected
  9362. */
  9363. bool connect (const String& remoteHostname,
  9364. const int remotePortNumber,
  9365. const int timeOutMillisecs = 3000);
  9366. /** True if the socket is currently connected. */
  9367. bool isConnected() const throw() { return connected; }
  9368. /** Closes the connection. */
  9369. void close();
  9370. /** Returns the name of the currently connected host. */
  9371. const String& getHostName() const throw() { return hostName; }
  9372. /** Returns the port number that's currently open. */
  9373. int getPort() const throw() { return portNumber; }
  9374. /** True if the socket is connected to this machine rather than over the network. */
  9375. bool isLocal() const throw();
  9376. /** Waits until the socket is ready for reading or writing.
  9377. If readyForReading is true, it will wait until the socket is ready for
  9378. reading; if false, it will wait until it's ready for writing.
  9379. If the timeout is < 0, it will wait forever, or else will give up after
  9380. the specified time.
  9381. If the socket is ready on return, this returns 1. If it times-out before
  9382. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9383. */
  9384. int waitUntilReady (const bool readyForReading,
  9385. const int timeoutMsecs) const;
  9386. /** Reads bytes from the socket (blocking).
  9387. Note that this method will block unless you have checked the socket is ready
  9388. for reading before calling it (see the waitUntilReady() method).
  9389. @returns the number of bytes read, or -1 if there was an error.
  9390. */
  9391. int read (void* destBuffer, const int maxBytesToRead);
  9392. /** Writes bytes to the socket from a buffer.
  9393. Note that this method will block unless you have checked the socket is ready
  9394. for writing before calling it (see the waitUntilReady() method).
  9395. @returns the number of bytes written, or -1 if there was an error.
  9396. */
  9397. int write (const void* sourceBuffer, const int numBytesToWrite);
  9398. /** This waits for incoming data to be sent, and returns a socket that can be used
  9399. to read it.
  9400. The object that gets returned is owned by the caller, and can't be used for
  9401. sending, but can be used to read the data.
  9402. */
  9403. DatagramSocket* waitForNextConnection() const;
  9404. juce_UseDebuggingNewOperator
  9405. private:
  9406. String hostName;
  9407. int volatile portNumber, handle;
  9408. bool connected;
  9409. void* serverAddress;
  9410. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9411. DatagramSocket (const DatagramSocket&);
  9412. const DatagramSocket& operator= (const DatagramSocket&);
  9413. };
  9414. #endif // __JUCE_SOCKET_JUCEHEADER__
  9415. /********* End of inlined file: juce_Socket.h *********/
  9416. #endif
  9417. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9418. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9419. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9420. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9421. /** Writes data to an internal memory buffer, which grows as required.
  9422. The data that was written into the stream can then be accessed later as
  9423. a contiguous block of memory.
  9424. */
  9425. class JUCE_API MemoryOutputStream : public OutputStream
  9426. {
  9427. public:
  9428. /** Creates a memory stream ready for writing into.
  9429. @param initialSize the intial amount of space to allocate for writing into
  9430. @param granularity the increments by which the internal storage will be increased
  9431. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9432. place that the data gets stored. If it's zero, the stream
  9433. will allocate its own storage internally, which you can
  9434. access using getData() and getDataSize()
  9435. */
  9436. MemoryOutputStream (const int initialSize = 256,
  9437. const int granularity = 256,
  9438. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9439. /** Destructor.
  9440. This will free any data that was written to it.
  9441. */
  9442. ~MemoryOutputStream() throw();
  9443. /** Returns a pointer to the data that has been written to the stream.
  9444. @see getDataSize
  9445. */
  9446. const char* getData() throw();
  9447. /** Returns the number of bytes of data that have been written to the stream.
  9448. @see getData
  9449. */
  9450. int getDataSize() const throw();
  9451. /** Resets the stream, clearing any data that has been written to it so far. */
  9452. void reset() throw();
  9453. void flush();
  9454. bool write (const void* buffer, int howMany);
  9455. int64 getPosition();
  9456. bool setPosition (int64 newPosition);
  9457. juce_UseDebuggingNewOperator
  9458. private:
  9459. MemoryBlock* data;
  9460. int position, size, blockSize;
  9461. bool ownsMemoryBlock;
  9462. };
  9463. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9464. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9465. #endif
  9466. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9467. /********* Start of inlined file: juce_SubregionStream.h *********/
  9468. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9469. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9470. /** Wraps another input stream, and reads from a specific part of it.
  9471. This lets you take a subsection of a stream and present it as an entire
  9472. stream in its own right.
  9473. */
  9474. class JUCE_API SubregionStream : public InputStream
  9475. {
  9476. public:
  9477. /** Creates a SubregionStream from an input source.
  9478. @param sourceStream the source stream to read from
  9479. @param startPositionInSourceStream this is the position in the source stream that
  9480. corresponds to position 0 in this stream
  9481. @param lengthOfSourceStream this specifies the maximum number of bytes
  9482. from the source stream that will be passed through
  9483. by this stream. When the position of this stream
  9484. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9485. If the length passed in here is greater than the length
  9486. of the source stream (as returned by getTotalLength()),
  9487. then the smaller value will be used.
  9488. Passing a negative value for this parameter means it
  9489. will keep reading until the source's end-of-stream.
  9490. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9491. deleted by this object when it is itself deleted.
  9492. */
  9493. SubregionStream (InputStream* const sourceStream,
  9494. const int64 startPositionInSourceStream,
  9495. const int64 lengthOfSourceStream,
  9496. const bool deleteSourceWhenDestroyed) throw();
  9497. /** Destructor.
  9498. This may also delete the source stream, if that option was chosen when the
  9499. buffered stream was created.
  9500. */
  9501. ~SubregionStream() throw();
  9502. int64 getTotalLength();
  9503. int64 getPosition();
  9504. bool setPosition (int64 newPosition);
  9505. int read (void* destBuffer, int maxBytesToRead);
  9506. bool isExhausted();
  9507. juce_UseDebuggingNewOperator
  9508. private:
  9509. InputStream* const source;
  9510. const bool deleteSourceWhenDestroyed;
  9511. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9512. SubregionStream (const SubregionStream&);
  9513. const SubregionStream& operator= (const SubregionStream&);
  9514. };
  9515. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9516. /********* End of inlined file: juce_SubregionStream.h *********/
  9517. #endif
  9518. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9519. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9520. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9521. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9522. /** Wraps another input stream, and reads from it using an intermediate buffer
  9523. If you're using an input stream such as a file input stream, and making lots of
  9524. small read accesses to it, it's probably sensible to wrap it in one of these,
  9525. so that the source stream gets accessed in larger chunk sizes, meaning less
  9526. work for the underlying stream.
  9527. */
  9528. class JUCE_API BufferedInputStream : public InputStream
  9529. {
  9530. public:
  9531. /** Creates a BufferedInputStream from an input source.
  9532. @param sourceStream the source stream to read from
  9533. @param bufferSize the size of reservoir to use to buffer the source
  9534. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9535. deleted by this object when it is itself deleted.
  9536. */
  9537. BufferedInputStream (InputStream* const sourceStream,
  9538. const int bufferSize,
  9539. const bool deleteSourceWhenDestroyed) throw();
  9540. /** Destructor.
  9541. This may also delete the source stream, if that option was chosen when the
  9542. buffered stream was created.
  9543. */
  9544. ~BufferedInputStream() throw();
  9545. int64 getTotalLength();
  9546. int64 getPosition();
  9547. bool setPosition (int64 newPosition);
  9548. int read (void* destBuffer, int maxBytesToRead);
  9549. const String readString();
  9550. bool isExhausted();
  9551. juce_UseDebuggingNewOperator
  9552. private:
  9553. InputStream* const source;
  9554. const bool deleteSourceWhenDestroyed;
  9555. int bufferSize;
  9556. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9557. char* buffer;
  9558. void ensureBuffered();
  9559. BufferedInputStream (const BufferedInputStream&);
  9560. const BufferedInputStream& operator= (const BufferedInputStream&);
  9561. };
  9562. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9563. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9564. #endif
  9565. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9566. /********* Start of inlined file: juce_FileInputSource.h *********/
  9567. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9568. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9569. /********* Start of inlined file: juce_InputSource.h *********/
  9570. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9571. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9572. /**
  9573. A lightweight object that can create a stream to read some kind of resource.
  9574. This may be used to refer to a file, or some other kind of source, allowing a
  9575. caller to create an input stream that can read from it when required.
  9576. @see FileInputSource
  9577. */
  9578. class JUCE_API InputSource
  9579. {
  9580. public:
  9581. InputSource() throw() {}
  9582. /** Destructor. */
  9583. virtual ~InputSource() {}
  9584. /** Returns a new InputStream to read this item.
  9585. @returns an inputstream that the caller will delete, or 0 if
  9586. the filename isn't found.
  9587. */
  9588. virtual InputStream* createInputStream() = 0;
  9589. /** Returns a new InputStream to read an item, relative.
  9590. @param relatedItemPath the relative pathname of the resource that is required
  9591. @returns an inputstream that the caller will delete, or 0 if
  9592. the item isn't found.
  9593. */
  9594. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9595. /** Returns a hash code that uniquely represents this item.
  9596. */
  9597. virtual int64 hashCode() const = 0;
  9598. juce_UseDebuggingNewOperator
  9599. };
  9600. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9601. /********* End of inlined file: juce_InputSource.h *********/
  9602. /**
  9603. A type of InputSource that represents a normal file.
  9604. @see InputSource
  9605. */
  9606. class JUCE_API FileInputSource : public InputSource
  9607. {
  9608. public:
  9609. FileInputSource (const File& file) throw();
  9610. ~FileInputSource();
  9611. InputStream* createInputStream();
  9612. InputStream* createInputStreamFor (const String& relatedItemPath);
  9613. int64 hashCode() const;
  9614. juce_UseDebuggingNewOperator
  9615. private:
  9616. const File file;
  9617. FileInputSource (const FileInputSource&);
  9618. const FileInputSource& operator= (const FileInputSource&);
  9619. };
  9620. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9621. /********* End of inlined file: juce_FileInputSource.h *********/
  9622. #endif
  9623. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9624. #endif
  9625. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9626. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9627. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9628. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9629. /**
  9630. A stream which uses zlib to compress the data written into it.
  9631. @see GZIPDecompressorInputStream
  9632. */
  9633. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9634. {
  9635. public:
  9636. /** Creates a compression stream.
  9637. @param destStream the stream into which the compressed data should
  9638. be written
  9639. @param compressionLevel how much to compress the data, between 1 and 9, where
  9640. 1 is the fastest/lowest compression, and 9 is the
  9641. slowest/highest compression. Any value outside this range
  9642. indicates that a default compression level should be used.
  9643. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9644. this stream is destroyed
  9645. @param noWrap this is used internally by the ZipFile class
  9646. and should be ignored by user applications
  9647. */
  9648. GZIPCompressorOutputStream (OutputStream* const destStream,
  9649. int compressionLevel = 0,
  9650. const bool deleteDestStreamWhenDestroyed = false,
  9651. const bool noWrap = false);
  9652. /** Destructor. */
  9653. ~GZIPCompressorOutputStream();
  9654. void flush();
  9655. int64 getPosition();
  9656. bool setPosition (int64 newPosition);
  9657. bool write (const void* destBuffer, int howMany);
  9658. juce_UseDebuggingNewOperator
  9659. private:
  9660. OutputStream* const destStream;
  9661. const bool deleteDestStream;
  9662. uint8* buffer;
  9663. void* helper;
  9664. bool doNextBlock();
  9665. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9666. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9667. };
  9668. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9669. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9670. #endif
  9671. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9672. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9673. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9674. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9675. /**
  9676. This stream will decompress a source-stream using zlib.
  9677. Tip: if you're reading lots of small items from one of these streams, you
  9678. can increase the performance enormously by passing it through a
  9679. BufferedInputStream, so that it has to read larger blocks less often.
  9680. @see GZIPCompressorOutputStream
  9681. */
  9682. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9683. {
  9684. public:
  9685. /** Creates a decompressor stream.
  9686. @param sourceStream the stream to read from
  9687. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9688. when this object is destroyed
  9689. @param noWrap this is used internally by the ZipFile class
  9690. and should be ignored by user applications
  9691. @param uncompressedStreamLength if the creator knows the length that the
  9692. uncompressed stream will be, then it can supply this
  9693. value, which will be returned by getTotalLength()
  9694. */
  9695. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9696. const bool deleteSourceWhenDestroyed,
  9697. const bool noWrap = false,
  9698. const int64 uncompressedStreamLength = -1);
  9699. /** Destructor. */
  9700. ~GZIPDecompressorInputStream();
  9701. int64 getPosition();
  9702. bool setPosition (int64 pos);
  9703. int64 getTotalLength();
  9704. bool isExhausted();
  9705. int read (void* destBuffer, int maxBytesToRead);
  9706. juce_UseDebuggingNewOperator
  9707. private:
  9708. InputStream* const sourceStream;
  9709. const int64 uncompressedStreamLength;
  9710. const bool deleteSourceWhenDestroyed, noWrap;
  9711. bool isEof;
  9712. int activeBufferSize;
  9713. int64 originalSourcePos, currentPos;
  9714. uint8* buffer;
  9715. void* helper;
  9716. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9717. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9718. };
  9719. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9720. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9721. #endif
  9722. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9723. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9724. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9725. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9726. /**
  9727. Allows a block of data and to be accessed as a stream.
  9728. This can either be used to refer to a shared block of memory, or can make its
  9729. own internal copy of the data when the MemoryInputStream is created.
  9730. */
  9731. class JUCE_API MemoryInputStream : public InputStream
  9732. {
  9733. public:
  9734. /** Creates a MemoryInputStream.
  9735. @param sourceData the block of data to use as the stream's source
  9736. @param sourceDataSize the number of bytes in the source data block
  9737. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9738. the source data, so this data shouldn't be changed
  9739. for the lifetime of the stream; if this parameter is
  9740. true, the stream will make its own copy of the
  9741. data and use that.
  9742. */
  9743. MemoryInputStream (const void* const sourceData,
  9744. const int sourceDataSize,
  9745. const bool keepInternalCopyOfData) throw();
  9746. /** Destructor. */
  9747. ~MemoryInputStream() throw();
  9748. int64 getPosition();
  9749. bool setPosition (int64 pos);
  9750. int64 getTotalLength();
  9751. bool isExhausted();
  9752. int read (void* destBuffer, int maxBytesToRead);
  9753. juce_UseDebuggingNewOperator
  9754. private:
  9755. const char* data;
  9756. int dataSize, position;
  9757. MemoryBlock internalCopy;
  9758. };
  9759. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9760. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9761. #endif
  9762. #ifndef __JUCE_UUID_JUCEHEADER__
  9763. /********* Start of inlined file: juce_Uuid.h *********/
  9764. #ifndef __JUCE_UUID_JUCEHEADER__
  9765. #define __JUCE_UUID_JUCEHEADER__
  9766. /**
  9767. A universally unique 128-bit identifier.
  9768. This class generates very random unique numbers based on the system time
  9769. and MAC addresses if any are available. It's extremely unlikely that two identical
  9770. UUIDs would ever be created by chance.
  9771. The class includes methods for saving the ID as a string or as raw binary data.
  9772. */
  9773. class JUCE_API Uuid
  9774. {
  9775. public:
  9776. /** Creates a new unique ID. */
  9777. Uuid();
  9778. /** Destructor. */
  9779. ~Uuid() throw();
  9780. /** Creates a copy of another UUID. */
  9781. Uuid (const Uuid& other);
  9782. /** Copies another UUID. */
  9783. Uuid& operator= (const Uuid& other);
  9784. /** Returns true if the ID is zero. */
  9785. bool isNull() const throw();
  9786. /** Compares two UUIDs. */
  9787. bool operator== (const Uuid& other) const;
  9788. /** Compares two UUIDs. */
  9789. bool operator!= (const Uuid& other) const;
  9790. /** Returns a stringified version of this UUID.
  9791. A Uuid object can later be reconstructed from this string using operator= or
  9792. the constructor that takes a string parameter.
  9793. @returns a 32 character hex string.
  9794. */
  9795. const String toString() const;
  9796. /** Creates an ID from an encoded string version.
  9797. @see toString
  9798. */
  9799. Uuid (const String& uuidString);
  9800. /** Copies from a stringified UUID.
  9801. The string passed in should be one that was created with the toString() method.
  9802. */
  9803. Uuid& operator= (const String& uuidString);
  9804. /** Returns a pointer to the internal binary representation of the ID.
  9805. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  9806. the constructor or operator= method that takes an array of uint8s.
  9807. */
  9808. const uint8* getRawData() const throw() { return value.asBytes; }
  9809. /** Creates a UUID from a 16-byte array.
  9810. @see getRawData
  9811. */
  9812. Uuid (const uint8* const rawData);
  9813. /** Sets this UUID from 16-bytes of raw data. */
  9814. Uuid& operator= (const uint8* const rawData);
  9815. juce_UseDebuggingNewOperator
  9816. private:
  9817. union
  9818. {
  9819. uint8 asBytes [16];
  9820. int asInt[4];
  9821. int64 asInt64[2];
  9822. } value;
  9823. };
  9824. #endif // __JUCE_UUID_JUCEHEADER__
  9825. /********* End of inlined file: juce_Uuid.h *********/
  9826. #endif
  9827. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9828. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9829. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9830. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9831. /** A timer for measuring performance of code and dumping the results to a file.
  9832. e.g. @code
  9833. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9834. for (;;)
  9835. {
  9836. pc.start();
  9837. doSomethingFishy();
  9838. pc.stop();
  9839. }
  9840. @endcode
  9841. In this example, the time of each period between calling start/stop will be
  9842. measured and averaged over 50 runs, and the results printed to a file
  9843. every 50 times round the loop.
  9844. */
  9845. class JUCE_API PerformanceCounter
  9846. {
  9847. public:
  9848. /** Creates a PerformanceCounter object.
  9849. @param counterName the name used when printing out the statistics
  9850. @param runsPerPrintout the number of start/stop iterations before calling
  9851. printStatistics()
  9852. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9853. the results are just written to the debugger output
  9854. */
  9855. PerformanceCounter (const String& counterName,
  9856. int runsPerPrintout = 100,
  9857. const File& loggingFile = File::nonexistent);
  9858. /** Destructor. */
  9859. ~PerformanceCounter();
  9860. /** Starts timing.
  9861. @see stop
  9862. */
  9863. void start();
  9864. /** Stops timing and prints out the results.
  9865. The number of iterations before doing a printout of the
  9866. results is set in the constructor.
  9867. @see start
  9868. */
  9869. void stop();
  9870. /** Dumps the current metrics to the debugger output and to a file.
  9871. As well as using Logger::outputDebugString to print the results,
  9872. this will write then to the file specified in the constructor (if
  9873. this was valid).
  9874. */
  9875. void printStatistics();
  9876. juce_UseDebuggingNewOperator
  9877. private:
  9878. String name;
  9879. int numRuns, runsPerPrint;
  9880. double totalTime;
  9881. int64 started;
  9882. File outputFile;
  9883. };
  9884. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9885. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9886. #endif
  9887. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  9888. /********* Start of inlined file: juce_ZipFile.h *********/
  9889. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  9890. #define __JUCE_ZIPFILE_JUCEHEADER__
  9891. /**
  9892. Decodes a ZIP file from a stream.
  9893. This can enumerate the items in a ZIP file and can create suitable stream objects
  9894. to read each one.
  9895. */
  9896. class JUCE_API ZipFile
  9897. {
  9898. public:
  9899. /** Creates a ZipFile for a given stream.
  9900. @param inputStream the stream to read from
  9901. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  9902. will be deleted when this ZipFile object is deleted
  9903. */
  9904. ZipFile (InputStream* const inputStream,
  9905. const bool deleteStreamWhenDestroyed) throw();
  9906. /** Creates a ZipFile based for a file. */
  9907. ZipFile (const File& file);
  9908. /** Creates a ZipFile for an input source.
  9909. The inputSource object will be owned by the zip file, which will delete
  9910. it later when not needed.
  9911. */
  9912. ZipFile (InputSource* const inputSource);
  9913. /** Destructor. */
  9914. ~ZipFile() throw();
  9915. /**
  9916. Contains information about one of the entries in a ZipFile.
  9917. @see ZipFile::getEntry
  9918. */
  9919. struct ZipEntry
  9920. {
  9921. /** The name of the file, which may also include a partial pathname. */
  9922. String filename;
  9923. /** The file's original size. */
  9924. unsigned int uncompressedSize;
  9925. /** The last time the file was modified. */
  9926. Time fileTime;
  9927. };
  9928. /** Returns the number of items in the zip file. */
  9929. int getNumEntries() const throw();
  9930. /** Returns a structure that describes one of the entries in the zip file.
  9931. This may return zero if the index is out of range.
  9932. @see ZipFile::ZipEntry
  9933. */
  9934. const ZipEntry* getEntry (const int index) const throw();
  9935. /** Returns the index of the first entry with a given filename.
  9936. This uses a case-sensitive comparison to look for a filename in the
  9937. list of entries. It might return -1 if no match is found.
  9938. @see ZipFile::ZipEntry
  9939. */
  9940. int getIndexOfFileName (const String& fileName) const throw();
  9941. /** Returns a structure that describes one of the entries in the zip file.
  9942. This uses a case-sensitive comparison to look for a filename in the
  9943. list of entries. It might return 0 if no match is found.
  9944. @see ZipFile::ZipEntry
  9945. */
  9946. const ZipEntry* getEntry (const String& fileName) const throw();
  9947. /** Sorts the list of entries, based on the filename.
  9948. */
  9949. void sortEntriesByFilename();
  9950. /** Creates a stream that can read from one of the zip file's entries.
  9951. The stream that is returned must be deleted by the caller (and
  9952. zero might be returned if a stream can't be opened for some reason).
  9953. The stream must not be used after the ZipFile object that created
  9954. has been deleted.
  9955. */
  9956. InputStream* createStreamForEntry (const int index);
  9957. /** Uncompresses all of the files in the zip file.
  9958. This will expand all the entires into a target directory. The relative
  9959. paths of the entries are used.
  9960. @param targetDirectory the root folder to uncompress to
  9961. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  9962. */
  9963. void uncompressTo (const File& targetDirectory,
  9964. const bool shouldOverwriteFiles = true);
  9965. juce_UseDebuggingNewOperator
  9966. private:
  9967. VoidArray entries;
  9968. friend class ZipInputStream;
  9969. CriticalSection lock;
  9970. InputStream* inputStream;
  9971. InputSource* inputSource;
  9972. bool deleteStreamWhenDestroyed;
  9973. int numEntries, centralRecStart;
  9974. #ifdef JUCE_DEBUG
  9975. int numOpenStreams;
  9976. #endif
  9977. void init();
  9978. int findEndOfZipEntryTable (InputStream* in);
  9979. ZipFile (const ZipFile&);
  9980. const ZipFile& operator= (const ZipFile&);
  9981. };
  9982. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  9983. /********* End of inlined file: juce_ZipFile.h *********/
  9984. #endif
  9985. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9986. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9987. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9988. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9989. /**
  9990. A collection of miscellaneous platform-specific utilities.
  9991. */
  9992. class JUCE_API PlatformUtilities
  9993. {
  9994. public:
  9995. /** Plays the operating system's default alert 'beep' sound. */
  9996. static void beep();
  9997. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9998. const String& emailSubject,
  9999. const String& bodyText,
  10000. const StringArray& filesToAttach);
  10001. #if JUCE_MAC || DOXYGEN
  10002. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10003. static const String cfStringToJuceString (CFStringRef cfString);
  10004. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10005. static CFStringRef juceStringToCFString (const String& s);
  10006. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10007. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10008. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10009. static const String makePathFromFSRef (FSRef* file);
  10010. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10011. their precomposed equivalents.
  10012. */
  10013. static const String convertToPrecomposedUnicode (const String& s);
  10014. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10015. static OSType getTypeOfFile (const String& filename);
  10016. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10017. static bool isBundle (const String& filename);
  10018. #endif
  10019. #if JUCE_WIN32 || DOXYGEN
  10020. // Some registry helper functions:
  10021. /** WIN32 ONLY - Returns a string from the registry.
  10022. The path is a string for the entire path of a value in the registry,
  10023. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10024. */
  10025. static const String getRegistryValue (const String& regValuePath,
  10026. const String& defaultValue = String::empty);
  10027. /** WIN32 ONLY - Sets a registry value as a string.
  10028. This will take care of creating any groups needed to get to the given
  10029. registry value.
  10030. */
  10031. static void setRegistryValue (const String& regValuePath,
  10032. const String& value);
  10033. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10034. static bool registryValueExists (const String& regValuePath);
  10035. /** WIN32 ONLY - Deletes a registry value. */
  10036. static void deleteRegistryValue (const String& regValuePath);
  10037. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10038. static void deleteRegistryKey (const String& regKeyPath);
  10039. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10040. In a normal Juce application this will be set to the module handle
  10041. of the application executable.
  10042. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10043. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10044. to set the correct module handle in your DllMain() function, because
  10045. the win32 system relies on the correct instance handle when opening windows.
  10046. */
  10047. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10048. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10049. @see getCurrentModuleInstanceHandle()
  10050. */
  10051. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10052. /** WIN32 ONLY - Gets the command-line params as a string.
  10053. This is needed to avoid unicode problems with the argc type params.
  10054. */
  10055. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  10056. #endif
  10057. /** Clears the floating point unit's flags.
  10058. Only has an effect under win32, currently.
  10059. */
  10060. static void fpuReset();
  10061. #if JUCE_LINUX || JUCE_WIN32
  10062. /** Loads a dynamically-linked library into the process's address space.
  10063. @param pathOrFilename the platform-dependent name and search path
  10064. @returns a handle which can be used by getProcedureEntryPoint(), or
  10065. zero if it fails.
  10066. @see freeDynamicLibrary, getProcedureEntryPoint
  10067. */
  10068. static void* loadDynamicLibrary (const String& pathOrFilename);
  10069. /** Frees a dynamically-linked library.
  10070. @param libraryHandle a handle created by loadDynamicLibrary
  10071. @see loadDynamicLibrary, getProcedureEntryPoint
  10072. */
  10073. static void freeDynamicLibrary (void* libraryHandle);
  10074. /** Finds a procedure call in a dynamically-linked library.
  10075. @param libraryHandle a library handle returned by loadDynamicLibrary
  10076. @param procedureName the name of the procedure call to try to load
  10077. @returns a pointer to the function if found, or 0 if it fails
  10078. @see loadDynamicLibrary
  10079. */
  10080. static void* getProcedureEntryPoint (void* libraryHandle,
  10081. const String& procedureName);
  10082. #endif
  10083. #if JUCE_LINUX || DOXYGEN
  10084. #endif
  10085. };
  10086. #if JUCE_MAC
  10087. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10088. using RAII.
  10089. */
  10090. class ScopedAutoReleasePool
  10091. {
  10092. public:
  10093. ScopedAutoReleasePool();
  10094. ~ScopedAutoReleasePool();
  10095. private:
  10096. void* pool;
  10097. };
  10098. /**
  10099. A wrapper class for picking up events from an Apple IR remote control device.
  10100. To use it, just create a subclass of this class, implementing the buttonPressed()
  10101. callback, then call start() and stop() to start or stop receiving events.
  10102. */
  10103. class JUCE_API AppleRemoteDevice
  10104. {
  10105. public:
  10106. AppleRemoteDevice();
  10107. virtual ~AppleRemoteDevice();
  10108. /** The set of buttons that may be pressed.
  10109. @see buttonPressed
  10110. */
  10111. enum ButtonType
  10112. {
  10113. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10114. playButton, /**< The play button. */
  10115. plusButton, /**< The plus or volume-up button. */
  10116. minusButton, /**< The minus or volume-down button. */
  10117. rightButton, /**< The right button (if it's held for a short time). */
  10118. leftButton, /**< The left button (if it's held for a short time). */
  10119. rightButton_Long, /**< The right button (if it's held for a long time). */
  10120. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10121. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10122. playButtonSleepMode,
  10123. switched
  10124. };
  10125. /** Override this method to receive the callback about a button press.
  10126. The callback will happen on the application's message thread.
  10127. Some buttons trigger matching up and down events, in which the isDown parameter
  10128. will be true and then false. Others only send a single event when the
  10129. button is pressed.
  10130. */
  10131. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10132. /** Starts the device running and responding to events.
  10133. Returns true if it managed to open the device.
  10134. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10135. and will not be available to any other part of the system. If
  10136. false, it will be shared with other apps.
  10137. @see stop
  10138. */
  10139. bool start (const bool inExclusiveMode) throw();
  10140. /** Stops the device running.
  10141. @see start
  10142. */
  10143. void stop() throw();
  10144. /** Returns true if the device has been started successfully.
  10145. */
  10146. bool isActive() const throw();
  10147. /** Returns the ID number of the remote, if it has sent one.
  10148. */
  10149. int getRemoteId() const throw() { return remoteId; }
  10150. juce_UseDebuggingNewOperator
  10151. /** @internal */
  10152. void handleCallbackInternal();
  10153. private:
  10154. void* device;
  10155. void* queue;
  10156. int remoteId;
  10157. bool open (const bool openInExclusiveMode) throw();
  10158. };
  10159. #endif
  10160. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10161. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10162. #endif
  10163. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10164. #endif
  10165. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10166. #endif
  10167. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10168. #endif
  10169. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10170. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10171. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10172. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10173. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10174. string into a localised version using the LocalisedStrings class.
  10175. @see LocalisedStrings
  10176. */
  10177. #define TRANS(stringLiteral) \
  10178. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10179. /**
  10180. Used to convert strings to localised foreign-language versions.
  10181. This is basically a look-up table of strings and their translated equivalents.
  10182. It can be loaded from a text file, so that you can supply a set of localised
  10183. versions of strings that you use in your app.
  10184. To use it in your code, simply call the translate() method on each string that
  10185. might have foreign versions, and if none is found, the method will just return
  10186. the original string.
  10187. The translation file should start with some lines specifying a description of
  10188. the language it contains, and also a list of ISO country codes where it might
  10189. be appropriate to use the file. After that, each line of the file should contain
  10190. a pair of quoted strings with an '=' sign.
  10191. E.g. for a french translation, the file might be:
  10192. @code
  10193. language: French
  10194. countries: fr be mc ch lu
  10195. "hello" = "bonjour"
  10196. "goodbye" = "au revoir"
  10197. @endcode
  10198. If the strings need to contain a quote character, they can use '\"' instead, and
  10199. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10200. (you can use this to add comments).
  10201. Note that this is a singleton class, so don't create or destroy the object directly.
  10202. There's also a TRANS(text) macro defined to make it easy to use the this.
  10203. E.g. @code
  10204. printSomething (TRANS("hello"));
  10205. @endcode
  10206. This macro is used in the Juce classes themselves, so your application has a chance to
  10207. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10208. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10209. code).
  10210. */
  10211. class JUCE_API LocalisedStrings
  10212. {
  10213. public:
  10214. /** Creates a set of translations from the text of a translation file.
  10215. When you create one of these, you can call setCurrentMappings() to make it
  10216. the set of mappings that the system's using.
  10217. */
  10218. LocalisedStrings (const String& fileContents) throw();
  10219. /** Creates a set of translations from a file.
  10220. When you create one of these, you can call setCurrentMappings() to make it
  10221. the set of mappings that the system's using.
  10222. */
  10223. LocalisedStrings (const File& fileToLoad) throw();
  10224. /** Destructor. */
  10225. ~LocalisedStrings() throw();
  10226. /** Selects the current set of mappings to be used by the system.
  10227. The object you pass in will be automatically deleted when no longer needed, so
  10228. don't keep a pointer to it. You can also pass in zero to remove the current
  10229. mappings.
  10230. See also the TRANS() macro, which uses the current set to do its translation.
  10231. @see translateWithCurrentMappings
  10232. */
  10233. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10234. /** Returns the currently selected set of mappings.
  10235. This is the object that was last passed to setCurrentMappings(). It may
  10236. be 0 if none has been created.
  10237. */
  10238. static LocalisedStrings* getCurrentMappings() throw();
  10239. /** Tries to translate a string using the currently selected set of mappings.
  10240. If no mapping has been set, or if the mapping doesn't contain a translation
  10241. for the string, this will just return the original string.
  10242. See also the TRANS() macro, which uses this method to do its translation.
  10243. @see setCurrentMappings, getCurrentMappings
  10244. */
  10245. static const String translateWithCurrentMappings (const String& text) throw();
  10246. /** Tries to translate a string using the currently selected set of mappings.
  10247. If no mapping has been set, or if the mapping doesn't contain a translation
  10248. for the string, this will just return the original string.
  10249. See also the TRANS() macro, which uses this method to do its translation.
  10250. @see setCurrentMappings, getCurrentMappings
  10251. */
  10252. static const String translateWithCurrentMappings (const char* text) throw();
  10253. /** Attempts to look up a string and return its localised version.
  10254. If the string isn't found in the list, the original string will be returned.
  10255. */
  10256. const String translate (const String& text) const throw();
  10257. /** Returns the name of the language specified in the translation file.
  10258. This is specified in the file using a line starting with "language:", e.g.
  10259. @code
  10260. language: german
  10261. @endcode
  10262. */
  10263. const String getLanguageName() const throw() { return languageName; }
  10264. /** Returns the list of suitable country codes listed in the translation file.
  10265. These is specified in the file using a line starting with "countries:", e.g.
  10266. @code
  10267. countries: fr be mc ch lu
  10268. @endcode
  10269. The country codes are supposed to be 2-character ISO complient codes.
  10270. */
  10271. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10272. juce_UseDebuggingNewOperator
  10273. private:
  10274. String languageName;
  10275. StringArray countryCodes;
  10276. StringPairArray translations;
  10277. void loadFromText (const String& fileContents) throw();
  10278. };
  10279. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10280. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10281. #endif
  10282. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10283. /********* Start of inlined file: juce_XmlDocument.h *********/
  10284. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10285. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10286. /**
  10287. Parses a text-based XML document and creates an XmlElement object from it.
  10288. The parser will parse DTDs to load external entities but won't
  10289. check the document for validity against the DTD.
  10290. e.g.
  10291. @code
  10292. XmlDocument myDocument (File ("myfile.xml"));
  10293. XmlElement* mainElement = myDocument.getDocumentElement();
  10294. if (mainElement == 0)
  10295. {
  10296. String error = myDocument.getLastParseError();
  10297. }
  10298. else
  10299. {
  10300. ..use the element
  10301. }
  10302. @endcode
  10303. @see XmlElement
  10304. */
  10305. class JUCE_API XmlDocument
  10306. {
  10307. public:
  10308. /** Creates an XmlDocument from the xml text.
  10309. The text doesn't actually get parsed until the getDocumentElement() method is
  10310. called.
  10311. */
  10312. XmlDocument (const String& documentText) throw();
  10313. /** Creates an XmlDocument from a file.
  10314. The text doesn't actually get parsed until the getDocumentElement() method is
  10315. called.
  10316. */
  10317. XmlDocument (const File& file);
  10318. /** Destructor. */
  10319. ~XmlDocument() throw();
  10320. /** Creates an XmlElement object to represent the main document node.
  10321. This method will do the actual parsing of the text, and if there's a
  10322. parse error, it may returns 0 (and you can find out the error using
  10323. the getLastParseError() method).
  10324. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10325. first section of the file, and will only
  10326. return the outer document element - this
  10327. allows quick checking of large files to
  10328. see if they contain the correct type of
  10329. tag, without having to parse the entire file
  10330. @returns a new XmlElement which the caller will need to delete, or null if
  10331. there was an error.
  10332. @see getLastParseError
  10333. */
  10334. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10335. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10336. @returns the error, or an empty string if there was no error.
  10337. */
  10338. const String& getLastParseError() const throw();
  10339. /** Sets an input source object to use for parsing documents that reference external entities.
  10340. If the document has been created from a file, this probably won't be needed, but
  10341. if you're parsing some text and there might be a DTD that references external
  10342. files, you may need to create a custom input source that can retrieve the
  10343. other files it needs.
  10344. The object that is passed-in will be deleted automatically when no longer needed.
  10345. @see InputSource
  10346. */
  10347. void setInputSource (InputSource* const newSource) throw();
  10348. juce_UseDebuggingNewOperator
  10349. private:
  10350. String originalText;
  10351. const tchar* input;
  10352. bool outOfData, errorOccurred;
  10353. bool identifierLookupTable [128];
  10354. String lastError, dtdText;
  10355. StringArray tokenisedDTD;
  10356. bool needToLoadDTD;
  10357. InputSource* inputSource;
  10358. void setLastError (const String& desc, const bool carryOn) throw();
  10359. void skipHeader() throw();
  10360. void skipNextWhiteSpace() throw();
  10361. tchar readNextChar() throw();
  10362. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10363. void readChildElements (XmlElement* parent) throw();
  10364. int findNextTokenLength() throw();
  10365. void readQuotedString (String& result) throw();
  10366. void readEntity (String& result) throw();
  10367. const String getFileContents (const String& filename) const;
  10368. const String expandEntity (const String& entity);
  10369. const String expandExternalEntity (const String& entity);
  10370. const String getParameterEntity (const String& entity);
  10371. };
  10372. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10373. /********* End of inlined file: juce_XmlDocument.h *********/
  10374. #endif
  10375. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10376. #endif
  10377. #ifndef __JUCE_STRING_JUCEHEADER__
  10378. #endif
  10379. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10380. /********* Start of inlined file: juce_ThreadPool.h *********/
  10381. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10382. #define __JUCE_THREADPOOL_JUCEHEADER__
  10383. /********* Start of inlined file: juce_Thread.h *********/
  10384. #ifndef __JUCE_THREAD_JUCEHEADER__
  10385. #define __JUCE_THREAD_JUCEHEADER__
  10386. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10387. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10388. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10389. /**
  10390. Allows threads to wait for events triggered by other threads.
  10391. A thread can call wait() on a WaitableObject, and this will suspend the
  10392. calling thread until another thread wakes it up by calling the signal()
  10393. method.
  10394. */
  10395. class JUCE_API WaitableEvent
  10396. {
  10397. public:
  10398. /** Creates a WaitableEvent object. */
  10399. WaitableEvent() throw();
  10400. /** Destructor.
  10401. If other threads are waiting on this object when it gets deleted, this
  10402. can cause nasty errors, so be careful!
  10403. */
  10404. ~WaitableEvent() throw();
  10405. /** Suspends the calling thread until the event has been signalled.
  10406. This will wait until the object's signal() method is called by another thread,
  10407. or until the timeout expires.
  10408. After the event has been signalled, this method will return true and reset
  10409. the event.
  10410. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10411. value will cause it to wait forever.
  10412. @returns true if the object has been signalled, false if the timeout expires first.
  10413. @see signal, reset
  10414. */
  10415. bool wait (const int timeOutMilliseconds = -1) const throw();
  10416. /** Wakes up any threads that are currently waiting on this object.
  10417. If signal() is called when nothing is waiting, the next thread to call wait()
  10418. will return immediately and reset the signal.
  10419. @see wait, reset
  10420. */
  10421. void signal() const throw();
  10422. /** Resets the event to an unsignalled state.
  10423. If it's not already signalled, this does nothing.
  10424. */
  10425. void reset() const throw();
  10426. juce_UseDebuggingNewOperator
  10427. private:
  10428. void* internal;
  10429. WaitableEvent (const WaitableEvent&);
  10430. const WaitableEvent& operator= (const WaitableEvent&);
  10431. };
  10432. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10433. /********* End of inlined file: juce_WaitableEvent.h *********/
  10434. /**
  10435. Encapsulates a thread.
  10436. Subclasses derive from Thread and implement the run() method, in which they
  10437. do their business. The thread can then be started with the startThread() method
  10438. and controlled with various other methods.
  10439. This class also contains some thread-related static methods, such
  10440. as sleep(), yield(), getCurrentThreadId() etc.
  10441. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10442. MessageManagerLock
  10443. */
  10444. class JUCE_API Thread
  10445. {
  10446. public:
  10447. /**
  10448. Creates a thread.
  10449. When first created, the thread is not running. Use the startThread()
  10450. method to start it.
  10451. */
  10452. Thread (const String& threadName);
  10453. /** Destructor.
  10454. Deleting a Thread object that is running will only give the thread a
  10455. brief opportunity to stop itself cleanly, so it's recommended that you
  10456. should always call stopThread() with a decent timeout before deleting,
  10457. to avoid the thread being forcibly killed (which is a Bad Thing).
  10458. */
  10459. virtual ~Thread();
  10460. /** Must be implemented to perform the thread's actual code.
  10461. Remember that the thread must regularly check the threadShouldExit()
  10462. method whilst running, and if this returns true it should return from
  10463. the run() method as soon as possible to avoid being forcibly killed.
  10464. @see threadShouldExit, startThread
  10465. */
  10466. virtual void run() = 0;
  10467. // Thread control functions..
  10468. /** Starts the thread running.
  10469. This will start the thread's run() method.
  10470. (if it's already started, startThread() won't do anything).
  10471. @see stopThread
  10472. */
  10473. void startThread() throw();
  10474. /** Starts the thread with a given priority.
  10475. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10476. If the thread is already running, its priority will be changed.
  10477. @see startThread, setPriority
  10478. */
  10479. void startThread (const int priority) throw();
  10480. /** Attempts to stop the thread running.
  10481. This method will cause the threadShouldExit() method to return true
  10482. and call notify() in case the thread is currently waiting.
  10483. Hopefully the thread will then respond to this by exiting cleanly, and
  10484. the stopThread method will wait for a given time-period for this to
  10485. happen.
  10486. If the thread is stuck and fails to respond after the time-out, it gets
  10487. forcibly killed, which is a very bad thing to happen, as it could still
  10488. be holding locks, etc. which are needed by other parts of your program.
  10489. @param timeOutMilliseconds The number of milliseconds to wait for the
  10490. thread to finish before killing it by force. A negative
  10491. value in here will wait forever.
  10492. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10493. */
  10494. void stopThread (const int timeOutMilliseconds) throw();
  10495. /** Returns true if the thread is currently active */
  10496. bool isThreadRunning() const throw();
  10497. /** Sets a flag to tell the thread it should stop.
  10498. Calling this means that the threadShouldExit() method will then return true.
  10499. The thread should be regularly checking this to see whether it should exit.
  10500. @see threadShouldExit
  10501. @see waitForThreadToExit
  10502. */
  10503. void signalThreadShouldExit() throw();
  10504. /** Checks whether the thread has been told to stop running.
  10505. Threads need to check this regularly, and if it returns true, they should
  10506. return from their run() method at the first possible opportunity.
  10507. @see signalThreadShouldExit
  10508. */
  10509. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10510. /** Waits for the thread to stop.
  10511. This will waits until isThreadRunning() is false or until a timeout expires.
  10512. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10513. is less than zero, it will wait forever.
  10514. @returns true if the thread exits, or false if the timeout expires first.
  10515. */
  10516. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10517. /** Changes the thread's priority.
  10518. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10519. of 5 is normal.
  10520. */
  10521. void setPriority (const int priority) throw();
  10522. /** Changes the priority of the caller thread.
  10523. Similar to setPriority(), but this static method acts on the caller thread.
  10524. @see setPriority
  10525. */
  10526. static void setCurrentThreadPriority (const int priority) throw();
  10527. /** Sets the affinity mask for the thread.
  10528. This will only have an effect next time the thread is started - i.e. if the
  10529. thread is already running when called, it'll have no effect.
  10530. @see setCurrentThreadAffinityMask
  10531. */
  10532. void setAffinityMask (const uint32 affinityMask) throw();
  10533. /** Changes the affinity mask for the caller thread.
  10534. This will change the affinity mask for the thread that calls this static method.
  10535. @see setAffinityMask
  10536. */
  10537. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10538. // this can be called from any thread that needs to pause..
  10539. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10540. /** Yields the calling thread's current time-slot. */
  10541. static void JUCE_CALLTYPE yield() throw();
  10542. /** Makes the thread wait for a notification.
  10543. This puts the thread to sleep until either the timeout period expires, or
  10544. another thread calls the notify() method to wake it up.
  10545. @returns true if the event has been signalled, false if the timeout expires.
  10546. */
  10547. bool wait (const int timeOutMilliseconds) const throw();
  10548. /** Wakes up the thread.
  10549. If the thread has called the wait() method, this will wake it up.
  10550. @see wait
  10551. */
  10552. void notify() const throw();
  10553. /** Returns an id that identifies the caller thread.
  10554. To find the ID of a particular thread object, use getThreadId().
  10555. @returns a unique identifier that identifies the calling thread.
  10556. @see getThreadId
  10557. */
  10558. static int64 getCurrentThreadId() throw();
  10559. /** Finds the thread object that is currently running.
  10560. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10561. object associated with them, so this will return 0.
  10562. */
  10563. static Thread* getCurrentThread() throw();
  10564. /** Returns the ID of this thread.
  10565. That means the ID of this thread object - not of the thread that's calling the method.
  10566. This can change when the thread is started and stopped, and will be invalid if the
  10567. thread's not actually running.
  10568. @see getCurrentThreadId
  10569. */
  10570. int64 getThreadId() const throw();
  10571. /** Returns the name of the thread.
  10572. This is the name that gets set in the constructor.
  10573. */
  10574. const String getThreadName() const throw() { return threadName_; }
  10575. /** Returns the number of currently-running threads.
  10576. @returns the number of Thread objects known to be currently running.
  10577. @see stopAllThreads
  10578. */
  10579. static int getNumRunningThreads() throw();
  10580. /** Tries to stop all currently-running threads.
  10581. This will attempt to stop all the threads known to be running at the moment.
  10582. */
  10583. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10584. juce_UseDebuggingNewOperator
  10585. private:
  10586. const String threadName_;
  10587. void* volatile threadHandle_;
  10588. CriticalSection startStopLock;
  10589. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10590. int threadPriority_;
  10591. int64 threadId_;
  10592. uint32 affinityMask_;
  10593. bool volatile threadShouldExit_;
  10594. friend void JUCE_API juce_threadEntryPoint (void*);
  10595. static void threadEntryPoint (Thread* thread) throw();
  10596. Thread (const Thread&);
  10597. const Thread& operator= (const Thread&);
  10598. };
  10599. #endif // __JUCE_THREAD_JUCEHEADER__
  10600. /********* End of inlined file: juce_Thread.h *********/
  10601. class ThreadPool;
  10602. class ThreadPoolThread;
  10603. /**
  10604. A task that is executed by a ThreadPool object.
  10605. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  10606. its threads.
  10607. The runJob() method needs to be implemented to do the task, and if the code that
  10608. does the work takes a significant time to run, it must keep checking the shouldExit()
  10609. method to see if something is trying to interrupt the job. If shouldExit() returns
  10610. true, the runJob() method must return immediately.
  10611. @see ThreadPool, Thread
  10612. */
  10613. class JUCE_API ThreadPoolJob
  10614. {
  10615. public:
  10616. /** Creates a thread pool job object.
  10617. After creating your job, add it to a thread pool with ThreadPool::addJob().
  10618. */
  10619. ThreadPoolJob (const String& name);
  10620. /** Destructor. */
  10621. virtual ~ThreadPoolJob();
  10622. /** Returns the name of this job.
  10623. @see setJobName
  10624. */
  10625. const String getJobName() const;
  10626. /** Changes the job's name.
  10627. @see getJobName
  10628. */
  10629. void setJobName (const String& newName);
  10630. /** These are the values that can be returned by the runJob() method.
  10631. */
  10632. enum JobStatus
  10633. {
  10634. jobHasFinished = 0, /**< indicates that the job has finished and can be
  10635. removed from the pool. */
  10636. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  10637. should be automatically deleted by the pool. */
  10638. jobNeedsRunningAgain /**< indicates that the job would like to be called
  10639. again when a thread is free. */
  10640. };
  10641. /** Peforms the actual work that this job needs to do.
  10642. Your subclass must implement this method, in which is does its work.
  10643. If the code in this method takes a significant time to run, it must repeatedly check
  10644. the shouldExit() method to see if something is trying to interrupt the job.
  10645. If shouldExit() ever returns true, the runJob() method must return immediately.
  10646. If this method returns jobHasFinished, then the job will be removed from the pool
  10647. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  10648. pool and will get a chance to run again as soon as a thread is free.
  10649. @see shouldExit()
  10650. */
  10651. virtual JobStatus runJob() = 0;
  10652. /** Returns true if this job is currently running its runJob() method. */
  10653. bool isRunning() const throw() { return isActive; }
  10654. /** Returns true if something is trying to interrupt this job and make it stop.
  10655. Your runJob() method must call this whenever it gets a chance, and if it ever
  10656. returns true, the runJob() method must return immediately.
  10657. @see signalJobShouldExit()
  10658. */
  10659. bool shouldExit() const throw() { return shouldStop; }
  10660. /** Calling this will cause the shouldExit() method to return true, and the job
  10661. should (if it's been implemented correctly) stop as soon as possible.
  10662. @see shouldExit()
  10663. */
  10664. void signalJobShouldExit();
  10665. juce_UseDebuggingNewOperator
  10666. private:
  10667. friend class ThreadPool;
  10668. friend class ThreadPoolThread;
  10669. String jobName;
  10670. ThreadPool* pool;
  10671. bool shouldStop, isActive, shouldBeDeleted;
  10672. };
  10673. /**
  10674. A set of threads that will run a list of jobs.
  10675. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  10676. will be called by the next pooled thread that becomes free.
  10677. @see ThreadPoolJob, Thread
  10678. */
  10679. class JUCE_API ThreadPool
  10680. {
  10681. public:
  10682. /** Creates a thread pool.
  10683. Once you've created a pool, you can give it some things to do with the addJob()
  10684. method.
  10685. @param numberOfThreads the maximum number of actual threads to run.
  10686. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  10687. until there are some jobs to run. If false, then
  10688. all the threads will be fired-up immediately so that
  10689. they're ready for action
  10690. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  10691. inactive for this length of time, they will automatically
  10692. be stopped until more jobs come along and they're needed
  10693. */
  10694. ThreadPool (const int numberOfThreads,
  10695. const bool startThreadsOnlyWhenNeeded = true,
  10696. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  10697. /** Destructor.
  10698. This will attempt to remove all the jobs before deleting, but if you want to
  10699. specify a timeout, you should call removeAllJobs() explicitly before deleting
  10700. the pool.
  10701. */
  10702. ~ThreadPool();
  10703. /** Adds a job to the queue.
  10704. Once a job has been added, then the next time a thread is free, it will run
  10705. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  10706. runJob() method, the pool will either remove the job from the pool or add it to
  10707. the back of the queue to be run again.
  10708. */
  10709. void addJob (ThreadPoolJob* const job);
  10710. /** Tries to remove a job from the pool.
  10711. If the job isn't yet running, this will simply remove it. If it is running, it
  10712. will wait for it to finish.
  10713. If the timeout period expires before the job finishes running, then the job will be
  10714. left in the pool and this will return false. It returns true if the job is sucessfully
  10715. stopped and removed.
  10716. @param job the job to remove
  10717. @param interruptIfRunning if true, then if the job is currently busy, its
  10718. ThreadPoolJob::signalJobShouldExit() method will be called to try
  10719. to interrupt it. If false, then if the job will be allowed to run
  10720. until it stops normally (or the timeout expires)
  10721. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  10722. before giving up and returning false
  10723. */
  10724. bool removeJob (ThreadPoolJob* const job,
  10725. const bool interruptIfRunning,
  10726. const int timeOutMilliseconds);
  10727. /** Tries clear all jobs from the pool.
  10728. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  10729. methods called to try to interrupt them
  10730. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  10731. before giving up and returning false
  10732. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  10733. expires while waiting for them to stop
  10734. */
  10735. bool removeAllJobs (const bool interruptRunningJobs,
  10736. const int timeOutMilliseconds);
  10737. /** Returns the number of jobs currently running or queued.
  10738. */
  10739. int getNumJobs() const throw();
  10740. /** Returns one of the jobs in the queue.
  10741. Note that this can be a very volatile list as jobs might be continuously getting shifted
  10742. around in the list, and this method may return 0 if the index is currently out-of-range.
  10743. */
  10744. ThreadPoolJob* getJob (const int index) const;
  10745. /** Returns true if the given job is currently queued or running.
  10746. @see isJobRunning()
  10747. */
  10748. bool contains (const ThreadPoolJob* const job) const throw();
  10749. /** Returns true if the given job is currently being run by a thread.
  10750. */
  10751. bool isJobRunning (const ThreadPoolJob* const job) const;
  10752. /** Waits until a job has finished running and has been removed from the pool.
  10753. This will wait until the job is no longer in the pool - i.e. until its
  10754. runJob() method returns ThreadPoolJob::jobHasFinished.
  10755. If the timeout period expires before the job finishes, this will return false;
  10756. it returns true if the job has finished successfully.
  10757. */
  10758. bool waitForJobToFinish (const ThreadPoolJob* const job,
  10759. const int timeOutMilliseconds) const;
  10760. /** Returns a list of the names of all the jobs currently running or queued.
  10761. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  10762. */
  10763. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  10764. /** Changes the priority of all the threads.
  10765. This will call Thread::setPriority() for each thread in the pool.
  10766. */
  10767. void setThreadPriorities (const int newPriority);
  10768. juce_UseDebuggingNewOperator
  10769. private:
  10770. const int numThreads, threadStopTimeout;
  10771. int priority;
  10772. Thread** threads;
  10773. VoidArray jobs;
  10774. CriticalSection lock;
  10775. uint32 lastJobEndTime;
  10776. friend class ThreadPoolThread;
  10777. bool runNextJob();
  10778. ThreadPool (const ThreadPool&);
  10779. const ThreadPool& operator= (const ThreadPool&);
  10780. };
  10781. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  10782. /********* End of inlined file: juce_ThreadPool.h *********/
  10783. #endif
  10784. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10785. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  10786. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10787. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10788. /**
  10789. Used by the TimeSliceThread class.
  10790. To register your class with a TimeSliceThread, derive from this class and
  10791. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  10792. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  10793. deleting your client!
  10794. @see TimeSliceThread
  10795. */
  10796. class JUCE_API TimeSliceClient
  10797. {
  10798. public:
  10799. /** Destructor. */
  10800. virtual ~TimeSliceClient() {}
  10801. /** Called back by a TimeSliceThread.
  10802. When you register this class with it, a TimeSliceThread will repeatedly call
  10803. this method.
  10804. The implementation of this method should use its time-slice to do something that's
  10805. quick - never block for longer than absolutely necessary.
  10806. @returns Your method should return true if it needs more time, or false if it's
  10807. not too busy and doesn't need calling back urgently. If all the thread's
  10808. clients indicate that they're not busy, then it'll save CPU by sleeping for
  10809. up to half a second in between callbacks. You can force the TimeSliceThread
  10810. to wake up and poll again immediately by calling its notify() method.
  10811. */
  10812. virtual bool useTimeSlice() = 0;
  10813. };
  10814. /**
  10815. A thread that keeps a list of clients, and calls each one in turn, giving them
  10816. all a chance to run some sort of short task.
  10817. @see TimeSliceClient, Thread
  10818. */
  10819. class JUCE_API TimeSliceThread : public Thread
  10820. {
  10821. public:
  10822. /**
  10823. Creates a TimeSliceThread.
  10824. When first created, the thread is not running. Use the startThread()
  10825. method to start it.
  10826. */
  10827. TimeSliceThread (const String& threadName);
  10828. /** Destructor.
  10829. Deleting a Thread object that is running will only give the thread a
  10830. brief opportunity to stop itself cleanly, so it's recommended that you
  10831. should always call stopThread() with a decent timeout before deleting,
  10832. to avoid the thread being forcibly killed (which is a Bad Thing).
  10833. */
  10834. ~TimeSliceThread();
  10835. /** Adds a client to the list.
  10836. The client's callbacks will start immediately (possibly before the method
  10837. has returned).
  10838. */
  10839. void addTimeSliceClient (TimeSliceClient* const client);
  10840. /** Removes a client from the list.
  10841. This method will make sure that all callbacks to the client have completely
  10842. finished before the method returns.
  10843. */
  10844. void removeTimeSliceClient (TimeSliceClient* const client);
  10845. /** Returns the number of registered clients. */
  10846. int getNumClients() const throw();
  10847. /** Returns one of the registered clients. */
  10848. TimeSliceClient* getClient (const int index) const throw();
  10849. /** @internal */
  10850. void run();
  10851. juce_UseDebuggingNewOperator
  10852. private:
  10853. CriticalSection callbackLock, listLock;
  10854. Array <TimeSliceClient*> clients;
  10855. int index;
  10856. TimeSliceClient* clientBeingCalled;
  10857. bool clientsChanged;
  10858. TimeSliceThread (const TimeSliceThread&);
  10859. const TimeSliceThread& operator= (const TimeSliceThread&);
  10860. };
  10861. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10862. /********* End of inlined file: juce_TimeSliceThread.h *********/
  10863. #endif
  10864. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10865. #endif
  10866. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10867. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  10868. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10869. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10870. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10871. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10872. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10873. /**
  10874. A critical section that allows multiple simultaneous readers.
  10875. Features of this type of lock are:
  10876. - Multiple readers can hold the lock at the same time, but only one writer
  10877. can hold it at once.
  10878. - Writers trying to gain the lock will be blocked until all readers and writers
  10879. have released it
  10880. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  10881. blocked until the writer has obtained and released it
  10882. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  10883. there are no other readers
  10884. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  10885. - Recursive locking is supported.
  10886. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  10887. */
  10888. class JUCE_API ReadWriteLock
  10889. {
  10890. public:
  10891. /**
  10892. Creates a ReadWriteLock object.
  10893. */
  10894. ReadWriteLock() throw();
  10895. /** Destructor.
  10896. If the object is deleted whilst locked, any subsequent behaviour
  10897. is unpredictable.
  10898. */
  10899. ~ReadWriteLock() throw();
  10900. /** Locks this object for reading.
  10901. Multiple threads can simulaneously lock the object for reading, but if another
  10902. thread has it locked for writing, then this will block until it releases the
  10903. lock.
  10904. @see exitRead, ScopedReadLock
  10905. */
  10906. void enterRead() const throw();
  10907. /** Releases the read-lock.
  10908. If the caller thread hasn't got the lock, this can have unpredictable results.
  10909. If the enterRead() method has been called multiple times by the thread, each
  10910. call must be matched by a call to exitRead() before other threads will be allowed
  10911. to take over the lock.
  10912. @see enterRead, ScopedReadLock
  10913. */
  10914. void exitRead() const throw();
  10915. /** Locks this object for writing.
  10916. This will block until any other threads that have it locked for reading or
  10917. writing have released their lock.
  10918. @see exitWrite, ScopedWriteLock
  10919. */
  10920. void enterWrite() const throw();
  10921. /** Tries to lock this object for writing.
  10922. This is like enterWrite(), but doesn't block - it returns true if it manages
  10923. to obtain the lock.
  10924. @see enterWrite
  10925. */
  10926. bool tryEnterWrite() const throw();
  10927. /** Releases the write-lock.
  10928. If the caller thread hasn't got the lock, this can have unpredictable results.
  10929. If the enterWrite() method has been called multiple times by the thread, each
  10930. call must be matched by a call to exit() before other threads will be allowed
  10931. to take over the lock.
  10932. @see enterWrite, ScopedWriteLock
  10933. */
  10934. void exitWrite() const throw();
  10935. juce_UseDebuggingNewOperator
  10936. private:
  10937. CriticalSection accessLock;
  10938. WaitableEvent waitEvent;
  10939. mutable int numWaitingWriters, numWriters;
  10940. mutable int64 writerThreadId;
  10941. mutable Array <int64> readerThreads;
  10942. ReadWriteLock (const ReadWriteLock&);
  10943. const ReadWriteLock& operator= (const ReadWriteLock&);
  10944. };
  10945. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  10946. /********* End of inlined file: juce_ReadWriteLock.h *********/
  10947. /**
  10948. Automatically locks and unlocks a ReadWriteLock object.
  10949. Use one of these as a local variable to control access to a ReadWriteLock.
  10950. e.g. @code
  10951. ReadWriteLock myLock;
  10952. for (;;)
  10953. {
  10954. const ScopedReadLock myScopedLock (myLock);
  10955. // myLock is now locked
  10956. ...do some stuff...
  10957. // myLock gets unlocked here.
  10958. }
  10959. @endcode
  10960. @see ReadWriteLock, ScopedWriteLock
  10961. */
  10962. class JUCE_API ScopedReadLock
  10963. {
  10964. public:
  10965. /** Creates a ScopedReadLock.
  10966. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  10967. when the ScopedReadLock object is deleted, the ReadWriteLock will
  10968. be unlocked.
  10969. Make sure this object is created and deleted by the same thread,
  10970. otherwise there are no guarantees what will happen! Best just to use it
  10971. as a local stack object, rather than creating one with the new() operator.
  10972. */
  10973. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  10974. /** Destructor.
  10975. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  10976. Make sure this object is created and deleted by the same thread,
  10977. otherwise there are no guarantees what will happen!
  10978. */
  10979. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  10980. private:
  10981. const ReadWriteLock& lock_;
  10982. ScopedReadLock (const ScopedReadLock&);
  10983. const ScopedReadLock& operator= (const ScopedReadLock&);
  10984. };
  10985. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10986. /********* End of inlined file: juce_ScopedReadLock.h *********/
  10987. #endif
  10988. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10989. /********* Start of inlined file: juce_Process.h *********/
  10990. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10991. #define __JUCE_PROCESS_JUCEHEADER__
  10992. /** Represents the current executable's process.
  10993. This contains methods for controlling the current application at the
  10994. process-level.
  10995. @see Thread, JUCEApplication
  10996. */
  10997. class JUCE_API Process
  10998. {
  10999. public:
  11000. enum ProcessPriority
  11001. {
  11002. LowPriority = 0,
  11003. NormalPriority = 1,
  11004. HighPriority = 2,
  11005. RealtimePriority = 3
  11006. };
  11007. /** Changes the current process's priority.
  11008. @param priority the process priority, where
  11009. 0=low, 1=normal, 2=high, 3=realtime
  11010. */
  11011. static void setPriority (const ProcessPriority priority);
  11012. /** Kills the current process immediately.
  11013. This is an emergency process terminator that kills the application
  11014. immediately - it's intended only for use only when something goes
  11015. horribly wrong.
  11016. @see JUCEApplication::quit
  11017. */
  11018. static void terminate();
  11019. /** Returns true if this application process is the one that the user is
  11020. currently using.
  11021. */
  11022. static bool isForegroundProcess() throw();
  11023. /** Raises the current process's privilege level.
  11024. Does nothing if this isn't supported by the current OS, or if process
  11025. privilege level is fixed.
  11026. */
  11027. static void raisePrivilege();
  11028. /** Lowers the current process's privilege level.
  11029. Does nothing if this isn't supported by the current OS, or if process
  11030. privilege level is fixed.
  11031. */
  11032. static void lowerPrivilege();
  11033. /** Returns true if this process is being hosted by a debugger.
  11034. */
  11035. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  11036. };
  11037. #endif // __JUCE_PROCESS_JUCEHEADER__
  11038. /********* End of inlined file: juce_Process.h *********/
  11039. #endif
  11040. #ifndef __JUCE_THREAD_JUCEHEADER__
  11041. #endif
  11042. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11043. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  11044. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11045. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11046. /**
  11047. Automatically tries to lock and unlock a CriticalSection object.
  11048. Use one of these as a local variable to control access to a CriticalSection.
  11049. e.g. @code
  11050. CriticalSection myCriticalSection;
  11051. for (;;)
  11052. {
  11053. const ScopedTryLock myScopedTryLock (myCriticalSection);
  11054. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  11055. // should test this with the isLocked() method before doing your thread-unsafe
  11056. // action..
  11057. if (myScopedTryLock.isLocked())
  11058. {
  11059. ...do some stuff...
  11060. }
  11061. else
  11062. {
  11063. ..our attempt at locking failed because another thread had already locked it..
  11064. }
  11065. // myCriticalSection gets unlocked here (if it was locked)
  11066. }
  11067. @endcode
  11068. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  11069. */
  11070. class JUCE_API ScopedTryLock
  11071. {
  11072. public:
  11073. /** Creates a ScopedTryLock.
  11074. As soon as it is created, this will try to lock the CriticalSection, and
  11075. when the ScopedTryLock object is deleted, the CriticalSection will
  11076. be unlocked if the lock was successful.
  11077. Make sure this object is created and deleted by the same thread,
  11078. otherwise there are no guarantees what will happen! Best just to use it
  11079. as a local stack object, rather than creating one with the new() operator.
  11080. */
  11081. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  11082. /** Destructor.
  11083. The CriticalSection will be unlocked (if locked) when the destructor is called.
  11084. Make sure this object is created and deleted by the same thread,
  11085. otherwise there are no guarantees what will happen!
  11086. */
  11087. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  11088. /** Lock state
  11089. @return True if the CriticalSection is locked.
  11090. */
  11091. bool isLocked() const throw() { return lockWasSuccessful; }
  11092. private:
  11093. const CriticalSection& lock_;
  11094. const bool lockWasSuccessful;
  11095. ScopedTryLock (const ScopedTryLock&);
  11096. const ScopedTryLock& operator= (const ScopedTryLock&);
  11097. };
  11098. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11099. /********* End of inlined file: juce_ScopedTryLock.h *********/
  11100. #endif
  11101. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  11102. #endif
  11103. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11104. /********* Start of inlined file: juce_InterProcessLock.h *********/
  11105. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11106. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11107. /**
  11108. Acts as a critical section which processes can use to block each other.
  11109. @see CriticalSection
  11110. */
  11111. class JUCE_API InterProcessLock
  11112. {
  11113. public:
  11114. /** Creates a lock object.
  11115. @param name a name that processes will use to identify this lock object
  11116. */
  11117. InterProcessLock (const String& name) throw();
  11118. /** Destructor.
  11119. This will also release the lock if it's currently held by this process.
  11120. */
  11121. ~InterProcessLock() throw();
  11122. /** Attempts to lock the critical section.
  11123. @param timeOutMillisecs how many milliseconds to wait if the lock
  11124. is already held by another process - a value of
  11125. 0 will return immediately, negative values will wait
  11126. forever
  11127. @returns true if the lock could be gained within the timeout period, or
  11128. false if the timeout expired.
  11129. */
  11130. bool enter (int timeOutMillisecs = -1) throw();
  11131. /** Releases the lock if it's currently held by this process.
  11132. */
  11133. void exit() throw();
  11134. juce_UseDebuggingNewOperator
  11135. private:
  11136. void* internal;
  11137. String name;
  11138. int reentrancyLevel;
  11139. InterProcessLock (const InterProcessLock&);
  11140. const InterProcessLock& operator= (const InterProcessLock&);
  11141. };
  11142. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11143. /********* End of inlined file: juce_InterProcessLock.h *********/
  11144. #endif
  11145. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11146. #endif
  11147. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11148. #endif
  11149. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11150. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  11151. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11152. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11153. /**
  11154. Automatically locks and unlocks a ReadWriteLock object.
  11155. Use one of these as a local variable to control access to a ReadWriteLock.
  11156. e.g. @code
  11157. ReadWriteLock myLock;
  11158. for (;;)
  11159. {
  11160. const ScopedWriteLock myScopedLock (myLock);
  11161. // myLock is now locked
  11162. ...do some stuff...
  11163. // myLock gets unlocked here.
  11164. }
  11165. @endcode
  11166. @see ReadWriteLock, ScopedReadLock
  11167. */
  11168. class JUCE_API ScopedWriteLock
  11169. {
  11170. public:
  11171. /** Creates a ScopedWriteLock.
  11172. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  11173. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  11174. be unlocked.
  11175. Make sure this object is created and deleted by the same thread,
  11176. otherwise there are no guarantees what will happen! Best just to use it
  11177. as a local stack object, rather than creating one with the new() operator.
  11178. */
  11179. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  11180. /** Destructor.
  11181. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  11182. Make sure this object is created and deleted by the same thread,
  11183. otherwise there are no guarantees what will happen!
  11184. */
  11185. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  11186. private:
  11187. const ReadWriteLock& lock_;
  11188. ScopedWriteLock (const ScopedWriteLock&);
  11189. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  11190. };
  11191. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11192. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  11193. #endif
  11194. #endif
  11195. /********* End of inlined file: juce_core_includes.h *********/
  11196. // if you're compiling a command-line app, you might want to just include the core headers,
  11197. // so you can set this macro before including juce.h
  11198. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11199. /********* Start of inlined file: juce_app_includes.h *********/
  11200. #ifndef __JUCE_APP_INCLUDES_JUCEHEADER__
  11201. #define __JUCE_APP_INCLUDES_JUCEHEADER__
  11202. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11203. /********* Start of inlined file: juce_Application.h *********/
  11204. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11205. #define __JUCE_APPLICATION_JUCEHEADER__
  11206. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11207. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11208. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11209. /********* Start of inlined file: juce_Component.h *********/
  11210. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11211. #define __JUCE_COMPONENT_JUCEHEADER__
  11212. /********* Start of inlined file: juce_MouseCursor.h *********/
  11213. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11214. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11215. class Image;
  11216. class RefCountedMouseCursor;
  11217. class ComponentPeer;
  11218. class Component;
  11219. /**
  11220. Represents a mouse cursor image.
  11221. This object can either be used to represent one of the standard mouse
  11222. cursor shapes, or a custom one generated from an image.
  11223. */
  11224. class JUCE_API MouseCursor
  11225. {
  11226. public:
  11227. /** The set of available standard mouse cursors. */
  11228. enum StandardCursorType
  11229. {
  11230. NoCursor = 0, /**< An invisible cursor. */
  11231. NormalCursor, /**< The stardard arrow cursor. */
  11232. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11233. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11234. CrosshairCursor, /**< A pair of crosshairs. */
  11235. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11236. that you're dragging a copy of something. */
  11237. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11238. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11239. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11240. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11241. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11242. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11243. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11244. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11245. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11246. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11247. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11248. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11249. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11250. };
  11251. /** Creates the standard arrow cursor. */
  11252. MouseCursor() throw();
  11253. /** Creates one of the standard mouse cursor */
  11254. MouseCursor (const StandardCursorType type) throw();
  11255. /** Creates a custom cursor from an image.
  11256. @param image the image to use for the cursor - if this is bigger than the
  11257. system can manage, it might get scaled down first, and might
  11258. also have to be turned to black-and-white if it can't do colour
  11259. cursors.
  11260. @param hotSpotX the x position of the cursor's hotspot within the image
  11261. @param hotSpotY the y position of the cursor's hotspot within the image
  11262. */
  11263. MouseCursor (Image& image,
  11264. const int hotSpotX,
  11265. const int hotSpotY) throw();
  11266. /** Creates a copy of another cursor object. */
  11267. MouseCursor (const MouseCursor& other) throw();
  11268. /** Copies this cursor from another object. */
  11269. const MouseCursor& operator= (const MouseCursor& other) throw();
  11270. /** Destructor. */
  11271. ~MouseCursor() throw();
  11272. /** Checks whether two mouse cursors are the same.
  11273. For custom cursors, two cursors created from the same image won't be
  11274. recognised as the same, only MouseCursor objects that have been
  11275. copied from the same object.
  11276. */
  11277. bool operator== (const MouseCursor& other) const throw();
  11278. /** Checks whether two mouse cursors are the same.
  11279. For custom cursors, two cursors created from the same image won't be
  11280. recognised as the same, only MouseCursor objects that have been
  11281. copied from the same object.
  11282. */
  11283. bool operator!= (const MouseCursor& other) const throw();
  11284. /** Makes the system show its default 'busy' cursor.
  11285. This will turn the system cursor to an hourglass or spinning beachball
  11286. until the next time the mouse is moved, or hideWaitCursor() is called.
  11287. This is handy if the message loop is about to block for a couple of
  11288. seconds while busy and you want to give the user feedback about this.
  11289. @see MessageManager::setTimeBeforeShowingWaitCursor
  11290. */
  11291. static void showWaitCursor() throw();
  11292. /** If showWaitCursor has been called, this will return the mouse to its
  11293. normal state.
  11294. This will look at what component is under the mouse, and update the
  11295. cursor to be the correct one for that component.
  11296. @see showWaitCursor
  11297. */
  11298. static void hideWaitCursor() throw();
  11299. juce_UseDebuggingNewOperator
  11300. private:
  11301. RefCountedMouseCursor* cursorHandle;
  11302. friend class Component;
  11303. void showInWindow (ComponentPeer* window) const throw();
  11304. void showInAllWindows() const throw();
  11305. void* getHandle() const throw();
  11306. };
  11307. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11308. /********* End of inlined file: juce_MouseCursor.h *********/
  11309. /********* Start of inlined file: juce_MouseListener.h *********/
  11310. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11311. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11312. /********* Start of inlined file: juce_MouseEvent.h *********/
  11313. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11314. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11315. class Component;
  11316. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11317. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11318. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11319. /**
  11320. Represents the state of the mouse buttons and modifier keys.
  11321. This is used both by mouse events and by KeyPress objects to describe
  11322. the state of keys such as shift, control, alt, etc.
  11323. @see KeyPress, MouseEvent::mods
  11324. */
  11325. class JUCE_API ModifierKeys
  11326. {
  11327. public:
  11328. /** Creates a ModifierKeys object from a raw set of flags.
  11329. @param flags to represent the keys that are down
  11330. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11331. rightButtonModifier, commandModifier, popupMenuClickModifier
  11332. */
  11333. ModifierKeys (const int flags = 0) throw();
  11334. /** Creates a copy of another object. */
  11335. ModifierKeys (const ModifierKeys& other) throw();
  11336. /** Copies this object from another one. */
  11337. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11338. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11339. This is a platform-agnostic way of checking for the operating system's
  11340. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11341. Windows/Linux, it's actually checking for the CTRL key.
  11342. */
  11343. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11344. /** Checks whether the user is trying to launch a pop-up menu.
  11345. This checks for platform-specific modifiers that might indicate that the user
  11346. is following the operating system's normal method of showing a pop-up menu.
  11347. So on Windows/Linux, this method is really testing for a right-click.
  11348. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11349. */
  11350. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11351. /** Checks whether the flag is set for the left mouse-button. */
  11352. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11353. /** Checks whether the flag is set for the right mouse-button.
  11354. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11355. this is platform-independent (and makes your code more explanatory too).
  11356. */
  11357. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11358. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11359. /** Tests for any of the mouse-button flags. */
  11360. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11361. /** Tests for any of the modifier key flags. */
  11362. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11363. /** Checks whether the shift key's flag is set. */
  11364. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11365. /** Checks whether the CTRL key's flag is set.
  11366. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11367. popup-menu modifiers.
  11368. @see isCommandDown, isPopupMenu
  11369. */
  11370. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11371. /** Checks whether the shift key's flag is set. */
  11372. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11373. /** Flags that represent the different keys. */
  11374. enum Flags
  11375. {
  11376. /** Shift key flag. */
  11377. shiftModifier = 1,
  11378. /** CTRL key flag. */
  11379. ctrlModifier = 2,
  11380. /** ALT key flag. */
  11381. altModifier = 4,
  11382. /** Left mouse button flag. */
  11383. leftButtonModifier = 16,
  11384. /** Right mouse button flag. */
  11385. rightButtonModifier = 32,
  11386. /** Middle mouse button flag. */
  11387. middleButtonModifier = 64,
  11388. #if JUCE_MAC
  11389. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11390. commandModifier = 8,
  11391. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11392. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11393. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11394. #else
  11395. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11396. commandModifier = ctrlModifier,
  11397. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11398. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11399. popupMenuClickModifier = rightButtonModifier,
  11400. #endif
  11401. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11402. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11403. /** Represents a combination of all the mouse buttons at once. */
  11404. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11405. };
  11406. /** Returns the raw flags for direct testing. */
  11407. inline int getRawFlags() const throw() { return flags; }
  11408. /** Tests a combination of flags and returns true if any of them are set. */
  11409. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11410. /** Creates a ModifierKeys object to represent the last-known state of the
  11411. keyboard and mouse buttons.
  11412. @see getCurrentModifiersRealtime
  11413. */
  11414. static const ModifierKeys getCurrentModifiers() throw();
  11415. /** Creates a ModifierKeys object to represent the current state of the
  11416. keyboard and mouse buttons.
  11417. This isn't often needed and isn't recommended, but will actively check all the
  11418. mouse and key states rather than just returning their last-known state like
  11419. getCurrentModifiers() does.
  11420. This is only needed in special circumstances for up-to-date modifier information
  11421. at times when the app's event loop isn't running normally.
  11422. */
  11423. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11424. private:
  11425. int flags;
  11426. static int currentModifierFlags;
  11427. friend class ComponentPeer;
  11428. static void updateCurrentModifiers() throw();
  11429. };
  11430. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11431. /********* End of inlined file: juce_ModifierKeys.h *********/
  11432. /**
  11433. Contains position and status information about a mouse event.
  11434. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11435. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11436. */
  11437. class JUCE_API MouseEvent
  11438. {
  11439. public:
  11440. /** Creates a MouseEvent.
  11441. Normally an application will never need to use this.
  11442. @param x the x position of the mouse, relative to the component that is passed-in
  11443. @param y the y position of the mouse, relative to the component that is passed-in
  11444. @param modifiers the key modifiers at the time of the event
  11445. @param originator the component that the mouse event applies to
  11446. @param eventTime the time the event happened
  11447. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11448. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11449. the same as the current mouse-x position.
  11450. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11451. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11452. the same as the current mouse-y position.
  11453. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11454. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11455. the same as the current mouse-event time.
  11456. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11457. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11458. */
  11459. MouseEvent (const int x, const int y,
  11460. const ModifierKeys& modifiers,
  11461. Component* const originator,
  11462. const Time& eventTime,
  11463. const int mouseDownX,
  11464. const int mouseDownY,
  11465. const Time& mouseDownTime,
  11466. const int numberOfClicks,
  11467. const bool mouseWasDragged) throw();
  11468. /** Destructor. */
  11469. ~MouseEvent() throw();
  11470. /** The x-position of the mouse when the event occurred.
  11471. This value is relative to the top-left of the component to which the
  11472. event applies (as indicated by the MouseEvent::eventComponent field).
  11473. */
  11474. int x;
  11475. /** The y-position of the mouse when the event occurred.
  11476. This value is relative to the top-left of the component to which the
  11477. event applies (as indicated by the MouseEvent::eventComponent field).
  11478. */
  11479. int y;
  11480. /** The key modifiers associated with the event.
  11481. This will let you find out which mouse buttons were down, as well as which
  11482. modifier keys were held down.
  11483. When used for mouse-up events, this will indicate the state of the mouse buttons
  11484. just before they were released, so that you can tell which button they let go of.
  11485. */
  11486. ModifierKeys mods;
  11487. /** The component that this event applies to.
  11488. This is usually the component that the mouse was over at the time, but for mouse-drag
  11489. events the mouse could actually be over a different component and the events are
  11490. still sent to the component that the button was originally pressed on.
  11491. The x and y member variables are relative to this component's position.
  11492. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11493. component, this pointer will be updated, but originalComponent remains unchanged.
  11494. @see originalComponent
  11495. */
  11496. Component* eventComponent;
  11497. /** The component that the event first occurred on.
  11498. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11499. component, this value remains unchanged to indicate the first component that received it.
  11500. @see eventComponent
  11501. */
  11502. Component* originalComponent;
  11503. /** The time that this mouse-event occurred.
  11504. */
  11505. Time eventTime;
  11506. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11507. The co-ordinate is relative to the component specified in MouseEvent::component.
  11508. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11509. */
  11510. int getMouseDownX() const throw();
  11511. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11512. The co-ordinate is relative to the component specified in MouseEvent::component.
  11513. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11514. */
  11515. int getMouseDownY() const throw();
  11516. /** Returns the straight-line distance between where the mouse is now and where it
  11517. was the last time the button was pressed.
  11518. This is quite handy for things like deciding whether the user has moved far enough
  11519. for it to be considered a drag operation.
  11520. @see getDistanceFromDragStartX
  11521. */
  11522. int getDistanceFromDragStart() const throw();
  11523. /** Returns the difference between the mouse's current x postion and where it was
  11524. when the button was last pressed.
  11525. @see getDistanceFromDragStart
  11526. */
  11527. int getDistanceFromDragStartX() const throw();
  11528. /** Returns the difference between the mouse's current y postion and where it was
  11529. when the button was last pressed.
  11530. @see getDistanceFromDragStart
  11531. */
  11532. int getDistanceFromDragStartY() const throw();
  11533. /** Returns true if the mouse has just been clicked.
  11534. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11535. the user has dragged the mouse more than a few pixels from the place where the
  11536. mouse-down occurred.
  11537. Once they have dragged it far enough for this method to return false, it will continue
  11538. to return false until the mouse-up, even if they move the mouse back to the same
  11539. position where they originally pressed it. This means that it's very handy for
  11540. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11541. callback to ignore any small movements they might make while clicking.
  11542. @returns true if the mouse wasn't dragged by more than a few pixels between
  11543. the last time the button was pressed and released.
  11544. */
  11545. bool mouseWasClicked() const throw();
  11546. /** For a click event, the number of times the mouse was clicked in succession.
  11547. So for example a double-click event will return 2, a triple-click 3, etc.
  11548. */
  11549. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11550. /** Returns the time that the mouse button has been held down for.
  11551. If called from a mouseDrag or mouseUp callback, this will return the
  11552. number of milliseconds since the corresponding mouseDown event occurred.
  11553. If called in other contexts, e.g. a mouseMove, then the returned value
  11554. may be 0 or an undefined value.
  11555. */
  11556. int getLengthOfMousePress() const throw();
  11557. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11558. The co-ordinates are relative to the top-left of the main monitor.
  11559. @see getMouseDownScreenX, Desktop::getMousePosition
  11560. */
  11561. int getScreenX() const throw();
  11562. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11563. The co-ordinates are relative to the top-left of the main monitor.
  11564. @see getMouseDownScreenY, Desktop::getMousePosition
  11565. */
  11566. int getScreenY() const throw();
  11567. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11568. The co-ordinates are relative to the top-left of the main monitor.
  11569. @see getScreenX, Desktop::getMousePosition
  11570. */
  11571. int getMouseDownScreenX() const throw();
  11572. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11573. The co-ordinates are relative to the top-left of the main monitor.
  11574. @see getScreenY, Desktop::getMousePosition
  11575. */
  11576. int getMouseDownScreenY() const throw();
  11577. /** Creates a version of this event that is relative to a different component.
  11578. The x and y positions of the event that is returned will have been
  11579. adjusted to be relative to the new component.
  11580. */
  11581. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11582. /** Changes the application-wide setting for the double-click time limit.
  11583. This is the maximum length of time between mouse-clicks for it to be
  11584. considered a double-click. It's used by the Component class.
  11585. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11586. */
  11587. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11588. /** Returns the application-wide setting for the double-click time limit.
  11589. This is the maximum length of time between mouse-clicks for it to be
  11590. considered a double-click. It's used by the Component class.
  11591. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11592. */
  11593. static int getDoubleClickTimeout() throw();
  11594. juce_UseDebuggingNewOperator
  11595. private:
  11596. int mouseDownX, mouseDownY;
  11597. Time mouseDownTime;
  11598. int numberOfClicks;
  11599. bool wasMovedSinceMouseDown;
  11600. };
  11601. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11602. /********* End of inlined file: juce_MouseEvent.h *********/
  11603. /**
  11604. A MouseListener can be registered with a component to receive callbacks
  11605. about mouse events that happen to that component.
  11606. @see Component::addMouseListener, Component::removeMouseListener
  11607. */
  11608. class JUCE_API MouseListener
  11609. {
  11610. public:
  11611. /** Destructor. */
  11612. virtual ~MouseListener() {}
  11613. /** Called when the mouse moves inside a component.
  11614. If the mouse button isn't pressed and the mouse moves over a component,
  11615. this will be called to let the component react to this.
  11616. A component will always get a mouseEnter callback before a mouseMove.
  11617. @param e details about the position and status of the mouse event, including
  11618. the source component in which it occurred
  11619. @see mouseEnter, mouseExit, mouseDrag, contains
  11620. */
  11621. virtual void mouseMove (const MouseEvent& e);
  11622. /** Called when the mouse first enters a component.
  11623. If the mouse button isn't pressed and the mouse moves into a component,
  11624. this will be called to let the component react to this.
  11625. When the mouse button is pressed and held down while being moved in
  11626. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11627. mouseDrag messages are sent to the component that the mouse was originally
  11628. clicked on, until the button is released.
  11629. @param e details about the position and status of the mouse event, including
  11630. the source component in which it occurred
  11631. @see mouseExit, mouseDrag, mouseMove, contains
  11632. */
  11633. virtual void mouseEnter (const MouseEvent& e);
  11634. /** Called when the mouse moves out of a component.
  11635. This will be called when the mouse moves off the edge of this
  11636. component.
  11637. If the mouse button was pressed, and it was then dragged off the
  11638. edge of the component and released, then this callback will happen
  11639. when the button is released, after the mouseUp callback.
  11640. @param e details about the position and status of the mouse event, including
  11641. the source component in which it occurred
  11642. @see mouseEnter, mouseDrag, mouseMove, contains
  11643. */
  11644. virtual void mouseExit (const MouseEvent& e);
  11645. /** Called when a mouse button is pressed.
  11646. The MouseEvent object passed in contains lots of methods for finding out
  11647. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11648. were held down at the time.
  11649. Once a button is held down, the mouseDrag method will be called when the
  11650. mouse moves, until the button is released.
  11651. @param e details about the position and status of the mouse event, including
  11652. the source component in which it occurred
  11653. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11654. */
  11655. virtual void mouseDown (const MouseEvent& e);
  11656. /** Called when the mouse is moved while a button is held down.
  11657. When a mouse button is pressed inside a component, that component
  11658. receives mouseDrag callbacks each time the mouse moves, even if the
  11659. mouse strays outside the component's bounds.
  11660. @param e details about the position and status of the mouse event, including
  11661. the source component in which it occurred
  11662. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11663. */
  11664. virtual void mouseDrag (const MouseEvent& e);
  11665. /** Called when a mouse button is released.
  11666. A mouseUp callback is sent to the component in which a button was pressed
  11667. even if the mouse is actually over a different component when the
  11668. button is released.
  11669. The MouseEvent object passed in contains lots of methods for finding out
  11670. which buttons were down just before they were released.
  11671. @param e details about the position and status of the mouse event, including
  11672. the source component in which it occurred
  11673. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11674. */
  11675. virtual void mouseUp (const MouseEvent& e);
  11676. /** Called when a mouse button has been double-clicked on a component.
  11677. The MouseEvent object passed in contains lots of methods for finding out
  11678. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11679. were held down at the time.
  11680. @param e details about the position and status of the mouse event, including
  11681. the source component in which it occurred
  11682. @see mouseDown, mouseUp
  11683. */
  11684. virtual void mouseDoubleClick (const MouseEvent& e);
  11685. /** Called when the mouse-wheel is moved.
  11686. This callback is sent to the component that the mouse is over when the
  11687. wheel is moved.
  11688. If not overridden, the component will forward this message to its parent, so
  11689. that parent components can collect mouse-wheel messages that happen to
  11690. child components which aren't interested in them.
  11691. @param e details about the position and status of the mouse event, including
  11692. the source component in which it occurred
  11693. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11694. value means the wheel has been pushed to the right, negative means it
  11695. was pushed to the left
  11696. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11697. value means the wheel has been pushed upwards, negative means it
  11698. was pushed downwards
  11699. */
  11700. virtual void mouseWheelMove (const MouseEvent& e,
  11701. float wheelIncrementX,
  11702. float wheelIncrementY);
  11703. private:
  11704. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11705. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11706. // if that happens, update your code to use the new one above.
  11707. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11708. };
  11709. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11710. /********* End of inlined file: juce_MouseListener.h *********/
  11711. /********* Start of inlined file: juce_ComponentListener.h *********/
  11712. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11713. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11714. class Component;
  11715. /**
  11716. Gets informed about changes to a component's hierarchy or position.
  11717. To monitor a component for changes, register a subclass of ComponentListener
  11718. with the component using Component::addComponentListener().
  11719. Be sure to deregister listeners before you delete them!
  11720. @see Component::addComponentListener, Component::removeComponentListener
  11721. */
  11722. class JUCE_API ComponentListener
  11723. {
  11724. public:
  11725. /** Destructor. */
  11726. virtual ~ComponentListener() {}
  11727. /** Called when the component's position or size changes.
  11728. @param component the component that was moved or resized
  11729. @param wasMoved true if the component's top-left corner has just moved
  11730. @param wasResized true if the component's width or height has just changed
  11731. @see Component::setBounds, Component::resized, Component::moved
  11732. */
  11733. virtual void componentMovedOrResized (Component& component,
  11734. bool wasMoved,
  11735. bool wasResized);
  11736. /** Called when the component is brought to the top of the z-order.
  11737. @param component the component that was moved
  11738. @see Component::toFront, Component::broughtToFront
  11739. */
  11740. virtual void componentBroughtToFront (Component& component);
  11741. /** Called when the component is made visible or invisible.
  11742. @param component the component that changed
  11743. @see Component::setVisible
  11744. */
  11745. virtual void componentVisibilityChanged (Component& component);
  11746. /** Called when the component has children added or removed.
  11747. @param component the component whose children were changed
  11748. @see Component::childrenChanged, Component::addChildComponent,
  11749. Component::removeChildComponent
  11750. */
  11751. virtual void componentChildrenChanged (Component& component);
  11752. /** Called to indicate that the component's parents have changed.
  11753. When a component is added or removed from its parent, all of its children
  11754. will produce this notification (recursively - so all children of its
  11755. children will also be called as well).
  11756. @param component the component that this listener is registered with
  11757. @see Component::parentHierarchyChanged
  11758. */
  11759. virtual void componentParentHierarchyChanged (Component& component);
  11760. /** Called when the component's name is changed.
  11761. @see Component::setName, Component::getName
  11762. */
  11763. virtual void componentNameChanged (Component& component);
  11764. };
  11765. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11766. /********* End of inlined file: juce_ComponentListener.h *********/
  11767. /********* Start of inlined file: juce_KeyListener.h *********/
  11768. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11769. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11770. /********* Start of inlined file: juce_KeyPress.h *********/
  11771. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11772. #define __JUCE_KEYPRESS_JUCEHEADER__
  11773. /**
  11774. Represents a key press, including any modifier keys that are needed.
  11775. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11776. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11777. */
  11778. class JUCE_API KeyPress
  11779. {
  11780. public:
  11781. /** Creates an (invalid) KeyPress.
  11782. @see isValid
  11783. */
  11784. KeyPress() throw();
  11785. /** Creates a KeyPress for a key and some modifiers.
  11786. e.g.
  11787. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11788. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11789. @param keyCode a code that represents the key - this value must be
  11790. one of special constants listed in this class, or an
  11791. 8-bit character code such as a letter (case is ignored),
  11792. digit or a simple key like "," or ".". Note that this
  11793. isn't the same as the textCharacter parameter, so for example
  11794. a keyCode of 'a' and a shift-key modifier should have a
  11795. textCharacter value of 'A'.
  11796. @param modifiers the modifiers to associate with the keystroke
  11797. @param textCharacter the character that would be printed if someone typed
  11798. this keypress into a text editor. This value may be
  11799. null if the keypress is a non-printing character
  11800. @see getKeyCode, isKeyCode, getModifiers
  11801. */
  11802. KeyPress (const int keyCode,
  11803. const ModifierKeys& modifiers,
  11804. const juce_wchar textCharacter) throw();
  11805. /** Creates a keypress with a keyCode but no modifiers or text character.
  11806. */
  11807. KeyPress (const int keyCode) throw();
  11808. /** Creates a copy of another KeyPress. */
  11809. KeyPress (const KeyPress& other) throw();
  11810. /** Copies this KeyPress from another one. */
  11811. const KeyPress& operator= (const KeyPress& other) throw();
  11812. /** Compares two KeyPress objects. */
  11813. bool operator== (const KeyPress& other) const throw();
  11814. /** Compares two KeyPress objects. */
  11815. bool operator!= (const KeyPress& other) const throw();
  11816. /** Returns true if this is a valid KeyPress.
  11817. A null keypress can be created by the default constructor, in case it's
  11818. needed.
  11819. */
  11820. bool isValid() const throw() { return keyCode != 0; }
  11821. /** Returns the key code itself.
  11822. This will either be one of the special constants defined in this class,
  11823. or an 8-bit character code.
  11824. */
  11825. int getKeyCode() const throw() { return keyCode; }
  11826. /** Returns the key modifiers.
  11827. @see ModifierKeys
  11828. */
  11829. const ModifierKeys getModifiers() const throw() { return mods; }
  11830. /** Returns the character that is associated with this keypress.
  11831. This is the character that you'd expect to see printed if you press this
  11832. keypress in a text editor or similar component.
  11833. */
  11834. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11835. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11836. the modifiers.
  11837. The values for key codes can either be one of the special constants defined in
  11838. this class, or an 8-bit character code.
  11839. @see getKeyCode
  11840. */
  11841. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11842. /** Converts a textual key description to a KeyPress.
  11843. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11844. This isn't designed to cope with any kind of input, but should be given the
  11845. strings that are created by the getTextDescription() method.
  11846. If the string can't be parsed, the object returned will be invalid.
  11847. @see getTextDescription
  11848. */
  11849. static const KeyPress createFromDescription (const String& textVersion) throw();
  11850. /** Creates a textual description of the key combination.
  11851. e.g. "CTRL + C" or "DELETE".
  11852. To store a keypress in a file, use this method, along with createFromDescription()
  11853. to retrieve it later.
  11854. */
  11855. const String getTextDescription() const throw();
  11856. /** Checks whether the user is currently holding down the keys that make up this
  11857. KeyPress.
  11858. Note that this will return false if any extra modifier keys are
  11859. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11860. then it will be false.
  11861. */
  11862. bool isCurrentlyDown() const throw();
  11863. /** Checks whether a particular key is held down, irrespective of modifiers.
  11864. The values for key codes can either be one of the special constants defined in
  11865. this class, or an 8-bit character code.
  11866. */
  11867. static bool isKeyCurrentlyDown (int keyCode) throw();
  11868. // Key codes
  11869. //
  11870. // Note that the actual values of these are platform-specific and may change
  11871. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  11872. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  11873. //
  11874. static const int spaceKey; /**< key-code for the space bar */
  11875. static const int escapeKey; /**< key-code for the escape key */
  11876. static const int returnKey; /**< key-code for the return key*/
  11877. static const int tabKey; /**< key-code for the tab key*/
  11878. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  11879. static const int backspaceKey; /**< key-code for the backspace key */
  11880. static const int insertKey; /**< key-code for the insert key */
  11881. static const int upKey; /**< key-code for the cursor-up key */
  11882. static const int downKey; /**< key-code for the cursor-down key */
  11883. static const int leftKey; /**< key-code for the cursor-left key */
  11884. static const int rightKey; /**< key-code for the cursor-right key */
  11885. static const int pageUpKey; /**< key-code for the page-up key */
  11886. static const int pageDownKey; /**< key-code for the page-down key */
  11887. static const int homeKey; /**< key-code for the home key */
  11888. static const int endKey; /**< key-code for the end key */
  11889. static const int F1Key; /**< key-code for the F1 key */
  11890. static const int F2Key; /**< key-code for the F2 key */
  11891. static const int F3Key; /**< key-code for the F3 key */
  11892. static const int F4Key; /**< key-code for the F4 key */
  11893. static const int F5Key; /**< key-code for the F5 key */
  11894. static const int F6Key; /**< key-code for the F6 key */
  11895. static const int F7Key; /**< key-code for the F7 key */
  11896. static const int F8Key; /**< key-code for the F8 key */
  11897. static const int F9Key; /**< key-code for the F9 key */
  11898. static const int F10Key; /**< key-code for the F10 key */
  11899. static const int F11Key; /**< key-code for the F11 key */
  11900. static const int F12Key; /**< key-code for the F12 key */
  11901. static const int F13Key; /**< key-code for the F13 key */
  11902. static const int F14Key; /**< key-code for the F14 key */
  11903. static const int F15Key; /**< key-code for the F15 key */
  11904. static const int F16Key; /**< key-code for the F16 key */
  11905. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  11906. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  11907. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  11908. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  11909. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  11910. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  11911. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  11912. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  11913. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  11914. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  11915. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  11916. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  11917. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  11918. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  11919. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  11920. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  11921. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  11922. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  11923. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  11924. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  11925. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  11926. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  11927. juce_UseDebuggingNewOperator
  11928. private:
  11929. int keyCode;
  11930. ModifierKeys mods;
  11931. juce_wchar textCharacter;
  11932. };
  11933. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  11934. /********* End of inlined file: juce_KeyPress.h *********/
  11935. class Component;
  11936. /**
  11937. Receives callbacks when keys are pressed.
  11938. You can add a key listener to a component to be informed when that component
  11939. gets key events. See the Component::addListener method for more details.
  11940. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  11941. */
  11942. class JUCE_API KeyListener
  11943. {
  11944. public:
  11945. /** Destructor. */
  11946. virtual ~KeyListener() {}
  11947. /** Called to indicate that a key has been pressed.
  11948. If your implementation returns true, then the key event is considered to have
  11949. been consumed, and will not be passed on to any other components. If it returns
  11950. false, then the key will be passed to other components that might want to use it.
  11951. @param key the keystroke, including modifier keys
  11952. @param originatingComponent the component that received the key event
  11953. @see keyStateChanged, Component::keyPressed
  11954. */
  11955. virtual bool keyPressed (const KeyPress& key,
  11956. Component* originatingComponent) = 0;
  11957. /** Called when any key is pressed or released.
  11958. When this is called, classes that might be interested in
  11959. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  11960. check whether their key has changed.
  11961. If your implementation returns true, then the key event is considered to have
  11962. been consumed, and will not be passed on to any other components. If it returns
  11963. false, then the key will be passed to other components that might want to use it.
  11964. @param originatingComponent the component that received the key event
  11965. @see KeyPress, Component::keyStateChanged
  11966. */
  11967. virtual bool keyStateChanged (Component* originatingComponent);
  11968. };
  11969. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  11970. /********* End of inlined file: juce_KeyListener.h *********/
  11971. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  11972. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  11973. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  11974. class Component;
  11975. /**
  11976. Controls the order in which focus moves between components.
  11977. The default algorithm used by this class to work out the order of traversal
  11978. is as follows:
  11979. - if two components both have an explicit focus order specified, then the
  11980. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  11981. method).
  11982. - any component with an explicit focus order greater than 0 comes before ones
  11983. that don't have an order specified.
  11984. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  11985. order.
  11986. If you need traversal in a more customised way, you can create a subclass
  11987. of KeyboardFocusTraverser that uses your own algorithm, and use
  11988. Component::createFocusTraverser() to create it.
  11989. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  11990. */
  11991. class JUCE_API KeyboardFocusTraverser
  11992. {
  11993. public:
  11994. KeyboardFocusTraverser();
  11995. /** Destructor. */
  11996. virtual ~KeyboardFocusTraverser();
  11997. /** Returns the component that should be given focus after the specified one
  11998. when moving "forwards".
  11999. The default implementation will return the next component which is to the
  12000. right of or below this one.
  12001. This may return 0 if there's no suitable candidate.
  12002. */
  12003. virtual Component* getNextComponent (Component* current);
  12004. /** Returns the component that should be given focus after the specified one
  12005. when moving "backwards".
  12006. The default implementation will return the next component which is to the
  12007. left of or above this one.
  12008. This may return 0 if there's no suitable candidate.
  12009. */
  12010. virtual Component* getPreviousComponent (Component* current);
  12011. /** Returns the component that should receive focus be default within the given
  12012. parent component.
  12013. The default implementation will just return the foremost child component that
  12014. wants focus.
  12015. This may return 0 if there's no suitable candidate.
  12016. */
  12017. virtual Component* getDefaultComponent (Component* parentComponent);
  12018. };
  12019. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12020. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12021. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12022. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12023. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12024. /********* Start of inlined file: juce_Graphics.h *********/
  12025. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12026. #define __JUCE_GRAPHICS_JUCEHEADER__
  12027. /********* Start of inlined file: juce_Font.h *********/
  12028. #ifndef __JUCE_FONT_JUCEHEADER__
  12029. #define __JUCE_FONT_JUCEHEADER__
  12030. /********* Start of inlined file: juce_Typeface.h *********/
  12031. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12032. #define __JUCE_TYPEFACE_JUCEHEADER__
  12033. /********* Start of inlined file: juce_Path.h *********/
  12034. #ifndef __JUCE_PATH_JUCEHEADER__
  12035. #define __JUCE_PATH_JUCEHEADER__
  12036. /********* Start of inlined file: juce_AffineTransform.h *********/
  12037. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12038. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12039. /**
  12040. Represents a 2D affine-transformation matrix.
  12041. An affine transformation is a transformation such as a rotation, scale, shear,
  12042. resize or translation.
  12043. These are used for various 2D transformation tasks, e.g. with Path objects.
  12044. @see Path, Point, Line
  12045. */
  12046. class JUCE_API AffineTransform
  12047. {
  12048. public:
  12049. /** Creates an identity transform. */
  12050. AffineTransform() throw();
  12051. /** Creates a copy of another transform. */
  12052. AffineTransform (const AffineTransform& other) throw();
  12053. /** Creates a transform from a set of raw matrix values.
  12054. The resulting matrix is:
  12055. (mat00 mat01 mat02)
  12056. (mat10 mat11 mat12)
  12057. ( 0 0 1 )
  12058. */
  12059. AffineTransform (const float mat00, const float mat01, const float mat02,
  12060. const float mat10, const float mat11, const float mat12) throw();
  12061. /** Copies from another AffineTransform object */
  12062. const AffineTransform& operator= (const AffineTransform& other) throw();
  12063. /** Compares two transforms. */
  12064. bool operator== (const AffineTransform& other) const throw();
  12065. /** Compares two transforms. */
  12066. bool operator!= (const AffineTransform& other) const throw();
  12067. /** A ready-to-use identity transform, which you can use to append other
  12068. transformations to.
  12069. e.g. @code
  12070. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12071. .scaled (2.0f);
  12072. @endcode
  12073. */
  12074. static const AffineTransform identity;
  12075. /** Transforms a 2D co-ordinate using this matrix. */
  12076. void transformPoint (float& x,
  12077. float& y) const throw();
  12078. /** Transforms a 2D co-ordinate using this matrix. */
  12079. void transformPoint (double& x,
  12080. double& y) const throw();
  12081. /** Returns a new transform which is the same as this one followed by a translation. */
  12082. const AffineTransform translated (const float deltaX,
  12083. const float deltaY) const throw();
  12084. /** Returns a new transform which is a translation. */
  12085. static const AffineTransform translation (const float deltaX,
  12086. const float deltaY) throw();
  12087. /** Returns a transform which is the same as this one followed by a rotation.
  12088. The rotation is specified by a number of radians to rotate clockwise, centred around
  12089. the origin (0, 0).
  12090. */
  12091. const AffineTransform rotated (const float angleInRadians) const throw();
  12092. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12093. The rotation is specified by a number of radians to rotate clockwise, centred around
  12094. the co-ordinates passed in.
  12095. */
  12096. const AffineTransform rotated (const float angleInRadians,
  12097. const float pivotX,
  12098. const float pivotY) const throw();
  12099. /** Returns a new transform which is a rotation about (0, 0). */
  12100. static const AffineTransform rotation (const float angleInRadians) throw();
  12101. /** Returns a new transform which is a rotation about a given point. */
  12102. static const AffineTransform rotation (const float angleInRadians,
  12103. const float pivotX,
  12104. const float pivotY) throw();
  12105. /** Returns a transform which is the same as this one followed by a re-scaling.
  12106. The scaling is centred around the origin (0, 0).
  12107. */
  12108. const AffineTransform scaled (const float factorX,
  12109. const float factorY) const throw();
  12110. /** Returns a new transform which is a re-scale about the origin. */
  12111. static const AffineTransform scale (const float factorX,
  12112. const float factorY) throw();
  12113. /** Returns a transform which is the same as this one followed by a shear.
  12114. The shear is centred around the origin (0, 0).
  12115. */
  12116. const AffineTransform sheared (const float shearX,
  12117. const float shearY) const throw();
  12118. /** Returns a matrix which is the inverse operation of this one.
  12119. Some matrices don't have an inverse - in this case, the method will just return
  12120. an identity transform.
  12121. */
  12122. const AffineTransform inverted() const throw();
  12123. /** Returns the result of concatenating another transformation after this one. */
  12124. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12125. /** Returns true if this transform has no effect on points. */
  12126. bool isIdentity() const throw();
  12127. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12128. bool isSingularity() const throw();
  12129. juce_UseDebuggingNewOperator
  12130. /* The transform matrix is:
  12131. (mat00 mat01 mat02)
  12132. (mat10 mat11 mat12)
  12133. ( 0 0 1 )
  12134. */
  12135. float mat00, mat01, mat02;
  12136. float mat10, mat11, mat12;
  12137. private:
  12138. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12139. const float mat10, const float mat11, const float mat12) const throw();
  12140. };
  12141. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12142. /********* End of inlined file: juce_AffineTransform.h *********/
  12143. /********* Start of inlined file: juce_Point.h *********/
  12144. #ifndef __JUCE_POINT_JUCEHEADER__
  12145. #define __JUCE_POINT_JUCEHEADER__
  12146. /**
  12147. A pair of (x, y) co-ordinates.
  12148. Uses 32-bit floating point accuracy.
  12149. @see Line, Path, AffineTransform
  12150. */
  12151. class JUCE_API Point
  12152. {
  12153. public:
  12154. /** Creates a point with co-ordinates (0, 0). */
  12155. Point() throw();
  12156. /** Creates a copy of another point. */
  12157. Point (const Point& other) throw();
  12158. /** Creates a point from an (x, y) position. */
  12159. Point (const float x, const float y) throw();
  12160. /** Copies this point from another one.
  12161. @see setXY
  12162. */
  12163. const Point& operator= (const Point& other) throw();
  12164. /** Destructor. */
  12165. ~Point() throw();
  12166. /** Returns the point's x co-ordinate. */
  12167. inline float getX() const throw() { return x; }
  12168. /** Returns the point's y co-ordinate. */
  12169. inline float getY() const throw() { return y; }
  12170. /** Changes the point's x and y co-ordinates. */
  12171. void setXY (const float x,
  12172. const float y) throw();
  12173. /** Uses a transform to change the point's co-ordinates.
  12174. @see AffineTransform::transformPoint
  12175. */
  12176. void applyTransform (const AffineTransform& transform) throw();
  12177. juce_UseDebuggingNewOperator
  12178. private:
  12179. float x, y;
  12180. };
  12181. #endif // __JUCE_POINT_JUCEHEADER__
  12182. /********* End of inlined file: juce_Point.h *********/
  12183. /********* Start of inlined file: juce_Justification.h *********/
  12184. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12185. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12186. /**
  12187. Represents a type of justification to be used when positioning graphical items.
  12188. e.g. it indicates whether something should be placed top-left, top-right,
  12189. centred, etc.
  12190. It is used in various places wherever this kind of information is needed.
  12191. */
  12192. class JUCE_API Justification
  12193. {
  12194. public:
  12195. /** Creates a Justification object using a combination of flags. */
  12196. inline Justification (const int flags_) throw() : flags (flags_) {}
  12197. /** Creates a copy of another Justification object. */
  12198. Justification (const Justification& other) throw();
  12199. /** Copies another Justification object. */
  12200. const Justification& operator= (const Justification& other) throw();
  12201. /** Returns the raw flags that are set for this Justification object. */
  12202. inline int getFlags() const throw() { return flags; }
  12203. /** Tests a set of flags for this object.
  12204. @returns true if any of the flags passed in are set on this object.
  12205. */
  12206. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12207. /** Returns just the flags from this object that deal with vertical layout. */
  12208. int getOnlyVerticalFlags() const throw();
  12209. /** Returns just the flags from this object that deal with horizontal layout. */
  12210. int getOnlyHorizontalFlags() const throw();
  12211. /** Adjusts the position of a rectangle to fit it into a space.
  12212. The (x, y) position of the rectangle will be updated to position it inside the
  12213. given space according to the justification flags.
  12214. */
  12215. void applyToRectangle (int& x, int& y,
  12216. const int w, const int h,
  12217. const int spaceX, const int spaceY,
  12218. const int spaceW, const int spaceH) const throw();
  12219. /** Flag values that can be combined and used in the constructor. */
  12220. enum
  12221. {
  12222. /** Indicates that the item should be aligned against the left edge of the available space. */
  12223. left = 1,
  12224. /** Indicates that the item should be aligned against the right edge of the available space. */
  12225. right = 2,
  12226. /** Indicates that the item should be placed in the centre between the left and right
  12227. sides of the available space. */
  12228. horizontallyCentred = 4,
  12229. /** Indicates that the item should be aligned against the top edge of the available space. */
  12230. top = 8,
  12231. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12232. bottom = 16,
  12233. /** Indicates that the item should be placed in the centre between the top and bottom
  12234. sides of the available space. */
  12235. verticallyCentred = 32,
  12236. /** Indicates that lines of text should be spread out to fill the maximum width
  12237. available, so that both margins are aligned vertically.
  12238. */
  12239. horizontallyJustified = 64,
  12240. /** Indicates that the item should be centred vertically and horizontally.
  12241. This is equivalent to (horizontallyCentred | verticallyCentred)
  12242. */
  12243. centred = 36,
  12244. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12245. This is equivalent to (left | verticallyCentred)
  12246. */
  12247. centredLeft = 33,
  12248. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12249. This is equivalent to (right | verticallyCentred)
  12250. */
  12251. centredRight = 34,
  12252. /** Indicates that the item should be centred horizontally and placed at the top.
  12253. This is equivalent to (horizontallyCentred | top)
  12254. */
  12255. centredTop = 12,
  12256. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12257. This is equivalent to (horizontallyCentred | bottom)
  12258. */
  12259. centredBottom = 20,
  12260. /** Indicates that the item should be placed in the top-left corner.
  12261. This is equivalent to (left | top)
  12262. */
  12263. topLeft = 9,
  12264. /** Indicates that the item should be placed in the top-right corner.
  12265. This is equivalent to (right | top)
  12266. */
  12267. topRight = 10,
  12268. /** Indicates that the item should be placed in the bottom-left corner.
  12269. This is equivalent to (left | bottom)
  12270. */
  12271. bottomLeft = 17,
  12272. /** Indicates that the item should be placed in the bottom-left corner.
  12273. This is equivalent to (right | bottom)
  12274. */
  12275. bottomRight = 18
  12276. };
  12277. private:
  12278. int flags;
  12279. };
  12280. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12281. /********* End of inlined file: juce_Justification.h *********/
  12282. /**
  12283. A path is a sequence of lines and curves that may either form a closed shape
  12284. or be open-ended.
  12285. To use a path, you can create an empty one, then add lines and curves to it
  12286. to create shapes, then it can be rendered by a Graphics context or used
  12287. for geometric operations.
  12288. e.g. @code
  12289. Path myPath;
  12290. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12291. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12292. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12293. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12294. // add an ellipse as well, which will form a second sub-path within the path..
  12295. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12296. // double the width of the whole thing..
  12297. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12298. // and draw it to a graphics context with a 5-pixel thick outline.
  12299. g.strokePath (myPath, PathStrokeType (5.0f));
  12300. @endcode
  12301. A path object can actually contain multiple sub-paths, which may themselves
  12302. be open or closed.
  12303. @see PathFlatteningIterator, PathStrokeType, Graphics
  12304. */
  12305. class JUCE_API Path : private ArrayAllocationBase <float>
  12306. {
  12307. public:
  12308. /** Creates an empty path. */
  12309. Path() throw();
  12310. /** Creates a copy of another path. */
  12311. Path (const Path& other) throw();
  12312. /** Destructor. */
  12313. ~Path() throw();
  12314. /** Copies this path from another one. */
  12315. const Path& operator= (const Path& other) throw();
  12316. /** Returns true if the path doesn't contain any lines or curves. */
  12317. bool isEmpty() const throw();
  12318. /** Returns the smallest rectangle that contains all points within the path.
  12319. */
  12320. void getBounds (float& x, float& y,
  12321. float& w, float& h) const throw();
  12322. /** Returns the smallest rectangle that contains all points within the path
  12323. after it's been transformed with the given tranasform matrix.
  12324. */
  12325. void getBoundsTransformed (const AffineTransform& transform,
  12326. float& x, float& y,
  12327. float& w, float& h) const throw();
  12328. /** Checks whether a point lies within the path.
  12329. This is only relevent for closed paths (see closeSubPath()), and
  12330. may produce false results if used on a path which has open sub-paths.
  12331. The path's winding rule is taken into account by this method.
  12332. @see closeSubPath, setUsingNonZeroWinding
  12333. */
  12334. bool contains (const float x,
  12335. const float y) const throw();
  12336. /** Checks whether a line crosses the path.
  12337. This will return positive if the line crosses any of the paths constituent
  12338. lines or curves. It doesn't take into account whether the line is inside
  12339. or outside the path, or whether the path is open or closed.
  12340. */
  12341. bool intersectsLine (const float x1, const float y1,
  12342. const float x2, const float y2) throw();
  12343. /** Removes all lines and curves, resetting the path completely. */
  12344. void clear() throw();
  12345. /** Begins a new subpath with a given starting position.
  12346. This will move the path's current position to the co-ordinates passed in and
  12347. make it ready to draw lines or curves starting from this position.
  12348. After adding whatever lines and curves are needed, you can either
  12349. close the current sub-path using closeSubPath() or call startNewSubPath()
  12350. to move to a new sub-path, leaving the old one open-ended.
  12351. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12352. */
  12353. void startNewSubPath (const float startX,
  12354. const float startY) throw();
  12355. /** Closes a the current sub-path with a line back to its start-point.
  12356. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12357. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12358. to join the final point back to the start.
  12359. This ensures that closes shapes are recognised as such, and this is
  12360. important for tasks like drawing strokes, which needs to know whether to
  12361. draw end-caps or not.
  12362. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12363. */
  12364. void closeSubPath() throw();
  12365. /** Adds a line from the shape's last position to a new end-point.
  12366. This will connect the end-point of the last line or curve that was added
  12367. to a new point, using a straight line.
  12368. See the class description for an example of how to add lines and curves to a path.
  12369. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12370. */
  12371. void lineTo (const float endX,
  12372. const float endY) throw();
  12373. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12374. This will connect the end-point of the last line or curve that was added
  12375. to a new point, using a quadratic spline with one control-point.
  12376. See the class description for an example of how to add lines and curves to a path.
  12377. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12378. */
  12379. void quadraticTo (const float controlPointX,
  12380. const float controlPointY,
  12381. const float endPointX,
  12382. const float endPointY) throw();
  12383. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12384. This will connect the end-point of the last line or curve that was added
  12385. to a new point, using a cubic spline with two control-points.
  12386. See the class description for an example of how to add lines and curves to a path.
  12387. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12388. */
  12389. void cubicTo (const float controlPoint1X,
  12390. const float controlPoint1Y,
  12391. const float controlPoint2X,
  12392. const float controlPoint2Y,
  12393. const float endPointX,
  12394. const float endPointY) throw();
  12395. /** Returns the last point that was added to the path by one of the drawing methods.
  12396. */
  12397. const Point getCurrentPosition() const;
  12398. /** Adds a rectangle to the path.
  12399. The rectangle is added as a new sub-path. (Any currently open paths will be
  12400. left open).
  12401. @see addRoundedRectangle, addTriangle
  12402. */
  12403. void addRectangle (const float x, const float y,
  12404. const float w, const float h) throw();
  12405. /** Adds a rectangle with rounded corners to the path.
  12406. The rectangle is added as a new sub-path. (Any currently open paths will be
  12407. left open).
  12408. @see addRectangle, addTriangle
  12409. */
  12410. void addRoundedRectangle (const float x, const float y,
  12411. const float w, const float h,
  12412. float cornerSize) throw();
  12413. /** Adds a rectangle with rounded corners to the path.
  12414. The rectangle is added as a new sub-path. (Any currently open paths will be
  12415. left open).
  12416. @see addRectangle, addTriangle
  12417. */
  12418. void addRoundedRectangle (const float x, const float y,
  12419. const float w, const float h,
  12420. float cornerSizeX,
  12421. float cornerSizeY) throw();
  12422. /** Adds a triangle to the path.
  12423. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12424. left open).
  12425. Note that whether the vertices are specified in clockwise or anticlockwise
  12426. order will affect how the triangle is filled when it overlaps other
  12427. shapes (the winding order setting will affect this of course).
  12428. */
  12429. void addTriangle (const float x1, const float y1,
  12430. const float x2, const float y2,
  12431. const float x3, const float y3) throw();
  12432. /** Adds a quadrilateral to the path.
  12433. The quad is added as a new closed sub-path. (Any currently open paths will be
  12434. left open).
  12435. Note that whether the vertices are specified in clockwise or anticlockwise
  12436. order will affect how the quad is filled when it overlaps other
  12437. shapes (the winding order setting will affect this of course).
  12438. */
  12439. void addQuadrilateral (const float x1, const float y1,
  12440. const float x2, const float y2,
  12441. const float x3, const float y3,
  12442. const float x4, const float y4) throw();
  12443. /** Adds an ellipse to the path.
  12444. The shape is added as a new sub-path. (Any currently open paths will be
  12445. left open).
  12446. @see addArc
  12447. */
  12448. void addEllipse (const float x, const float y,
  12449. const float width, const float height) throw();
  12450. /** Adds an elliptical arc to the current path.
  12451. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12452. or anti-clockwise according to whether the end angle is greater than the start. This means
  12453. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12454. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12455. @param y the top edge of the rectangle in which the elliptical outline fits
  12456. @param width the width of the rectangle in which the elliptical outline fits
  12457. @param height the height of the rectangle in which the elliptical outline fits
  12458. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12459. top-centre of the ellipse)
  12460. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12461. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12462. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12463. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12464. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12465. it will be added to the current sub-path, continuing from the current postition
  12466. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12467. */
  12468. void addArc (const float x, const float y,
  12469. const float width, const float height,
  12470. const float fromRadians,
  12471. const float toRadians,
  12472. const bool startAsNewSubPath = false) throw();
  12473. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12474. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12475. or anti-clockwise according to whether the end angle is greater than the start. This means
  12476. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12477. @param centreX the centre x of the ellipse
  12478. @param centreY the centre y of the ellipse
  12479. @param radiusX the horizontal radius of the ellipse
  12480. @param radiusY the vertical radius of the ellipse
  12481. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12482. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12483. top-centre of the ellipse)
  12484. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12485. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12486. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12487. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12488. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12489. it will be added to the current sub-path, continuing from the current postition
  12490. @see addArc, arcTo
  12491. */
  12492. void addCentredArc (const float centreX, const float centreY,
  12493. const float radiusX, const float radiusY,
  12494. const float rotationOfEllipse,
  12495. const float fromRadians,
  12496. const float toRadians,
  12497. const bool startAsNewSubPath = false) throw();
  12498. /** Adds a "pie-chart" shape to the path.
  12499. The shape is added as a new sub-path. (Any currently open paths will be
  12500. left open).
  12501. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12502. or anti-clockwise according to whether the end angle is greater than the start. This means
  12503. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12504. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12505. @param y the top edge of the rectangle in which the elliptical outline fits
  12506. @param width the width of the rectangle in which the elliptical outline fits
  12507. @param height the height of the rectangle in which the elliptical outline fits
  12508. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12509. top-centre of the ellipse)
  12510. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12511. top-centre of the ellipse)
  12512. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12513. ellipse at its centre, where this value indicates the inner ellipse's size with
  12514. respect to the outer one.
  12515. @see addArc
  12516. */
  12517. void addPieSegment (const float x, const float y,
  12518. const float width, const float height,
  12519. const float fromRadians,
  12520. const float toRadians,
  12521. const float innerCircleProportionalSize);
  12522. /** Adds a line with a specified thickness.
  12523. The line is added as a new closed sub-path. (Any currently open paths will be
  12524. left open).
  12525. @see addArrow
  12526. */
  12527. void addLineSegment (const float startX, const float startY,
  12528. const float endX, const float endY,
  12529. float lineThickness) throw();
  12530. /** Adds a line with an arrowhead on the end.
  12531. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12532. left open).
  12533. */
  12534. void addArrow (const float startX, const float startY,
  12535. const float endX, const float endY,
  12536. float lineThickness,
  12537. float arrowheadWidth,
  12538. float arrowheadLength) throw();
  12539. /** Adds a star shape to the path.
  12540. */
  12541. void addStar (const float centreX,
  12542. const float centreY,
  12543. const int numberOfPoints,
  12544. const float innerRadius,
  12545. const float outerRadius,
  12546. const float startAngle = 0.0f);
  12547. /** Adds a speech-bubble shape to the path.
  12548. @param bodyX the left of the main body area of the bubble
  12549. @param bodyY the top of the main body area of the bubble
  12550. @param bodyW the width of the main body area of the bubble
  12551. @param bodyH the height of the main body area of the bubble
  12552. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12553. @param arrowTipX the x position that the tip of the arrow should connect to
  12554. @param arrowTipY the y position that the tip of the arrow should connect to
  12555. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12556. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12557. arrow's base should be - this is a proportional distance between 0 and 1.0
  12558. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12559. */
  12560. void addBubble (float bodyX, float bodyY,
  12561. float bodyW, float bodyH,
  12562. float cornerSize,
  12563. float arrowTipX,
  12564. float arrowTipY,
  12565. int whichSide,
  12566. float arrowPositionAlongEdgeProportional,
  12567. float arrowWidth);
  12568. /** Adds another path to this one.
  12569. The new path is added as a new sub-path. (Any currently open paths in this
  12570. path will be left open).
  12571. @param pathToAppend the path to add
  12572. */
  12573. void addPath (const Path& pathToAppend) throw();
  12574. /** Adds another path to this one, transforming it on the way in.
  12575. The new path is added as a new sub-path, its points being transformed by the given
  12576. matrix before being added.
  12577. @param pathToAppend the path to add
  12578. @param transformToApply an optional transform to apply to the incoming vertices
  12579. */
  12580. void addPath (const Path& pathToAppend,
  12581. const AffineTransform& transformToApply) throw();
  12582. /** Swaps the contents of this path with another one.
  12583. The internal data of the two paths is swapped over, so this is much faster than
  12584. copying it to a temp variable and back.
  12585. */
  12586. void swapWithPath (Path& other);
  12587. /** Applies a 2D transform to all the vertices in the path.
  12588. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12589. */
  12590. void applyTransform (const AffineTransform& transform) throw();
  12591. /** Rescales this path to make it fit neatly into a given space.
  12592. This is effectively a quick way of calling
  12593. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12594. @param x the x position of the rectangle to fit the path inside
  12595. @param y the y position of the rectangle to fit the path inside
  12596. @param width the width of the rectangle to fit the path inside
  12597. @param height the height of the rectangle to fit the path inside
  12598. @param preserveProportions if true, it will fit the path into the space without altering its
  12599. horizontal/vertical scale ratio; if false, it will distort the
  12600. path to fill the specified ratio both horizontally and vertically
  12601. @see applyTransform, getTransformToScaleToFit
  12602. */
  12603. void scaleToFit (const float x, const float y,
  12604. const float width, const float height,
  12605. const bool preserveProportions) throw();
  12606. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12607. @param x the x position of the rectangle to fit the path inside
  12608. @param y the y position of the rectangle to fit the path inside
  12609. @param width the width of the rectangle to fit the path inside
  12610. @param height the height of the rectangle to fit the path inside
  12611. @param preserveProportions if true, it will fit the path into the space without altering its
  12612. horizontal/vertical scale ratio; if false, it will distort the
  12613. path to fill the specified ratio both horizontally and vertically
  12614. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12615. than the available rectangle, so this describes how it should be
  12616. positioned within the space.
  12617. @returns an appropriate transformation
  12618. @see applyTransform, scaleToFit
  12619. */
  12620. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12621. const float width, const float height,
  12622. const bool preserveProportions,
  12623. const Justification& justificationType = Justification::centred) const throw();
  12624. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12625. Wherever two lines meet at an angle, this will replace the corner with a curve
  12626. of the given radius.
  12627. */
  12628. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12629. /** Changes the winding-rule to be used when filling the path.
  12630. If set to true (which is the default), then the path uses a non-zero-winding rule
  12631. to determine which points are inside the path. If set to false, it uses an
  12632. alternate-winding rule.
  12633. The winding-rule comes into play when areas of the shape overlap other
  12634. areas, and determines whether the overlapping regions are considered to be
  12635. inside or outside.
  12636. Changing this value just sets a flag - it doesn't affect the contents of the
  12637. path.
  12638. @see isUsingNonZeroWinding
  12639. */
  12640. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12641. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12642. The default for a new path is true.
  12643. @see setUsingNonZeroWinding
  12644. */
  12645. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12646. /** Iterates the lines and curves that a path contains.
  12647. @see Path, PathFlatteningIterator
  12648. */
  12649. class JUCE_API Iterator
  12650. {
  12651. public:
  12652. Iterator (const Path& path);
  12653. ~Iterator();
  12654. /** Moves onto the next element in the path.
  12655. If this returns false, there are no more elements. If it returns true,
  12656. the elementType variable will be set to the type of the current element,
  12657. and some of the x and y variables will be filled in with values.
  12658. */
  12659. bool next();
  12660. enum PathElementType
  12661. {
  12662. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12663. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12664. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12665. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12666. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12667. };
  12668. PathElementType elementType;
  12669. float x1, y1, x2, y2, x3, y3;
  12670. private:
  12671. const Path& path;
  12672. int index;
  12673. Iterator (const Iterator&);
  12674. const Iterator& operator= (const Iterator&);
  12675. };
  12676. /** Loads a stored path from a data stream.
  12677. The data in the stream must have been written using writePathToStream().
  12678. Note that this will append the stored path to whatever is currently in
  12679. this path, so you might need to call clear() beforehand.
  12680. @see loadPathFromData, writePathToStream
  12681. */
  12682. void loadPathFromStream (InputStream& source);
  12683. /** Loads a stored path from a block of data.
  12684. This is similar to loadPathFromStream(), but just reads from a block
  12685. of data. Useful if you're including stored shapes in your code as a
  12686. block of static data.
  12687. @see loadPathFromStream, writePathToStream
  12688. */
  12689. void loadPathFromData (const unsigned char* const data,
  12690. const int numberOfBytes) throw();
  12691. /** Stores the path by writing it out to a stream.
  12692. After writing out a path, you can reload it using loadPathFromStream().
  12693. @see loadPathFromStream, loadPathFromData
  12694. */
  12695. void writePathToStream (OutputStream& destination) const;
  12696. /** Creates a string containing a textual representation of this path.
  12697. @see restoreFromString
  12698. */
  12699. const String toString() const;
  12700. /** Restores this path from a string that was created with the toString() method.
  12701. @see toString()
  12702. */
  12703. void restoreFromString (const String& stringVersion);
  12704. juce_UseDebuggingNewOperator
  12705. private:
  12706. friend class PathFlatteningIterator;
  12707. friend class Path::Iterator;
  12708. int numElements;
  12709. float pathXMin, pathXMax, pathYMin, pathYMax;
  12710. bool useNonZeroWinding;
  12711. static const float lineMarker;
  12712. static const float moveMarker;
  12713. static const float quadMarker;
  12714. static const float cubicMarker;
  12715. static const float closeSubPathMarker;
  12716. };
  12717. #endif // __JUCE_PATH_JUCEHEADER__
  12718. /********* End of inlined file: juce_Path.h *********/
  12719. class Font;
  12720. class Typeface;
  12721. /**
  12722. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12723. @see Typeface, PositionedGlyph, GlyphArrangement
  12724. */
  12725. class JUCE_API TypefaceGlyphInfo
  12726. {
  12727. public:
  12728. /** Returns the path that describes the glyph's outline.
  12729. This is normalised to a height of 1.0, and its origin is the
  12730. left-hand edge of the glyph's baseline.
  12731. */
  12732. const Path& getPath() const throw() { return path; }
  12733. /** Returns the unicode character that this glyph represents. */
  12734. juce_wchar getCharacter() const throw() { return character; }
  12735. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12736. /** Returns the distance to leave between this and a following character.
  12737. The value returned is expressed as a proportion of the font's height.
  12738. */
  12739. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12740. /** Returns the typeface that this glyph belongs to. */
  12741. Typeface* getTypeface() const throw() { return typeface; }
  12742. private:
  12743. friend class Typeface;
  12744. struct KerningPair
  12745. {
  12746. juce_wchar character2;
  12747. float kerningAmount;
  12748. };
  12749. const juce_wchar character;
  12750. const Path path;
  12751. float width;
  12752. MemoryBlock kerningPairs;
  12753. Typeface* const typeface;
  12754. TypefaceGlyphInfo (const juce_wchar character,
  12755. const Path& shape,
  12756. const float horizontalSeparation,
  12757. Typeface* const typeface) throw();
  12758. ~TypefaceGlyphInfo() throw();
  12759. KerningPair& getKerningPair (const int index) const throw();
  12760. int getNumKerningPairs() const throw();
  12761. void addKerningPair (const juce_wchar subsequentCharacter,
  12762. const float extraKerningAmount) throw();
  12763. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12764. };
  12765. /**
  12766. Represents a size-independent system font.
  12767. A Font object represents a particular Typeface along with a specific size,
  12768. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12769. of the shapes of the glyphs and their properties.
  12770. */
  12771. class JUCE_API Typeface : public ReferenceCountedObject
  12772. {
  12773. public:
  12774. /** Tries to load a named system font and to initialise all the glyphs
  12775. appropriately from it.
  12776. @param faceName the name of the typeface, e.g. "Times"
  12777. @param bold whether to try to find a bold version of the font (may not always be available)
  12778. @param italic whether to try to find an italicised version of the font (may not always be available)
  12779. */
  12780. Typeface (const String& faceName,
  12781. const bool bold,
  12782. const bool italic);
  12783. /** Creates a copy of another typeface */
  12784. Typeface (const Typeface& other);
  12785. /** Destructor. */
  12786. ~Typeface();
  12787. /** Copies another typeface over this one. */
  12788. const Typeface& operator= (const Typeface& other) throw();
  12789. /** Returns a unique ID for the typeface.
  12790. This is based on the name and style, so can be used to compare two Typeface objects.
  12791. */
  12792. int hashCode() const throw() { return hash; }
  12793. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12794. const String& getName() const throw() { return typefaceName; }
  12795. /** Returns the font's ascent as a proportion of its height. */
  12796. float getAscent() const throw() { return ascent; }
  12797. /** Returns true if the font is flagged as being bold. */
  12798. bool isBold() const throw() { return bold; }
  12799. /** Returns true if the typeface's 'italic' flag is set. */
  12800. bool isItalic() const throw() { return italic; }
  12801. /** Finds the Path that describes the outline shape of a character.
  12802. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12803. height of the font).
  12804. This may return 0 if the typeface has no characters, but if the character
  12805. that is asked for is not found, it will first try to return a default
  12806. character instead.
  12807. */
  12808. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12809. /** Tries to find the information describing a glyph for this character.
  12810. If there isn't a glyph specifically for the character it will return
  12811. a default glyph instead; if the typeface is empty, it may return a null
  12812. pointer.
  12813. */
  12814. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12815. /** Deletes all the glyphs and kerning data fom the typeface. */
  12816. void clear() throw();
  12817. /** Adds a glyph to the typeface.
  12818. This is typically only called by the platform-specific code that generates
  12819. the typeface from a system font.
  12820. */
  12821. void addGlyph (const juce_wchar character,
  12822. const Path& path,
  12823. const float horizontalSpacing) throw();
  12824. /** Adds a kerning distance to the typeface.
  12825. The extra amount passed in is expressed as a proportion of the font's
  12826. height, normalised to 1.0.
  12827. This is typically only called by the platform-specific code that generates
  12828. the typeface from a system font.
  12829. */
  12830. void addKerningPair (const juce_wchar firstChar,
  12831. const juce_wchar secondChar,
  12832. const float extraAmount) throw();
  12833. /** Sets the typeface's name.
  12834. This is typically only called by the platform-specific code that generates
  12835. the typeface from a system font. Calling this method won't actually affect
  12836. the underlying font being used.
  12837. */
  12838. void setName (const String& name) throw();
  12839. /** Sets the font's ascent value, as a proportion of the font height.
  12840. This is typically only called by the platform-specific code that generates
  12841. the typeface from a system font.
  12842. */
  12843. void setAscent (const float newAscent) throw();
  12844. /** Sets the typeface's 'bold' flag.
  12845. This is typically only called by the platform-specific code that generates
  12846. the typeface from a system font.
  12847. */
  12848. void setBold (const bool shouldBeBold) throw();
  12849. /** Sets the typeface's 'italic' flag.
  12850. This is typically only called by the platform-specific code that generates
  12851. the typeface from a system font.
  12852. */
  12853. void setItalic (const bool shouldBeItalic) throw();
  12854. /** Changes the character index to use as the default character.
  12855. This is the character that gets returned for characters which don't have a
  12856. glyph set for them.
  12857. */
  12858. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12859. /** Creates a typeface from data created using Typeface::serialise().
  12860. This will attempt to load a compressed typeface that was created using
  12861. the Typeface::serialise() method. This is handy if you want to store
  12862. a typeface in your application as a binary blob, and use it without
  12863. having to actually install it on the computer.
  12864. @see Typeface::serialise()
  12865. */
  12866. Typeface (InputStream& serialisedTypefaceStream);
  12867. /** Writes the typeface to a stream (using a proprietary format).
  12868. This lets you save a typeface and reload it using the
  12869. Typeface::Typeface (InputStream&) constructor. The data's saved in
  12870. a compressed format.
  12871. @see Typeface::Typeface (InputStream&)
  12872. */
  12873. void serialise (OutputStream& outputStream);
  12874. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  12875. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  12876. juce_UseDebuggingNewOperator
  12877. private:
  12878. VoidArray glyphs;
  12879. short lookupTable [128];
  12880. String typefaceName;
  12881. int hash;
  12882. float ascent; // as a proportion of the height
  12883. bool bold, italic, isFullyPopulated;
  12884. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  12885. Typeface() throw();
  12886. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  12887. friend class Font;
  12888. friend class TypefaceCache;
  12889. friend class FontGlyphAlphaMap;
  12890. static const Ptr getTypefaceFor (const Font& font) throw();
  12891. // this is a platform-dependent method that will look for the given typeface
  12892. // and set up its kerning tables, etc. accordingly.
  12893. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  12894. // to the typeface immediately, rather than having to add them later on-demand.
  12895. void initialiseTypefaceCharacteristics (const String& fontName,
  12896. bool bold, bool italic,
  12897. bool addAllGlyphsToFont) throw();
  12898. // platform-specific routine to look up and add a glyph to this typeface
  12899. bool findAndAddSystemGlyph (juce_wchar character) throw();
  12900. void updateHashCode() throw();
  12901. };
  12902. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  12903. /********* End of inlined file: juce_Typeface.h *********/
  12904. /**
  12905. Represents a particular font, including its size, style, etc.
  12906. Apart from the typeface to be used, a Font object also dictates whether
  12907. the font is bold, italic, underlined, how big it is, and its kerning and
  12908. horizontal scale factor.
  12909. @see Typeface
  12910. */
  12911. class JUCE_API Font
  12912. {
  12913. public:
  12914. /** A combination of these values is used by the constructor to specify the
  12915. style of font to use.
  12916. */
  12917. enum FontStyleFlags
  12918. {
  12919. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  12920. bold = 1, /**< boldens the font. @see setStyleFlags */
  12921. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  12922. underlined = 4 /**< underlines the font. @see setStyleFlags */
  12923. };
  12924. /** Creates a sans-serif font in a given size.
  12925. @param fontHeight the height in pixels (can be fractional)
  12926. @param styleFlags the style to use - this can be a combination of the
  12927. Font::bold, Font::italic and Font::underlined, or
  12928. just Font::plain for the normal style.
  12929. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12930. */
  12931. Font (const float fontHeight,
  12932. const int styleFlags = plain) throw();
  12933. /** Creates a font with a given typeface and parameters.
  12934. @param typefaceName the name of the typeface to use
  12935. @param fontHeight the height in pixels (can be fractional)
  12936. @param styleFlags the style to use - this can be a combination of the
  12937. Font::bold, Font::italic and Font::underlined, or
  12938. just Font::plain for the normal style.
  12939. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12940. */
  12941. Font (const String& typefaceName,
  12942. const float fontHeight,
  12943. const int styleFlags) throw();
  12944. /** Creates a copy of another Font object. */
  12945. Font (const Font& other) throw();
  12946. /** Creates a font based on a typeface.
  12947. The font object stores its own internal copy of the typeface, so you can safely
  12948. delete the one passed in after calling this.
  12949. */
  12950. Font (const Typeface& typeface) throw();
  12951. /** Creates a basic sans-serif font at a default height.
  12952. You should use one of the other constructors for creating a font that you're planning
  12953. on drawing with - this constructor is here to help initialise objects before changing
  12954. the font's settings later.
  12955. */
  12956. Font() throw();
  12957. /** Copies this font from another one. */
  12958. const Font& operator= (const Font& other) throw();
  12959. bool operator== (const Font& other) const throw();
  12960. bool operator!= (const Font& other) const throw();
  12961. /** Destructor. */
  12962. ~Font() throw();
  12963. /** Changes the name of the typeface family.
  12964. e.g. "Arial", "Courier", etc.
  12965. If a suitable font isn't found on the machine, it'll just use a default instead.
  12966. */
  12967. void setTypefaceName (const String& faceName) throw();
  12968. /** Returns the name of the typeface family that this font uses.
  12969. e.g. "Arial", "Courier", etc.
  12970. */
  12971. const String& getTypefaceName() const throw() { return typefaceName; }
  12972. /** Returns a platform-specific font family that is recommended for sans-serif fonts.
  12973. This is the typeface that will be used when a font is created without
  12974. specifying another name.
  12975. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  12976. setDefaultSansSerifFontName
  12977. */
  12978. static const String getDefaultSansSerifFontName() throw();
  12979. /** Returns a platform-specific font family that is recommended for serif fonts.
  12980. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  12981. */
  12982. static const String getDefaultSerifFontName() throw();
  12983. /** Returns a platform-specific font family that is recommended for monospaced fonts.
  12984. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  12985. */
  12986. static const String getDefaultMonospacedFontName() throw();
  12987. /** Changes the default sans-serif typeface family name.
  12988. This changes the value that is returned by getDefaultSansSerifFontName(), so
  12989. changing this will change the default system font used.
  12990. @see getDefaultSansSerifFontName
  12991. */
  12992. static void setDefaultSansSerifFontName (const String& name) throw();
  12993. /** Returns the total height of this font.
  12994. This is the maximum height, from the top of the ascent to the bottom of the
  12995. descenders.
  12996. @see setHeight, setHeightWithoutChangingWidth, getAscent
  12997. */
  12998. float getHeight() const throw() { return height; }
  12999. /** Changes the font's height.
  13000. @see getHeight, setHeightWithoutChangingWidth
  13001. */
  13002. void setHeight (float newHeight) throw();
  13003. /** Changes the font's height without changing its width.
  13004. This alters the horizontal scale to compensate for the change in height.
  13005. */
  13006. void setHeightWithoutChangingWidth (float newHeight) throw();
  13007. /** Returns the height of the font above its baseline.
  13008. This is the maximum height from the baseline to the top.
  13009. @see getHeight, getDescent
  13010. */
  13011. float getAscent() const throw();
  13012. /** Returns the amount that the font descends below its baseline.
  13013. This is calculated as (getHeight() - getAscent()).
  13014. @see getAscent, getHeight
  13015. */
  13016. float getDescent() const throw();
  13017. /** Returns the font's style flags.
  13018. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13019. enum, to describe whether the font is bold, italic, etc.
  13020. @see FontStyleFlags
  13021. */
  13022. int getStyleFlags() const throw() { return styleFlags; }
  13023. /** Changes the font's style.
  13024. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13025. enum, to set the font's properties
  13026. @see FontStyleFlags
  13027. */
  13028. void setStyleFlags (const int newFlags) throw();
  13029. /** Makes the font bold or non-bold. */
  13030. void setBold (const bool shouldBeBold) throw();
  13031. /** Returns true if the font is bold. */
  13032. bool isBold() const throw();
  13033. /** Makes the font italic or non-italic. */
  13034. void setItalic (const bool shouldBeItalic) throw();
  13035. /** Returns true if the font is italic. */
  13036. bool isItalic() const throw();
  13037. /** Makes the font underlined or non-underlined. */
  13038. void setUnderline (const bool shouldBeUnderlined) throw();
  13039. /** Returns true if the font is underlined. */
  13040. bool isUnderlined() const throw();
  13041. /** Changes the font's horizontal scale factor.
  13042. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13043. narrower, greater than 1.0 will be stretched out.
  13044. */
  13045. void setHorizontalScale (const float scaleFactor) throw();
  13046. /** Returns the font's horizontal scale.
  13047. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13048. than 1.0 will be stretched out.
  13049. @see setHorizontalScale
  13050. */
  13051. float getHorizontalScale() const throw() { return horizontalScale; }
  13052. /** Changes the font's kerning.
  13053. @param extraKerning a multiple of the font's height that will be added
  13054. to space between the characters. So a value of zero is
  13055. normal spacing, positive values spread the letters out,
  13056. negative values make them closer together.
  13057. */
  13058. void setExtraKerningFactor (const float extraKerning) throw();
  13059. /** Returns the font's kerning.
  13060. This is the extra space added between adjacent characters, as a proportion
  13061. of the font's height.
  13062. A value of zero is normal spacing, positive values will spread the letters
  13063. out more, and negative values make them closer together.
  13064. */
  13065. float getExtraKerningFactor() const throw() { return kerning; }
  13066. /** Changes all the font's characteristics with one call. */
  13067. void setSizeAndStyle (const float newHeight,
  13068. const int newStyleFlags,
  13069. const float newHorizontalScale,
  13070. const float newKerningAmount) throw();
  13071. /** Resets this font's characteristics.
  13072. This is basically like saying "myFont = Font();", because it resets the
  13073. typeface, size, style, etc to a default state. Not very useful to most
  13074. people, its raison d'etre is to help the Graphics class be more efficient.
  13075. */
  13076. void resetToDefaultState() throw();
  13077. /** Returns the total width of a string as it would be drawn using this font.
  13078. For a more accurate floating-point result, use getStringWidthFloat().
  13079. */
  13080. int getStringWidth (const String& text) const throw();
  13081. /** Returns the total width of a string as it would be drawn using this font.
  13082. @see getStringWidth
  13083. */
  13084. float getStringWidthFloat (const String& text) const throw();
  13085. /** Returns the typeface used by this font.
  13086. Note that the object returned may go out of scope if this font is deleted
  13087. or has its style changed.
  13088. */
  13089. Typeface* getTypeface() const throw();
  13090. /** Creates an array of Font objects to represent all the fonts on the system.
  13091. If you just need the names of the typefaces, you can also use
  13092. findAllTypefaceNames() instead.
  13093. @param results the array to which new Font objects will be added.
  13094. */
  13095. static void findFonts (OwnedArray<Font>& results) throw();
  13096. /** Returns a list of all the available typeface names.
  13097. The names returned can be passed into setTypefaceName().
  13098. You can use this instead of findFonts() if you only need their names, and not
  13099. font objects.
  13100. */
  13101. static const StringArray findAllTypefaceNames() throw();
  13102. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13103. in the requested typeface.
  13104. */
  13105. static const String getFallbackFontName() throw();
  13106. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13107. available in whatever font you're trying to use.
  13108. */
  13109. static void setFallbackFontName (const String& name) throw();
  13110. juce_UseDebuggingNewOperator
  13111. private:
  13112. friend class FontGlyphAlphaMap;
  13113. friend class TypefaceCache;
  13114. String typefaceName;
  13115. float height, horizontalScale, kerning;
  13116. mutable float ascent;
  13117. int styleFlags;
  13118. mutable Typeface::Ptr typeface;
  13119. // platform-specific calls
  13120. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13121. friend void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  13122. static void initialiseDefaultFontNames() throw();
  13123. };
  13124. #endif // __JUCE_FONT_JUCEHEADER__
  13125. /********* End of inlined file: juce_Font.h *********/
  13126. /********* Start of inlined file: juce_Rectangle.h *********/
  13127. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13128. #define __JUCE_RECTANGLE_JUCEHEADER__
  13129. /**
  13130. A rectangle, specified using integer co-ordinates.
  13131. @see RectangleList, Path, Line, Point
  13132. */
  13133. class JUCE_API Rectangle
  13134. {
  13135. public:
  13136. /** Creates a rectangle of zero size.
  13137. The default co-ordinates will be (0, 0, 0, 0).
  13138. */
  13139. Rectangle() throw();
  13140. /** Creates a copy of another rectangle. */
  13141. Rectangle (const Rectangle& other) throw();
  13142. /** Creates a rectangle with a given position and size. */
  13143. Rectangle (const int x, const int y,
  13144. const int width, const int height) throw();
  13145. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13146. Rectangle (const int width, const int height) throw();
  13147. /** Destructor. */
  13148. ~Rectangle() throw();
  13149. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13150. inline int getX() const throw() { return x; }
  13151. /** Returns the y co-ordinate of the rectangle's top edge. */
  13152. inline int getY() const throw() { return y; }
  13153. /** Returns the width of the rectangle. */
  13154. inline int getWidth() const throw() { return w; }
  13155. /** Returns the height of the rectangle. */
  13156. inline int getHeight() const throw() { return h; }
  13157. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13158. inline int getRight() const throw() { return x + w; }
  13159. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13160. inline int getBottom() const throw() { return y + h; }
  13161. /** Returns the x co-ordinate of the rectangle's centre. */
  13162. inline int getCentreX() const throw() { return x + (w >> 1); }
  13163. /** Returns the y co-ordinate of the rectangle's centre. */
  13164. inline int getCentreY() const throw() { return y + (h >> 1); }
  13165. /** Returns true if the rectangle's width and height are both zero or less */
  13166. bool isEmpty() const throw();
  13167. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13168. void setPosition (const int x, const int y) throw();
  13169. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13170. void setSize (const int w, const int h) throw();
  13171. /** Changes all the rectangle's co-ordinates. */
  13172. void setBounds (const int newX, const int newY,
  13173. const int newWidth, const int newHeight) throw();
  13174. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13175. void translate (const int deltaX,
  13176. const int deltaY) throw();
  13177. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13178. const Rectangle translated (const int deltaX,
  13179. const int deltaY) const throw();
  13180. /** Expands the rectangle by a given amount.
  13181. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13182. @see expanded, reduce, reduced
  13183. */
  13184. void expand (const int deltaX,
  13185. const int deltaY) throw();
  13186. /** Returns a rectangle that is larger than this one by a given amount.
  13187. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13188. @see expand, reduce, reduced
  13189. */
  13190. const Rectangle expanded (const int deltaX,
  13191. const int deltaY) const throw();
  13192. /** Shrinks the rectangle by a given amount.
  13193. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13194. @see reduced, expand, expanded
  13195. */
  13196. void reduce (const int deltaX,
  13197. const int deltaY) throw();
  13198. /** Returns a rectangle that is smaller than this one by a given amount.
  13199. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13200. @see reduce, expand, expanded
  13201. */
  13202. const Rectangle reduced (const int deltaX,
  13203. const int deltaY) const throw();
  13204. /** Returns true if the two rectangles are identical. */
  13205. bool operator== (const Rectangle& other) const throw();
  13206. /** Returns true if the two rectangles are not identical. */
  13207. bool operator!= (const Rectangle& other) const throw();
  13208. /** Returns true if this co-ordinate is inside the rectangle. */
  13209. bool contains (const int x, const int y) const throw();
  13210. /** Returns true if this other rectangle is completely inside this one. */
  13211. bool contains (const Rectangle& other) const throw();
  13212. /** Returns true if any part of another rectangle overlaps this one. */
  13213. bool intersects (const Rectangle& other) const throw();
  13214. /** Returns the region that is the overlap between this and another rectangle.
  13215. If the two rectangles don't overlap, the rectangle returned will be empty.
  13216. */
  13217. const Rectangle getIntersection (const Rectangle& other) const throw();
  13218. /** Clips a rectangle so that it lies only within this one.
  13219. This is a non-static version of intersectRectangles().
  13220. Returns false if the two regions didn't overlap.
  13221. */
  13222. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13223. /** Returns the smallest rectangle that contains both this one and the one
  13224. passed-in.
  13225. */
  13226. const Rectangle getUnion (const Rectangle& other) const throw();
  13227. /** If this rectangle merged with another one results in a simple rectangle, this
  13228. will set this rectangle to the result, and return true.
  13229. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13230. or if they form a complex region.
  13231. */
  13232. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13233. /** If after removing another rectangle from this one the result is a simple rectangle,
  13234. this will set this object's bounds to be the result, and return true.
  13235. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13236. or if removing the other one would form a complex region.
  13237. */
  13238. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13239. /** Static utility to intersect two sets of rectangular co-ordinates.
  13240. Returns false if the two regions didn't overlap.
  13241. @see intersectRectangle
  13242. */
  13243. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13244. int x2, int y2, int w2, int h2) throw();
  13245. /** Creates a string describing this rectangle.
  13246. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13247. Coupled with the fromString() method, this is very handy for things like
  13248. storing rectangles (particularly component positions) in XML attributes.
  13249. @see fromString
  13250. */
  13251. const String toString() const throw();
  13252. /** Parses a string containing a rectangle's details.
  13253. The string should contain 4 integer tokens, in the form "x y width height". They
  13254. can be comma or whitespace separated.
  13255. This method is intended to go with the toString() method, to form an easy way
  13256. of saving/loading rectangles as strings.
  13257. @see toString
  13258. */
  13259. static const Rectangle fromString (const String& stringVersion);
  13260. juce_UseDebuggingNewOperator
  13261. private:
  13262. friend class RectangleList;
  13263. int x, y, w, h;
  13264. };
  13265. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13266. /********* End of inlined file: juce_Rectangle.h *********/
  13267. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13268. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13269. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13270. /**
  13271. Describes a type of stroke used to render a solid outline along a path.
  13272. A PathStrokeType object can be used directly to create the shape of an outline
  13273. around a path, and is used by Graphics::strokePath to specify the type of
  13274. stroke to draw.
  13275. @see Path, Graphics::strokePath
  13276. */
  13277. class JUCE_API PathStrokeType
  13278. {
  13279. public:
  13280. /** The type of shape to use for the corners between two adjacent line segments. */
  13281. enum JointStyle
  13282. {
  13283. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13284. Note that for angles that curve back on themselves, drawing a
  13285. mitre could require extending the point too far away from the
  13286. path, so a mitre limit is imposed and any corners that exceed it
  13287. are drawn as bevelled instead. */
  13288. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13289. beveled /**< Indicates that corners should be drawn with a line flattening their
  13290. outside edge. */
  13291. };
  13292. /** The type shape to use for the ends of lines. */
  13293. enum EndCapStyle
  13294. {
  13295. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13296. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13297. the thickness of the stroke. */
  13298. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13299. };
  13300. /** Creates a stroke type.
  13301. @param strokeThickness the width of the line to use
  13302. @param jointStyle the type of joints to use for corners
  13303. @param endStyle the type of end-caps to use for the ends of open paths.
  13304. */
  13305. PathStrokeType (const float strokeThickness,
  13306. const JointStyle jointStyle = mitered,
  13307. const EndCapStyle endStyle = butt) throw();
  13308. /** Createes a copy of another stroke type. */
  13309. PathStrokeType (const PathStrokeType& other) throw();
  13310. /** Copies another stroke onto this one. */
  13311. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13312. /** Destructor. */
  13313. ~PathStrokeType() throw();
  13314. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13315. @param destPath the resultant stroked outline shape will be copied into this path.
  13316. Note that it's ok for the source and destination Paths to be
  13317. the same object, so you can easily turn a path into a stroked version
  13318. of itself.
  13319. @param sourcePath the path to use as the source
  13320. @param transform an optional transform to apply to the points from the source path
  13321. as they are being used
  13322. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13323. a higher resolution, which improved the quality if you'll later want
  13324. to enlarge the stroked path
  13325. @see createDashedStroke
  13326. */
  13327. void createStrokedPath (Path& destPath,
  13328. const Path& sourcePath,
  13329. const AffineTransform& transform = AffineTransform::identity,
  13330. const float extraAccuracy = 1.0f) const throw();
  13331. /** Applies this stroke type to a path, creating a dashed line.
  13332. This is similar to createStrokedPath, but uses the array passed in to
  13333. break the stroke up into a series of dashes.
  13334. @param destPath the resultant stroked outline shape will be copied into this path.
  13335. Note that it's ok for the source and destination Paths to be
  13336. the same object, so you can easily turn a path into a stroked version
  13337. of itself.
  13338. @param sourcePath the path to use as the source
  13339. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13340. a line of length 2, then skip a length of 3, then add a line of length 4,
  13341. skip 5, and keep repeating this pattern.
  13342. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13343. an even number, otherwise the pattern will get out of step as it
  13344. repeats.
  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. */
  13351. void createDashedStroke (Path& destPath,
  13352. const Path& sourcePath,
  13353. const float* dashLengths,
  13354. int numDashLengths,
  13355. const AffineTransform& transform = AffineTransform::identity,
  13356. const float extraAccuracy = 1.0f) const throw();
  13357. /** Returns the stroke thickness. */
  13358. float getStrokeThickness() const throw() { return thickness; }
  13359. /** Returns the joint style. */
  13360. JointStyle getJointStyle() const throw() { return jointStyle; }
  13361. /** Returns the end-cap style. */
  13362. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13363. juce_UseDebuggingNewOperator
  13364. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13365. bool operator== (const PathStrokeType& other) const throw();
  13366. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13367. bool operator!= (const PathStrokeType& other) const throw();
  13368. private:
  13369. float thickness;
  13370. JointStyle jointStyle;
  13371. EndCapStyle endStyle;
  13372. };
  13373. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13374. /********* End of inlined file: juce_PathStrokeType.h *********/
  13375. /********* Start of inlined file: juce_Line.h *********/
  13376. #ifndef __JUCE_LINE_JUCEHEADER__
  13377. #define __JUCE_LINE_JUCEHEADER__
  13378. /**
  13379. Represents a line, using 32-bit float co-ordinates.
  13380. This class contains a bunch of useful methods for various geometric
  13381. tasks.
  13382. @see Point, Rectangle, Path, Graphics::drawLine
  13383. */
  13384. class JUCE_API Line
  13385. {
  13386. public:
  13387. /** Creates a line, using (0, 0) as its start and end points. */
  13388. Line() throw();
  13389. /** Creates a copy of another line. */
  13390. Line (const Line& other) throw();
  13391. /** Creates a line based on the co-ordinates of its start and end points. */
  13392. Line (const float startX,
  13393. const float startY,
  13394. const float endX,
  13395. const float endY) throw();
  13396. /** Creates a line from its start and end points. */
  13397. Line (const Point& start,
  13398. const Point& end) throw();
  13399. /** Copies a line from another one. */
  13400. const Line& operator= (const Line& other) throw();
  13401. /** Destructor. */
  13402. ~Line() throw();
  13403. /** Returns the x co-ordinate of the line's start point. */
  13404. inline float getStartX() const throw() { return startX; }
  13405. /** Returns the y co-ordinate of the line's start point. */
  13406. inline float getStartY() const throw() { return startY; }
  13407. /** Returns the x co-ordinate of the line's end point. */
  13408. inline float getEndX() const throw() { return endX; }
  13409. /** Returns the y co-ordinate of the line's end point. */
  13410. inline float getEndY() const throw() { return endY; }
  13411. /** Returns the line's start point. */
  13412. const Point getStart() const throw();
  13413. /** Returns the line's end point. */
  13414. const Point getEnd() const throw();
  13415. /** Changes this line's start point */
  13416. void setStart (const float newStartX,
  13417. const float newStartY) throw();
  13418. /** Changes this line's end point */
  13419. void setEnd (const float newEndX,
  13420. const float newEndY) throw();
  13421. /** Changes this line's start point */
  13422. void setStart (const Point& newStart) throw();
  13423. /** Changes this line's end point */
  13424. void setEnd (const Point& newEnd) throw();
  13425. /** Applies an affine transform to the line's start and end points. */
  13426. void applyTransform (const AffineTransform& transform) throw();
  13427. /** Returns the length of the line. */
  13428. float getLength() const throw();
  13429. /** Returns true if the line's start and end x co-ordinates are the same. */
  13430. bool isVertical() const throw();
  13431. /** Returns true if the line's start and end y co-ordinates are the same. */
  13432. bool isHorizontal() const throw();
  13433. /** Returns the line's angle.
  13434. This value is the number of radians clockwise from the 3 o'clock direction,
  13435. where the line's start point is considered to be at the centre.
  13436. */
  13437. float getAngle() const throw();
  13438. /** Compares two lines. */
  13439. bool operator== (const Line& other) const throw();
  13440. /** Compares two lines. */
  13441. bool operator!= (const Line& other) const throw();
  13442. /** Finds the intersection between two lines.
  13443. @param line the other line
  13444. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13445. where they would meet if they were infinitely long)
  13446. the intersection (if the lines intersect). If the lines
  13447. are parallel, this will just be set to the position
  13448. of one of the line's endpoints.
  13449. @param intersectionY the y co-ordinate of the point where the lines meet
  13450. @returns true if the line segments intersect; false if they dont. Even if they
  13451. don't intersect, the intersection co-ordinates returned will still
  13452. be valid
  13453. */
  13454. bool intersects (const Line& line,
  13455. float& intersectionX,
  13456. float& intersectionY) const throw();
  13457. /** Returns the location of the point which is a given distance along this line.
  13458. @param distanceFromStart the distance to move along the line from its
  13459. start point. This value can be negative or longer
  13460. than the line itself
  13461. @see getPointAlongLineProportionally
  13462. */
  13463. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13464. /** Returns a point which is a certain distance along and to the side of this line.
  13465. This effectively moves a given distance along the line, then another distance
  13466. perpendicularly to this, and returns the resulting position.
  13467. @param distanceFromStart the distance to move along the line from its
  13468. start point. This value can be negative or longer
  13469. than the line itself
  13470. @param perpendicularDistance how far to move sideways from the line. If you're
  13471. looking along the line from its start towards its
  13472. end, then a positive value here will move to the
  13473. right, negative value move to the left.
  13474. */
  13475. const Point getPointAlongLine (const float distanceFromStart,
  13476. const float perpendicularDistance) const throw();
  13477. /** Returns the location of the point which is a given distance along this line
  13478. proportional to the line's length.
  13479. @param proportionOfLength the distance to move along the line from its
  13480. start point, in multiples of the line's length.
  13481. So a value of 0.0 will return the line's start point
  13482. and a value of 1.0 will return its end point. (This value
  13483. can be negative or greater than 1.0).
  13484. @see getPointAlongLine
  13485. */
  13486. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13487. /** Returns the smallest distance between this line segment and a given point.
  13488. So if the point is close to the line, this will return the perpendicular
  13489. distance from the line; if the point is a long way beyond one of the line's
  13490. end-point's, it'll return the straight-line distance to the nearest end-point.
  13491. @param x x position of the point to test
  13492. @param y y position of the point to test
  13493. @returns the point's distance from the line
  13494. @see getPositionAlongLineOfNearestPoint
  13495. */
  13496. float getDistanceFromLine (const float x,
  13497. const float y) const throw();
  13498. /** Finds the point on this line which is nearest to a given point, and
  13499. returns its position as a proportional position along the line.
  13500. @param x x position of the point to test
  13501. @param y y position of the point to test
  13502. @returns a value 0 to 1.0 which is the distance along this line from the
  13503. line's start to the point which is nearest to the point passed-in. To
  13504. turn this number into a position, use getPointAlongLineProportionally().
  13505. @see getDistanceFromLine, getPointAlongLineProportionally
  13506. */
  13507. float findNearestPointTo (const float x,
  13508. const float y) const throw();
  13509. /** Returns true if the given point lies above this line.
  13510. The return value is true if the point's y coordinate is less than the y
  13511. coordinate of this line at the given x (assuming the line extends infinitely
  13512. in both directions).
  13513. */
  13514. bool isPointAbove (const float x, const float y) const throw();
  13515. /** Returns a shortened copy of this line.
  13516. This will chop off part of the start of this line by a certain amount, (leaving the
  13517. end-point the same), and return the new line.
  13518. */
  13519. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13520. /** Returns a shortened copy of this line.
  13521. This will chop off part of the end of this line by a certain amount, (leaving the
  13522. start-point the same), and return the new line.
  13523. */
  13524. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13525. /** Cuts off parts of this line to keep the parts that are either inside or
  13526. outside a path.
  13527. Note that this isn't smart enough to cope with situations where the
  13528. line would need to be cut into multiple pieces to correctly clip against
  13529. a re-entrant shape.
  13530. @param path the path to clip against
  13531. @param keepSectionOutsidePath if true, it's the section outside the path
  13532. that will be kept; if false its the section inside
  13533. the path
  13534. @returns true if the line was changed.
  13535. */
  13536. bool clipToPath (const Path& path,
  13537. const bool keepSectionOutsidePath) throw();
  13538. juce_UseDebuggingNewOperator
  13539. private:
  13540. float startX, startY, endX, endY;
  13541. };
  13542. #endif // __JUCE_LINE_JUCEHEADER__
  13543. /********* End of inlined file: juce_Line.h *********/
  13544. /********* Start of inlined file: juce_Colours.h *********/
  13545. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13546. #define __JUCE_COLOURS_JUCEHEADER__
  13547. /********* Start of inlined file: juce_Colour.h *********/
  13548. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13549. #define __JUCE_COLOUR_JUCEHEADER__
  13550. /********* Start of inlined file: juce_PixelFormats.h *********/
  13551. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13552. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13553. #if JUCE_MSVC
  13554. #pragma pack (push, 1)
  13555. #define PACKED
  13556. #elif JUCE_GCC
  13557. #define PACKED __attribute__((packed))
  13558. #else
  13559. #define PACKED
  13560. #endif
  13561. /**
  13562. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13563. operations with it.
  13564. This is used internally by the imaging classes.
  13565. @see PixelRGB
  13566. */
  13567. class JUCE_API PixelARGB
  13568. {
  13569. public:
  13570. /** Creates a pixel without defining its colour. */
  13571. PixelARGB() throw() {}
  13572. ~PixelARGB() throw() {}
  13573. /** Creates a pixel from a 32-bit argb value.
  13574. */
  13575. PixelARGB (const uint32 argb_) throw()
  13576. : argb (argb_)
  13577. {
  13578. }
  13579. forcedinline uint32 getARGB() const throw() { return argb; }
  13580. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13581. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13582. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13583. forcedinline uint8 getRed() const throw() { return components.r; }
  13584. forcedinline uint8 getGreen() const throw() { return components.g; }
  13585. forcedinline uint8 getBlue() const throw() { return components.b; }
  13586. /** Blends another pixel onto this one.
  13587. This takes into account the opacity of the pixel being overlaid, and blends
  13588. it accordingly.
  13589. */
  13590. template <class Pixel>
  13591. forcedinline void blend (const Pixel& src) throw()
  13592. {
  13593. uint32 sargb = src.getARGB();
  13594. const uint32 alpha = 0x100 - (sargb >> 24);
  13595. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13596. sargb += 0xff00ff00 & (getAG() * alpha);
  13597. argb = sargb;
  13598. }
  13599. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13600. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13601. being used, so this can blend semi-transparently from a PixelRGB argument.
  13602. */
  13603. template <class Pixel>
  13604. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13605. {
  13606. ++extraAlpha;
  13607. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13608. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13609. const uint32 alpha = 0x100 - (sargb >> 24);
  13610. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13611. sargb += 0xff00ff00 & (getAG() * alpha);
  13612. argb = sargb;
  13613. }
  13614. /** Blends another pixel with this one, creating a colour that is somewhere
  13615. between the two, as specified by the amount.
  13616. */
  13617. template <class Pixel>
  13618. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13619. {
  13620. uint32 drb = getRB();
  13621. drb += (((src.getRB() - drb) * amount) >> 8);
  13622. drb &= 0x00ff00ff;
  13623. uint32 dag = getAG();
  13624. dag += (((src.getAG() - dag) * amount) >> 8);
  13625. dag &= 0x00ff00ff;
  13626. dag <<= 8;
  13627. dag |= drb;
  13628. argb = dag;
  13629. }
  13630. /** Copies another pixel colour over this one.
  13631. This doesn't blend it - this colour is simply replaced by the other one.
  13632. */
  13633. template <class Pixel>
  13634. forcedinline void set (const Pixel& src) throw()
  13635. {
  13636. argb = src.getARGB();
  13637. }
  13638. /** Replaces the colour's alpha value with another one. */
  13639. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13640. {
  13641. components.a = newAlpha;
  13642. }
  13643. /** Multiplies the colour's alpha value with another one. */
  13644. forcedinline void multiplyAlpha (int multiplier) throw()
  13645. {
  13646. ++multiplier;
  13647. argb = ((multiplier * getAG()) & 0xff00ff00)
  13648. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13649. }
  13650. forcedinline void multiplyAlpha (const float multiplier) throw()
  13651. {
  13652. multiplyAlpha ((int) (multiplier * 256.0f));
  13653. }
  13654. /** Sets the pixel's colour from individual components. */
  13655. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13656. {
  13657. components.b = b;
  13658. components.g = g;
  13659. components.r = r;
  13660. components.a = a;
  13661. }
  13662. /** Premultiplies the pixel's RGB values by its alpha. */
  13663. forcedinline void premultiply() throw()
  13664. {
  13665. const uint32 alpha = components.a;
  13666. if (alpha < 0xff)
  13667. {
  13668. if (alpha == 0)
  13669. {
  13670. components.b = 0;
  13671. components.g = 0;
  13672. components.r = 0;
  13673. }
  13674. else
  13675. {
  13676. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13677. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13678. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13679. }
  13680. }
  13681. }
  13682. /** Unpremultiplies the pixel's RGB values. */
  13683. forcedinline void unpremultiply() throw()
  13684. {
  13685. const uint32 alpha = components.a;
  13686. if (alpha < 0xff)
  13687. {
  13688. if (alpha == 0)
  13689. {
  13690. components.b = 0;
  13691. components.g = 0;
  13692. components.r = 0;
  13693. }
  13694. else
  13695. {
  13696. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13697. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13698. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13699. }
  13700. }
  13701. }
  13702. forcedinline void desaturate() throw()
  13703. {
  13704. if (components.a < 0xff && components.a > 0)
  13705. {
  13706. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13707. components.r = components.g = components.b
  13708. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13709. }
  13710. else
  13711. {
  13712. components.r = components.g = components.b
  13713. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13714. }
  13715. }
  13716. private:
  13717. union
  13718. {
  13719. uint32 argb;
  13720. struct
  13721. {
  13722. #if JUCE_BIG_ENDIAN
  13723. uint8 a : 8, r : 8, g : 8, b : 8;
  13724. #else
  13725. uint8 b, g, r, a;
  13726. #endif
  13727. } PACKED components;
  13728. };
  13729. } PACKED;
  13730. /**
  13731. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13732. This is used internally by the imaging classes.
  13733. @see PixelARGB
  13734. */
  13735. class JUCE_API PixelRGB
  13736. {
  13737. public:
  13738. /** Creates a pixel without defining its colour. */
  13739. PixelRGB() throw() {}
  13740. ~PixelRGB() throw() {}
  13741. /** Creates a pixel from a 32-bit argb value.
  13742. (The argb format is that used by PixelARGB)
  13743. */
  13744. PixelRGB (const uint32 argb) throw()
  13745. {
  13746. r = (uint8) (argb >> 16);
  13747. g = (uint8) (argb >> 8);
  13748. b = (uint8) (argb);
  13749. }
  13750. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13751. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13752. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13753. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13754. forcedinline uint8 getRed() const throw() { return r; }
  13755. forcedinline uint8 getGreen() const throw() { return g; }
  13756. forcedinline uint8 getBlue() const throw() { return b; }
  13757. /** Blends another pixel onto this one.
  13758. This takes into account the opacity of the pixel being overlaid, and blends
  13759. it accordingly.
  13760. */
  13761. forcedinline void blend (const PixelARGB& src) throw()
  13762. {
  13763. uint32 sargb = src.getARGB();
  13764. const uint32 alpha = 0x100 - (sargb >> 24);
  13765. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13766. sargb += 0x0000ff00 & (g * alpha);
  13767. r = (uint8) (sargb >> 16);
  13768. g = (uint8) (sargb >> 8);
  13769. b = (uint8) sargb;
  13770. }
  13771. forcedinline void blend (const PixelRGB& src) throw()
  13772. {
  13773. set (src);
  13774. }
  13775. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13776. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13777. being used, so this can blend semi-transparently from a PixelRGB argument.
  13778. */
  13779. template <class Pixel>
  13780. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13781. {
  13782. ++extraAlpha;
  13783. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13784. const uint32 sag = extraAlpha * src.getAG();
  13785. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13786. const uint32 alpha = 0x100 - (sargb >> 24);
  13787. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13788. sargb += 0x0000ff00 & (g * alpha);
  13789. b = (uint8) sargb;
  13790. g = (uint8) (sargb >> 8);
  13791. r = (uint8) (sargb >> 16);
  13792. }
  13793. /** Blends another pixel with this one, creating a colour that is somewhere
  13794. between the two, as specified by the amount.
  13795. */
  13796. template <class Pixel>
  13797. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13798. {
  13799. uint32 drb = getRB();
  13800. drb += (((src.getRB() - drb) * amount) >> 8);
  13801. uint32 dag = getAG();
  13802. dag += (((src.getAG() - dag) * amount) >> 8);
  13803. b = (uint8) drb;
  13804. g = (uint8) dag;
  13805. r = (uint8) (drb >> 16);
  13806. }
  13807. /** Copies another pixel colour over this one.
  13808. This doesn't blend it - this colour is simply replaced by the other one.
  13809. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13810. is thrown away.
  13811. */
  13812. template <class Pixel>
  13813. forcedinline void set (const Pixel& src) throw()
  13814. {
  13815. b = src.getBlue();
  13816. g = src.getGreen();
  13817. r = src.getRed();
  13818. }
  13819. /** This method is included for compatibility with the PixelARGB class. */
  13820. forcedinline void setAlpha (const uint8) throw() {}
  13821. /** Multiplies the colour's alpha value with another one. */
  13822. forcedinline void multiplyAlpha (int) throw() {}
  13823. /** Sets the pixel's colour from individual components. */
  13824. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  13825. {
  13826. r = r_;
  13827. g = g_;
  13828. b = b_;
  13829. }
  13830. /** Premultiplies the pixel's RGB values by its alpha. */
  13831. forcedinline void premultiply() throw() {}
  13832. /** Unpremultiplies the pixel's RGB values. */
  13833. forcedinline void unpremultiply() throw() {}
  13834. forcedinline void desaturate() throw()
  13835. {
  13836. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  13837. }
  13838. private:
  13839. #if JUCE_MAC
  13840. uint8 r, g, b;
  13841. #else
  13842. uint8 b, g, r;
  13843. #endif
  13844. } PACKED;
  13845. #if JUCE_MSVC
  13846. #pragma pack (pop)
  13847. #endif
  13848. #undef PACKED
  13849. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  13850. /********* End of inlined file: juce_PixelFormats.h *********/
  13851. /**
  13852. Represents a colour, also including a transparency value.
  13853. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  13854. */
  13855. class JUCE_API Colour
  13856. {
  13857. public:
  13858. /** Creates a transparent black colour. */
  13859. Colour() throw();
  13860. /** Creates a copy of another Colour object. */
  13861. Colour (const Colour& other) throw();
  13862. /** Creates a colour from a 32-bit ARGB value.
  13863. The format of this number is:
  13864. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13865. All components in the range 0x00 to 0xff.
  13866. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13867. @see getPixelARGB
  13868. */
  13869. explicit Colour (const uint32 argb) throw();
  13870. /** Creates an opaque colour using 8-bit red, green and blue values */
  13871. Colour (const uint8 red,
  13872. const uint8 green,
  13873. const uint8 blue) throw();
  13874. /** Creates an opaque colour using 8-bit red, green and blue values */
  13875. static const Colour fromRGB (const uint8 red,
  13876. const uint8 green,
  13877. const uint8 blue) throw();
  13878. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13879. Colour (const uint8 red,
  13880. const uint8 green,
  13881. const uint8 blue,
  13882. const uint8 alpha) throw();
  13883. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13884. static const Colour fromRGBA (const uint8 red,
  13885. const uint8 green,
  13886. const uint8 blue,
  13887. const uint8 alpha) throw();
  13888. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  13889. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  13890. Values outside the valid range will be clipped.
  13891. */
  13892. Colour (const uint8 red,
  13893. const uint8 green,
  13894. const uint8 blue,
  13895. const float alpha) throw();
  13896. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  13897. static const Colour fromRGBAFloat (const uint8 red,
  13898. const uint8 green,
  13899. const uint8 blue,
  13900. const float alpha) throw();
  13901. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13902. The floating point values must be between 0.0 and 1.0.
  13903. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13904. Values outside the valid range will be clipped.
  13905. */
  13906. Colour (const float hue,
  13907. const float saturation,
  13908. const float brightness,
  13909. const uint8 alpha) throw();
  13910. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  13911. All values must be between 0.0 and 1.0.
  13912. Numbers outside the valid range will be clipped.
  13913. */
  13914. Colour (const float hue,
  13915. const float saturation,
  13916. const float brightness,
  13917. const float alpha) throw();
  13918. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13919. The floating point values must be between 0.0 and 1.0.
  13920. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13921. Values outside the valid range will be clipped.
  13922. */
  13923. static const Colour fromHSV (const float hue,
  13924. const float saturation,
  13925. const float brightness,
  13926. const float alpha) throw();
  13927. /** Destructor. */
  13928. ~Colour() throw();
  13929. /** Copies another Colour object. */
  13930. const Colour& operator= (const Colour& other) throw();
  13931. /** Compares two colours. */
  13932. bool operator== (const Colour& other) const throw();
  13933. /** Compares two colours. */
  13934. bool operator!= (const Colour& other) const throw();
  13935. /** Returns the red component of this colour.
  13936. @returns a value between 0x00 and 0xff.
  13937. */
  13938. uint8 getRed() const throw() { return argb.getRed(); }
  13939. /** Returns the green component of this colour.
  13940. @returns a value between 0x00 and 0xff.
  13941. */
  13942. uint8 getGreen() const throw() { return argb.getGreen(); }
  13943. /** Returns the blue component of this colour.
  13944. @returns a value between 0x00 and 0xff.
  13945. */
  13946. uint8 getBlue() const throw() { return argb.getBlue(); }
  13947. /** Returns the red component of this colour as a floating point value.
  13948. @returns a value between 0.0 and 1.0
  13949. */
  13950. float getFloatRed() const throw();
  13951. /** Returns the green component of this colour as a floating point value.
  13952. @returns a value between 0.0 and 1.0
  13953. */
  13954. float getFloatGreen() const throw();
  13955. /** Returns the blue component of this colour as a floating point value.
  13956. @returns a value between 0.0 and 1.0
  13957. */
  13958. float getFloatBlue() const throw();
  13959. /** Returns a premultiplied ARGB pixel object that represents this colour.
  13960. */
  13961. const PixelARGB getPixelARGB() const throw();
  13962. /** Returns a 32-bit integer that represents this colour.
  13963. The format of this number is:
  13964. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13965. */
  13966. uint32 getARGB() const throw();
  13967. /** Returns the colour's alpha (opacity).
  13968. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  13969. */
  13970. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  13971. /** Returns the colour's alpha (opacity) as a floating point value.
  13972. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  13973. */
  13974. float getFloatAlpha() const throw();
  13975. /** Returns true if this colour is completely opaque.
  13976. Equivalent to (getAlpha() == 0xff).
  13977. */
  13978. bool isOpaque() const throw();
  13979. /** Returns true if this colour is completely transparent.
  13980. Equivalent to (getAlpha() == 0x00).
  13981. */
  13982. bool isTransparent() const throw();
  13983. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  13984. const Colour withAlpha (const uint8 newAlpha) const throw();
  13985. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  13986. const Colour withAlpha (const float newAlpha) const throw();
  13987. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  13988. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  13989. */
  13990. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  13991. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  13992. If the foreground colour is semi-transparent, it is blended onto this colour
  13993. accordingly.
  13994. */
  13995. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  13996. /** Returns the colour's hue component.
  13997. The value returned is in the range 0.0 to 1.0
  13998. */
  13999. float getHue() const throw();
  14000. /** Returns the colour's saturation component.
  14001. The value returned is in the range 0.0 to 1.0
  14002. */
  14003. float getSaturation() const throw();
  14004. /** Returns the colour's brightness component.
  14005. The value returned is in the range 0.0 to 1.0
  14006. */
  14007. float getBrightness() const throw();
  14008. /** Returns the colour's hue, saturation and brightness components all at once.
  14009. The values returned are in the range 0.0 to 1.0
  14010. */
  14011. void getHSB (float& hue,
  14012. float& saturation,
  14013. float& brightness) const throw();
  14014. /** Returns a copy of this colour with a different hue. */
  14015. const Colour withHue (const float newHue) const throw();
  14016. /** Returns a copy of this colour with a different saturation. */
  14017. const Colour withSaturation (const float newSaturation) const throw();
  14018. /** Returns a copy of this colour with a different brightness.
  14019. @see brighter, darker, withMultipliedBrightness
  14020. */
  14021. const Colour withBrightness (const float newBrightness) const throw();
  14022. /** Returns a copy of this colour with it hue rotated.
  14023. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14024. @see brighter, darker, withMultipliedBrightness
  14025. */
  14026. const Colour withRotatedHue (const float amountToRotate) const throw();
  14027. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14028. The new colour's saturation is (this->getSaturation() * multiplier)
  14029. (the result is clipped to legal limits).
  14030. */
  14031. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14032. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14033. The new colour's saturation is (this->getBrightness() * multiplier)
  14034. (the result is clipped to legal limits).
  14035. */
  14036. const Colour withMultipliedBrightness (const float amount) const throw();
  14037. /** Returns a brighter version of this colour.
  14038. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14039. unchanged, and higher values make it brighter
  14040. @see withMultipliedBrightness
  14041. */
  14042. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14043. /** Returns a darker version of this colour.
  14044. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14045. unchanged, and higher values make it darker
  14046. @see withMultipliedBrightness
  14047. */
  14048. const Colour darker (float amountDarker = 0.4f) const throw();
  14049. /** Returns a colour that will be clearly visible against this colour.
  14050. The amount parameter indicates how contrasting the new colour should
  14051. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14052. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14053. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14054. */
  14055. const Colour contrasting (const float amount = 1.0f) const throw();
  14056. /** Returns a colour that contrasts against two colours.
  14057. Looks for a colour that contrasts with both of the colours passed-in.
  14058. Handy for things like choosing a highlight colour in text editors, etc.
  14059. */
  14060. static const Colour contrasting (const Colour& colour1,
  14061. const Colour& colour2) throw();
  14062. /** Returns an opaque shade of grey.
  14063. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14064. */
  14065. static const Colour greyLevel (const float brightness) throw();
  14066. /** Returns a stringified version of this colour.
  14067. The string can be turned back into a colour using the fromString() method.
  14068. */
  14069. const String toString() const throw();
  14070. /** Reads the colour from a string that was created with toString().
  14071. */
  14072. static const Colour fromString (const String& encodedColourString);
  14073. juce_UseDebuggingNewOperator
  14074. private:
  14075. PixelARGB argb;
  14076. };
  14077. #endif // __JUCE_COLOUR_JUCEHEADER__
  14078. /********* End of inlined file: juce_Colour.h *********/
  14079. /**
  14080. Contains a set of predefined named colours (mostly standard HTML colours)
  14081. @see Colour, Colours::greyLevel
  14082. */
  14083. class Colours
  14084. {
  14085. public:
  14086. static JUCE_API const Colour
  14087. transparentBlack, /**< ARGB = 0x00000000 */
  14088. transparentWhite, /**< ARGB = 0x00ffffff */
  14089. black, /**< ARGB = 0xff000000 */
  14090. white, /**< ARGB = 0xffffffff */
  14091. blue, /**< ARGB = 0xff0000ff */
  14092. grey, /**< ARGB = 0xff808080 */
  14093. green, /**< ARGB = 0xff008000 */
  14094. red, /**< ARGB = 0xffff0000 */
  14095. yellow, /**< ARGB = 0xffffff00 */
  14096. aliceblue, antiquewhite, aqua, aquamarine,
  14097. azure, beige, bisque, blanchedalmond,
  14098. blueviolet, brown, burlywood, cadetblue,
  14099. chartreuse, chocolate, coral, cornflowerblue,
  14100. cornsilk, crimson, cyan, darkblue,
  14101. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14102. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14103. darkorchid, darkred, darksalmon, darkseagreen,
  14104. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14105. deeppink, deepskyblue, dimgrey, dodgerblue,
  14106. firebrick, floralwhite, forestgreen, fuchsia,
  14107. gainsboro, gold, goldenrod, greenyellow,
  14108. honeydew, hotpink, indianred, indigo,
  14109. ivory, khaki, lavender, lavenderblush,
  14110. lemonchiffon, lightblue, lightcoral, lightcyan,
  14111. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14112. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14113. lightsteelblue, lightyellow, lime, limegreen,
  14114. linen, magenta, maroon, mediumaquamarine,
  14115. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14116. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14117. midnightblue, mintcream, mistyrose, navajowhite,
  14118. navy, oldlace, olive, olivedrab,
  14119. orange, orangered, orchid, palegoldenrod,
  14120. palegreen, paleturquoise, palevioletred, papayawhip,
  14121. peachpuff, peru, pink, plum,
  14122. powderblue, purple, rosybrown, royalblue,
  14123. saddlebrown, salmon, sandybrown, seagreen,
  14124. seashell, sienna, silver, skyblue,
  14125. slateblue, slategrey, snow, springgreen,
  14126. steelblue, tan, teal, thistle,
  14127. tomato, turquoise, violet, wheat,
  14128. whitesmoke, yellowgreen;
  14129. /** Attempts to look up a string in the list of known colour names, and return
  14130. the appropriate colour.
  14131. A non-case-sensitive search is made of the list of predefined colours, and
  14132. if a match is found, that colour is returned. If no match is found, the
  14133. colour passed in as the defaultColour parameter is returned.
  14134. */
  14135. static JUCE_API const Colour findColourForName (const String& colourName,
  14136. const Colour& defaultColour);
  14137. private:
  14138. // this isn't a class you should ever instantiate - it's just here for the
  14139. // static values in it.
  14140. Colours();
  14141. };
  14142. #endif // __JUCE_COLOURS_JUCEHEADER__
  14143. /********* End of inlined file: juce_Colours.h *********/
  14144. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14145. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14146. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14147. /********* Start of inlined file: juce_Brush.h *********/
  14148. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14149. #define __JUCE_BRUSH_JUCEHEADER__
  14150. class Path;
  14151. class AffineTransform;
  14152. class LowLevelGraphicsContext;
  14153. class Image;
  14154. class Graphics;
  14155. /**
  14156. A brush is used to fill areas with colours, patterns, or images.
  14157. The Graphics class has an idea of a current brush which it uses to render
  14158. shapes, rectangles, lines, text, etc.
  14159. This is the base class - there are subclasses for useful types of fill pattern,
  14160. and applications can define their own brushes too.
  14161. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14162. */
  14163. class JUCE_API Brush
  14164. {
  14165. protected:
  14166. /** Creates a Brush.
  14167. (Nothing much happens in the base class).
  14168. */
  14169. Brush() throw();
  14170. public:
  14171. /** Destructor. */
  14172. virtual ~Brush() throw();
  14173. /** Creates a copy of whatever class of Brush this is. */
  14174. virtual Brush* createCopy() const throw() = 0;
  14175. /** Does whatever is relevent to transform the geometry of this brush. */
  14176. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14177. /** Does whatever is relevent to change the opacity of this brush. */
  14178. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14179. /** Must return true if this brush won't draw any pixels. */
  14180. virtual bool isInvisible() const throw() = 0;
  14181. virtual void paintPath (LowLevelGraphicsContext& context,
  14182. const Path& path, const AffineTransform& transform) throw() = 0;
  14183. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14184. int x, int y, int w, int h) throw() = 0;
  14185. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14186. const Image& alphaChannelImage, int imageX, int imageY,
  14187. int x, int y, int w, int h) throw() = 0;
  14188. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14189. int x, float y1, float y2) throw();
  14190. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14191. int y, float x1, float x2) throw();
  14192. virtual void paintLine (LowLevelGraphicsContext& context,
  14193. float x1, float y1, float x2, float y2) throw();
  14194. private:
  14195. Brush (const Brush&);
  14196. const Brush& operator= (const Brush&);
  14197. };
  14198. #endif // __JUCE_BRUSH_JUCEHEADER__
  14199. /********* End of inlined file: juce_Brush.h *********/
  14200. /**
  14201. A Brush that fills its area with a solid (or semi-transparent) colour.
  14202. An application won't normally need to use this class directly, as drawing
  14203. with solid colours is taken care of automatically by the Graphics class
  14204. (it actually uses one of these brushes internally when you set the colour
  14205. with the Graphics::setColour() method).
  14206. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14207. */
  14208. class JUCE_API SolidColourBrush : public Brush
  14209. {
  14210. public:
  14211. /** Creates a SolidColourBrush to draw with the given colour.
  14212. The colour can be changed later with the setColour() method.
  14213. */
  14214. SolidColourBrush (const Colour& colour) throw();
  14215. /** Creates a SolidColourBrush set to black.
  14216. The colour can be changed later with the setColour() method.
  14217. */
  14218. SolidColourBrush() throw();
  14219. /** Destructor. */
  14220. ~SolidColourBrush() throw();
  14221. /** Returns the colour currently being used. */
  14222. const Colour& getColour() const throw() { return colour; }
  14223. /** Sets the colour to use for drawing. */
  14224. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14225. Brush* createCopy() const throw();
  14226. void applyTransform (const AffineTransform& transform) throw();
  14227. bool isInvisible() const throw();
  14228. void multiplyOpacity (const float multiple) throw();
  14229. void paintPath (LowLevelGraphicsContext& context,
  14230. const Path& path, const AffineTransform& transform) throw();
  14231. void paintRectangle (LowLevelGraphicsContext& context,
  14232. int x, int y, int w, int h) throw();
  14233. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14234. const Image& alphaChannelImage, int imageX, int imageY,
  14235. int x, int y, int w, int h) throw();
  14236. void paintVerticalLine (LowLevelGraphicsContext& context,
  14237. int x, float y1, float y2) throw();
  14238. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14239. int y, float x1, float x2) throw();
  14240. void paintLine (LowLevelGraphicsContext& context,
  14241. float x1, float y1, float x2, float y2) throw();
  14242. juce_UseDebuggingNewOperator
  14243. private:
  14244. Colour colour;
  14245. SolidColourBrush (const SolidColourBrush&);
  14246. const SolidColourBrush& operator= (const SolidColourBrush&);
  14247. };
  14248. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14249. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14250. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14251. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14252. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14253. /**
  14254. Defines the method used to postion some kind of rectangular object within
  14255. a rectangular viewport.
  14256. Although similar to Justification, this is more specific, and has some extra
  14257. options.
  14258. */
  14259. class JUCE_API RectanglePlacement
  14260. {
  14261. public:
  14262. /** Creates a RectanglePlacement object using a combination of flags. */
  14263. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14264. /** Creates a copy of another Justification object. */
  14265. RectanglePlacement (const RectanglePlacement& other) throw();
  14266. /** Copies another Justification object. */
  14267. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14268. /** Flag values that can be combined and used in the constructor. */
  14269. enum
  14270. {
  14271. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14272. xLeft = 1,
  14273. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14274. xRight = 2,
  14275. /** Indicates that the source should be placed in the centre between the left and right
  14276. sides of the available space. */
  14277. xMid = 4,
  14278. /** Indicates that the source's top edge should be aligned with the top edge of the
  14279. destination rectangle. */
  14280. yTop = 8,
  14281. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14282. destination rectangle. */
  14283. yBottom = 16,
  14284. /** Indicates that the source should be placed in the centre between the top and bottom
  14285. sides of the available space. */
  14286. yMid = 32,
  14287. /** If this flag is set, then the source rectangle will be resized to completely fill
  14288. the destination rectangle, and all other flags are ignored.
  14289. */
  14290. stretchToFit = 64,
  14291. /** If this flag is set, then the source rectangle will be resized so that it is the
  14292. minimum size to completely fill the destination rectangle. This means that some
  14293. of the source rectangle may fall outside the destination.
  14294. If this flag is not set, the source will be given the maximum size at which none
  14295. of it falls outside the destination rectangle.
  14296. */
  14297. fillDestination = 128,
  14298. /** Indicates that the source rectangle can be reduced in size if required, but should
  14299. never be made larger than its original size.
  14300. */
  14301. onlyReduceInSize = 256,
  14302. /** Indicates that the source rectangle can be enlarged if required, but should
  14303. never be made smaller than its original size.
  14304. */
  14305. onlyIncreaseInSize = 512,
  14306. /** Indicates that the source rectangle's size should be left unchanged.
  14307. */
  14308. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14309. /** A shorthand value that is equivalent to (xMid | yMid). */
  14310. centred = 4 + 32
  14311. };
  14312. /** Returns the raw flags that are set for this object. */
  14313. inline int getFlags() const throw() { return flags; }
  14314. /** Tests a set of flags for this object.
  14315. @returns true if any of the flags passed in are set on this object.
  14316. */
  14317. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14318. /** Adjusts the position and size of a rectangle to fit it into a space.
  14319. The source rectangle co-ordinates will be adjusted so that they fit into
  14320. the destination rectangle based on this object's flags.
  14321. */
  14322. void applyTo (double& sourceX,
  14323. double& sourceY,
  14324. double& sourceW,
  14325. double& sourceH,
  14326. const double destinationX,
  14327. const double destinationY,
  14328. const double destinationW,
  14329. const double destinationH) const throw();
  14330. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14331. into the destination rectangle using the current flags.
  14332. */
  14333. const AffineTransform getTransformToFit (float sourceX,
  14334. float sourceY,
  14335. float sourceW,
  14336. float sourceH,
  14337. const float destinationX,
  14338. const float destinationY,
  14339. const float destinationW,
  14340. const float destinationH) const throw();
  14341. private:
  14342. int flags;
  14343. };
  14344. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14345. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14346. class LowLevelGraphicsContext;
  14347. class Image;
  14348. class RectangleList;
  14349. /**
  14350. A graphics context, used for drawing a component or image.
  14351. When a Component needs painting, a Graphics context is passed to its
  14352. Component::paint() method, and this you then call methods within this
  14353. object to actually draw the component's content.
  14354. A Graphics can also be created from an image, to allow drawing directly onto
  14355. that image.
  14356. @see Component::paint
  14357. */
  14358. class JUCE_API Graphics
  14359. {
  14360. public:
  14361. /** Creates a Graphics object to draw directly onto the given image.
  14362. The graphics object that is created will be set up to draw onto the image,
  14363. with the context's clipping area being the entire size of the image, and its
  14364. origin being the image's origin. To draw into a subsection of an image, use the
  14365. reduceClipRegion() and setOrigin() methods.
  14366. Obviously you shouldn't delete the image before this context is deleted.
  14367. */
  14368. Graphics (Image& imageToDrawOnto) throw();
  14369. /** Destructor. */
  14370. ~Graphics() throw();
  14371. /** Changes the current drawing colour.
  14372. This sets the colour that will now be used for drawing operations - it also
  14373. sets the opacity to that of the colour passed-in.
  14374. If a brush is being used when this method is called, the brush will be deselected,
  14375. and any subsequent drawing will be done with a solid colour brush instead.
  14376. @see setOpacity, setBrush, getColour
  14377. */
  14378. void setColour (const Colour& newColour) throw();
  14379. /** Returns the colour that's currently being used.
  14380. This will return the last colour set by setColour(), even if the colour's not
  14381. currently being used for drawing because a brush has been selected instead.
  14382. @see setColour
  14383. */
  14384. const Colour& getCurrentColour() const throw();
  14385. /** Changes the opacity to use with the current colour.
  14386. If a solid colour is being used for drawing, this changes its opacity (and this
  14387. will be reflected by calls to the getColour() method).
  14388. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14389. */
  14390. void setOpacity (const float newOpacity) throw();
  14391. /** Changes the current brush to use for drawing.
  14392. If a null pointer is passed in, the context will revert to using a solid
  14393. colour for drawing (using the last colour set by setColour()).
  14394. If a brush is passed in, a copy of it will be used for subsequent drawing
  14395. operations until setColour() or setBrush() is called.
  14396. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14397. */
  14398. void setBrush (const Brush* const newBrush) throw();
  14399. /** Changes the font to use for subsequent text-drawing functions.
  14400. Note there's also a setFont (float, int) method to quickly change the size and
  14401. style of the current font.
  14402. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14403. */
  14404. void setFont (const Font& newFont) throw();
  14405. /** Changes the size and style of the currently-selected font.
  14406. This is a convenient shortcut that changes the context's current font to a
  14407. different size or style. The typeface won't be changed.
  14408. @see Font
  14409. */
  14410. void setFont (const float newFontHeight,
  14411. const int fontStyleFlags = Font::plain) throw();
  14412. /** Returns the font that's currently being used for text operations.
  14413. @see setFont
  14414. */
  14415. const Font& getCurrentFont() const throw();
  14416. /** Draws a one-line text string.
  14417. This will use the current colour (or brush) to fill the text. The font is the last
  14418. one specified by setFont().
  14419. @param text the string to draw
  14420. @param startX the position to draw the left-hand edge of the text
  14421. @param baselineY the position of the text's baseline
  14422. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14423. */
  14424. void drawSingleLineText (const String& text,
  14425. const int startX,
  14426. const int baselineY) const throw();
  14427. /** Draws text across multiple lines.
  14428. This will break the text onto a new line where there's a new-line or
  14429. carriage-return character, or at a word-boundary when the text becomes wider
  14430. than the size specified by the maximumLineWidth parameter.
  14431. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14432. */
  14433. void drawMultiLineText (const String& text,
  14434. const int startX,
  14435. const int baselineY,
  14436. const int maximumLineWidth) const throw();
  14437. /** Renders a string of text as a vector path.
  14438. This allows a string to be transformed with an arbitrary AffineTransform and
  14439. rendered using the current colour/brush. It's much slower than the normal text methods
  14440. but more accurate.
  14441. @see setFont
  14442. */
  14443. void drawTextAsPath (const String& text,
  14444. const AffineTransform& transform) const throw();
  14445. /** Draws a line of text within a specified rectangle.
  14446. The text will be positioned within the rectangle based on the justification
  14447. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14448. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14449. flag is true).
  14450. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14451. */
  14452. void drawText (const String& text,
  14453. const int x,
  14454. const int y,
  14455. const int width,
  14456. const int height,
  14457. const Justification& justificationType,
  14458. const bool useEllipsesIfTooBig) const throw();
  14459. /** Tries to draw a text string inside a given space.
  14460. This does its best to make the given text readable within the specified rectangle,
  14461. so it useful for labelling things.
  14462. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14463. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14464. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14465. it's been truncated.
  14466. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14467. both horizontally and vertically.
  14468. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14469. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14470. can set this value to 1.0f.
  14471. @see GlyphArrangement::addFittedText
  14472. */
  14473. void drawFittedText (const String& text,
  14474. const int x,
  14475. const int y,
  14476. const int width,
  14477. const int height,
  14478. const Justification& justificationFlags,
  14479. const int maximumNumberOfLines,
  14480. const float minimumHorizontalScale = 0.7f) const throw();
  14481. /** Fills the context's entire clip region with the current colour or brush.
  14482. (See also the fillAll (const Colour&) method which is a quick way of filling
  14483. it with a given colour).
  14484. */
  14485. void fillAll() const throw();
  14486. /** Fills the context's entire clip region with a given colour.
  14487. This leaves the context's current colour and brush unchanged, it just
  14488. uses the specified colour temporarily.
  14489. */
  14490. void fillAll (const Colour& colourToUse) const throw();
  14491. /** Fills a rectangle with the current colour or brush.
  14492. @see drawRect, fillRoundedRectangle
  14493. */
  14494. void fillRect (int x,
  14495. int y,
  14496. int width,
  14497. int height) const throw();
  14498. /** Fills a rectangle with the current colour or brush. */
  14499. void fillRect (const Rectangle& rectangle) const throw();
  14500. /** Fills a rectangle with the current colour or brush.
  14501. This uses sub-pixel positioning so is slower than the fillRect method which
  14502. takes integer co-ordinates.
  14503. */
  14504. void fillRect (const float x,
  14505. const float y,
  14506. const float width,
  14507. const float height) const throw();
  14508. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14509. @see drawRoundedRectangle, Path::addRoundedRectangle
  14510. */
  14511. void fillRoundedRectangle (const float x,
  14512. const float y,
  14513. const float width,
  14514. const float height,
  14515. const float cornerSize) const throw();
  14516. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14517. @see drawRoundedRectangle, Path::addRoundedRectangle
  14518. */
  14519. void fillRoundedRectangle (const Rectangle& rectangle,
  14520. const float cornerSize) const throw();
  14521. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14522. */
  14523. void fillCheckerBoard (int x, int y,
  14524. int width, int height,
  14525. const int checkWidth,
  14526. const int checkHeight,
  14527. const Colour& colour1,
  14528. const Colour& colour2) const throw();
  14529. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14530. The lines are drawn inside the given rectangle, and greater line thicknesses
  14531. extend inwards.
  14532. @see fillRect
  14533. */
  14534. void drawRect (const int x,
  14535. const int y,
  14536. const int width,
  14537. const int height,
  14538. const int lineThickness = 1) const throw();
  14539. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14540. The lines are drawn inside the given rectangle, and greater line thicknesses
  14541. extend inwards.
  14542. @see fillRect
  14543. */
  14544. void drawRect (const float x,
  14545. const float y,
  14546. const float width,
  14547. const float height,
  14548. const float lineThickness = 1.0f) const throw();
  14549. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14550. The lines are drawn inside the given rectangle, and greater line thicknesses
  14551. extend inwards.
  14552. @see fillRect
  14553. */
  14554. void drawRect (const Rectangle& rectangle,
  14555. const int lineThickness = 1) const throw();
  14556. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14557. @see fillRoundedRectangle, Path::addRoundedRectangle
  14558. */
  14559. void drawRoundedRectangle (const float x,
  14560. const float y,
  14561. const float width,
  14562. const float height,
  14563. const float cornerSize,
  14564. const float lineThickness) const throw();
  14565. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14566. @see fillRoundedRectangle, Path::addRoundedRectangle
  14567. */
  14568. void drawRoundedRectangle (const Rectangle& rectangle,
  14569. const float cornerSize,
  14570. const float lineThickness) const throw();
  14571. /** Draws a 3D raised (or indented) bevel using two colours.
  14572. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14573. extend inwards.
  14574. The top-left colour is used for the top- and left-hand edges of the
  14575. bevel; the bottom-right colour is used for the bottom- and right-hand
  14576. edges.
  14577. */
  14578. void drawBevel (const int x,
  14579. const int y,
  14580. const int width,
  14581. const int height,
  14582. const int bevelThickness,
  14583. const Colour& topLeftColour = Colours::white,
  14584. const Colour& bottomRightColour = Colours::black,
  14585. const bool useGradient = true) const throw();
  14586. /** Draws a pixel using the current colour or brush.
  14587. */
  14588. void setPixel (int x, int y) const throw();
  14589. /** Fills an ellipse with the current colour or brush.
  14590. The ellipse is drawn to fit inside the given rectangle.
  14591. @see drawEllipse, Path::addEllipse
  14592. */
  14593. void fillEllipse (const float x,
  14594. const float y,
  14595. const float width,
  14596. const float height) const throw();
  14597. /** Draws an elliptical stroke using the current colour or brush.
  14598. @see fillEllipse, Path::addEllipse
  14599. */
  14600. void drawEllipse (const float x,
  14601. const float y,
  14602. const float width,
  14603. const float height,
  14604. const float lineThickness) const throw();
  14605. /** Draws a line between two points.
  14606. The line is 1 pixel wide and drawn with the current colour or brush.
  14607. */
  14608. void drawLine (float startX,
  14609. float startY,
  14610. float endX,
  14611. float endY) const throw();
  14612. /** Draws a line between two points with a given thickness.
  14613. @see Path::addLineSegment
  14614. */
  14615. void drawLine (const float startX,
  14616. const float startY,
  14617. const float endX,
  14618. const float endY,
  14619. const float lineThickness) const throw();
  14620. /** Draws a line between two points.
  14621. The line is 1 pixel wide and drawn with the current colour or brush.
  14622. */
  14623. void drawLine (const Line& line) const throw();
  14624. /** Draws a line between two points with a given thickness.
  14625. @see Path::addLineSegment
  14626. */
  14627. void drawLine (const Line& line,
  14628. const float lineThickness) const throw();
  14629. /** Draws a dashed line using a custom set of dash-lengths.
  14630. @param startX the line's start x co-ordinate
  14631. @param startY the line's start y co-ordinate
  14632. @param endX the line's end x co-ordinate
  14633. @param endY the line's end y co-ordinate
  14634. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14635. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14636. draw 6 pixels, skip 7 pixels, and then repeat.
  14637. @param numDashLengths the number of elements in the array (this must be an even number).
  14638. @param lineThickness the thickness of the line to draw
  14639. @see PathStrokeType::createDashedStroke
  14640. */
  14641. void drawDashedLine (const float startX,
  14642. const float startY,
  14643. const float endX,
  14644. const float endY,
  14645. const float* const dashLengths,
  14646. const int numDashLengths,
  14647. const float lineThickness = 1.0f) const throw();
  14648. /** Draws a vertical line of pixels at a given x position.
  14649. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14650. positions, and these will be anti-aliased if necessary.
  14651. */
  14652. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14653. /** Draws a horizontal line of pixels at a given y position.
  14654. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14655. positions, and these will be anti-aliased if necessary.
  14656. */
  14657. void drawHorizontalLine (const int y, float left, float right) const throw();
  14658. /** Fills a path using the currently selected colour or brush.
  14659. */
  14660. void fillPath (const Path& path,
  14661. const AffineTransform& transform = AffineTransform::identity) const throw();
  14662. /** Draws a path's outline using the currently selected colour or brush.
  14663. */
  14664. void strokePath (const Path& path,
  14665. const PathStrokeType& strokeType,
  14666. const AffineTransform& transform = AffineTransform::identity) const throw();
  14667. /** Draws a line with an arrowhead.
  14668. @param startX the line's start x co-ordinate
  14669. @param startY the line's start y co-ordinate
  14670. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14671. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14672. @param lineThickness the thickness of the line
  14673. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14674. @param arrowheadLength the length of the arrow head (along the length of the line)
  14675. */
  14676. void drawArrow (const float startX,
  14677. const float startY,
  14678. const float endX,
  14679. const float endY,
  14680. const float lineThickness,
  14681. const float arrowheadWidth,
  14682. const float arrowheadLength) const throw();
  14683. /** Types of rendering quality that can be specified when drawing images.
  14684. @see blendImage, Graphics::setImageResamplingQuality
  14685. */
  14686. enum ResamplingQuality
  14687. {
  14688. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14689. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14690. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14691. };
  14692. /** Changes the quality that will be used when resampling images.
  14693. By default a Graphics object will be set to mediumRenderingQuality.
  14694. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14695. */
  14696. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14697. /** Draws an image.
  14698. This will draw the whole of an image, positioning its top-left corner at the
  14699. given co-ordinates, and keeping its size the same. This is the simplest image
  14700. drawing method - the others give more control over the scaling and clipping
  14701. of the images.
  14702. Images are composited using the context's current opacity, so if you
  14703. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14704. (or setColour() with an opaque colour) before drawing images.
  14705. */
  14706. void drawImageAt (const Image* const imageToDraw,
  14707. const int topLeftX,
  14708. const int topLeftY,
  14709. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14710. /** Draws part of an image, rescaling it to fit in a given target region.
  14711. The specified area of the source image is rescaled and drawn to fill the
  14712. specifed destination rectangle.
  14713. Images are composited using the context's current opacity, so if you
  14714. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14715. (or setColour() with an opaque colour) before drawing images.
  14716. @param imageToDraw the image to overlay
  14717. @param destX the left of the destination rectangle
  14718. @param destY the top of the destination rectangle
  14719. @param destWidth the width of the destination rectangle
  14720. @param destHeight the height of the destination rectangle
  14721. @param sourceX the left of the rectangle to copy from the source image
  14722. @param sourceY the top of the rectangle to copy from the source image
  14723. @param sourceWidth the width of the rectangle to copy from the source image
  14724. @param sourceHeight the height of the rectangle to copy from the source image
  14725. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14726. the source image's alpha channel is used as a mask with
  14727. which to fill the destination using the current colour
  14728. or brush. (If the source is has no alpha channel, then
  14729. it will just fill the target with a solid rectangle)
  14730. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14731. */
  14732. void drawImage (const Image* const imageToDraw,
  14733. int destX,
  14734. int destY,
  14735. int destWidth,
  14736. int destHeight,
  14737. int sourceX,
  14738. int sourceY,
  14739. int sourceWidth,
  14740. int sourceHeight,
  14741. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14742. /** Draws part of an image, having applied an affine transform to it.
  14743. This lets you throw the image around in some wacky ways, rotate it, shear,
  14744. scale it, etc.
  14745. A clipping subregion is specified within the source image and no pixels
  14746. outside this region will be used.
  14747. Images are composited using the context's current opacity, so if you
  14748. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14749. (or setColour() with an opaque colour) before drawing images.
  14750. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14751. are ignored and it is filled with the current brush, masked by its alpha channel.
  14752. @see setImageResamplingQuality, drawImage
  14753. */
  14754. void drawImageTransformed (const Image* const imageToDraw,
  14755. int sourceClipX,
  14756. int sourceClipY,
  14757. int sourceClipWidth,
  14758. int sourceClipHeight,
  14759. const AffineTransform& transform,
  14760. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14761. /** Draws an image to fit within a designated rectangle.
  14762. If the image is too big or too small for the space, it will be rescaled
  14763. to fit as nicely as it can do without affecting its aspect ratio. It will
  14764. then be placed within the target rectangle according to the justification flags
  14765. specified.
  14766. @param imageToDraw the source image to draw
  14767. @param destX top-left of the target rectangle to fit it into
  14768. @param destY top-left of the target rectangle to fit it into
  14769. @param destWidth size of the target rectangle to fit the image into
  14770. @param destHeight size of the target rectangle to fit the image into
  14771. @param placementWithinTarget this specifies how the image should be positioned
  14772. within the target rectangle - see the RectanglePlacement
  14773. class for more details about this.
  14774. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14775. alpha channel will be used as a mask with which to
  14776. draw with the current brush or colour. This is
  14777. similar to fillAlphaMap(), and see also drawImage()
  14778. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14779. */
  14780. void drawImageWithin (const Image* const imageToDraw,
  14781. const int destX,
  14782. const int destY,
  14783. const int destWidth,
  14784. const int destHeight,
  14785. const RectanglePlacement& placementWithinTarget,
  14786. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14787. /** Returns the position of the bounding box for the current clipping region.
  14788. @see getClipRegion, clipRegionIntersects
  14789. */
  14790. const Rectangle getClipBounds() const throw();
  14791. /** Checks whether a rectangle overlaps the context's clipping region.
  14792. If this returns false, no part of the given area can be drawn onto, so this
  14793. method can be used to optimise a component's paint() method, by letting it
  14794. avoid drawing complex objects that aren't within the region being repainted.
  14795. */
  14796. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14797. /** Intersects the current clipping region with another region.
  14798. @returns true if the resulting clipping region is non-zero in size
  14799. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14800. */
  14801. bool reduceClipRegion (const int x, const int y,
  14802. const int width, const int height) throw();
  14803. /** Intersects the current clipping region with a rectangle list region.
  14804. @returns true if the resulting clipping region is non-zero in size
  14805. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14806. */
  14807. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14808. /** Excludes a rectangle to stop it being drawn into. */
  14809. void excludeClipRegion (const int x, const int y,
  14810. const int width, const int height) throw();
  14811. /** Returns true if no drawing can be done because the clip region is zero. */
  14812. bool isClipEmpty() const throw();
  14813. /** Saves the current graphics state on an internal stack.
  14814. To restore the state, use restoreState().
  14815. */
  14816. void saveState() throw();
  14817. /** Restores a graphics state that was previously saved with saveState().
  14818. */
  14819. void restoreState() throw();
  14820. /** Moves the position of the context's origin.
  14821. This changes the position that the context considers to be (0, 0) to
  14822. the specified position.
  14823. So if you call setOrigin (100, 100), then the position that was previously
  14824. referred to as (100, 100) will subsequently be considered to be (0, 0).
  14825. @see reduceClipRegion
  14826. */
  14827. void setOrigin (const int newOriginX,
  14828. const int newOriginY) throw();
  14829. /** Resets the current colour, brush, and font to default settings. */
  14830. void resetToDefaultState() throw();
  14831. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  14832. bool isVectorDevice() const throw();
  14833. juce_UseDebuggingNewOperator
  14834. /** Create a graphics that uses a given low-level renderer.
  14835. For internal use only.
  14836. NB. The context will NOT be deleted by this object when it is deleted.
  14837. */
  14838. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  14839. /** @internal */
  14840. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  14841. private:
  14842. LowLevelGraphicsContext* const context;
  14843. const bool ownsContext;
  14844. struct GraphicsState
  14845. {
  14846. GraphicsState() throw();
  14847. GraphicsState (const GraphicsState&) throw();
  14848. ~GraphicsState() throw();
  14849. Colour colour;
  14850. Brush* brush;
  14851. Font font;
  14852. ResamplingQuality quality;
  14853. };
  14854. GraphicsState* state;
  14855. OwnedArray <GraphicsState> stateStack;
  14856. bool saveStatePending;
  14857. void saveStateIfPending() throw();
  14858. const Graphics& operator= (const Graphics& other);
  14859. Graphics (const Graphics&);
  14860. };
  14861. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  14862. /********* End of inlined file: juce_Graphics.h *********/
  14863. /**
  14864. A graphical effect filter that can be applied to components.
  14865. An ImageEffectFilter can be applied to the image that a component
  14866. paints before it hits the screen.
  14867. This is used for adding effects like shadows, blurs, etc.
  14868. @see Component::setComponentEffect
  14869. */
  14870. class JUCE_API ImageEffectFilter
  14871. {
  14872. public:
  14873. /** Overridden to render the effect.
  14874. The implementation of this method must use the image that is passed in
  14875. as its source, and should render its output to the graphics context passed in.
  14876. @param sourceImage the image that the source component has just rendered with
  14877. its paint() method. The image may or may not have an alpha
  14878. channel, depending on whether the component is opaque.
  14879. @param destContext the graphics context to use to draw the resultant image.
  14880. */
  14881. virtual void applyEffect (Image& sourceImage,
  14882. Graphics& destContext) = 0;
  14883. /** Destructor. */
  14884. virtual ~ImageEffectFilter() {}
  14885. };
  14886. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  14887. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  14888. /********* Start of inlined file: juce_RectangleList.h *********/
  14889. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  14890. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  14891. /**
  14892. Maintains a set of rectangles as a complex region.
  14893. This class allows a set of rectangles to be treated as a solid shape, and can
  14894. add and remove rectangular sections of it, and simplify overlapping or
  14895. adjacent rectangles.
  14896. @see Rectangle
  14897. */
  14898. class JUCE_API RectangleList
  14899. {
  14900. public:
  14901. /** Creates an empty RectangleList */
  14902. RectangleList() throw();
  14903. /** Creates a copy of another list */
  14904. RectangleList (const RectangleList& other) throw();
  14905. /** Creates a list containing just one rectangle. */
  14906. RectangleList (const Rectangle& rect) throw();
  14907. /** Copies this list from another one. */
  14908. const RectangleList& operator= (const RectangleList& other) throw();
  14909. /** Destructor. */
  14910. ~RectangleList() throw();
  14911. /** Returns true if the region is empty. */
  14912. bool isEmpty() const throw();
  14913. /** Returns the number of rectangles in the list. */
  14914. int getNumRectangles() const throw() { return rects.size(); }
  14915. /** Returns one of the rectangles at a particular index.
  14916. @returns the rectangle at the index, or an empty rectangle if the
  14917. index is out-of-range.
  14918. */
  14919. const Rectangle getRectangle (const int index) const throw();
  14920. /** Removes all rectangles to leave an empty region. */
  14921. void clear() throw();
  14922. /** Merges a new rectangle into the list.
  14923. The rectangle being added will first be clipped to remove any parts of it
  14924. that overlap existing rectangles in the list.
  14925. */
  14926. void add (const int x, const int y,
  14927. const int w, const int h) throw();
  14928. /** Merges a new rectangle into the list.
  14929. The rectangle being added will first be clipped to remove any parts of it
  14930. that overlap existing rectangles in the list, and adjacent rectangles will be
  14931. merged into it.
  14932. */
  14933. void add (const Rectangle& rect) throw();
  14934. /** Dumbly adds a rectangle to the list without checking for overlaps.
  14935. This simply adds the rectangle to the end, it doesn't merge it or remove
  14936. any overlapping bits.
  14937. */
  14938. void addWithoutMerging (const Rectangle& rect) throw();
  14939. /** Merges another rectangle list into this one.
  14940. Any overlaps between the two lists will be clipped, so that the result is
  14941. the union of both lists.
  14942. */
  14943. void add (const RectangleList& other) throw();
  14944. /** Removes a rectangular region from the list.
  14945. Any rectangles in the list which overlap this will be clipped and subdivided
  14946. if necessary.
  14947. */
  14948. void subtract (const Rectangle& rect) throw();
  14949. /** Removes all areas in another RectangleList from this one.
  14950. Any rectangles in the list which overlap this will be clipped and subdivided
  14951. if necessary.
  14952. */
  14953. void subtract (const RectangleList& otherList) throw();
  14954. /** Removes any areas of the region that lie outside a given rectangle.
  14955. Any rectangles in the list which overlap this will be clipped and subdivided
  14956. if necessary.
  14957. Returns true if the resulting region is not empty, false if it is empty.
  14958. @see getIntersectionWith
  14959. */
  14960. bool clipTo (const Rectangle& rect) throw();
  14961. /** Removes any areas of the region that lie outside a given rectangle list.
  14962. Any rectangles in this object which overlap the specified list will be clipped
  14963. and subdivided if necessary.
  14964. Returns true if the resulting region is not empty, false if it is empty.
  14965. @see getIntersectionWith
  14966. */
  14967. bool clipTo (const RectangleList& other) throw();
  14968. /** Creates a region which is the result of clipping this one to a given rectangle.
  14969. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  14970. resulting region into the list whose reference is passed-in.
  14971. Returns true if the resulting region is not empty, false if it is empty.
  14972. @see clipTo
  14973. */
  14974. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  14975. /** Swaps the contents of this and another list.
  14976. This swaps their internal pointers, so is hugely faster than using copy-by-value
  14977. to swap them.
  14978. */
  14979. void swapWith (RectangleList& otherList) throw();
  14980. /** Checks whether the region contains a given point.
  14981. @returns true if the point lies within one of the rectangles in the list
  14982. */
  14983. bool containsPoint (const int x, const int y) const throw();
  14984. /** Checks whether the region contains the whole of a given rectangle.
  14985. @returns true all parts of the rectangle passed in lie within the region
  14986. defined by this object
  14987. @see intersectsRectangle, containsPoint
  14988. */
  14989. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  14990. /** Checks whether the region contains any part of a given rectangle.
  14991. @returns true if any part of the rectangle passed in lies within the region
  14992. defined by this object
  14993. @see containsRectangle
  14994. */
  14995. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  14996. /** Checks whether this region intersects any part of another one.
  14997. @see intersectsRectangle
  14998. */
  14999. bool intersects (const RectangleList& other) const throw();
  15000. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15001. const Rectangle getBounds() const throw();
  15002. /** Optimises the list into a minimum number of constituent rectangles.
  15003. This will try to combine any adjacent rectangles into larger ones where
  15004. possible, to simplify lists that might have been fragmented by repeated
  15005. add/subtract calls.
  15006. */
  15007. void consolidate() throw();
  15008. /** Adds an x and y value to all the co-ordinates. */
  15009. void offsetAll (const int dx, const int dy) throw();
  15010. /** Creates a Path object to represent this region. */
  15011. const Path toPath() const throw();
  15012. /** An iterator for accessing all the rectangles in a RectangleList. */
  15013. class Iterator
  15014. {
  15015. public:
  15016. Iterator (const RectangleList& list) throw();
  15017. ~Iterator() throw();
  15018. /** Advances to the next rectangle, and returns true if it's not finished.
  15019. Call this before using getRectangle() to find the rectangle that was returned.
  15020. */
  15021. bool next() throw();
  15022. /** Returns the current rectangle. */
  15023. const Rectangle* getRectangle() const throw() { return current; }
  15024. juce_UseDebuggingNewOperator
  15025. private:
  15026. const Rectangle* current;
  15027. const RectangleList& owner;
  15028. int index;
  15029. Iterator (const Iterator&);
  15030. const Iterator& operator= (const Iterator&);
  15031. };
  15032. juce_UseDebuggingNewOperator
  15033. private:
  15034. friend class Iterator;
  15035. Array <Rectangle> rects;
  15036. };
  15037. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15038. /********* End of inlined file: juce_RectangleList.h *********/
  15039. /********* Start of inlined file: juce_BorderSize.h *********/
  15040. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15041. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15042. /**
  15043. Specifies a set of gaps to be left around the sides of a rectangle.
  15044. This is basically the size of the spaces at the top, bottom, left and right of
  15045. a rectangle. It's used by various component classes to specify borders.
  15046. @see Rectangle
  15047. */
  15048. class JUCE_API BorderSize
  15049. {
  15050. public:
  15051. /** Creates a null border.
  15052. All sizes are left as 0.
  15053. */
  15054. BorderSize() throw();
  15055. /** Creates a copy of another border. */
  15056. BorderSize (const BorderSize& other) throw();
  15057. /** Creates a border with the given gaps. */
  15058. BorderSize (const int topGap,
  15059. const int leftGap,
  15060. const int bottomGap,
  15061. const int rightGap) throw();
  15062. /** Creates a border with the given gap on all sides. */
  15063. BorderSize (const int allGaps) throw();
  15064. /** Destructor. */
  15065. ~BorderSize() throw();
  15066. /** Returns the gap that should be left at the top of the region. */
  15067. int getTop() const throw() { return top; }
  15068. /** Returns the gap that should be left at the top of the region. */
  15069. int getLeft() const throw() { return left; }
  15070. /** Returns the gap that should be left at the top of the region. */
  15071. int getBottom() const throw() { return bottom; }
  15072. /** Returns the gap that should be left at the top of the region. */
  15073. int getRight() const throw() { return right; }
  15074. /** Returns the sum of the top and bottom gaps. */
  15075. int getTopAndBottom() const throw() { return top + bottom; }
  15076. /** Returns the sum of the left and right gaps. */
  15077. int getLeftAndRight() const throw() { return left + right; }
  15078. /** Changes the top gap. */
  15079. void setTop (const int newTopGap) throw();
  15080. /** Changes the left gap. */
  15081. void setLeft (const int newLeftGap) throw();
  15082. /** Changes the bottom gap. */
  15083. void setBottom (const int newBottomGap) throw();
  15084. /** Changes the right gap. */
  15085. void setRight (const int newRightGap) throw();
  15086. /** Returns a rectangle with these borders removed from it. */
  15087. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15088. /** Removes this border from a given rectangle. */
  15089. void subtractFrom (Rectangle& rectangle) const throw();
  15090. /** Returns a rectangle with these borders added around it. */
  15091. const Rectangle addedTo (const Rectangle& original) const throw();
  15092. /** Adds this border around a given rectangle. */
  15093. void addTo (Rectangle& original) const throw();
  15094. bool operator== (const BorderSize& other) const throw();
  15095. bool operator!= (const BorderSize& other) const throw();
  15096. juce_UseDebuggingNewOperator
  15097. private:
  15098. int top, left, bottom, right;
  15099. };
  15100. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15101. /********* End of inlined file: juce_BorderSize.h *********/
  15102. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15103. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15104. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15105. class Component;
  15106. class Graphics;
  15107. /********* Start of inlined file: juce_MessageListener.h *********/
  15108. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15109. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15110. /********* Start of inlined file: juce_Message.h *********/
  15111. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15112. #define __JUCE_MESSAGE_JUCEHEADER__
  15113. class MessageListener;
  15114. class MessageManager;
  15115. /** The base class for objects that can be delivered to a MessageListener.
  15116. The simplest Message object contains a few integer and pointer parameters
  15117. that the user can set, and this is enough for a lot of purposes. For passing more
  15118. complex data, subclasses of Message can also be used.
  15119. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15120. */
  15121. class JUCE_API Message
  15122. {
  15123. public:
  15124. /** Creates an uninitialised message.
  15125. The class's variables will also be left uninitialised.
  15126. */
  15127. Message() throw();
  15128. /** Creates a message object, filling in the member variables.
  15129. The corresponding public member variables will be set from the parameters
  15130. passed in.
  15131. */
  15132. Message (const int intParameter1,
  15133. const int intParameter2,
  15134. const int intParameter3,
  15135. void* const pointerParameter) throw();
  15136. /** Destructor. */
  15137. virtual ~Message() throw();
  15138. // These values can be used for carrying simple data that the application needs to
  15139. // pass around. For more complex messages, just create a subclass.
  15140. int intParameter1; /**< user-defined integer value. */
  15141. int intParameter2; /**< user-defined integer value. */
  15142. int intParameter3; /**< user-defined integer value. */
  15143. void* pointerParameter; /**< user-defined pointer value. */
  15144. juce_UseDebuggingNewOperator
  15145. private:
  15146. friend class MessageListener;
  15147. friend class MessageManager;
  15148. MessageListener* messageRecipient;
  15149. Message (const Message&);
  15150. const Message& operator= (const Message&);
  15151. };
  15152. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15153. /********* End of inlined file: juce_Message.h *********/
  15154. /**
  15155. MessageListener subclasses can post and receive Message objects.
  15156. @see Message, MessageManager, ActionListener, ChangeListener
  15157. */
  15158. class JUCE_API MessageListener
  15159. {
  15160. protected:
  15161. /** Creates a MessageListener. */
  15162. MessageListener() throw();
  15163. public:
  15164. /** Destructor.
  15165. When a MessageListener is deleted, it removes itself from a global list
  15166. of registered listeners, so that the isValidMessageListener() method
  15167. will no longer return true.
  15168. */
  15169. virtual ~MessageListener();
  15170. /** This is the callback method that receives incoming messages.
  15171. This is called by the MessageManager from its dispatch loop.
  15172. @see postMessage
  15173. */
  15174. virtual void handleMessage (const Message& message) = 0;
  15175. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15176. later on.
  15177. This method can be called safely by any thread.
  15178. @param message the message object to send - this will be deleted
  15179. automatically by the message queue, so don't keep any
  15180. references to it after calling this method.
  15181. @see handleMessage
  15182. */
  15183. void postMessage (Message* const message) const throw();
  15184. /** Checks whether this MessageListener has been deleted.
  15185. Although not foolproof, this method is safe to call on dangling or null
  15186. pointers. A list of active MessageListeners is kept internally, so this
  15187. checks whether the object is on this list or not.
  15188. Note that it's possible to get a false-positive here, if an object is
  15189. deleted and another is subsequently created that happens to be at the
  15190. exact same memory location, but I can't think of a good way of avoiding
  15191. this.
  15192. */
  15193. bool isValidMessageListener() const throw();
  15194. };
  15195. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15196. /********* End of inlined file: juce_MessageListener.h *********/
  15197. class ComponentBoundsConstrainer;
  15198. class ComponentDeletionWatcher;
  15199. /**
  15200. The base class for window objects that wrap a component as a real operating
  15201. system object.
  15202. This is an abstract base class - the platform specific code contains default
  15203. implementations of it that create and manage windows.
  15204. @see Component::createNewPeer
  15205. */
  15206. class JUCE_API ComponentPeer : public MessageListener
  15207. {
  15208. public:
  15209. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15210. enum StyleFlags
  15211. {
  15212. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15213. entry on the taskbar (ignored on MacOSX) */
  15214. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15215. tooltip, etc. */
  15216. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15217. through it (may not be possible on some platforms). */
  15218. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15219. title bar and frame\. if not specified, the window will be
  15220. borderless. */
  15221. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15222. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15223. minimise button on it. */
  15224. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15225. maximise button on it. */
  15226. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15227. close button on it. */
  15228. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15229. not be possible on all platforms). */
  15230. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15231. do its own repainting, but only to repaint when the
  15232. performAnyPendingRepaintsNow() method is called. */
  15233. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15234. be used for things like plugin windows, to stop them interfering
  15235. with the host's shortcut keys */
  15236. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15237. };
  15238. /** Creates a peer.
  15239. The component is the one that we intend to represent, and the style flags are
  15240. a combination of the values in the StyleFlags enum
  15241. */
  15242. ComponentPeer (Component* const component,
  15243. const int styleFlags) throw();
  15244. /** Destructor. */
  15245. virtual ~ComponentPeer();
  15246. /** Returns the component being represented by this peer. */
  15247. Component* getComponent() const throw() { return component; }
  15248. /** Returns the set of style flags that were set when the window was created.
  15249. @see Component::addToDesktop
  15250. */
  15251. int getStyleFlags() const throw() { return styleFlags; }
  15252. /** Returns the raw handle to whatever kind of window is being used.
  15253. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15254. but rememeber there's no guarantees what you'll get back.
  15255. */
  15256. virtual void* getNativeHandle() const = 0;
  15257. /** Shows or hides the window. */
  15258. virtual void setVisible (bool shouldBeVisible) = 0;
  15259. /** Changes the title of the window. */
  15260. virtual void setTitle (const String& title) = 0;
  15261. /** Moves the window without changing its size.
  15262. If the native window is contained in another window, then the co-ordinates are
  15263. relative to the parent window's origin, not the screen origin.
  15264. This should result in a callback to handleMovedOrResized().
  15265. */
  15266. virtual void setPosition (int x, int y) = 0;
  15267. /** Resizes the window without changing its position.
  15268. This should result in a callback to handleMovedOrResized().
  15269. */
  15270. virtual void setSize (int w, int h) = 0;
  15271. /** Moves and resizes the window.
  15272. If the native window is contained in another window, then the co-ordinates are
  15273. relative to the parent window's origin, not the screen origin.
  15274. This should result in a callback to handleMovedOrResized().
  15275. */
  15276. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15277. /** Returns the current position and size of the window.
  15278. If the native window is contained in another window, then the co-ordinates are
  15279. relative to the parent window's origin, not the screen origin.
  15280. */
  15281. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15282. /** Returns the x-position of this window, relative to the screen's origin. */
  15283. virtual int getScreenX() const = 0;
  15284. /** Returns the y-position of this window, relative to the screen's origin. */
  15285. virtual int getScreenY() const = 0;
  15286. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15287. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15288. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15289. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15290. /** Minimises the window. */
  15291. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15292. /** True if the window is currently minimised. */
  15293. virtual bool isMinimised() const = 0;
  15294. /** Enable/disable fullscreen mode for the window. */
  15295. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15296. /** True if the window is currently full-screen. */
  15297. virtual bool isFullScreen() const = 0;
  15298. /** Sets the size to restore to if fullscreen mode is turned off. */
  15299. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15300. /** Returns the size to restore to if fullscreen mode is turned off. */
  15301. const Rectangle& getNonFullScreenBounds() const throw();
  15302. /** Attempts to change the icon associated with this window.
  15303. */
  15304. virtual void setIcon (const Image& newIcon) = 0;
  15305. /** Sets a constrainer to use if the peer can resize itself.
  15306. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15307. */
  15308. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15309. /** Returns the current constrainer, if one has been set. */
  15310. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15311. /** Checks if a point is in the window.
  15312. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15313. is false, then this returns false if the point is actually inside a child of this
  15314. window.
  15315. */
  15316. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15317. /** Returns the size of the window frame that's around this window.
  15318. Whether or not the window has a normal window frame depends on the flags
  15319. that were set when the window was created by Component::addToDesktop()
  15320. */
  15321. virtual const BorderSize getFrameSize() const = 0;
  15322. /** This is called when the window's bounds change.
  15323. A peer implementation must call this when the window is moved and resized, so that
  15324. this method can pass the message on to the component.
  15325. */
  15326. void handleMovedOrResized();
  15327. /** This is called if the screen resolution changes.
  15328. A peer implementation must call this if the monitor arrangement changes or the available
  15329. screen size changes.
  15330. */
  15331. void handleScreenSizeChange();
  15332. /** This is called to repaint the component into the given context. */
  15333. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15334. /** Sets this window to either be always-on-top or normal.
  15335. Some kinds of window might not be able to do this, so should return false.
  15336. */
  15337. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15338. /** Brings the window to the top, optionally also giving it focus. */
  15339. virtual void toFront (bool makeActive) = 0;
  15340. /** Moves the window to be just behind another one. */
  15341. virtual void toBehind (ComponentPeer* other) = 0;
  15342. /** Called when the window is brought to the front, either by the OS or by a call
  15343. to toFront().
  15344. */
  15345. void handleBroughtToFront();
  15346. /** True if the window has the keyboard focus. */
  15347. virtual bool isFocused() const = 0;
  15348. /** Tries to give the window keyboard focus. */
  15349. virtual void grabFocus() = 0;
  15350. /** Tells the window that text input may be required at the given position.
  15351. This may cause things like a virtual on-screen keyboard to appear, depending
  15352. on the OS.
  15353. */
  15354. virtual void textInputRequired (int x, int y) = 0;
  15355. /** Called when the window gains keyboard focus. */
  15356. void handleFocusGain();
  15357. /** Called when the window loses keyboard focus. */
  15358. void handleFocusLoss();
  15359. Component* getLastFocusedSubcomponent() const throw();
  15360. /** Called when a key is pressed.
  15361. For keycode info, see the KeyPress class.
  15362. Returns true if the keystroke was used.
  15363. */
  15364. bool handleKeyPress (const int keyCode,
  15365. const juce_wchar textCharacter);
  15366. /** Called whenever a key is pressed or released.
  15367. Returns true if the keystroke was used.
  15368. */
  15369. bool handleKeyUpOrDown();
  15370. /** Called whenever a modifier key is pressed or released. */
  15371. void handleModifierKeysChange();
  15372. /** Invalidates a region of the window to be repainted asynchronously. */
  15373. virtual void repaint (int x, int y, int w, int h) = 0;
  15374. /** This can be called (from the message thread) to cause the immediate redrawing
  15375. of any areas of this window that need repainting.
  15376. You shouldn't ever really need to use this, it's mainly for special purposes
  15377. like supporting audio plugins where the host's event loop is out of our control.
  15378. */
  15379. virtual void performAnyPendingRepaintsNow() = 0;
  15380. void handleMouseEnter (int x, int y, const int64 time);
  15381. void handleMouseMove (int x, int y, const int64 time);
  15382. void handleMouseDown (int x, int y, const int64 time);
  15383. void handleMouseDrag (int x, int y, const int64 time);
  15384. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15385. void handleMouseExit (int x, int y, const int64 time);
  15386. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15387. /** Causes a mouse-move callback to be made asynchronously. */
  15388. void sendFakeMouseMove() throw();
  15389. void handleUserClosingWindow();
  15390. void handleFileDragMove (const StringArray& files, int x, int y);
  15391. void handleFileDragExit (const StringArray& files);
  15392. void handleFileDragDrop (const StringArray& files, int x, int y);
  15393. /** Resets the masking region.
  15394. The subclass should call this every time it's about to call the handlePaint
  15395. method.
  15396. @see addMaskedRegion
  15397. */
  15398. void clearMaskedRegion() throw();
  15399. /** Adds a rectangle to the set of areas not to paint over.
  15400. A component can call this on its peer during its paint() method, to signal
  15401. that the painting code should ignore a given region. The reason
  15402. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15403. The masked region is cleared each time before a paint happens, so a component
  15404. will have to make sure it calls this every time it's painted.
  15405. */
  15406. void addMaskedRegion (int x, int y, int w, int h) throw();
  15407. /** Returns the number of currently-active peers.
  15408. @see getPeer
  15409. */
  15410. static int getNumPeers() throw();
  15411. /** Returns one of the currently-active peers.
  15412. @see getNumPeers
  15413. */
  15414. static ComponentPeer* getPeer (const int index) throw();
  15415. /** Checks if this peer object is valid.
  15416. @see getNumPeers
  15417. */
  15418. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15419. juce_UseDebuggingNewOperator
  15420. protected:
  15421. Component* const component;
  15422. const int styleFlags;
  15423. RectangleList maskedRegion;
  15424. Rectangle lastNonFullscreenBounds;
  15425. uint32 lastPaintTime;
  15426. ComponentBoundsConstrainer* constrainer;
  15427. static void updateCurrentModifiers() throw();
  15428. /** @internal */
  15429. void handleMessage (const Message& message);
  15430. private:
  15431. Component* lastFocusedComponent;
  15432. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15433. Component* lastDragAndDropCompUnderMouse;
  15434. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15435. friend class Component;
  15436. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15437. void setLastDragDropTarget (Component* comp);
  15438. ComponentPeer (const ComponentPeer&);
  15439. const ComponentPeer& operator= (const ComponentPeer&);
  15440. };
  15441. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15442. /********* End of inlined file: juce_ComponentPeer.h *********/
  15443. class LookAndFeel;
  15444. /**
  15445. The base class for all JUCE user-interface objects.
  15446. */
  15447. class JUCE_API Component : public MouseListener,
  15448. protected MessageListener
  15449. {
  15450. public:
  15451. /** Creates a component.
  15452. To get it to actually appear, you'll also need to:
  15453. - Either add it to a parent component or use the addToDesktop() method to
  15454. make it a desktop window
  15455. - Set its size and position to something sensible
  15456. - Use setVisible() to make it visible
  15457. And for it to serve any useful purpose, you'll need to write a
  15458. subclass of Component or use one of the other types of component from
  15459. the library.
  15460. */
  15461. Component() throw();
  15462. /** Destructor.
  15463. Note that when a component is deleted, any child components it might
  15464. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15465. */
  15466. virtual ~Component();
  15467. /** Creates a component, setting its name at the same time.
  15468. @see getName, setName
  15469. */
  15470. Component (const String& componentName) throw();
  15471. /** Returns the name of this component.
  15472. @see setName
  15473. */
  15474. const String& getName() const throw() { return componentName_; }
  15475. /** Sets the name of this component.
  15476. When the name changes, all registered ComponentListeners will receive a
  15477. ComponentListener::componentNameChanged() callback.
  15478. @see getName
  15479. */
  15480. virtual void setName (const String& newName);
  15481. /** Checks whether this Component object has been deleted.
  15482. This will check whether this object is still a valid component, or whether
  15483. it's been deleted.
  15484. It's safe to call this on null or dangling pointers, but note that there is a
  15485. small risk if another new (but different) component has been created at the
  15486. same memory address which this one occupied, this methods can return a
  15487. false positive.
  15488. */
  15489. bool isValidComponent() const throw();
  15490. /** Makes the component visible or invisible.
  15491. This method will show or hide the component.
  15492. Note that components default to being non-visible when first created.
  15493. Also note that visible components won't be seen unless all their parent components
  15494. are also visible.
  15495. This method will call visibilityChanged() and also componentVisibilityChanged()
  15496. for any component listeners that are interested in this component.
  15497. @param shouldBeVisible whether to show or hide the component
  15498. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15499. */
  15500. virtual void setVisible (bool shouldBeVisible);
  15501. /** Tests whether the component is visible or not.
  15502. this doesn't necessarily tell you whether this comp is actually on the screen
  15503. because this depends on whether all the parent components are also visible - use
  15504. isShowing() to find this out.
  15505. @see isShowing, setVisible
  15506. */
  15507. bool isVisible() const throw() { return flags.visibleFlag; }
  15508. /** Called when this component's visiblility changes.
  15509. @see setVisible, isVisible
  15510. */
  15511. virtual void visibilityChanged();
  15512. /** Tests whether this component and all its parents are visible.
  15513. @returns true only if this component and all its parents are visible.
  15514. @see isVisible
  15515. */
  15516. bool isShowing() const throw();
  15517. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15518. To do this, this function will cunningly:
  15519. - take a snapshot of the component as it currently looks
  15520. - call setVisible(false) on the component
  15521. - replace it with a special component that will continue drawing the
  15522. snapshot, animating it and gradually making it more transparent
  15523. - when it's gone, the special component will also be deleted
  15524. As soon as this method returns, the component can be safely removed and deleted
  15525. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15526. component's destructor.
  15527. Passing non-zero x and y values will cause the ghostly component image to
  15528. also whizz off by this distance while fading out. If the scale factor is
  15529. not 1.0, it will also zoom from the component's current size to this new size.
  15530. One thing to be careful about is that the parent component must be able to cope
  15531. with this unknown component type being added to it.
  15532. */
  15533. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15534. const int deltaXToMove = 0,
  15535. const int deltaYToMove = 0,
  15536. const float scaleFactorAtEnd = 1.0f);
  15537. /** Makes this component appear as a window on the desktop.
  15538. Note that before calling this, you should make sure that the component's opacity is
  15539. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15540. system will try to create a special transparent window for it, which will generally take
  15541. a lot more CPU to operate (and might not even be possible on some platforms).
  15542. If the component is inside a parent component at the time this method is called, it
  15543. will be first be removed from that parent. Likewise if a component on the desktop
  15544. is subsequently added to another component, it'll be removed from the desktop.
  15545. @param windowStyleFlags a combination of the flags specified in the
  15546. ComponentPeer::StyleFlags enum, which define the
  15547. window's characteristics.
  15548. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15549. in which the juce component should place itself. On Windows,
  15550. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15551. supported on all platforms, and best left as 0 unless you know
  15552. what you're doing
  15553. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15554. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15555. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15556. */
  15557. virtual void addToDesktop (int windowStyleFlags,
  15558. void* nativeWindowToAttachTo = 0);
  15559. /** If the component is currently showing on the desktop, this will hide it.
  15560. You can also use setVisible() to hide a desktop window temporarily, but
  15561. removeFromDesktop() will free any system resources that are being used up.
  15562. @see addToDesktop, isOnDesktop
  15563. */
  15564. void removeFromDesktop();
  15565. /** Returns true if this component is currently showing on the desktop.
  15566. @see addToDesktop, removeFromDesktop
  15567. */
  15568. bool isOnDesktop() const throw();
  15569. /** Returns the heavyweight window that contains this component.
  15570. If this component is itself on the desktop, this will return the window
  15571. object that it is using. Otherwise, it will return the window of
  15572. its top-level parent component.
  15573. This may return 0 if there isn't a desktop component.
  15574. @see addToDesktop, isOnDesktop
  15575. */
  15576. ComponentPeer* getPeer() const throw();
  15577. /** For components on the desktop, this is called if the system wants to close the window.
  15578. This is a signal that either the user or the system wants the window to close. The
  15579. default implementation of this method will trigger an assertion to warn you that your
  15580. component should do something about it, but you can override this to ignore the event
  15581. if you want.
  15582. */
  15583. virtual void userTriedToCloseWindow();
  15584. /** Called for a desktop component which has just been minimised or un-minimised.
  15585. This will only be called for components on the desktop.
  15586. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15587. */
  15588. virtual void minimisationStateChanged (bool isNowMinimised);
  15589. /** Brings the component to the front of its siblings.
  15590. If some of the component's siblings have had their 'always-on-top' flag set,
  15591. then they will still be kept in front of this one (unless of course this
  15592. one is also 'always-on-top').
  15593. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15594. to the component (see grabKeyboardFocus() for more details)
  15595. @see toBack, toBehind, setAlwaysOnTop
  15596. */
  15597. void toFront (const bool shouldAlsoGainFocus);
  15598. /** Changes this component's z-order to be at the back of all its siblings.
  15599. If the component is set to be 'always-on-top', it will only be moved to the
  15600. back of the other other 'always-on-top' components.
  15601. @see toFront, toBehind, setAlwaysOnTop
  15602. */
  15603. void toBack();
  15604. /** Changes this component's z-order so that it's just behind another component.
  15605. @see toFront, toBack
  15606. */
  15607. void toBehind (Component* const other);
  15608. /** Sets whether the component should always be kept at the front of its siblings.
  15609. @see isAlwaysOnTop
  15610. */
  15611. void setAlwaysOnTop (const bool shouldStayOnTop);
  15612. /** Returns true if this component is set to always stay in front of its siblings.
  15613. @see setAlwaysOnTop
  15614. */
  15615. bool isAlwaysOnTop() const throw();
  15616. /** Returns the x co-ordinate of the component's left edge.
  15617. This is a distance in pixels from the left edge of the component's parent.
  15618. @see getScreenX
  15619. */
  15620. inline int getX() const throw() { return bounds_.getX(); }
  15621. /** Returns the y co-ordinate of the top of this component.
  15622. This is a distance in pixels from the top edge of the component's parent.
  15623. @see getScreenY
  15624. */
  15625. inline int getY() const throw() { return bounds_.getY(); }
  15626. /** Returns the component's width in pixels. */
  15627. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15628. /** Returns the component's height in pixels. */
  15629. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15630. /** Returns the x co-ordinate of the component's right-hand edge.
  15631. This is a distance in pixels from the left edge of the component's parent.
  15632. */
  15633. int getRight() const throw() { return bounds_.getRight(); }
  15634. /** Returns the y co-ordinate of the bottom edge of this component.
  15635. This is a distance in pixels from the top edge of the component's parent.
  15636. */
  15637. int getBottom() const throw() { return bounds_.getBottom(); }
  15638. /** Returns this component's bounding box.
  15639. The rectangle returned is relative to the top-left of the component's parent.
  15640. */
  15641. const Rectangle& getBounds() const throw() { return bounds_; }
  15642. /** Returns the region of this component that's not obscured by other, opaque components.
  15643. The RectangleList that is returned represents the area of this component
  15644. which isn't covered by opaque child components.
  15645. If includeSiblings is true, it will also take into account any siblings
  15646. that may be overlapping the component.
  15647. */
  15648. void getVisibleArea (RectangleList& result,
  15649. const bool includeSiblings) const;
  15650. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15651. @see getX, relativePositionToGlobal
  15652. */
  15653. int getScreenX() const throw();
  15654. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15655. @see getY, relativePositionToGlobal
  15656. */
  15657. int getScreenY() const throw();
  15658. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15659. @see globalPositionToRelative, relativePositionToOtherComponent
  15660. */
  15661. void relativePositionToGlobal (int& x, int& y) const throw();
  15662. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15663. @see relativePositionToGlobal, relativePositionToOtherComponent
  15664. */
  15665. void globalPositionToRelative (int& x, int& y) const throw();
  15666. /** Converts a position relative to this component's top-left into a position
  15667. relative to another component's top-left.
  15668. @see relativePositionToGlobal, globalPositionToRelative
  15669. */
  15670. void relativePositionToOtherComponent (const Component* const targetComponent,
  15671. int& x, int& y) const throw();
  15672. /** Moves the component to a new position.
  15673. Changes the component's top-left position (without changing its size).
  15674. The position is relative to the top-left of the component's parent.
  15675. If the component actually moves, this method will make a synchronous call to moved().
  15676. @see setBounds, ComponentListener::componentMovedOrResized
  15677. */
  15678. void setTopLeftPosition (const int x, const int y);
  15679. /** Moves the component to a new position.
  15680. Changes the position of the component's top-right corner (keeping it the same size).
  15681. The position is relative to the top-left of the component's parent.
  15682. If the component actually moves, this method will make a synchronous call to moved().
  15683. */
  15684. void setTopRightPosition (const int x, const int y);
  15685. /** Changes the size of the component.
  15686. A synchronous call to resized() will be occur if the size actually changes.
  15687. */
  15688. void setSize (const int newWidth, const int newHeight);
  15689. /** Changes the component's position and size.
  15690. The co-ordinates are relative to the top-left of the component's parent, or relative
  15691. to the origin of the screen is the component is on the desktop.
  15692. If this method changes the component's top-left position, it will make a synchronous
  15693. call to moved(). If it changes the size, it will also make a call to resized().
  15694. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15695. */
  15696. void setBounds (int x, int y, int width, int height);
  15697. /** Changes the component's position and size.
  15698. @see setBounds
  15699. */
  15700. void setBounds (const Rectangle& newBounds);
  15701. /** Changes the component's position and size in terms of fractions of its parent's size.
  15702. The values are factors of the parent's size, so for example
  15703. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15704. width and height of the parent, with its top-left position 20% of
  15705. the way across and down the parent.
  15706. */
  15707. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15708. const float proportionalWidth, const float proportionalHeight);
  15709. /** Changes the component's position and size based on the amount of space to leave around it.
  15710. This will position the component within its parent, leaving the specified number of
  15711. pixels around each edge.
  15712. */
  15713. void setBoundsInset (const BorderSize& borders);
  15714. /** Positions the component within a given rectangle, keeping its proportions
  15715. unchanged.
  15716. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15717. rectangle as possible without changing its aspect ratio (the component's
  15718. current size is used to determine its aspect ratio, so a zero-size component
  15719. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15720. too big to fit inside the rectangle.
  15721. It will then be positioned within the rectangle according to the justification flags
  15722. specified.
  15723. */
  15724. void setBoundsToFit (int x, int y, int width, int height,
  15725. const Justification& justification,
  15726. const bool onlyReduceInSize);
  15727. /** Changes the position of the component's centre.
  15728. Leaves the component's size unchanged, but sets the position of its centre
  15729. relative to its parent's top-left.
  15730. */
  15731. void setCentrePosition (const int x, const int y);
  15732. /** Changes the position of the component's centre.
  15733. Leaves the position unchanged, but positions its centre relative to its
  15734. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15735. its parent.
  15736. */
  15737. void setCentreRelative (const float x, const float y);
  15738. /** Changes the component's size and centres it within its parent.
  15739. After changing the size, the component will be moved so that it's
  15740. centred within its parent.
  15741. */
  15742. void centreWithSize (const int width, const int height);
  15743. /** Returns a proportion of the component's width.
  15744. This is a handy equivalent of (getWidth() * proportion).
  15745. */
  15746. int proportionOfWidth (const float proportion) const throw();
  15747. /** Returns a proportion of the component's height.
  15748. This is a handy equivalent of (getHeight() * proportion).
  15749. */
  15750. int proportionOfHeight (const float proportion) const throw();
  15751. /** Returns the width of the component's parent.
  15752. If the component has no parent (i.e. if it's on the desktop), this will return
  15753. the width of the screen.
  15754. */
  15755. int getParentWidth() const throw();
  15756. /** Returns the height of the component's parent.
  15757. If the component has no parent (i.e. if it's on the desktop), this will return
  15758. the height of the screen.
  15759. */
  15760. int getParentHeight() const throw();
  15761. /** Returns the screen co-ordinates of the monitor that contains this component.
  15762. If there's only one monitor, this will return its size - if there are multiple
  15763. monitors, it will return the area of the monitor that contains the component's
  15764. centre.
  15765. */
  15766. const Rectangle getParentMonitorArea() const throw();
  15767. /** Returns the number of child components that this component contains.
  15768. @see getChildComponent, getIndexOfChildComponent
  15769. */
  15770. int getNumChildComponents() const throw();
  15771. /** Returns one of this component's child components, by it index.
  15772. The component with index 0 is at the back of the z-order, the one at the
  15773. front will have index (getNumChildComponents() - 1).
  15774. If the index is out-of-range, this will return a null pointer.
  15775. @see getNumChildComponents, getIndexOfChildComponent
  15776. */
  15777. Component* getChildComponent (const int index) const throw();
  15778. /** Returns the index of this component in the list of child components.
  15779. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15780. values are further towards the front.
  15781. Returns -1 if the component passed-in is not a child of this component.
  15782. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15783. */
  15784. int getIndexOfChildComponent (const Component* const child) const throw();
  15785. /** Adds a child component to this one.
  15786. @param child the new component to add. If the component passed-in is already
  15787. the child of another component, it'll first be removed from that.
  15788. @param zOrder The index in the child-list at which this component should be inserted.
  15789. A value of -1 will insert it in front of the others, 0 is the back.
  15790. @see removeChildComponent, addAndMakeVisible, getChild,
  15791. ComponentListener::componentChildrenChanged
  15792. */
  15793. void addChildComponent (Component* const child,
  15794. int zOrder = -1);
  15795. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15796. Quite a useful function, this is just the same as calling addChildComponent()
  15797. followed by setVisible (true) on the child.
  15798. */
  15799. void addAndMakeVisible (Component* const child,
  15800. int zOrder = -1);
  15801. /** Removes one of this component's child-components.
  15802. If the child passed-in isn't actually a child of this component (either because
  15803. it's invalid or is the child of a different parent), then nothing is done.
  15804. Note that removing a child will not delete it!
  15805. @see addChildComponent, ComponentListener::componentChildrenChanged
  15806. */
  15807. void removeChildComponent (Component* const childToRemove);
  15808. /** Removes one of this component's child-components by index.
  15809. This will return a pointer to the component that was removed, or null if
  15810. the index was out-of-range.
  15811. Note that removing a child will not delete it!
  15812. @see addChildComponent, ComponentListener::componentChildrenChanged
  15813. */
  15814. Component* removeChildComponent (const int childIndexToRemove);
  15815. /** Removes all this component's children.
  15816. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  15817. */
  15818. void removeAllChildren();
  15819. /** Removes all this component's children, and deletes them.
  15820. @see removeAllChildren
  15821. */
  15822. void deleteAllChildren();
  15823. /** Returns the component which this component is inside.
  15824. If this is the highest-level component or hasn't yet been added to
  15825. a parent, this will return null.
  15826. */
  15827. Component* getParentComponent() const throw() { return parentComponent_; }
  15828. /** Searches the parent components for a component of a specified class.
  15829. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  15830. component that can be dynamically cast to a MyComp, or will return 0 if none
  15831. of the parents are suitable.
  15832. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  15833. */
  15834. template <class TargetClass>
  15835. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  15836. {
  15837. (void) dummyParameter;
  15838. Component* p = parentComponent_;
  15839. while (p != 0)
  15840. {
  15841. TargetClass* target = dynamic_cast <TargetClass*> (p);
  15842. if (target != 0)
  15843. return target;
  15844. p = p->parentComponent_;
  15845. }
  15846. return 0;
  15847. }
  15848. /** Returns the highest-level component which contains this one or its parents.
  15849. This will search upwards in the parent-hierarchy from this component, until it
  15850. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  15851. not yet added to a parent), and will return that.
  15852. */
  15853. Component* getTopLevelComponent() const throw();
  15854. /** Checks whether a component is anywhere inside this component or its children.
  15855. This will recursively check through this components children to see if the
  15856. given component is anywhere inside.
  15857. */
  15858. bool isParentOf (const Component* possibleChild) const throw();
  15859. /** Called to indicate that the component's parents have changed.
  15860. When a component is added or removed from its parent, this method will
  15861. be called on all of its children (recursively - so all children of its
  15862. children will also be called as well).
  15863. Subclasses can override this if they need to react to this in some way.
  15864. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  15865. */
  15866. virtual void parentHierarchyChanged();
  15867. /** Subclasses can use this callback to be told when children are added or removed.
  15868. @see parentHierarchyChanged
  15869. */
  15870. virtual void childrenChanged();
  15871. /** Tests whether a given point inside the component.
  15872. Overriding this method allows you to create components which only intercept
  15873. mouse-clicks within a user-defined area.
  15874. This is called to find out whether a particular x, y co-ordinate is
  15875. considered to be inside the component or not, and is used by methods such
  15876. as contains() and getComponentAt() to work out which component
  15877. the mouse is clicked on.
  15878. Components with custom shapes will probably want to override it to perform
  15879. some more complex hit-testing.
  15880. The default implementation of this method returns either true or false,
  15881. depending on the value that was set by calling setInterceptsMouseClicks() (true
  15882. is the default return value).
  15883. Note that the hit-test region is not related to the opacity with which
  15884. areas of a component are painted.
  15885. Applications should never call hitTest() directly - instead use the
  15886. contains() method, because this will also test for occlusion by the
  15887. component's parent.
  15888. Note that for components on the desktop, this method will be ignored, because it's
  15889. not always possible to implement this behaviour on all platforms.
  15890. @param x the x co-ordinate to test, relative to the left hand edge of this
  15891. component. This value is guaranteed to be greater than or equal to
  15892. zero, and less than the component's width
  15893. @param y the y co-ordinate to test, relative to the top edge of this
  15894. component. This value is guaranteed to be greater than or equal to
  15895. zero, and less than the component's height
  15896. @returns true if the click is considered to be inside the component
  15897. @see setInterceptsMouseClicks, contains
  15898. */
  15899. virtual bool hitTest (int x, int y);
  15900. /** Changes the default return value for the hitTest() method.
  15901. Setting this to false is an easy way to make a component pass its mouse-clicks
  15902. through to the components behind it.
  15903. When a component is created, the default setting for this is true.
  15904. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  15905. return false (or true for child components if allowClicksOnChildComponents
  15906. is true)
  15907. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  15908. components can be clicked on as normal but clicks on this component pass
  15909. straight through; if this is false and allowClicksOnThisComponent
  15910. is false, then neither this component nor any child components can
  15911. be clicked on
  15912. @see hitTest, getInterceptsMouseClicks
  15913. */
  15914. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  15915. const bool allowClicksOnChildComponents) throw();
  15916. /** Retrieves the current state of the mouse-click interception flags.
  15917. On return, the two parameters are set to the state used in the last call to
  15918. setInterceptsMouseClicks().
  15919. @see setInterceptsMouseClicks
  15920. */
  15921. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  15922. bool& allowsClicksOnChildComponents) const throw();
  15923. /** Returns true if a given point lies within this component or one of its children.
  15924. Never override this method! Use hitTest to create custom hit regions.
  15925. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15926. @param y the y co-ordinate to test, relative to this component's top edge.
  15927. @returns true if the point is within the component's hit-test area, but only if
  15928. that part of the component isn't clipped by its parent component. Note
  15929. that this won't take into account any overlapping sibling components
  15930. which might be in the way - for that, see reallyContains()
  15931. @see hitTest, reallyContains, getComponentAt
  15932. */
  15933. virtual bool contains (int x, int y);
  15934. /** Returns true if a given point lies in this component, taking any overlapping
  15935. siblings into account.
  15936. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15937. @param y the y co-ordinate to test, relative to this component's top edge.
  15938. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  15939. component, this determines the value that will
  15940. be returned.
  15941. @see contains, getComponentAt
  15942. */
  15943. bool reallyContains (int x, int y,
  15944. const bool returnTrueIfWithinAChild);
  15945. /** Returns the component at a certain point within this one.
  15946. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15947. @param y the y co-ordinate to test, relative to this component's top edge.
  15948. @returns the component that is at this position - which may be 0, this component,
  15949. or one of its children. Note that overlapping siblings that might actually
  15950. be in the way are not taken into account by this method - to account for these,
  15951. instead call getComponentAt on the top-level parent of this component.
  15952. @see hitTest, contains, reallyContains
  15953. */
  15954. Component* getComponentAt (const int x, const int y);
  15955. /** Marks the whole component as needing to be redrawn.
  15956. Calling this will not do any repainting immediately, but will mark the component
  15957. as 'dirty'. At some point in the near future the operating system will send a paint
  15958. message, which will redraw all the dirty regions of all components.
  15959. There's no guarantee about how soon after calling repaint() the redraw will actually
  15960. happen, and other queued events may be delivered before a redraw is done.
  15961. If the setBufferedToImage() method has been used to cause this component
  15962. to use a buffer, the repaint() call will invalidate the component's buffer.
  15963. To redraw just a subsection of the component rather than the whole thing,
  15964. use the repaint (int, int, int, int) method.
  15965. @see paint
  15966. */
  15967. void repaint() throw();
  15968. /** Marks a subsection of this component as needing to be redrawn.
  15969. Calling this will not do any repainting immediately, but will mark the given region
  15970. of the component as 'dirty'. At some point in the near future the operating system
  15971. will send a paint message, which will redraw all the dirty regions of all components.
  15972. There's no guarantee about how soon after calling repaint() the redraw will actually
  15973. happen, and other queued events may be delivered before a redraw is done.
  15974. The region that is passed in will be clipped to keep it within the bounds of this
  15975. component.
  15976. @see repaint()
  15977. */
  15978. void repaint (const int x, const int y,
  15979. const int width, const int height) throw();
  15980. /** Makes the component use an internal buffer to optimise its redrawing.
  15981. Setting this flag to true will cause the component to allocate an
  15982. internal buffer into which it paints itself, so that when asked to
  15983. redraw itself, it can use this buffer rather than actually calling the
  15984. paint() method.
  15985. The buffer is kept until the repaint() method is called directly on
  15986. this component (or until it is resized), when the image is invalidated
  15987. and then redrawn the next time the component is painted.
  15988. Note that only the drawing that happens within the component's paint()
  15989. method is drawn into the buffer, it's child components are not buffered, and
  15990. nor is the paintOverChildren() method.
  15991. @see repaint, paint, createComponentSnapshot
  15992. */
  15993. void setBufferedToImage (const bool shouldBeBuffered) throw();
  15994. /** Generates a snapshot of part of this component.
  15995. This will return a new Image, the size of the rectangle specified,
  15996. containing a snapshot of the specified area of the component and all
  15997. its children.
  15998. The image may or may not have an alpha-channel, depending on whether the
  15999. image is opaque or not.
  16000. If the clipImageToComponentBounds parameter is true and the area is greater than
  16001. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16002. then parts of the component beyond its bounds can be drawn.
  16003. The caller is responsible for deleting the image that is returned.
  16004. @see paintEntireComponent
  16005. */
  16006. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16007. const bool clipImageToComponentBounds = true);
  16008. /** Draws this component and all its subcomponents onto the specified graphics
  16009. context.
  16010. You should very rarely have to use this method, it's simply there in case you need
  16011. to draw a component with a custom graphics context for some reason, e.g. for
  16012. creating a snapshot of the component.
  16013. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16014. on its children in order to render the entire tree.
  16015. The graphics context may be left in an undefined state after this method returns,
  16016. so you may need to reset it if you're going to use it again.
  16017. */
  16018. void paintEntireComponent (Graphics& context);
  16019. /** Adds an effect filter to alter the component's appearance.
  16020. When a component has an effect filter set, then this is applied to the
  16021. results of its paint() method. There are a few preset effects, such as
  16022. a drop-shadow or glow, but they can be user-defined as well.
  16023. The effect that is passed in will not be deleted by the component - the
  16024. caller must take care of deleting it.
  16025. To remove an effect from a component, pass a null pointer in as the parameter.
  16026. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16027. */
  16028. void setComponentEffect (ImageEffectFilter* const newEffect);
  16029. /** Returns the current component effect.
  16030. @see setComponentEffect
  16031. */
  16032. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16033. /** Finds the appropriate look-and-feel to use for this component.
  16034. If the component hasn't had a look-and-feel explicitly set, this will
  16035. return the parent's look-and-feel, or just the default one if there's no
  16036. parent.
  16037. @see setLookAndFeel, lookAndFeelChanged
  16038. */
  16039. LookAndFeel& getLookAndFeel() const throw();
  16040. /** Sets the look and feel to use for this component.
  16041. This will also change the look and feel for any child components that haven't
  16042. had their look set explicitly.
  16043. The object passed in will not be deleted by the component, so it's the caller's
  16044. responsibility to manage it. It may be used at any time until this component
  16045. has been deleted.
  16046. Calling this method will also invoke the sendLookAndFeelChange() method.
  16047. @see getLookAndFeel, lookAndFeelChanged
  16048. */
  16049. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16050. /** Called to let the component react to a change in the look-and-feel setting.
  16051. When the look-and-feel is changed for a component, this will be called in
  16052. all its child components, recursively.
  16053. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16054. an application uses a LookAndFeel class that might have changed internally.
  16055. @see sendLookAndFeelChange, getLookAndFeel
  16056. */
  16057. virtual void lookAndFeelChanged();
  16058. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16059. This will recurse through the children and their children, calling lookAndFeelChanged()
  16060. on them all.
  16061. @see lookAndFeelChanged
  16062. */
  16063. void sendLookAndFeelChange();
  16064. /** Indicates whether any parts of the component might be transparent.
  16065. Components that always paint all of their contents with solid colour and
  16066. thus completely cover any components behind them should use this method
  16067. to tell the repaint system that they are opaque.
  16068. This information is used to optimise drawing, because it means that
  16069. objects underneath opaque windows don't need to be painted.
  16070. By default, components are considered transparent, unless this is used to
  16071. make it otherwise.
  16072. @see isOpaque, getVisibleArea
  16073. */
  16074. void setOpaque (const bool shouldBeOpaque) throw();
  16075. /** Returns true if no parts of this component are transparent.
  16076. @returns the value that was set by setOpaque, (the default being false)
  16077. @see setOpaque
  16078. */
  16079. bool isOpaque() const throw();
  16080. /** Indicates whether the component should be brought to the front when clicked.
  16081. Setting this flag to true will cause the component to be brought to the front
  16082. when the mouse is clicked somewhere inside it or its child components.
  16083. Note that a top-level desktop window might still be brought to the front by the
  16084. operating system when it's clicked, depending on how the OS works.
  16085. By default this is set to false.
  16086. @see setMouseClickGrabsKeyboardFocus
  16087. */
  16088. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16089. /** Indicates whether the component should be brought to the front when clicked-on.
  16090. @see setBroughtToFrontOnMouseClick
  16091. */
  16092. bool isBroughtToFrontOnMouseClick() const throw();
  16093. // Keyboard focus methods
  16094. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16095. By default components aren't actually interested in gaining the
  16096. focus, but this method can be used to turn this on.
  16097. See the grabKeyboardFocus() method for details about the way a component
  16098. is chosen to receive the focus.
  16099. @see grabKeyboardFocus, getWantsKeyboardFocus
  16100. */
  16101. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16102. /** Returns true if the component is interested in getting keyboard focus.
  16103. This returns the flag set by setWantsKeyboardFocus(). The default
  16104. setting is false.
  16105. @see setWantsKeyboardFocus
  16106. */
  16107. bool getWantsKeyboardFocus() const throw();
  16108. /** Chooses whether a click on this component automatically grabs the focus.
  16109. By default this is set to true, but you might want a component which can
  16110. be focused, but where you don't want the user to be able to affect it directly
  16111. by clicking.
  16112. */
  16113. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16114. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16115. See setMouseClickGrabsKeyboardFocus() for more info.
  16116. */
  16117. bool getMouseClickGrabsKeyboardFocus() const throw();
  16118. /** Tries to give keyboard focus to this component.
  16119. When the user clicks on a component or its grabKeyboardFocus()
  16120. method is called, the following procedure is used to work out which
  16121. component should get it:
  16122. - if the component that was clicked on actually wants focus (as indicated
  16123. by calling getWantsKeyboardFocus), it gets it.
  16124. - if the component itself doesn't want focus, it will try to pass it
  16125. on to whichever of its children is the default component, as determined by
  16126. KeyboardFocusTraverser::getDefaultComponent()
  16127. - if none of its children want focus at all, it will pass it up to its
  16128. parent instead, unless it's a top-level component without a parent,
  16129. in which case it just takes the focus itself.
  16130. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16131. getCurrentlyFocusedComponent, focusGained, focusLost,
  16132. keyPressed, keyStateChanged
  16133. */
  16134. void grabKeyboardFocus();
  16135. /** Returns true if this component currently has the keyboard focus.
  16136. @param trueIfChildIsFocused if this is true, then the method returns true if
  16137. either this component or any of its children (recursively)
  16138. have the focus. If false, the method only returns true if
  16139. this component has the focus.
  16140. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16141. focusGained, focusLost
  16142. */
  16143. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16144. /** Returns the component that currently has the keyboard focus.
  16145. @returns the focused component, or null if nothing is focused.
  16146. */
  16147. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16148. /** Tries to move the keyboard focus to one of this component's siblings.
  16149. This will try to move focus to either the next or previous component. (This
  16150. is the method that is used when shifting focus by pressing the tab key).
  16151. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16152. @param moveToNext if true, the focus will move forwards; if false, it will
  16153. move backwards
  16154. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16155. */
  16156. void moveKeyboardFocusToSibling (const bool moveToNext);
  16157. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16158. which focus should be passed from this component.
  16159. The default implementation of this method will return a default
  16160. KeyboardFocusTraverser if this component is a focus container (as determined
  16161. by the setFocusContainer() method). If the component isn't a focus
  16162. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16163. If you overrride this to return a custom KeyboardFocusTraverser, then
  16164. this component and all its sub-components will use the new object to
  16165. make their focusing decisions.
  16166. The method should return a new object, which the caller is required to
  16167. delete when no longer needed.
  16168. */
  16169. virtual KeyboardFocusTraverser* createFocusTraverser();
  16170. /** Returns the focus order of this component, if one has been specified.
  16171. By default components don't have a focus order - in that case, this
  16172. will return 0. Lower numbers indicate that the component will be
  16173. earlier in the focus traversal order.
  16174. To change the order, call setExplicitFocusOrder().
  16175. The focus order may be used by the KeyboardFocusTraverser class as part of
  16176. its algorithm for deciding the order in which components should be traversed.
  16177. See the KeyboardFocusTraverser class for more details on this.
  16178. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16179. */
  16180. int getExplicitFocusOrder() const throw();
  16181. /** Sets the index used in determining the order in which focusable components
  16182. should be traversed.
  16183. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16184. that traversal should use other factors, like the component's position.
  16185. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16186. */
  16187. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16188. /** Indicates whether this component is a parent for components that can have
  16189. their focus traversed.
  16190. This flag is used by the default implementation of the createFocusTraverser()
  16191. method, which uses the flag to find the first parent component (of the currently
  16192. focused one) which wants to be a focus container.
  16193. So using this method to set the flag to 'true' causes this component to
  16194. act as the top level within which focus is passed around.
  16195. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16196. */
  16197. void setFocusContainer (const bool isFocusContainer) throw();
  16198. /** Returns true if this component has been marked as a focus container.
  16199. See setFocusContainer() for more details.
  16200. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16201. */
  16202. bool isFocusContainer() const throw();
  16203. /** Returns true if the component (and all its parents) are enabled.
  16204. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16205. what difference this makes to the component depends on the type. E.g. buttons
  16206. and sliders will choose to draw themselves differently, etc.
  16207. Note that if one of this component's parents is disabled, this will always
  16208. return false, even if this component itself is enabled.
  16209. @see setEnabled, enablementChanged
  16210. */
  16211. bool isEnabled() const throw();
  16212. /** Enables or disables this component.
  16213. Disabling a component will also cause all of its child components to become
  16214. disabled.
  16215. Similarly, enabling a component which is inside a disabled parent
  16216. component won't make any difference until the parent is re-enabled.
  16217. @see isEnabled, enablementChanged
  16218. */
  16219. void setEnabled (const bool shouldBeEnabled);
  16220. /** Callback to indicate that this component has been enabled or disabled.
  16221. This can be triggered by one of the component's parent components
  16222. being enabled or disabled, as well as changes to the component itself.
  16223. The default implementation of this method does nothing; your class may
  16224. wish to repaint itself or something when this happens.
  16225. @see setEnabled, isEnabled
  16226. */
  16227. virtual void enablementChanged();
  16228. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16229. Note that the cursor set by this method can be overridden by the getMouseCursor
  16230. method.
  16231. @see MouseCursor
  16232. */
  16233. void setMouseCursor (const MouseCursor& cursorType) throw();
  16234. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16235. The default implementation will return the cursor that was set by setCursor()
  16236. but can be overridden for more specialised purposes, e.g. returning different
  16237. cursors depending on the mouse position.
  16238. @see MouseCursor
  16239. */
  16240. virtual const MouseCursor getMouseCursor();
  16241. /** Forces the current mouse cursor to be updated.
  16242. If you're overriding the getMouseCursor() method to control which cursor is
  16243. displayed, then this will only be checked each time the user moves the mouse. So
  16244. if you want to force the system to check that the cursor being displayed is
  16245. up-to-date (even if the mouse is just sitting there), call this method.
  16246. This isn't needed if you're only using setMouseCursor().
  16247. */
  16248. void updateMouseCursor() const throw();
  16249. /** Components can override this method to draw their content.
  16250. The paint() method gets called when a region of a component needs redrawing,
  16251. either because the component's repaint() method has been called, or because
  16252. something has happened on the screen that means a section of a window needs
  16253. to be redrawn.
  16254. Any child components will draw themselves over whatever this method draws. If
  16255. you need to paint over the top of your child components, you can also implement
  16256. the paintOverChildren() method to do this.
  16257. If you want to cause a component to redraw itself, this is done asynchronously -
  16258. calling the repaint() method marks a region of the component as "dirty", and the
  16259. paint() method will automatically be called sometime later, by the message thread,
  16260. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16261. you never redraw something synchronously.
  16262. You should never need to call this method directly - to take a snapshot of the
  16263. component you could use createComponentSnapshot() or paintEntireComponent().
  16264. @param g the graphics context that must be used to do the drawing operations.
  16265. @see repaint, paintOverChildren, Graphics
  16266. */
  16267. virtual void paint (Graphics& g);
  16268. /** Components can override this method to draw over the top of their children.
  16269. For most drawing operations, it's better to use the normal paint() method,
  16270. but if you need to overlay something on top of the children, this can be
  16271. used.
  16272. @see paint, Graphics
  16273. */
  16274. virtual void paintOverChildren (Graphics& g);
  16275. /** Called when the mouse moves inside this component.
  16276. If the mouse button isn't pressed and the mouse moves over a component,
  16277. this will be called to let the component react to this.
  16278. A component will always get a mouseEnter callback before a mouseMove.
  16279. @param e details about the position and status of the mouse event
  16280. @see mouseEnter, mouseExit, mouseDrag, contains
  16281. */
  16282. virtual void mouseMove (const MouseEvent& e);
  16283. /** Called when the mouse first enters this component.
  16284. If the mouse button isn't pressed and the mouse moves into a component,
  16285. this will be called to let the component react to this.
  16286. When the mouse button is pressed and held down while being moved in
  16287. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16288. mouseDrag messages are sent to the component that the mouse was originally
  16289. clicked on, until the button is released.
  16290. If you're writing a component that needs to repaint itself when the mouse
  16291. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16292. method.
  16293. @param e details about the position and status of the mouse event
  16294. @see mouseExit, mouseDrag, mouseMove, contains
  16295. */
  16296. virtual void mouseEnter (const MouseEvent& e);
  16297. /** Called when the mouse moves out of this component.
  16298. This will be called when the mouse moves off the edge of this
  16299. component.
  16300. If the mouse button was pressed, and it was then dragged off the
  16301. edge of the component and released, then this callback will happen
  16302. when the button is released, after the mouseUp callback.
  16303. If you're writing a component that needs to repaint itself when the mouse
  16304. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16305. method.
  16306. @param e details about the position and status of the mouse event
  16307. @see mouseEnter, mouseDrag, mouseMove, contains
  16308. */
  16309. virtual void mouseExit (const MouseEvent& e);
  16310. /** Called when a mouse button is pressed while it's over this component.
  16311. The MouseEvent object passed in contains lots of methods for finding out
  16312. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16313. were held down at the time.
  16314. Once a button is held down, the mouseDrag method will be called when the
  16315. mouse moves, until the button is released.
  16316. @param e details about the position and status of the mouse event
  16317. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16318. */
  16319. virtual void mouseDown (const MouseEvent& e);
  16320. /** Called when the mouse is moved while a button is held down.
  16321. When a mouse button is pressed inside a component, that component
  16322. receives mouseDrag callbacks each time the mouse moves, even if the
  16323. mouse strays outside the component's bounds.
  16324. If you want to be able to drag things off the edge of a component
  16325. and have the component scroll when you get to the edges, the
  16326. beginDragAutoRepeat() method might be useful.
  16327. @param e details about the position and status of the mouse event
  16328. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16329. */
  16330. virtual void mouseDrag (const MouseEvent& e);
  16331. /** Called when a mouse button is released.
  16332. A mouseUp callback is sent to the component in which a button was pressed
  16333. even if the mouse is actually over a different component when the
  16334. button is released.
  16335. The MouseEvent object passed in contains lots of methods for finding out
  16336. which buttons were down just before they were released.
  16337. @param e details about the position and status of the mouse event
  16338. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16339. */
  16340. virtual void mouseUp (const MouseEvent& e);
  16341. /** Called when a mouse button has been double-clicked in this component.
  16342. The MouseEvent object passed in contains lots of methods for finding out
  16343. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16344. were held down at the time.
  16345. For altering the time limit used to detect double-clicks,
  16346. see MouseEvent::setDoubleClickTimeout.
  16347. @param e details about the position and status of the mouse event
  16348. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16349. MouseEvent::getDoubleClickTimeout
  16350. */
  16351. virtual void mouseDoubleClick (const MouseEvent& e);
  16352. /** Called when the mouse-wheel is moved.
  16353. This callback is sent to the component that the mouse is over when the
  16354. wheel is moved.
  16355. If not overridden, the component will forward this message to its parent, so
  16356. that parent components can collect mouse-wheel messages that happen to
  16357. child components which aren't interested in them.
  16358. @param e details about the position and status of the mouse event
  16359. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16360. value means the wheel has been pushed to the right, negative means it
  16361. was pushed to the left
  16362. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16363. value means the wheel has been pushed upwards, negative means it
  16364. was pushed downwards
  16365. */
  16366. virtual void mouseWheelMove (const MouseEvent& e,
  16367. float wheelIncrementX,
  16368. float wheelIncrementY);
  16369. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16370. next mouse-drag operation.
  16371. This allows you to make sure that mouseDrag() events sent continuously, even
  16372. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16373. components when the mouse is near an edge.
  16374. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16375. minimum interval between consecutive mouse drag callbacks. The callbacks
  16376. will continue until the mouse is released, and then the interval will be reset,
  16377. so you need to make sure it's called every time you begin a drag event. If it
  16378. is called when the mouse isn't actually being pressed, it will apply to the next
  16379. mouse-drag operation that happens.
  16380. Passing an interval of 0 or less will cancel the auto-repeat.
  16381. @see mouseDrag
  16382. */
  16383. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16384. /** Causes automatic repaints when the mouse enters or exits this component.
  16385. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16386. on the component, it will trigger a repaint.
  16387. This is handy for things like buttons that need to draw themselves differently when
  16388. the mouse moves over them, and it avoids having to override all the different mouse
  16389. callbacks and call repaint().
  16390. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16391. */
  16392. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16393. /** Registers a listener to be told when mouse events occur in this component.
  16394. If you need to get informed about mouse events in a component but can't or
  16395. don't want to override its methods, you can attach any number of listeners
  16396. to the component, and these will get told about the events in addition to
  16397. the component's own callbacks being called.
  16398. Note that a MouseListener can also be attached to more than one component.
  16399. @param newListener the listener to register
  16400. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16401. for events that happen to any child component
  16402. within this component, including deeply-nested
  16403. child components. If false, it will only be
  16404. told about events that this component handles.
  16405. @see MouseListener, removeMouseListener
  16406. */
  16407. void addMouseListener (MouseListener* const newListener,
  16408. const bool wantsEventsForAllNestedChildComponents) throw();
  16409. /** Deregisters a mouse listener.
  16410. @see addMouseListener, MouseListener
  16411. */
  16412. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16413. /** Adds a listener that wants to hear about keypresses that this component receives.
  16414. The listeners that are registered with a component are called by its keyPressed() or
  16415. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16416. If you add an object as a key listener, be careful to remove it when the object
  16417. is deleted, or the component will be left with a dangling pointer.
  16418. @see keyPressed, keyStateChanged, removeKeyListener
  16419. */
  16420. void addKeyListener (KeyListener* const newListener) throw();
  16421. /** Removes a previously-registered key listener.
  16422. @see addKeyListener
  16423. */
  16424. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16425. /** Called when a key is pressed.
  16426. When a key is pressed, the component that has the keyboard focus will have this
  16427. method called. Remember that a component will only be given the focus if its
  16428. setWantsKeyboardFocus() method has been used to enable this.
  16429. If your implementation returns true, the event will be consumed and not passed
  16430. on to any other listeners. If it returns false, the key will be passed to any
  16431. KeyListeners that have been registered with this component. As soon as one of these
  16432. returns true, the process will stop, but if they all return false, the event will
  16433. be passed upwards to this component's parent, and so on.
  16434. The default implementation of this method does nothing and returns false.
  16435. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16436. */
  16437. virtual bool keyPressed (const KeyPress& key);
  16438. /** Called when a key is pressed or released.
  16439. Whenever a key on the keyboard is pressed or released (including modifier keys
  16440. like shift and ctrl), this method will be called on the component that currently
  16441. has the keyboard focus. Remember that a component will only be given the focus if
  16442. its setWantsKeyboardFocus() method has been used to enable this.
  16443. If your implementation returns true, the event will be consumed and not passed
  16444. on to any other listeners. If it returns false, then any KeyListeners that have
  16445. been registered with this component will have their keyStateChanged methods called.
  16446. As soon as one of these returns true, the process will stop, but if they all return
  16447. false, the event will be passed upwards to this component's parent, and so on.
  16448. The default implementation of this method does nothing and returns false.
  16449. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16450. method.
  16451. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16452. */
  16453. virtual bool keyStateChanged();
  16454. /** Called when a modifier key is pressed or released.
  16455. Whenever the shift, control, alt or command keys are pressed or released,
  16456. this method will be called on the component that currently has the keyboard focus.
  16457. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16458. method has been used to enable this.
  16459. The default implementation of this method actually calls its parent's modifierKeysChanged
  16460. method, so that focused components which aren't interested in this will give their
  16461. parents a chance to act on the event instead.
  16462. @see keyStateChanged, ModifierKeys
  16463. */
  16464. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16465. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16466. enum FocusChangeType
  16467. {
  16468. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16469. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16470. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16471. };
  16472. /** Called to indicate that this component has just acquired the keyboard focus.
  16473. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16474. */
  16475. virtual void focusGained (FocusChangeType cause);
  16476. /** Called to indicate that this component has just lost the keyboard focus.
  16477. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16478. */
  16479. virtual void focusLost (FocusChangeType cause);
  16480. /** Called to indicate that one of this component's children has been focused or unfocused.
  16481. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16482. changed. It happens when focus moves from one of this component's children (at any depth)
  16483. to a component that isn't contained in this one, (or vice-versa).
  16484. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16485. */
  16486. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16487. /** Returns true if the mouse is currently over this component.
  16488. If the mouse isn't over the component, this will return false, even if the
  16489. mouse is currently being dragged - so you can use this in your mouseDrag
  16490. method to find out whether it's really over the component or not.
  16491. Note that when the mouse button is being held down, then the only component
  16492. for which this method will return true is the one that was originally
  16493. clicked on.
  16494. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16495. */
  16496. bool isMouseOver() const throw();
  16497. /** Returns true if the mouse button is currently held down in this component.
  16498. Note that this is a test to see whether the mouse is being pressed in this
  16499. component, so it'll return false if called on component A when the mouse
  16500. is actually being dragged in component B.
  16501. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16502. */
  16503. bool isMouseButtonDown() const throw();
  16504. /** True if the mouse is over this component, or if it's being dragged in this component.
  16505. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16506. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16507. */
  16508. bool isMouseOverOrDragging() const throw();
  16509. /** Returns true if a mouse button is currently down.
  16510. Unlike isMouseButtonDown, this will test the current state of the
  16511. buttons without regard to which component (if any) it has been
  16512. pressed in.
  16513. @see isMouseButtonDown, ModifierKeys
  16514. */
  16515. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16516. /** Returns the mouse's current position, relative to this component.
  16517. The co-ordinates are relative to the component's top-left corner.
  16518. */
  16519. void getMouseXYRelative (int& x, int& y) const throw();
  16520. /** Returns the component that's currently underneath the mouse.
  16521. @returns the component or 0 if there isn't one.
  16522. @see contains, getComponentAt
  16523. */
  16524. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16525. /** Allows the mouse to move beyond the edges of the screen.
  16526. Calling this method when the mouse button is currently pressed inside this component
  16527. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16528. the edges of the screen.
  16529. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16530. can be used for things like custom slider controls or dragging objects around, where
  16531. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16532. The unbounded mode is automatically turned off when the mouse button is released, or
  16533. it can be turned off explicitly by calling this method again.
  16534. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16535. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16536. hidden; if true, it will only be hidden when it
  16537. is moved beyond the edge of the screen
  16538. */
  16539. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16540. bool keepCursorVisibleUntilOffscreen = false) throw();
  16541. /** Called when this component's size has been changed.
  16542. A component can implement this method to do things such as laying out its
  16543. child components when its width or height changes.
  16544. The method is called synchronously as a result of the setBounds or setSize
  16545. methods, so repeatedly changing a components size will repeatedly call its
  16546. resized method (unlike things like repainting, where multiple calls to repaint
  16547. are coalesced together).
  16548. If the component is a top-level window on the desktop, its size could also
  16549. be changed by operating-system factors beyond the application's control.
  16550. @see moved, setSize
  16551. */
  16552. virtual void resized();
  16553. /** Called when this component's position has been changed.
  16554. This is called when the position relative to its parent changes, not when
  16555. its absolute position on the screen changes (so it won't be called for
  16556. all child components when a parent component is moved).
  16557. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16558. or any of the other repositioning methods, and like resized(), it will be
  16559. called each time those methods are called.
  16560. If the component is a top-level window on the desktop, its position could also
  16561. be changed by operating-system factors beyond the application's control.
  16562. @see resized, setBounds
  16563. */
  16564. virtual void moved();
  16565. /** Called when one of this component's children is moved or resized.
  16566. If the parent wants to know about changes to its immediate children (not
  16567. to children of its children), this is the method to override.
  16568. @see moved, resized, parentSizeChanged
  16569. */
  16570. virtual void childBoundsChanged (Component* child);
  16571. /** Called when this component's immediate parent has been resized.
  16572. If the component is a top-level window, this indicates that the screen size
  16573. has changed.
  16574. @see childBoundsChanged, moved, resized
  16575. */
  16576. virtual void parentSizeChanged();
  16577. /** Called when this component has been moved to the front of its siblings.
  16578. The component may have been brought to the front by the toFront() method, or
  16579. by the operating system if it's a top-level window.
  16580. @see toFront
  16581. */
  16582. virtual void broughtToFront();
  16583. /** Adds a listener to be told about changes to the component hierarchy or position.
  16584. Component listeners get called when this component's size, position or children
  16585. change - see the ComponentListener class for more details.
  16586. @param newListener the listener to register - if this is already registered, it
  16587. will be ignored.
  16588. @see ComponentListener, removeComponentListener
  16589. */
  16590. void addComponentListener (ComponentListener* const newListener) throw();
  16591. /** Removes a component listener.
  16592. @see addComponentListener
  16593. */
  16594. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16595. /** Dispatches a numbered message to this component.
  16596. This is a quick and cheap way of allowing simple asynchronous messages to
  16597. be sent to components. It's also safe, because if the component that you
  16598. send the message to is a null or dangling pointer, this won't cause an error.
  16599. The command ID is later delivered to the component's handleCommandMessage() method by
  16600. the application's message queue.
  16601. @see handleCommandMessage
  16602. */
  16603. void postCommandMessage (const int commandId) throw();
  16604. /** Called to handle a command that was sent by postCommandMessage().
  16605. This is called by the message thread when a command message arrives, and
  16606. the component can override this method to process it in any way it needs to.
  16607. @see postCommandMessage
  16608. */
  16609. virtual void handleCommandMessage (int commandId);
  16610. /** Runs a component modally, waiting until the loop terminates.
  16611. This method first makes the component visible, brings it to the front and
  16612. gives it the keyboard focus.
  16613. It then runs a loop, dispatching messages from the system message queue, but
  16614. blocking all mouse or keyboard messages from reaching any components other
  16615. than this one and its children.
  16616. This loop continues until the component's exitModalState() method is called (or
  16617. the component is deleted), and then this method returns, returning the value
  16618. passed into exitModalState().
  16619. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16620. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16621. */
  16622. int runModalLoop();
  16623. /** Puts the component into a modal state.
  16624. This makes the component modal, so that messages are blocked from reaching
  16625. any components other than this one and its children, but unlike runModalLoop(),
  16626. this method returns immediately.
  16627. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16628. get the focus, which is usually what you'll want it to do. If not, it will leave
  16629. the focus unchanged.
  16630. @see exitModalState, runModalLoop
  16631. */
  16632. void enterModalState (const bool takeKeyboardFocus = true);
  16633. /** Ends a component's modal state.
  16634. If this component is currently modal, this will turn of its modalness, and return
  16635. a value to the runModalLoop() method that might have be running its modal loop.
  16636. @see runModalLoop, enterModalState, isCurrentlyModal
  16637. */
  16638. void exitModalState (const int returnValue);
  16639. /** Returns true if this component is the modal one.
  16640. It's possible to have nested modal components, e.g. a pop-up dialog box
  16641. that launches another pop-up, but this will only return true for
  16642. the one at the top of the stack.
  16643. @see getCurrentlyModalComponent
  16644. */
  16645. bool isCurrentlyModal() const throw();
  16646. /** Returns the component that is currently modal.
  16647. @returns the modal component, or null if no components are modal
  16648. @see runModalLoop, isCurrentlyModal
  16649. */
  16650. static Component* JUCE_CALLTYPE getCurrentlyModalComponent() throw();
  16651. /** Checks whether there's a modal component somewhere that's stopping this one
  16652. from receiving messages.
  16653. If there is a modal component, its canModalEventBeSentToComponent() method
  16654. will be called to see if it will still allow this component to receive events.
  16655. @see runModalLoop, getCurrentlyModalComponent
  16656. */
  16657. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16658. /** When a component is modal, this callback allows it to choose which other
  16659. components can still receive events.
  16660. When a modal component is active and the user clicks on a non-modal component,
  16661. this method is called on the modal component, and if it returns true, the
  16662. event is allowed to reach its target. If it returns false, the event is blocked
  16663. and the inputAttemptWhenModal() callback is made.
  16664. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16665. implementation just returns false in all cases.
  16666. */
  16667. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16668. /** Called when the user tries to click on a component that is blocked by another
  16669. modal component.
  16670. When a component is modal and the user clicks on one of the other components,
  16671. the modal component will receive this callback.
  16672. The default implementation of this method will play a beep, and bring the currently
  16673. modal component to the front, but it can be overridden to do other tasks.
  16674. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16675. */
  16676. virtual void inputAttemptWhenModal();
  16677. /** Returns one of the component's properties as a string.
  16678. @param keyName the name of the property to retrieve
  16679. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16680. properties, then it will check whether the parent component has
  16681. the key.
  16682. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16683. */
  16684. const String getComponentProperty (const String& keyName,
  16685. const bool useParentComponentIfNotFound,
  16686. const String& defaultReturnValue = String::empty) const throw();
  16687. /** Returns one of the properties as an integer.
  16688. @param keyName the name of the property to retrieve
  16689. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16690. properties, then it will check whether the parent component has
  16691. the key.
  16692. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16693. */
  16694. int getComponentPropertyInt (const String& keyName,
  16695. const bool useParentComponentIfNotFound,
  16696. const int defaultReturnValue = 0) const throw();
  16697. /** Returns one of the properties as an double.
  16698. @param keyName the name of the property to retrieve
  16699. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16700. properties, then it will check whether the parent component has
  16701. the key.
  16702. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16703. */
  16704. double getComponentPropertyDouble (const String& keyName,
  16705. const bool useParentComponentIfNotFound,
  16706. const double defaultReturnValue = 0.0) const throw();
  16707. /** Returns one of the properties as an boolean.
  16708. The result will be true if the string found for this key name can be parsed as a non-zero
  16709. integer.
  16710. @param keyName the name of the property to retrieve
  16711. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16712. properties, then it will check whether the parent component has
  16713. the key.
  16714. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16715. */
  16716. bool getComponentPropertyBool (const String& keyName,
  16717. const bool useParentComponentIfNotFound,
  16718. const bool defaultReturnValue = false) const throw();
  16719. /** Returns one of the properties as an colour.
  16720. @param keyName the name of the property to retrieve
  16721. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16722. properties, then it will check whether the parent component has
  16723. the key.
  16724. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16725. */
  16726. const Colour getComponentPropertyColour (const String& keyName,
  16727. const bool useParentComponentIfNotFound,
  16728. const Colour& defaultReturnValue = Colours::black) const throw();
  16729. /** Sets a named property as a string.
  16730. @param keyName the name of the property to set. (This mustn't be an empty string)
  16731. @param value the new value to set it to
  16732. @see removeComponentProperty
  16733. */
  16734. void setComponentProperty (const String& keyName, const String& value) throw();
  16735. /** Sets a named property to an integer.
  16736. @param keyName the name of the property to set. (This mustn't be an empty string)
  16737. @param value the new value to set it to
  16738. @see removeComponentProperty
  16739. */
  16740. void setComponentProperty (const String& keyName, const int value) throw();
  16741. /** Sets a named property to a double.
  16742. @param keyName the name of the property to set. (This mustn't be an empty string)
  16743. @param value the new value to set it to
  16744. @see removeComponentProperty
  16745. */
  16746. void setComponentProperty (const String& keyName, const double value) throw();
  16747. /** Sets a named property to a boolean.
  16748. @param keyName the name of the property to set. (This mustn't be an empty string)
  16749. @param value the new value to set it to
  16750. @see removeComponentProperty
  16751. */
  16752. void setComponentProperty (const String& keyName, const bool value) throw();
  16753. /** Sets a named property to a colour.
  16754. @param keyName the name of the property to set. (This mustn't be an empty string)
  16755. @param newColour the new colour to set it to
  16756. @see removeComponentProperty
  16757. */
  16758. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16759. /** Deletes a named component property.
  16760. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16761. @see setComponentProperty, getComponentProperty
  16762. */
  16763. void removeComponentProperty (const String& keyName) throw();
  16764. /** Returns the complete set of properties that have been set for this component.
  16765. If no properties have been set, this will return a null pointer.
  16766. @see getComponentProperty, setComponentProperty
  16767. */
  16768. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16769. /** Looks for a colour that has been registered with the given colour ID number.
  16770. If a colour has been set for this ID number using setColour(), then it is
  16771. returned. If none has been set, the method will try calling the component's
  16772. LookAndFeel class's findColour() method. If none has been registered with the
  16773. look-and-feel either, it will just return black.
  16774. The colour IDs for various purposes are stored as enums in the components that
  16775. they are relevent to - for an example, see Slider::ColourIds,
  16776. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16777. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16778. */
  16779. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16780. /** Registers a colour to be used for a particular purpose.
  16781. Changing a colour will cause a synchronous callback to the colourChanged()
  16782. method, which your component can override if it needs to do something when
  16783. colours are altered.
  16784. For more details about colour IDs, see the comments for findColour().
  16785. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16786. */
  16787. void setColour (const int colourId, const Colour& colour);
  16788. /** If a colour has been set with setColour(), this will remove it.
  16789. This allows you to make a colour revert to its default state.
  16790. */
  16791. void removeColour (const int colourId);
  16792. /** Returns true if the specified colour ID has been explicitly set for this
  16793. component using the setColour() method.
  16794. */
  16795. bool isColourSpecified (const int colourId) const throw();
  16796. /** This looks for any colours that have been specified for this component,
  16797. and copies them to the specified target component.
  16798. */
  16799. void copyAllExplicitColoursTo (Component& target) const throw();
  16800. /** This method is called when a colour is changed by the setColour() method.
  16801. @see setColour, findColour
  16802. */
  16803. virtual void colourChanged();
  16804. /** Returns the underlying native window handle for this component.
  16805. This is platform-dependent and strictly for power-users only!
  16806. */
  16807. void* getWindowHandle() const throw();
  16808. /** When created, each component is given a number to uniquely identify it.
  16809. The number is incremented each time a new component is created, so it's a more
  16810. unique way of identifying a component than using its memory location (which
  16811. may be reused after the component is deleted, of course).
  16812. */
  16813. uint32 getComponentUID() const throw() { return componentUID; }
  16814. juce_UseDebuggingNewOperator
  16815. private:
  16816. friend class ComponentPeer;
  16817. friend class InternalDragRepeater;
  16818. static Component* currentlyFocusedComponent;
  16819. static Component* componentUnderMouse;
  16820. String componentName_;
  16821. Component* parentComponent_;
  16822. uint32 componentUID;
  16823. Rectangle bounds_;
  16824. unsigned short numDeepMouseListeners;
  16825. Array <Component*> childComponentList_;
  16826. LookAndFeel* lookAndFeel_;
  16827. MouseCursor cursor_;
  16828. ImageEffectFilter* effect_;
  16829. Image* bufferedImage_;
  16830. VoidArray* mouseListeners_;
  16831. VoidArray* keyListeners_;
  16832. VoidArray* componentListeners_;
  16833. PropertySet* propertySet_;
  16834. struct ComponentFlags
  16835. {
  16836. bool hasHeavyweightPeerFlag : 1;
  16837. bool visibleFlag : 1;
  16838. bool opaqueFlag : 1;
  16839. bool ignoresMouseClicksFlag : 1;
  16840. bool allowChildMouseClicksFlag : 1;
  16841. bool wantsFocusFlag : 1;
  16842. bool isFocusContainerFlag : 1;
  16843. bool dontFocusOnMouseClickFlag : 1;
  16844. bool alwaysOnTopFlag : 1;
  16845. bool bufferToImageFlag : 1;
  16846. bool bringToFrontOnClickFlag : 1;
  16847. bool repaintOnMouseActivityFlag : 1;
  16848. bool draggingFlag : 1;
  16849. bool mouseOverFlag : 1;
  16850. bool mouseInsideFlag : 1;
  16851. bool currentlyModalFlag : 1;
  16852. bool isDisabledFlag : 1;
  16853. bool childCompFocusedFlag : 1;
  16854. #ifdef JUCE_DEBUG
  16855. bool isInsidePaintCall : 1;
  16856. #endif
  16857. };
  16858. union
  16859. {
  16860. uint32 componentFlags_;
  16861. ComponentFlags flags;
  16862. };
  16863. void internalMouseEnter (int x, int y, const int64 time);
  16864. void internalMouseExit (int x, int y, const int64 time);
  16865. void internalMouseDown (int x, int y);
  16866. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16867. void internalMouseDrag (int x, int y, const int64 time);
  16868. void internalMouseMove (int x, int y, const int64 time);
  16869. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  16870. void internalBroughtToFront();
  16871. void internalFocusGain (const FocusChangeType cause);
  16872. void internalFocusLoss (const FocusChangeType cause);
  16873. void internalChildFocusChange (FocusChangeType cause);
  16874. void internalModalInputAttempt();
  16875. void internalModifierKeysChanged();
  16876. void internalChildrenChanged();
  16877. void internalHierarchyChanged();
  16878. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  16879. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  16880. void repaintParent() throw();
  16881. void sendFakeMouseMove() const;
  16882. void takeKeyboardFocus (const FocusChangeType cause);
  16883. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  16884. static void giveAwayFocus();
  16885. void sendEnablementChangeMessage();
  16886. static void* runModalLoopCallback (void*);
  16887. void subtractObscuredRegions (RectangleList& result,
  16888. const int deltaX, const int deltaY,
  16889. const Rectangle& clipRect,
  16890. const Component* const compToAvoid) const throw();
  16891. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  16892. const int deltaX, const int deltaY) const throw();
  16893. // how much of the component is not off the edges of its parents
  16894. const Rectangle getUnclippedArea() const;
  16895. void sendVisibilityChangeMessage();
  16896. // This is included here just to cause a compile error if your code is still handling
  16897. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  16898. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  16899. // implement its methods instead of this Component method).
  16900. virtual void filesDropped (const StringArray&, int, int) {}
  16901. // components aren't allowed to have copy constructors, as this would mess up parent
  16902. // hierarchies. You might need to give your subclasses a private dummy constructor like
  16903. // this one to avoid compiler warnings.
  16904. Component (const Component&);
  16905. const Component& operator= (const Component&);
  16906. protected:
  16907. /** @internal */
  16908. virtual void internalRepaint (int x, int y, int w, int h);
  16909. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  16910. /** Overridden from the MessageListener parent class.
  16911. You can override this if you really need to, but be sure to pass your unwanted messages up
  16912. to this base class implementation, as the Component class needs to send itself messages
  16913. to work properly.
  16914. */
  16915. void handleMessage (const Message&);
  16916. };
  16917. #endif // __JUCE_COMPONENT_JUCEHEADER__
  16918. /********* End of inlined file: juce_Component.h *********/
  16919. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  16920. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16921. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16922. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  16923. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16924. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16925. /** A type used to hold the unique ID for an application command.
  16926. This is a numeric type, so it can be stored as an integer.
  16927. @see ApplicationCommandInfo, ApplicationCommandManager,
  16928. ApplicationCommandTarget, KeyPressMappingSet
  16929. */
  16930. typedef int CommandID;
  16931. /** A set of general-purpose application command IDs.
  16932. Because these commands are likely to be used in most apps, they're defined
  16933. here to help different apps to use the same numeric values for them.
  16934. Of course you don't have to use these, but some of them are used internally by
  16935. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  16936. @see ApplicationCommandInfo, ApplicationCommandManager,
  16937. ApplicationCommandTarget, KeyPressMappingSet
  16938. */
  16939. namespace StandardApplicationCommandIDs
  16940. {
  16941. /** This command ID should be used to send a "Quit the App" command.
  16942. This command is recognised by the JUCEApplication class, so if it is invoked
  16943. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  16944. object will catch it and call JUCEApplication::systemRequestedQuit().
  16945. */
  16946. static const CommandID quit = 0x1001;
  16947. /** The command ID that should be used to send a "Delete" command. */
  16948. static const CommandID del = 0x1002;
  16949. /** The command ID that should be used to send a "Cut" command. */
  16950. static const CommandID cut = 0x1003;
  16951. /** The command ID that should be used to send a "Copy to clipboard" command. */
  16952. static const CommandID copy = 0x1004;
  16953. /** The command ID that should be used to send a "Paste from clipboard" command. */
  16954. static const CommandID paste = 0x1005;
  16955. /** The command ID that should be used to send a "Select all" command. */
  16956. static const CommandID selectAll = 0x1006;
  16957. /** The command ID that should be used to send a "Deselect all" command. */
  16958. static const CommandID deselectAll = 0x1007;
  16959. }
  16960. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16961. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  16962. /**
  16963. Holds information describing an application command.
  16964. This object is used to pass information about a particular command, such as its
  16965. name, description and other usage flags.
  16966. When an ApplicationCommandTarget is asked to provide information about the commands
  16967. it can perform, this is the structure gets filled-in to describe each one.
  16968. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  16969. ApplicationCommandManager
  16970. */
  16971. struct JUCE_API ApplicationCommandInfo
  16972. {
  16973. ApplicationCommandInfo (const CommandID commandID) throw();
  16974. /** Sets a number of the structures values at once.
  16975. The meanings of each of the parameters is described below, in the appropriate
  16976. member variable's description.
  16977. */
  16978. void setInfo (const String& shortName,
  16979. const String& description,
  16980. const String& categoryName,
  16981. const int flags) throw();
  16982. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  16983. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  16984. is false, the bit is set.
  16985. */
  16986. void setActive (const bool isActive) throw();
  16987. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  16988. */
  16989. void setTicked (const bool isTicked) throw();
  16990. /** Handy method for adding a keypress to the defaultKeypresses array.
  16991. This is just so you can write things like:
  16992. @code
  16993. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  16994. @endcode
  16995. instead of
  16996. @code
  16997. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  16998. @endcode
  16999. */
  17000. void addDefaultKeypress (const int keyCode,
  17001. const ModifierKeys& modifiers) throw();
  17002. /** The command's unique ID number.
  17003. */
  17004. CommandID commandID;
  17005. /** A short name to describe the command.
  17006. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17007. You can use the setInfo() method to quickly set this and some of the command's
  17008. other properties.
  17009. */
  17010. String shortName;
  17011. /** A longer description of the command.
  17012. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17013. pop-up tooltip describing what the command does.
  17014. You can use the setInfo() method to quickly set this and some of the command's
  17015. other properties.
  17016. */
  17017. String description;
  17018. /** A named category that the command fits into.
  17019. You can give your commands any category you like, and these will be displayed in
  17020. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17021. commands together.
  17022. You can use the setInfo() method to quickly set this and some of the command's
  17023. other properties.
  17024. */
  17025. String categoryName;
  17026. /** A list of zero or more keypresses that should be used as the default keys for
  17027. this command.
  17028. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17029. this list to initialise the default set of key-to-command mappings.
  17030. @see addDefaultKeypress
  17031. */
  17032. Array <KeyPress> defaultKeypresses;
  17033. /** Flags describing the ways in which this command should be used.
  17034. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17035. variable.
  17036. */
  17037. enum CommandFlags
  17038. {
  17039. /** Indicates that the command can't currently be performed.
  17040. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17041. not currently permissable to perform the command. If the flag is set, then
  17042. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17043. command or show themselves as not being enabled.
  17044. @see ApplicationCommandInfo::setActive
  17045. */
  17046. isDisabled = 1 << 0,
  17047. /** Indicates that the command should have a tick next to it on a menu.
  17048. If your command is shown on a menu and this is set, it'll show a tick next to
  17049. it. Other components such as buttons may also use this flag to indicate that it
  17050. is a value that can be toggled, and is currently in the 'on' state.
  17051. @see ApplicationCommandInfo::setTicked
  17052. */
  17053. isTicked = 1 << 1,
  17054. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17055. it will call the command twice, once on key-down and again on key-up.
  17056. @see ApplicationCommandTarget::InvocationInfo
  17057. */
  17058. wantsKeyUpDownCallbacks = 1 << 2,
  17059. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17060. command in its list.
  17061. */
  17062. hiddenFromKeyEditor = 1 << 3,
  17063. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17064. command in its list, but won't allow the assigned keypress to be changed.
  17065. */
  17066. readOnlyInKeyEditor = 1 << 4,
  17067. /** If this flag is present and the command is invoked from a keypress, then any
  17068. buttons or menus that are also connected to the command will not flash to
  17069. indicate that they've been triggered.
  17070. */
  17071. dontTriggerVisualFeedback = 1 << 5
  17072. };
  17073. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17074. You can use the setInfo() method to quickly set this and some of the command's
  17075. other properties.
  17076. */
  17077. int flags;
  17078. };
  17079. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17080. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17081. /**
  17082. A command target publishes a list of command IDs that it can perform.
  17083. An ApplicationCommandManager despatches commands to targets, which must be
  17084. able to provide information about what commands they can handle.
  17085. To create a target, you'll need to inherit from this class, implementing all of
  17086. its pure virtual methods.
  17087. For info about how a target is chosen to receive a command, see
  17088. ApplicationCommandManager::getFirstCommandTarget().
  17089. @see ApplicationCommandManager, ApplicationCommandInfo
  17090. */
  17091. class JUCE_API ApplicationCommandTarget
  17092. {
  17093. public:
  17094. /** Creates a command target. */
  17095. ApplicationCommandTarget();
  17096. /** Destructor. */
  17097. virtual ~ApplicationCommandTarget();
  17098. /**
  17099. */
  17100. struct JUCE_API InvocationInfo
  17101. {
  17102. InvocationInfo (const CommandID commandID) throw();
  17103. /** The UID of the command that should be performed. */
  17104. CommandID commandID;
  17105. /** The command's flags.
  17106. See ApplicationCommandInfo for a description of these flag values.
  17107. */
  17108. int commandFlags;
  17109. /** The types of context in which the command might be called. */
  17110. enum InvocationMethod
  17111. {
  17112. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17113. fromKeyPress, /**< The command is being invoked by a key-press. */
  17114. fromMenu, /**< The command is being invoked by a menu selection. */
  17115. fromButton /**< The command is being invoked by a button click. */
  17116. };
  17117. /** The type of event that triggered this command. */
  17118. InvocationMethod invocationMethod;
  17119. /** If triggered by a keypress or menu, this will be the component that had the
  17120. keyboard focus at the time.
  17121. If triggered by a button, it may be set to that component, or it may be null.
  17122. */
  17123. Component* originatingComponent;
  17124. /** The keypress that was used to invoke it.
  17125. Note that this will be an invalid keypress if the command was invoked
  17126. by some other means than a keyboard shortcut.
  17127. */
  17128. KeyPress keyPress;
  17129. /** True if the callback is being invoked when the key is pressed,
  17130. false if the key is being released.
  17131. @see KeyPressMappingSet::addCommand()
  17132. */
  17133. bool isKeyDown;
  17134. /** If the key is being released, this indicates how long it had been held
  17135. down for.
  17136. (Only relevant if isKeyDown is false.)
  17137. */
  17138. int millisecsSinceKeyPressed;
  17139. };
  17140. /** This must return the next target to try after this one.
  17141. When a command is being sent, and the first target can't handle
  17142. that command, this method is used to determine the next target that should
  17143. be tried.
  17144. It may return 0 if it doesn't know of another target.
  17145. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17146. method to return a parent component that might want to handle it.
  17147. @see invoke
  17148. */
  17149. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17150. /** This must return a complete list of commands that this target can handle.
  17151. Your target should add all the command IDs that it handles to the array that is
  17152. passed-in.
  17153. */
  17154. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17155. /** This must provide details about one of the commands that this target can perform.
  17156. This will be called with one of the command IDs that the target provided in its
  17157. getAllCommands() methods.
  17158. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17159. suitable information about the command. (The commandID field will already have been filled-in
  17160. by the caller).
  17161. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17162. set all the fields at once.
  17163. If the command is currently inactive for some reason, this method must use
  17164. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17165. bit of the ApplicationCommandInfo::flags field).
  17166. Any default key-presses for the command should be appended to the
  17167. ApplicationCommandInfo::defaultKeypresses field.
  17168. Note that if you change something that affects the status of the commands
  17169. that would be returned by this method (e.g. something that makes some commands
  17170. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17171. to cause the manager to refresh its status.
  17172. */
  17173. virtual void getCommandInfo (const CommandID commandID,
  17174. ApplicationCommandInfo& result) = 0;
  17175. /** This must actually perform the specified command.
  17176. If this target is able to perform the command specified by the commandID field of the
  17177. InvocationInfo structure, then it should do so, and must return true.
  17178. If it can't handle this command, it should return false, which tells the caller to pass
  17179. the command on to the next target in line.
  17180. @see invoke, ApplicationCommandManager::invoke
  17181. */
  17182. virtual bool perform (const InvocationInfo& info) = 0;
  17183. /** Makes this target invoke a command.
  17184. Your code can call this method to invoke a command on this target, but normally
  17185. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17186. ApplicationCommandManager::invokeDirectly().
  17187. If this target can perform the given command, it will call its perform() method to
  17188. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17189. to try, and the command will be passed along to it.
  17190. @param invocationInfo this must be correctly filled-in, describing the context for
  17191. the invocation.
  17192. @param asynchronously if false, the command will be performed before this method returns.
  17193. If true, a message will be posted so that the command will be performed
  17194. later on the message thread, and this method will return immediately.
  17195. @see perform, ApplicationCommandManager::invoke
  17196. */
  17197. bool invoke (const InvocationInfo& invocationInfo,
  17198. const bool asynchronously);
  17199. /** Invokes a given command directly on this target.
  17200. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17201. structure.
  17202. */
  17203. bool invokeDirectly (const CommandID commandID,
  17204. const bool asynchronously);
  17205. /** Searches this target and all subsequent ones for the first one that can handle
  17206. the specified command.
  17207. This will use getNextCommandTarget() to determine the chain of targets to try
  17208. after this one.
  17209. */
  17210. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17211. /** Checks whether this command can currently be performed by this target.
  17212. This will return true only if a call to getCommandInfo() doesn't set the
  17213. isDisabled flag to indicate that the command is inactive.
  17214. */
  17215. bool isCommandActive (const CommandID commandID);
  17216. /** If this object is a Component, this method will seach upwards in its current
  17217. UI hierarchy for the next parent component that implements the
  17218. ApplicationCommandTarget class.
  17219. If your target is a Component, this is a very handy method to use in your
  17220. getNextCommandTarget() implementation.
  17221. */
  17222. ApplicationCommandTarget* findFirstTargetParentComponent();
  17223. juce_UseDebuggingNewOperator
  17224. private:
  17225. // (for async invocation of commands)
  17226. class CommandTargetMessageInvoker : public MessageListener
  17227. {
  17228. public:
  17229. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17230. ~CommandTargetMessageInvoker();
  17231. void handleMessage (const Message& message);
  17232. private:
  17233. ApplicationCommandTarget* const owner;
  17234. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17235. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17236. };
  17237. CommandTargetMessageInvoker* messageInvoker;
  17238. friend class CommandTargetMessageInvoker;
  17239. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17240. };
  17241. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17242. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17243. /********* Start of inlined file: juce_ActionListener.h *********/
  17244. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17245. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17246. /**
  17247. Receives callbacks to indicate that some kind of event has occurred.
  17248. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17249. about something that's happened.
  17250. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17251. */
  17252. class JUCE_API ActionListener
  17253. {
  17254. public:
  17255. /** Destructor. */
  17256. virtual ~ActionListener() {}
  17257. /** Overridden by your subclass to receive the callback.
  17258. @param message the string that was specified when the event was triggered
  17259. by a call to ActionListenerList::sendActionMessage()
  17260. */
  17261. virtual void actionListenerCallback (const String& message) = 0;
  17262. };
  17263. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17264. /********* End of inlined file: juce_ActionListener.h *********/
  17265. /**
  17266. An instance of this class is used to specify initialisation and shutdown
  17267. code for the application.
  17268. An application that wants to run in the JUCE framework needs to declare a
  17269. subclass of JUCEApplication and implement its various pure virtual methods.
  17270. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17271. to declare an instance of this class and generate a suitable platform-specific
  17272. main() function.
  17273. e.g. @code
  17274. class MyJUCEApp : public JUCEApplication
  17275. {
  17276. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17277. // objects, which you must create in the initialise() method.
  17278. MyApplicationWindow* myMainWindow;
  17279. public:
  17280. MyJUCEApp()
  17281. : myMainWindow (0)
  17282. {
  17283. // never create any Juce objects in the constructor - do all your initialisation
  17284. // in the initialise() method.
  17285. }
  17286. ~MyJUCEApp()
  17287. {
  17288. // all your shutdown code must have already been done in the shutdown() method -
  17289. // nothing should happen in this destructor.
  17290. }
  17291. void initialise (const String& commandLine)
  17292. {
  17293. myMainWindow = new MyApplicationWindow();
  17294. myMainWindow->setBounds (100, 100, 400, 500);
  17295. myMainWindow->setVisible (true);
  17296. }
  17297. void shutdown()
  17298. {
  17299. delete myMainWindow;
  17300. }
  17301. const String getApplicationName()
  17302. {
  17303. return T("Super JUCE-o-matic");
  17304. }
  17305. const String getApplicationVersion()
  17306. {
  17307. return T("1.0");
  17308. }
  17309. };
  17310. // this creates wrapper code to actually launch the app properly.
  17311. START_JUCE_APPLICATION (MyJUCEApp)
  17312. @endcode
  17313. Because this object will be created before Juce has properly initialised, you must
  17314. NEVER add any member variable objects that will be automatically constructed. Likewise
  17315. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17316. you want to add to the class must be pointers, which you should instantiate during the
  17317. initialise() method, and delete in the shutdown() method.
  17318. @see MessageManager, DeletedAtShutdown
  17319. */
  17320. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17321. private ActionListener
  17322. {
  17323. protected:
  17324. /** Constructs a JUCE app object.
  17325. If subclasses implement a constructor or destructor, they shouldn't call any
  17326. JUCE code in there - put your startup/shutdown code in initialise() and
  17327. shutdown() instead.
  17328. */
  17329. JUCEApplication();
  17330. public:
  17331. /** Destructor.
  17332. If subclasses implement a constructor or destructor, they shouldn't call any
  17333. JUCE code in there - put your startup/shutdown code in initialise() and
  17334. shutdown() instead.
  17335. */
  17336. virtual ~JUCEApplication();
  17337. /** Returns the global instance of the application object being run. */
  17338. static JUCEApplication* getInstance() throw();
  17339. /** Called when the application starts.
  17340. This will be called once to let the application do whatever initialisation
  17341. it needs, create its windows, etc.
  17342. After the method returns, the normal event-dispatch loop will be run,
  17343. until the quit() method is called, at which point the shutdown()
  17344. method will be called to let the application clear up anything it needs
  17345. to delete.
  17346. If during the initialise() method, the application decides not to start-up
  17347. after all, it can just call the quit() method and the event loop won't be run.
  17348. @param commandLineParameters the line passed in does not include the
  17349. name of the executable, just the parameter list.
  17350. @see shutdown, quit
  17351. */
  17352. virtual void initialise (const String& commandLineParameters) = 0;
  17353. /** Returns true if the application hasn't yet completed its initialise() method
  17354. and entered the main event loop.
  17355. This is handy for things like splash screens to know when the app's up-and-running
  17356. properly.
  17357. */
  17358. bool isInitialising() const throw();
  17359. /* Called to allow the application to clear up before exiting.
  17360. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17361. terminate, and this method will get called to allow the app to sort itself
  17362. out.
  17363. Be careful that nothing happens in this method that might rely on messages
  17364. being sent, or any kind of window activity, because the message loop is no
  17365. longer running at this point.
  17366. @see DeletedAtShutdown
  17367. */
  17368. virtual void shutdown() = 0;
  17369. /** Returns the application's name.
  17370. An application must implement this to name itself.
  17371. */
  17372. virtual const String getApplicationName() = 0;
  17373. /** Returns the application's version number.
  17374. An application can implement this to give itself a version.
  17375. (The default implementation of this just returns an empty string).
  17376. */
  17377. virtual const String getApplicationVersion();
  17378. /** Checks whether multiple instances of the app are allowed.
  17379. If you application class returns true for this, more than one instance is
  17380. permitted to run (except on the Mac where this isn't possible).
  17381. If it's false, the second instance won't start, but it you will still get a
  17382. callback to anotherInstanceStarted() to tell you about this - which
  17383. gives you a chance to react to what the user was trying to do.
  17384. */
  17385. virtual bool moreThanOneInstanceAllowed();
  17386. /** Indicates that the user has tried to start up another instance of the app.
  17387. This will get called even if moreThanOneInstanceAllowed() is false.
  17388. */
  17389. virtual void anotherInstanceStarted (const String& commandLine);
  17390. /** Called when the operating system is trying to close the application.
  17391. The default implementation of this method is to call quit(), but it may
  17392. be overloaded to ignore the request or do some other special behaviour
  17393. instead. For example, you might want to offer the user the chance to save
  17394. their changes before quitting, and give them the chance to cancel.
  17395. If you want to send a quit signal to your app, this is the correct method
  17396. to call, because it means that requests that come from the system get handled
  17397. in the same way as those from your own application code. So e.g. you'd
  17398. call this method from a "quit" item on a menu bar.
  17399. */
  17400. virtual void systemRequestedQuit();
  17401. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17402. callback will be triggered, in case you want to log them or do some other
  17403. type of error-handling.
  17404. If the type of exception is derived from the std::exception class, the pointer
  17405. passed-in will be valid. If the exception is of unknown type, this pointer
  17406. will be null.
  17407. */
  17408. virtual void unhandledException (const std::exception* e,
  17409. const String& sourceFilename,
  17410. const int lineNumber);
  17411. /** Signals that the main message loop should stop and the application should terminate.
  17412. This isn't synchronous, it just posts a quit message to the main queue, and
  17413. when this message arrives, the message loop will stop, the shutdown() method
  17414. will be called, and the app will exit.
  17415. Note that this will cause an unconditional quit to happen, so if you need an
  17416. extra level before this, e.g. to give the user the chance to save their work
  17417. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17418. method - see that method's help for more info.
  17419. @see MessageManager, DeletedAtShutdown
  17420. */
  17421. static void quit();
  17422. /** Sets the value that should be returned as the application's exit code when the
  17423. app quits.
  17424. This is the value that's returned by the main() function. Normally you'd leave this
  17425. as 0 unless you want to indicate an error code.
  17426. @see getApplicationReturnValue
  17427. */
  17428. void setApplicationReturnValue (const int newReturnValue) throw();
  17429. /** Returns the value that has been set as the application's exit code.
  17430. @see setApplicationReturnValue
  17431. */
  17432. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17433. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17434. /** @internal */
  17435. static int main (String& commandLine, JUCEApplication* const newApp);
  17436. /** @internal */
  17437. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17438. /** @internal */
  17439. static void sendUnhandledException (const std::exception* const e,
  17440. const char* const sourceFile,
  17441. const int lineNumber);
  17442. /** @internal */
  17443. ApplicationCommandTarget* getNextCommandTarget();
  17444. /** @internal */
  17445. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17446. /** @internal */
  17447. void getAllCommands (Array <CommandID>& commands);
  17448. /** @internal */
  17449. bool perform (const InvocationInfo& info);
  17450. /** @internal */
  17451. void actionListenerCallback (const String& message);
  17452. private:
  17453. int appReturnValue;
  17454. bool stillInitialising;
  17455. static int shutdownAppAndClearUp();
  17456. };
  17457. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17458. /********* End of inlined file: juce_Application.h *********/
  17459. #endif
  17460. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17461. #endif
  17462. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17463. #endif
  17464. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17465. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17466. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17467. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17468. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17469. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17470. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17471. /**
  17472. Has a callback method that is triggered asynchronously.
  17473. This object allows an asynchronous callback function to be triggered, for
  17474. tasks such as coalescing multiple updates into a single callback later on.
  17475. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17476. message thread calling handleAsyncUpdate() as soon as it can.
  17477. */
  17478. class JUCE_API AsyncUpdater
  17479. {
  17480. public:
  17481. /** Creates an AsyncUpdater object. */
  17482. AsyncUpdater() throw();
  17483. /** Destructor.
  17484. If there are any pending callbacks when the object is deleted, these are lost.
  17485. */
  17486. virtual ~AsyncUpdater();
  17487. /** Causes the callback to be triggered at a later time.
  17488. This method returns immediately, having made sure that a callback
  17489. to the handleAsyncUpdate() method will occur as soon as possible.
  17490. If an update callback is already pending but hasn't happened yet, calls
  17491. to this method will be ignored.
  17492. It's thread-safe to call this method from any number of threads without
  17493. needing to worry about locking.
  17494. */
  17495. void triggerAsyncUpdate() throw();
  17496. /** This will stop any pending updates from happening.
  17497. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17498. callback happens, this will cancel the handleAsyncUpdate() callback.
  17499. */
  17500. void cancelPendingUpdate() throw();
  17501. /** If an update has been triggered and is pending, this will invoke it
  17502. synchronously.
  17503. Use this as a kind of "flush" operation - if an update is pending, the
  17504. handleAsyncUpdate() method will be called immediately; if no update is
  17505. pending, then nothing will be done.
  17506. */
  17507. void handleUpdateNowIfNeeded();
  17508. /** Called back to do whatever your class needs to do.
  17509. This method is called by the message thread at the next convenient time
  17510. after the triggerAsyncUpdate() method has been called.
  17511. */
  17512. virtual void handleAsyncUpdate() = 0;
  17513. private:
  17514. class AsyncUpdaterInternal : public MessageListener
  17515. {
  17516. public:
  17517. AsyncUpdaterInternal() throw() {}
  17518. ~AsyncUpdaterInternal() {}
  17519. void handleMessage (const Message&);
  17520. AsyncUpdater* owner;
  17521. private:
  17522. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17523. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17524. };
  17525. AsyncUpdaterInternal internalAsyncHandler;
  17526. bool asyncMessagePending;
  17527. };
  17528. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17529. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17530. /********* Start of inlined file: juce_Desktop.h *********/
  17531. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17532. #define __JUCE_DESKTOP_JUCEHEADER__
  17533. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17534. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17535. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17536. /**
  17537. Classes derived from this will be automatically deleted when the application exits.
  17538. After JUCEApplication::shutdown() has been called, any objects derived from
  17539. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17540. order to that in which they were created.
  17541. So if you've got a singleton and don't want to have to explicitly delete it, just
  17542. inherit from this and it'll be taken care of.
  17543. */
  17544. class JUCE_API DeletedAtShutdown
  17545. {
  17546. protected:
  17547. /** Creates a DeletedAtShutdown object. */
  17548. DeletedAtShutdown() throw();
  17549. /** Destructor.
  17550. It's ok to delete these objects explicitly - it's only the ones left
  17551. dangling at the end that will be deleted automatically.
  17552. */
  17553. virtual ~DeletedAtShutdown();
  17554. public:
  17555. /** Deletes all extant objects.
  17556. This shouldn't be used by applications, as it's called automatically
  17557. in the shutdown code of the JUCEApplication class.
  17558. */
  17559. static void deleteAll();
  17560. private:
  17561. DeletedAtShutdown (const DeletedAtShutdown&);
  17562. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17563. };
  17564. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17565. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17566. /********* Start of inlined file: juce_Timer.h *********/
  17567. #ifndef __JUCE_TIMER_JUCEHEADER__
  17568. #define __JUCE_TIMER_JUCEHEADER__
  17569. class InternalTimerThread;
  17570. /**
  17571. Repeatedly calls a user-defined method at a specified time interval.
  17572. A Timer's timerCallback() method will be repeatedly called at a given
  17573. interval. Initially when a Timer object is created, they will do nothing
  17574. until the startTimer() method is called, then the message thread will
  17575. start calling it back until stopTimer() is called.
  17576. The time interval isn't guaranteed to be precise to any more than maybe
  17577. 10-20ms, and the intervals may end up being much longer than requested if the
  17578. system is busy. Because it's the message thread that is doing the callbacks,
  17579. any messages that take a significant amount of time to process will block
  17580. all the timers for that period.
  17581. If you need to have a single callback that is shared by multiple timers with
  17582. different frequencies, then the MultiTimer class allows you to do that - its
  17583. structure is very similar to the Timer class, but contains multiple timers
  17584. internally, each one identified by an ID number.
  17585. @see MultiTimer
  17586. */
  17587. class JUCE_API Timer
  17588. {
  17589. protected:
  17590. /** Creates a Timer.
  17591. When created, the timer is stopped, so use startTimer() to get it going.
  17592. */
  17593. Timer() throw();
  17594. /** Creates a copy of another timer.
  17595. Note that this timer won't be started, even if the one you're copying
  17596. is running.
  17597. */
  17598. Timer (const Timer& other) throw();
  17599. public:
  17600. /** Destructor. */
  17601. virtual ~Timer();
  17602. /** The user-defined callback routine that actually gets called periodically.
  17603. It's perfectly ok to call startTimer() or stopTimer() from within this
  17604. callback to change the subsequent intervals.
  17605. */
  17606. virtual void timerCallback() = 0;
  17607. /** Starts the timer and sets the length of interval required.
  17608. If the timer is already started, this will reset it, so the
  17609. time between calling this method and the next timer callback
  17610. will not be less than the interval length passed in.
  17611. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17612. rounded up to 1)
  17613. */
  17614. void startTimer (const int intervalInMilliseconds) throw();
  17615. /** Stops the timer.
  17616. No more callbacks will be made after this method returns.
  17617. If this is called from a different thread, any callbacks that may
  17618. be currently executing may be allowed to finish before the method
  17619. returns.
  17620. */
  17621. void stopTimer() throw();
  17622. /** Checks if the timer has been started.
  17623. @returns true if the timer is running.
  17624. */
  17625. bool isTimerRunning() const throw() { return periodMs > 0; }
  17626. /** Returns the timer's interval.
  17627. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17628. */
  17629. int getTimerInterval() const throw() { return periodMs; }
  17630. private:
  17631. friend class InternalTimerThread;
  17632. int countdownMs, periodMs;
  17633. Timer* previous;
  17634. Timer* next;
  17635. const Timer& operator= (const Timer&);
  17636. };
  17637. #endif // __JUCE_TIMER_JUCEHEADER__
  17638. /********* End of inlined file: juce_Timer.h *********/
  17639. /**
  17640. Classes can implement this interface and register themselves with the Desktop class
  17641. to receive callbacks when the currently focused component changes.
  17642. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17643. */
  17644. class JUCE_API FocusChangeListener
  17645. {
  17646. public:
  17647. /** Destructor. */
  17648. virtual ~FocusChangeListener() {}
  17649. /** Callback to indicate that the currently focused component has changed. */
  17650. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17651. };
  17652. /**
  17653. Describes and controls aspects of the computer's desktop.
  17654. */
  17655. class JUCE_API Desktop : private DeletedAtShutdown,
  17656. private Timer,
  17657. private AsyncUpdater
  17658. {
  17659. public:
  17660. /** There's only one dektop object, and this method will return it.
  17661. */
  17662. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17663. /** Returns a list of the positions of all the monitors available.
  17664. The first rectangle in the list will be the main monitor area.
  17665. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17666. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17667. */
  17668. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17669. /** Returns the position and size of the main monitor.
  17670. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17671. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17672. */
  17673. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17674. /** Returns the position and size of the monitor which contains this co-ordinate.
  17675. If none of the monitors contains the point, this will just return the
  17676. main monitor.
  17677. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17678. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17679. */
  17680. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17681. /** Returns the mouse position.
  17682. The co-ordinates are relative to the top-left of the main monitor.
  17683. */
  17684. static void getMousePosition (int& x, int& y) throw();
  17685. /** Makes the mouse pointer jump to a given location.
  17686. The co-ordinates are relative to the top-left of the main monitor.
  17687. */
  17688. static void setMousePosition (int x, int y) throw();
  17689. /** Returns the last position at which a mouse button was pressed.
  17690. */
  17691. static void getLastMouseDownPosition (int& x, int& y) throw();
  17692. /** Returns the number of times the mouse button has been clicked since the
  17693. app started.
  17694. Each mouse-down event increments this number by 1.
  17695. */
  17696. static int getMouseButtonClickCounter() throw();
  17697. /** This lets you prevent the screensaver from becoming active.
  17698. Handy if you're running some sort of presentation app where having a screensaver
  17699. appear would be annoying.
  17700. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17701. won't enable a screensaver unless the user has actually set one up).
  17702. The disablement will only happen while the Juce application is the foreground
  17703. process - if another task is running in front of it, then the screensaver will
  17704. be unaffected.
  17705. @see isScreenSaverEnabled
  17706. */
  17707. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17708. /** Returns true if the screensaver has not been turned off.
  17709. This will return the last value passed into setScreenSaverEnabled(). Note that
  17710. it won't tell you whether the user is actually using a screen saver, just
  17711. whether this app is deliberately preventing one from running.
  17712. @see setScreenSaverEnabled
  17713. */
  17714. static bool isScreenSaverEnabled() throw();
  17715. /** Registers a MouseListener that will receive all mouse events that occur on
  17716. any component.
  17717. @see removeGlobalMouseListener
  17718. */
  17719. void addGlobalMouseListener (MouseListener* const listener) throw();
  17720. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17721. method.
  17722. @see addGlobalMouseListener
  17723. */
  17724. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17725. /** Registers a MouseListener that will receive a callback whenever the focused
  17726. component changes.
  17727. */
  17728. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17729. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17730. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17731. /** Returns the number of components that are currently active as top-level
  17732. desktop windows.
  17733. @see getComponent, Component::addToDesktop
  17734. */
  17735. int getNumComponents() const throw();
  17736. /** Returns one of the top-level desktop window components.
  17737. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17738. index is out-of-range.
  17739. @see getNumComponents, Component::addToDesktop
  17740. */
  17741. Component* getComponent (const int index) const throw();
  17742. /** Finds the component at a given screen location.
  17743. This will drill down into top-level windows to find the child component at
  17744. the given position.
  17745. Returns 0 if the co-ordinates are inside a non-Juce window.
  17746. */
  17747. Component* findComponentAt (const int screenX,
  17748. const int screenY) const;
  17749. juce_UseDebuggingNewOperator
  17750. /** Tells this object to refresh its idea of what the screen resolution is.
  17751. (Called internally by the native code).
  17752. */
  17753. void refreshMonitorSizes() throw();
  17754. /** True if the OS supports semitransparent windows */
  17755. static bool canUseSemiTransparentWindows() throw();
  17756. private:
  17757. friend class Component;
  17758. friend class ComponentPeer;
  17759. SortedSet <void*> mouseListeners, focusListeners;
  17760. VoidArray desktopComponents;
  17761. friend class DeletedAtShutdown;
  17762. friend class TopLevelWindowManager;
  17763. Desktop() throw();
  17764. ~Desktop() throw();
  17765. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17766. int lastMouseX, lastMouseY;
  17767. void timerCallback();
  17768. void sendMouseMove();
  17769. void resetTimer() throw();
  17770. int getNumDisplayMonitors() const throw();
  17771. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17772. void addDesktopComponent (Component* const c) throw();
  17773. void removeDesktopComponent (Component* const c) throw();
  17774. void componentBroughtToFront (Component* const c) throw();
  17775. void triggerFocusCallback() throw();
  17776. void handleAsyncUpdate();
  17777. Desktop (const Desktop&);
  17778. const Desktop& operator= (const Desktop&);
  17779. };
  17780. #endif // __JUCE_DESKTOP_JUCEHEADER__
  17781. /********* End of inlined file: juce_Desktop.h *********/
  17782. class KeyPressMappingSet;
  17783. class ApplicationCommandManagerListener;
  17784. /**
  17785. One of these objects holds a list of all the commands your app can perform,
  17786. and despatches these commands when needed.
  17787. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  17788. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  17789. to invoke automatically, which means you don't have to handle the result of a menu
  17790. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  17791. which can choose which events they want to handle.
  17792. This architecture also allows for nested ApplicationCommandTargets, so that for example
  17793. you could have two different objects, one inside the other, both of which can respond to
  17794. a "delete" command. Depending on which one has focus, the command will be sent to the
  17795. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  17796. method.
  17797. To set up your app to use commands, you'll need to do the following:
  17798. - Create a global ApplicationCommandManager to hold the list of all possible
  17799. commands. (This will also manage a set of key-mappings for them).
  17800. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  17801. This allows the object to provide a list of commands that it can perform, and
  17802. to handle them.
  17803. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  17804. or ApplicationCommandManager::registerCommand().
  17805. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  17806. method to access the key-mapper object, which you will need to register as a key-listener
  17807. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  17808. about setting this up.
  17809. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  17810. cause these commands to be invoked automatically.
  17811. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  17812. When a command is invoked, the ApplicationCommandManager will try to choose the best
  17813. ApplicationCommandTarget to receive the specified command. To do this it will use the
  17814. current keyboard focus to see which component might be interested, and will search the
  17815. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  17816. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  17817. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  17818. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  17819. point if the command still hasn't been performed, it will be passed to the current
  17820. JUCEApplication object (which is itself an ApplicationCommandTarget).
  17821. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  17822. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  17823. the object yourself.
  17824. @see ApplicationCommandTarget, ApplicationCommandInfo
  17825. */
  17826. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  17827. private FocusChangeListener
  17828. {
  17829. public:
  17830. /** Creates an ApplicationCommandManager.
  17831. Once created, you'll need to register all your app's commands with it, using
  17832. ApplicationCommandManager::registerAllCommandsForTarget() or
  17833. ApplicationCommandManager::registerCommand().
  17834. */
  17835. ApplicationCommandManager();
  17836. /** Destructor.
  17837. Make sure that you don't delete this if pointers to it are still being used by
  17838. objects such as PopupMenus or Buttons.
  17839. */
  17840. virtual ~ApplicationCommandManager();
  17841. /** Clears the current list of all commands.
  17842. Note that this will also clear the contents of the KeyPressMappingSet.
  17843. */
  17844. void clearCommands();
  17845. /** Adds a command to the list of registered commands.
  17846. @see registerAllCommandsForTarget
  17847. */
  17848. void registerCommand (const ApplicationCommandInfo& newCommand);
  17849. /** Adds all the commands that this target publishes to the manager's list.
  17850. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  17851. to get details about all the commands that this target can do, and will call
  17852. registerCommand() to add each one to the manger's list.
  17853. @see registerCommand
  17854. */
  17855. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  17856. /** Removes the command with a specified ID.
  17857. Note that this will also remove any key mappings that are mapped to the command.
  17858. */
  17859. void removeCommand (const CommandID commandID);
  17860. /** This should be called to tell the manager that one of its registered commands may have changed
  17861. its active status.
  17862. Because the command manager only finds out whether a command is active or inactive by querying
  17863. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  17864. allows things like buttons to update their enablement, etc.
  17865. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  17866. for any registered listeners.
  17867. */
  17868. void commandStatusChanged();
  17869. /** Returns the number of commands that have been registered.
  17870. @see registerCommand
  17871. */
  17872. int getNumCommands() const throw() { return commands.size(); }
  17873. /** Returns the details about one of the registered commands.
  17874. The index is between 0 and (getNumCommands() - 1).
  17875. */
  17876. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  17877. /** Returns the details about a given command ID.
  17878. This will search the list of registered commands for one with the given command
  17879. ID number, and return its associated info. If no matching command is found, this
  17880. will return 0.
  17881. */
  17882. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  17883. /** Returns the name field for a command.
  17884. An empty string is returned if no command with this ID has been registered.
  17885. @see getDescriptionOfCommand
  17886. */
  17887. const String getNameOfCommand (const CommandID commandID) const throw();
  17888. /** Returns the description field for a command.
  17889. An empty string is returned if no command with this ID has been registered. If the
  17890. command has no description, this will return its short name field instead.
  17891. @see getNameOfCommand
  17892. */
  17893. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  17894. /** Returns the list of categories.
  17895. This will go through all registered commands, and return a list of all the distict
  17896. categoryName values from their ApplicationCommandInfo structure.
  17897. @see getCommandsInCategory()
  17898. */
  17899. const StringArray getCommandCategories() const throw();
  17900. /** Returns a list of all the command UIDs in a particular category.
  17901. @see getCommandCategories()
  17902. */
  17903. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  17904. /** Returns the manager's internal set of key mappings.
  17905. This object can be used to edit the keypresses. To actually link this object up
  17906. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  17907. class.
  17908. @see KeyPressMappingSet
  17909. */
  17910. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  17911. /** Invokes the given command directly, sending it to the default target.
  17912. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17913. structure.
  17914. */
  17915. bool invokeDirectly (const CommandID commandID,
  17916. const bool asynchronously);
  17917. /** Sends a command to the default target.
  17918. This will choose a target using getFirstCommandTarget(), and send the specified command
  17919. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  17920. first target can't handle the command, it will be passed on to targets further down the
  17921. chain (see ApplicationCommandTarget::invoke() for more info).
  17922. @param invocationInfo this must be correctly filled-in, describing the context for
  17923. the invocation.
  17924. @param asynchronously if false, the command will be performed before this method returns.
  17925. If true, a message will be posted so that the command will be performed
  17926. later on the message thread, and this method will return immediately.
  17927. @see ApplicationCommandTarget::invoke
  17928. */
  17929. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  17930. const bool asynchronously);
  17931. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  17932. Whenever the manager needs to know which target a command should be sent to, it calls
  17933. this method to determine the first one to try.
  17934. By default, this method will return the target that was set by calling setFirstCommandTarget().
  17935. If no target is set, it will return the result of findDefaultComponentTarget().
  17936. If you need to make sure all commands go via your own custom target, then you can
  17937. either use setFirstCommandTarget() to specify a single target, or override this method
  17938. if you need more complex logic to choose one.
  17939. It may return 0 if no targets are available.
  17940. @see getTargetForCommand, invoke, invokeDirectly
  17941. */
  17942. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  17943. /** Sets a target to be returned by getFirstCommandTarget().
  17944. If this is set to 0, then getFirstCommandTarget() will by default return the
  17945. result of findDefaultComponentTarget().
  17946. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  17947. deleting the target object.
  17948. */
  17949. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  17950. /** Tries to find the best target to use to perform a given command.
  17951. This will call getFirstCommandTarget() to find the preferred target, and will
  17952. check whether that target can handle the given command. If it can't, then it'll use
  17953. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  17954. so on until no more are available.
  17955. If no targets are found that can perform the command, this method will return 0.
  17956. If a target is found, then it will get the target to fill-in the upToDateInfo
  17957. structure with the latest info about that command, so that the caller can see
  17958. whether the command is disabled, ticked, etc.
  17959. */
  17960. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  17961. ApplicationCommandInfo& upToDateInfo);
  17962. /** Registers a listener that will be called when various events occur. */
  17963. void addListener (ApplicationCommandManagerListener* const listener) throw();
  17964. /** Deregisters a previously-added listener. */
  17965. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  17966. /** Looks for a suitable command target based on which Components have the keyboard focus.
  17967. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  17968. but is exposed here in case it's useful.
  17969. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  17970. windows, etc., and using the findTargetForComponent() method.
  17971. */
  17972. static ApplicationCommandTarget* findDefaultComponentTarget();
  17973. /** Examines this component and all its parents in turn, looking for the first one
  17974. which is a ApplicationCommandTarget.
  17975. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  17976. that class.
  17977. */
  17978. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  17979. juce_UseDebuggingNewOperator
  17980. private:
  17981. OwnedArray <ApplicationCommandInfo> commands;
  17982. SortedSet <void*> listeners;
  17983. KeyPressMappingSet* keyMappings;
  17984. ApplicationCommandTarget* firstTarget;
  17985. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  17986. void handleAsyncUpdate();
  17987. void globalFocusChanged (Component*);
  17988. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  17989. // version of this method.
  17990. virtual short getFirstCommandTarget() { return 0; }
  17991. };
  17992. /**
  17993. A listener that receives callbacks from an ApplicationCommandManager when
  17994. commands are invoked or the command list is changed.
  17995. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  17996. */
  17997. class JUCE_API ApplicationCommandManagerListener
  17998. {
  17999. public:
  18000. /** Destructor. */
  18001. virtual ~ApplicationCommandManagerListener() {}
  18002. /** Called when an app command is about to be invoked. */
  18003. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18004. /** Called when commands are registered or deregistered from the
  18005. command manager, or when commands are made active or inactive.
  18006. Note that if you're using this to watch for changes to whether a command is disabled,
  18007. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18008. whenever the status of your command might have changed.
  18009. */
  18010. virtual void applicationCommandListChanged() = 0;
  18011. };
  18012. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18013. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18014. #endif
  18015. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18016. #endif
  18017. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18018. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18019. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18020. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18021. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18022. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18023. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18024. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18025. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18026. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18027. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18028. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18029. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18030. /********* Start of inlined file: juce_ChangeListener.h *********/
  18031. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18032. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18033. /**
  18034. Receives callbacks about changes to some kind of object.
  18035. Many objects use a ChangeListenerList to keep a set of listeners which they
  18036. will inform when something changes. A subclass of ChangeListener
  18037. is used to receive these callbacks.
  18038. Note that the major difference between an ActionListener and a ChangeListener
  18039. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18040. callbacks, but ActionListeners perform one callback for every event posted.
  18041. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18042. */
  18043. class JUCE_API ChangeListener
  18044. {
  18045. public:
  18046. /** Destructor. */
  18047. virtual ~ChangeListener() {}
  18048. /** Overridden by your subclass to receive the callback.
  18049. @param objectThatHasChanged the value that was passed to the
  18050. ChangeListenerList::sendChangeMessage() method
  18051. */
  18052. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18053. };
  18054. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18055. /********* End of inlined file: juce_ChangeListener.h *********/
  18056. /**
  18057. A set of ChangeListeners.
  18058. Listeners can be added and removed from the list, and change messages can be
  18059. broadcast to all the listeners.
  18060. @see ChangeListener, ChangeBroadcaster
  18061. */
  18062. class JUCE_API ChangeListenerList : public MessageListener
  18063. {
  18064. public:
  18065. /** Creates an empty list. */
  18066. ChangeListenerList() throw();
  18067. /** Destructor. */
  18068. ~ChangeListenerList() throw();
  18069. /** Adds a listener to the list.
  18070. (Trying to add a listener that's already on the list will have no effect).
  18071. */
  18072. void addChangeListener (ChangeListener* const listener) throw();
  18073. /** Removes a listener from the list.
  18074. If the listener isn't on the list, this won't have any effect.
  18075. */
  18076. void removeChangeListener (ChangeListener* const listener) throw();
  18077. /** Removes all listeners from the list. */
  18078. void removeAllChangeListeners() throw();
  18079. /** Posts an asynchronous change message to all the listeners.
  18080. If a message has already been sent and hasn't yet been delivered, this
  18081. method won't send another - in this way it coalesces multiple frequent
  18082. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18083. with the ActionListener, which posts a new event for every call to its
  18084. sendActionMessage() method.
  18085. Only listeners which are on the list when the change event is delivered
  18086. will receive the event - and this may include listeners that weren't on
  18087. the list when the change message was sent.
  18088. @param objectThatHasChanged this pointer is passed to the
  18089. ChangeListener::changeListenerCallback() method,
  18090. and can be any value the application needs
  18091. @see sendSynchronousChangeMessage
  18092. */
  18093. void sendChangeMessage (void* objectThatHasChanged) throw();
  18094. /** This will synchronously callback all the ChangeListeners.
  18095. Use this if you need to synchronously force a call to all the
  18096. listeners' ChangeListener::changeListenerCallback() methods.
  18097. */
  18098. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18099. /** If a change message has been sent but not yet dispatched, this will
  18100. use sendSynchronousChangeMessage() to make the callback immediately.
  18101. */
  18102. void dispatchPendingMessages();
  18103. /** @internal */
  18104. void handleMessage (const Message&);
  18105. juce_UseDebuggingNewOperator
  18106. private:
  18107. SortedSet <void*> listeners;
  18108. CriticalSection lock;
  18109. void* lastChangedObject;
  18110. bool messagePending;
  18111. ChangeListenerList (const ChangeListenerList&);
  18112. const ChangeListenerList& operator= (const ChangeListenerList&);
  18113. };
  18114. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18115. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18116. /** Manages a list of ChangeListeners, and can send them messages.
  18117. To quickly add methods to your class that can add/remove change
  18118. listeners and broadcast to them, you can derive from this.
  18119. @see ChangeListenerList, ChangeListener
  18120. */
  18121. class JUCE_API ChangeBroadcaster
  18122. {
  18123. public:
  18124. /** Creates an ChangeBroadcaster. */
  18125. ChangeBroadcaster() throw();
  18126. /** Destructor. */
  18127. virtual ~ChangeBroadcaster();
  18128. /** Adds a listener to the list.
  18129. (Trying to add a listener that's already on the list will have no effect).
  18130. */
  18131. void addChangeListener (ChangeListener* const listener) throw();
  18132. /** Removes a listener from the list.
  18133. If the listener isn't on the list, this won't have any effect.
  18134. */
  18135. void removeChangeListener (ChangeListener* const listener) throw();
  18136. /** Removes all listeners from the list. */
  18137. void removeAllChangeListeners() throw();
  18138. /** Broadcasts a change message to all the registered listeners.
  18139. The message will be delivered asynchronously by the event thread, so this
  18140. method will not directly call any of the listeners. For a synchronous
  18141. message, use sendSynchronousChangeMessage().
  18142. @see ChangeListenerList::sendActionMessage
  18143. */
  18144. void sendChangeMessage (void* objectThatHasChanged) throw();
  18145. /** Sends a synchronous change message to all the registered listeners.
  18146. @see ChangeListenerList::sendSynchronousChangeMessage
  18147. */
  18148. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18149. /** If a change message has been sent but not yet dispatched, this will
  18150. use sendSynchronousChangeMessage() to make the callback immediately.
  18151. */
  18152. void dispatchPendingMessages();
  18153. private:
  18154. ChangeListenerList changeListenerList;
  18155. ChangeBroadcaster (const ChangeBroadcaster&);
  18156. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18157. };
  18158. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18159. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18160. /** Wrapper on a file that stores a list of key/value data pairs.
  18161. Useful for storing application settings, etc. See the PropertySet class for
  18162. the interfaces that read and write values.
  18163. Not designed for very large amounts of data, as it keeps all the values in
  18164. memory and writes them out to disk lazily when they are changed.
  18165. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18166. with it, and these will be signalled when a value changes.
  18167. @see PropertySet
  18168. */
  18169. class JUCE_API PropertiesFile : public PropertySet,
  18170. public ChangeBroadcaster,
  18171. private Timer
  18172. {
  18173. public:
  18174. enum FileFormatOptions
  18175. {
  18176. ignoreCaseOfKeyNames = 1,
  18177. storeAsBinary = 2,
  18178. storeAsCompressedBinary = 4,
  18179. storeAsXML = 8
  18180. };
  18181. /**
  18182. Creates a PropertiesFile object.
  18183. @param file the file to use
  18184. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18185. is changed, the object will wait for this amount
  18186. of time and then save the file. If zero, the file
  18187. will be written to disk immediately on being changed
  18188. (which might be slow, as it'll re-write synchronously
  18189. each time a value-change method is called). If it is
  18190. less than zero, the file won't be saved until
  18191. save() or saveIfNeeded() are explicitly called.
  18192. @param options a combination of the flags in the FileFormatOptions
  18193. enum, which specify the type of file to save, and other
  18194. options.
  18195. */
  18196. PropertiesFile (const File& file,
  18197. const int millisecondsBeforeSaving,
  18198. const int options) throw();
  18199. /** Destructor.
  18200. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18201. */
  18202. ~PropertiesFile();
  18203. /** This will flush all the values to disk if they've changed since the last
  18204. time they were saved.
  18205. Returns false if it fails to write to the file for some reason (maybe because
  18206. it's read-only or the directory doesn't exist or something).
  18207. @see save
  18208. */
  18209. bool saveIfNeeded();
  18210. /** This will force a write-to-disk of the current values, regardless of whether
  18211. anything has changed since the last save.
  18212. Returns false if it fails to write to the file for some reason (maybe because
  18213. it's read-only or the directory doesn't exist or something).
  18214. @see saveIfNeeded
  18215. */
  18216. bool save();
  18217. /** Returns true if the properties have been altered since the last time they were
  18218. saved.
  18219. */
  18220. bool needsToBeSaved() const throw();
  18221. /** Returns the file that's being used. */
  18222. const File getFile() const throw();
  18223. /** Handy utility to create a properties file in whatever the standard OS-specific
  18224. location is for these things.
  18225. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18226. creates a PropertiesFile object with the specified properties. See
  18227. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18228. what the parameters do.
  18229. @see getDefaultAppSettingsFile
  18230. */
  18231. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18232. const String& fileNameSuffix,
  18233. const String& folderName,
  18234. const bool commonToAllUsers,
  18235. const int millisecondsBeforeSaving,
  18236. const int propertiesFileOptions);
  18237. /** Handy utility to choose a file in the standard OS-dependent location for application
  18238. settings files.
  18239. So on a Mac, this will return a file called:
  18240. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18241. On Windows it'll return something like:
  18242. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18243. On Linux it'll return
  18244. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18245. If you pass an empty string as the folder name, it'll use the app name for this (or
  18246. omit the folder name on the Mac).
  18247. If commonToAllUsers is true, then this will return the same file for all users of the
  18248. computer, regardless of the current user. If it is false, the file will be specific to
  18249. only the current user. Use this to choose whether you're saving settings that are common
  18250. or user-specific.
  18251. */
  18252. static const File getDefaultAppSettingsFile (const String& applicationName,
  18253. const String& fileNameSuffix,
  18254. const String& folderName,
  18255. const bool commonToAllUsers);
  18256. juce_UseDebuggingNewOperator
  18257. protected:
  18258. virtual void propertyChanged();
  18259. private:
  18260. File file;
  18261. int timerInterval;
  18262. const int options;
  18263. bool needsWriting;
  18264. void timerCallback();
  18265. PropertiesFile (const PropertiesFile&);
  18266. const PropertiesFile& operator= (const PropertiesFile&);
  18267. };
  18268. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18269. /********* End of inlined file: juce_PropertiesFile.h *********/
  18270. /**
  18271. Manages a collection of properties.
  18272. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18273. as a singleton.
  18274. It holds two different PropertiesFile objects internally, one for user-specific
  18275. settings (stored in your user directory), and one for settings that are common to
  18276. all users (stored in a folder accessible to all users).
  18277. The class manages the creation of these files on-demand, allowing access via the
  18278. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18279. methods like testWriteAccess() to check that the files can be saved.
  18280. If you're using one of these as a singleton, then your app's start-up code should
  18281. first of all call setStorageParameters() to tell it the parameters to use to create
  18282. the properties files.
  18283. @see PropertiesFile
  18284. */
  18285. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18286. {
  18287. public:
  18288. /**
  18289. Creates an ApplicationProperties object.
  18290. Before using it, you must call setStorageParameters() to give it the info
  18291. it needs to create the property files.
  18292. */
  18293. ApplicationProperties() throw();
  18294. /** Destructor.
  18295. */
  18296. ~ApplicationProperties();
  18297. juce_DeclareSingleton (ApplicationProperties, false)
  18298. /** Gives the object the information it needs to create the appropriate properties files.
  18299. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18300. info about how these parameters are used.
  18301. */
  18302. void setStorageParameters (const String& applicationName,
  18303. const String& fileNameSuffix,
  18304. const String& folderName,
  18305. const int millisecondsBeforeSaving,
  18306. const int propertiesFileOptions) throw();
  18307. /** Tests whether the files can be successfully written to, and can show
  18308. an error message if not.
  18309. Returns true if none of the tests fail.
  18310. @param testUserSettings if true, the user settings file will be tested
  18311. @param testCommonSettings if true, the common settings file will be tested
  18312. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18313. message box if either of the tests fail
  18314. */
  18315. bool testWriteAccess (const bool testUserSettings,
  18316. const bool testCommonSettings,
  18317. const bool showWarningDialogOnFailure);
  18318. /** Returns the user settings file.
  18319. The first time this is called, it will create and load the properties file.
  18320. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18321. the common settings are used as a second-chance place to look. This is done via the
  18322. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18323. to the fallback for the user settings.
  18324. @see getCommonSettings
  18325. */
  18326. PropertiesFile* getUserSettings() throw();
  18327. /** Returns the common settings file.
  18328. The first time this is called, it will create and load the properties file.
  18329. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18330. read-only (e.g. because the user doesn't have permission to write
  18331. to shared files), then this will return the user settings instead,
  18332. (like getUserSettings() would do). This is handy if you'd like to
  18333. write a value to the common settings, but if that's no possible,
  18334. then you'd rather write to the user settings than none at all.
  18335. If returnUserPropsIfReadOnly is false, this method will always return
  18336. the common settings, even if any changes to them can't be saved.
  18337. @see getUserSettings
  18338. */
  18339. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18340. /** Saves both files if they need to be saved.
  18341. @see PropertiesFile::saveIfNeeded
  18342. */
  18343. bool saveIfNeeded();
  18344. /** Flushes and closes both files if they are open.
  18345. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18346. and closes both files. They will then be re-opened the next time getUserSettings()
  18347. or getCommonSettings() is called.
  18348. */
  18349. void closeFiles();
  18350. juce_UseDebuggingNewOperator
  18351. private:
  18352. PropertiesFile* userProps;
  18353. PropertiesFile* commonProps;
  18354. String appName, fileSuffix, folderName;
  18355. int msBeforeSaving, options;
  18356. int commonSettingsAreReadOnly;
  18357. ApplicationProperties (const ApplicationProperties&);
  18358. const ApplicationProperties& operator= (const ApplicationProperties&);
  18359. void openFiles() throw();
  18360. };
  18361. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18362. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18363. #endif
  18364. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18365. #endif
  18366. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18367. #endif
  18368. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18369. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18370. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18371. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18372. /**
  18373. Handles reading/writing to the system's clipboard.
  18374. */
  18375. class JUCE_API SystemClipboard
  18376. {
  18377. public:
  18378. /** Copies a string of text onto the clipboard */
  18379. static void copyTextToClipboard (const String& text) throw();
  18380. /** Gets the current clipboard's contents.
  18381. Obviously this might have come from another app, so could contain
  18382. anything..
  18383. */
  18384. static const String getTextFromClipboard() throw();
  18385. };
  18386. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18387. /********* End of inlined file: juce_SystemClipboard.h *********/
  18388. #endif
  18389. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18390. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18391. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18392. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18393. /********* Start of inlined file: juce_MidiMessage.h *********/
  18394. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18395. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18396. /**
  18397. Encapsulates a MIDI message.
  18398. @see MidiMessageSequence, MidiOutput, MidiInput
  18399. */
  18400. class JUCE_API MidiMessage
  18401. {
  18402. public:
  18403. /** Creates a 3-byte short midi message.
  18404. @param byte1 message byte 1
  18405. @param byte2 message byte 2
  18406. @param byte3 message byte 3
  18407. @param timeStamp the time to give the midi message - this value doesn't
  18408. use any particular units, so will be application-specific
  18409. */
  18410. MidiMessage (const int byte1,
  18411. const int byte2,
  18412. const int byte3,
  18413. const double timeStamp = 0) throw();
  18414. /** Creates a 2-byte short midi message.
  18415. @param byte1 message byte 1
  18416. @param byte2 message byte 2
  18417. @param timeStamp the time to give the midi message - this value doesn't
  18418. use any particular units, so will be application-specific
  18419. */
  18420. MidiMessage (const int byte1,
  18421. const int byte2,
  18422. const double timeStamp = 0) throw();
  18423. /** Creates a 1-byte short midi message.
  18424. @param byte1 message byte 1
  18425. @param timeStamp the time to give the midi message - this value doesn't
  18426. use any particular units, so will be application-specific
  18427. */
  18428. MidiMessage (const int byte1,
  18429. const double timeStamp = 0) throw();
  18430. /** Creates a midi message from a block of data. */
  18431. MidiMessage (const uint8* const data,
  18432. const int dataSize,
  18433. const double timeStamp = 0) throw();
  18434. /** Reads the next midi message from some data.
  18435. This will read as many bytes from a data stream as it needs to make a
  18436. complete message, and will return the number of bytes it used. This lets
  18437. you read a sequence of midi messages from a file or stream.
  18438. @param data the data to read from
  18439. @param size the maximum number of bytes it's allowed to read
  18440. @param numBytesUsed returns the number of bytes that were actually needed
  18441. @param lastStatusByte in a sequence of midi messages, the initial byte
  18442. can be dropped from a message if it's the same as the
  18443. first byte of the previous message, so this lets you
  18444. supply the byte to use if the first byte of the message
  18445. has in fact been dropped.
  18446. @param timeStamp the time to give the midi message - this value doesn't
  18447. use any particular units, so will be application-specific
  18448. */
  18449. MidiMessage (const uint8* data,
  18450. int size,
  18451. int& numBytesUsed,
  18452. uint8 lastStatusByte,
  18453. double timeStamp = 0) throw();
  18454. /** Creates a copy of another midi message. */
  18455. MidiMessage (const MidiMessage& other) throw();
  18456. /** Creates a copy of another midi message, with a different timestamp. */
  18457. MidiMessage (const MidiMessage& other,
  18458. const double newTimeStamp) throw();
  18459. /** Destructor. */
  18460. ~MidiMessage() throw();
  18461. /** Copies this message from another one. */
  18462. const MidiMessage& operator= (const MidiMessage& other) throw();
  18463. /** Returns a pointer to the raw midi data.
  18464. @see getRawDataSize
  18465. */
  18466. uint8* getRawData() const throw() { return data; }
  18467. /** Returns the number of bytes of data in the message.
  18468. @see getRawData
  18469. */
  18470. int getRawDataSize() const throw() { return size; }
  18471. /** Returns the timestamp associated with this message.
  18472. The units for the timestamp will be application-specific.
  18473. @see setTimeStamp, addToTimeStamp
  18474. */
  18475. double getTimeStamp() const throw() { return timeStamp; }
  18476. /** Changes the message's associated timestamp.
  18477. The units for the timestamp will be application-specific.
  18478. @see addToTimeStamp, getTimeStamp
  18479. */
  18480. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18481. /** Adds a value to the message's timestamp.
  18482. The units for the timestamp will be application-specific.
  18483. */
  18484. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18485. /** Returns the midi channel associated with the message.
  18486. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18487. if it's a sysex)
  18488. @see isForChannel, setChannel
  18489. */
  18490. int getChannel() const throw();
  18491. /** Returns true if the message applies to the given midi channel.
  18492. @param channelNumber the channel number to look for, in the range 1 to 16
  18493. @see getChannel, setChannel
  18494. */
  18495. bool isForChannel (const int channelNumber) const throw();
  18496. /** Changes the message's midi channel.
  18497. This won't do anything for non-channel messages like sysexes.
  18498. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18499. */
  18500. void setChannel (const int newChannelNumber) throw();
  18501. /** Returns true if this is a system-exclusive message.
  18502. */
  18503. bool isSysEx() const throw();
  18504. /** Returns a pointer to the sysex data inside the message.
  18505. If this event isn't a sysex event, it'll return 0.
  18506. @see getSysExDataSize
  18507. */
  18508. const uint8* getSysExData() const throw();
  18509. /** Returns the size of the sysex data.
  18510. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18511. @see getSysExData
  18512. */
  18513. int getSysExDataSize() const throw();
  18514. /** Returns true if this message is a 'key-down' event.
  18515. This will return false for a note-on event with a velocity of 0.
  18516. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18517. */
  18518. bool isNoteOn() const throw();
  18519. /** Creates a key-down message (using a floating-point velocity).
  18520. @param channel the midi channel, in the range 1 to 16
  18521. @param noteNumber the key number, 0 to 127
  18522. @param velocity in the range 0 to 1.0
  18523. @see isNoteOn
  18524. */
  18525. static const MidiMessage noteOn (const int channel,
  18526. const int noteNumber,
  18527. const float velocity) throw();
  18528. /** Creates a key-down message (using an integer velocity).
  18529. @param channel the midi channel, in the range 1 to 16
  18530. @param noteNumber the key number, 0 to 127
  18531. @param velocity in the range 0 to 127
  18532. @see isNoteOn
  18533. */
  18534. static const MidiMessage noteOn (const int channel,
  18535. const int noteNumber,
  18536. const uint8 velocity) throw();
  18537. /** Returns true if this message is a 'key-up' event.
  18538. This will also return true for a note-on event with a velocity of 0.
  18539. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18540. */
  18541. bool isNoteOff() const throw();
  18542. /** Creates a key-up message.
  18543. @param channel the midi channel, in the range 1 to 16
  18544. @param noteNumber the key number, 0 to 127
  18545. @see isNoteOff
  18546. */
  18547. static const MidiMessage noteOff (const int channel,
  18548. const int noteNumber) throw();
  18549. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18550. @see isNoteOn, isNoteOff
  18551. */
  18552. bool isNoteOnOrOff() const throw();
  18553. /** Returns the midi note number for note-on and note-off messages.
  18554. If the message isn't a note-on or off, the value returned will be
  18555. meaningless.
  18556. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18557. */
  18558. int getNoteNumber() const throw();
  18559. /** Changes the midi note number of a note-on or note-off message.
  18560. If the message isn't a note on or off, this will do nothing.
  18561. */
  18562. void setNoteNumber (const int newNoteNumber) throw();
  18563. /** Returns the velocity of a note-on or note-off message.
  18564. The value returned will be in the range 0 to 127.
  18565. If the message isn't a note-on or off event, it will return 0.
  18566. @see getFloatVelocity
  18567. */
  18568. uint8 getVelocity() const throw();
  18569. /** Returns the velocity of a note-on or note-off message.
  18570. The value returned will be in the range 0 to 1.0
  18571. If the message isn't a note-on or off event, it will return 0.
  18572. @see getVelocity, setVelocity
  18573. */
  18574. float getFloatVelocity() const throw();
  18575. /** Changes the velocity of a note-on or note-off message.
  18576. If the message isn't a note on or off, this will do nothing.
  18577. @param newVelocity the new velocity, in the range 0 to 1.0
  18578. @see getFloatVelocity, multiplyVelocity
  18579. */
  18580. void setVelocity (const float newVelocity) throw();
  18581. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18582. If the message isn't a note on or off, this will do nothing.
  18583. @param scaleFactor the value by which to multiply the velocity
  18584. @see setVelocity
  18585. */
  18586. void multiplyVelocity (const float scaleFactor) throw();
  18587. /** Returns true if the message is a program (patch) change message.
  18588. @see getProgramChangeNumber, getGMInstrumentName
  18589. */
  18590. bool isProgramChange() const throw();
  18591. /** Returns the new program number of a program change message.
  18592. If the message isn't a program change, the value returned will be
  18593. nonsense.
  18594. @see isProgramChange, getGMInstrumentName
  18595. */
  18596. int getProgramChangeNumber() const throw();
  18597. /** Creates a program-change message.
  18598. @param channel the midi channel, in the range 1 to 16
  18599. @param programNumber the midi program number, 0 to 127
  18600. @see isProgramChange, getGMInstrumentName
  18601. */
  18602. static const MidiMessage programChange (const int channel,
  18603. const int programNumber) throw();
  18604. /** Returns true if the message is a pitch-wheel move.
  18605. @see getPitchWheelValue, pitchWheel
  18606. */
  18607. bool isPitchWheel() const throw();
  18608. /** Returns the pitch wheel position from a pitch-wheel move message.
  18609. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18610. If called for messages which aren't pitch wheel events, the number returned will be
  18611. nonsense.
  18612. @see isPitchWheel
  18613. */
  18614. int getPitchWheelValue() const throw();
  18615. /** Creates a pitch-wheel move message.
  18616. @param channel the midi channel, in the range 1 to 16
  18617. @param position the wheel position, in the range 0 to 16383
  18618. @see isPitchWheel
  18619. */
  18620. static const MidiMessage pitchWheel (const int channel,
  18621. const int position) throw();
  18622. /** Returns true if the message is an aftertouch event.
  18623. For aftertouch events, use the getNoteNumber() method to find out the key
  18624. that it applies to, and getAftertouchValue() to find out the amount. Use
  18625. getChannel() to find out the channel.
  18626. @see getAftertouchValue, getNoteNumber
  18627. */
  18628. bool isAftertouch() const throw();
  18629. /** Returns the amount of aftertouch from an aftertouch messages.
  18630. The value returned is in the range 0 to 127, and will be nonsense for messages
  18631. other than aftertouch messages.
  18632. @see isAftertouch
  18633. */
  18634. int getAfterTouchValue() const throw();
  18635. /** Creates an aftertouch message.
  18636. @param channel the midi channel, in the range 1 to 16
  18637. @param noteNumber the key number, 0 to 127
  18638. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18639. @see isAftertouch
  18640. */
  18641. static const MidiMessage aftertouchChange (const int channel,
  18642. const int noteNumber,
  18643. const int aftertouchAmount) throw();
  18644. /** Returns true if the message is a channel-pressure change event.
  18645. This is like aftertouch, but common to the whole channel rather than a specific
  18646. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18647. to find out the channel.
  18648. @see channelPressureChange
  18649. */
  18650. bool isChannelPressure() const throw();
  18651. /** Returns the pressure from a channel pressure change message.
  18652. @returns the pressure, in the range 0 to 127
  18653. @see isChannelPressure, channelPressureChange
  18654. */
  18655. int getChannelPressureValue() const throw();
  18656. /** Creates a channel-pressure change event.
  18657. @param channel the midi channel: 1 to 16
  18658. @param pressure the pressure, 0 to 127
  18659. @see isChannelPressure
  18660. */
  18661. static const MidiMessage channelPressureChange (const int channel,
  18662. const int pressure) throw();
  18663. /** Returns true if this is a midi controller message.
  18664. @see getControllerNumber, getControllerValue, controllerEvent
  18665. */
  18666. bool isController() const throw();
  18667. /** Returns the controller number of a controller message.
  18668. The name of the controller can be looked up using the getControllerName() method.
  18669. Note that the value returned is invalid for messages that aren't controller changes.
  18670. @see isController, getControllerName, getControllerValue
  18671. */
  18672. int getControllerNumber() const throw();
  18673. /** Returns the controller value from a controller message.
  18674. A value 0 to 127 is returned to indicate the new controller position.
  18675. Note that the value returned is invalid for messages that aren't controller changes.
  18676. @see isController, getControllerNumber
  18677. */
  18678. int getControllerValue() const throw();
  18679. /** Creates a controller message.
  18680. @param channel the midi channel, in the range 1 to 16
  18681. @param controllerType the type of controller
  18682. @param value the controller value
  18683. @see isController
  18684. */
  18685. static const MidiMessage controllerEvent (const int channel,
  18686. const int controllerType,
  18687. const int value) throw();
  18688. /** Checks whether this message is an all-notes-off message.
  18689. @see allNotesOff
  18690. */
  18691. bool isAllNotesOff() const throw();
  18692. /** Checks whether this message is an all-sound-off message.
  18693. @see allSoundOff
  18694. */
  18695. bool isAllSoundOff() const throw();
  18696. /** Creates an all-notes-off message.
  18697. @param channel the midi channel, in the range 1 to 16
  18698. @see isAllNotesOff
  18699. */
  18700. static const MidiMessage allNotesOff (const int channel) throw();
  18701. /** Creates an all-sound-off message.
  18702. @param channel the midi channel, in the range 1 to 16
  18703. @see isAllSoundOff
  18704. */
  18705. static const MidiMessage allSoundOff (const int channel) throw();
  18706. /** Creates an all-controllers-off message.
  18707. @param channel the midi channel, in the range 1 to 16
  18708. */
  18709. static const MidiMessage allControllersOff (const int channel) throw();
  18710. /** Returns true if this event is a meta-event.
  18711. Meta-events are things like tempo changes, track names, etc.
  18712. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18713. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18714. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18715. */
  18716. bool isMetaEvent() const throw();
  18717. /** Returns a meta-event's type number.
  18718. If the message isn't a meta-event, this will return -1.
  18719. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18720. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18721. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18722. */
  18723. int getMetaEventType() const throw();
  18724. /** Returns a pointer to the data in a meta-event.
  18725. @see isMetaEvent, getMetaEventLength
  18726. */
  18727. const uint8* getMetaEventData() const throw();
  18728. /** Returns the length of the data for a meta-event.
  18729. @see isMetaEvent, getMetaEventData
  18730. */
  18731. int getMetaEventLength() const throw();
  18732. /** Returns true if this is a 'track' meta-event. */
  18733. bool isTrackMetaEvent() const throw();
  18734. /** Returns true if this is an 'end-of-track' meta-event. */
  18735. bool isEndOfTrackMetaEvent() const throw();
  18736. /** Creates an end-of-track meta-event.
  18737. @see isEndOfTrackMetaEvent
  18738. */
  18739. static const MidiMessage endOfTrack() throw();
  18740. /** Returns true if this is an 'track name' meta-event.
  18741. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18742. */
  18743. bool isTrackNameEvent() const throw();
  18744. /** Returns true if this is a 'text' meta-event.
  18745. @see getTextFromTextMetaEvent
  18746. */
  18747. bool isTextMetaEvent() const throw();
  18748. /** Returns the text from a text meta-event.
  18749. @see isTextMetaEvent
  18750. */
  18751. const String getTextFromTextMetaEvent() const throw();
  18752. /** Returns true if this is a 'tempo' meta-event.
  18753. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18754. */
  18755. bool isTempoMetaEvent() const throw();
  18756. /** Returns the tick length from a tempo meta-event.
  18757. @param timeFormat the 16-bit time format value from the midi file's header.
  18758. @returns the tick length (in seconds).
  18759. @see isTempoMetaEvent
  18760. */
  18761. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18762. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18763. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18764. */
  18765. double getTempoSecondsPerQuarterNote() const throw();
  18766. /** Creates a tempo meta-event.
  18767. @see isTempoMetaEvent
  18768. */
  18769. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18770. /** Returns true if this is a 'time-signature' meta-event.
  18771. @see getTimeSignatureInfo
  18772. */
  18773. bool isTimeSignatureMetaEvent() const throw();
  18774. /** Returns the time-signature values from a time-signature meta-event.
  18775. @see isTimeSignatureMetaEvent
  18776. */
  18777. void getTimeSignatureInfo (int& numerator,
  18778. int& denominator) const throw();
  18779. /** Creates a time-signature meta-event.
  18780. @see isTimeSignatureMetaEvent
  18781. */
  18782. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  18783. const int denominator) throw();
  18784. /** Returns true if this is a 'key-signature' meta-event.
  18785. @see getKeySignatureNumberOfSharpsOrFlats
  18786. */
  18787. bool isKeySignatureMetaEvent() const throw();
  18788. /** Returns the key from a key-signature meta-event.
  18789. @see isKeySignatureMetaEvent
  18790. */
  18791. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  18792. /** Returns true if this is a 'channel' meta-event.
  18793. A channel meta-event specifies the midi channel that should be used
  18794. for subsequent meta-events.
  18795. @see getMidiChannelMetaEventChannel
  18796. */
  18797. bool isMidiChannelMetaEvent() const throw();
  18798. /** Returns the channel number from a channel meta-event.
  18799. @returns the channel, in the range 1 to 16.
  18800. @see isMidiChannelMetaEvent
  18801. */
  18802. int getMidiChannelMetaEventChannel() const throw();
  18803. /** Creates a midi channel meta-event.
  18804. @param channel the midi channel, in the range 1 to 16
  18805. @see isMidiChannelMetaEvent
  18806. */
  18807. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  18808. /** Returns true if this is an active-sense message. */
  18809. bool isActiveSense() const throw();
  18810. /** Returns true if this is a midi start event.
  18811. @see midiStart
  18812. */
  18813. bool isMidiStart() const throw();
  18814. /** Creates a midi start event. */
  18815. static const MidiMessage midiStart() throw();
  18816. /** Returns true if this is a midi continue event.
  18817. @see midiContinue
  18818. */
  18819. bool isMidiContinue() const throw();
  18820. /** Creates a midi continue event. */
  18821. static const MidiMessage midiContinue() throw();
  18822. /** Returns true if this is a midi stop event.
  18823. @see midiStop
  18824. */
  18825. bool isMidiStop() const throw();
  18826. /** Creates a midi stop event. */
  18827. static const MidiMessage midiStop() throw();
  18828. /** Returns true if this is a midi clock event.
  18829. @see midiClock, songPositionPointer
  18830. */
  18831. bool isMidiClock() const throw();
  18832. /** Creates a midi clock event. */
  18833. static const MidiMessage midiClock() throw();
  18834. /** Returns true if this is a song-position-pointer message.
  18835. @see getSongPositionPointerMidiBeat, songPositionPointer
  18836. */
  18837. bool isSongPositionPointer() const throw();
  18838. /** Returns the midi beat-number of a song-position-pointer message.
  18839. @see isSongPositionPointer, songPositionPointer
  18840. */
  18841. int getSongPositionPointerMidiBeat() const throw();
  18842. /** Creates a song-position-pointer message.
  18843. The position is a number of midi beats from the start of the song, where 1 midi
  18844. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  18845. are 4 midi beats in a quarter-note.
  18846. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  18847. */
  18848. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  18849. /** Returns true if this is a quarter-frame midi timecode message.
  18850. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  18851. */
  18852. bool isQuarterFrame() const throw();
  18853. /** Returns the sequence number of a quarter-frame midi timecode message.
  18854. This will be a value between 0 and 7.
  18855. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  18856. */
  18857. int getQuarterFrameSequenceNumber() const throw();
  18858. /** Returns the value from a quarter-frame message.
  18859. This will be the lower nybble of the message's data-byte, a value
  18860. between 0 and 15
  18861. */
  18862. int getQuarterFrameValue() const throw();
  18863. /** Creates a quarter-frame MTC message.
  18864. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  18865. @param value a value 0 to 15 for the lower nybble of the message's data byte
  18866. */
  18867. static const MidiMessage quarterFrame (const int sequenceNumber,
  18868. const int value) throw();
  18869. /** SMPTE timecode types.
  18870. Used by the getFullFrameParameters() and fullFrame() methods.
  18871. */
  18872. enum SmpteTimecodeType
  18873. {
  18874. fps24 = 0,
  18875. fps25 = 1,
  18876. fps30drop = 2,
  18877. fps30 = 3
  18878. };
  18879. /** Returns true if this is a full-frame midi timecode message.
  18880. */
  18881. bool isFullFrame() const throw();
  18882. /** Extracts the timecode information from a full-frame midi timecode message.
  18883. You should only call this on messages where you've used isFullFrame() to
  18884. check that they're the right kind.
  18885. */
  18886. void getFullFrameParameters (int& hours,
  18887. int& minutes,
  18888. int& seconds,
  18889. int& frames,
  18890. SmpteTimecodeType& timecodeType) const throw();
  18891. /** Creates a full-frame MTC message.
  18892. */
  18893. static const MidiMessage fullFrame (const int hours,
  18894. const int minutes,
  18895. const int seconds,
  18896. const int frames,
  18897. SmpteTimecodeType timecodeType);
  18898. /** Types of MMC command.
  18899. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  18900. */
  18901. enum MidiMachineControlCommand
  18902. {
  18903. mmc_stop = 1,
  18904. mmc_play = 2,
  18905. mmc_deferredplay = 3,
  18906. mmc_fastforward = 4,
  18907. mmc_rewind = 5,
  18908. mmc_recordStart = 6,
  18909. mmc_recordStop = 7,
  18910. mmc_pause = 9
  18911. };
  18912. /** Checks whether this is an MMC message.
  18913. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  18914. */
  18915. bool isMidiMachineControlMessage() const throw();
  18916. /** For an MMC message, this returns its type.
  18917. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  18918. calling this method.
  18919. */
  18920. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  18921. /** Creates an MMC message.
  18922. */
  18923. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  18924. /** Checks whether this is an MMC "goto" message.
  18925. If it is, the parameters passed-in are set to the time that the message contains.
  18926. @see midiMachineControlGoto
  18927. */
  18928. bool isMidiMachineControlGoto (int& hours,
  18929. int& minutes,
  18930. int& seconds,
  18931. int& frames) const throw();
  18932. /** Creates an MMC "goto" message.
  18933. This messages tells the device to go to a specific frame.
  18934. @see isMidiMachineControlGoto
  18935. */
  18936. static const MidiMessage midiMachineControlGoto (int hours,
  18937. int minutes,
  18938. int seconds,
  18939. int frames);
  18940. /** Creates a master-volume change message.
  18941. @param volume the volume, 0 to 1.0
  18942. */
  18943. static const MidiMessage masterVolume (const float volume) throw();
  18944. /** Creates a system-exclusive message.
  18945. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  18946. */
  18947. static const MidiMessage createSysExMessage (const uint8* sysexData,
  18948. const int dataSize) throw();
  18949. /** Reads a midi variable-length integer.
  18950. @param data the data to read the number from
  18951. @param numBytesUsed on return, this will be set to the number of bytes that were read
  18952. */
  18953. static int readVariableLengthVal (const uint8* data,
  18954. int& numBytesUsed) throw();
  18955. /** Based on the first byte of a short midi message, this uses a lookup table
  18956. to return the message length (either 1, 2, or 3 bytes).
  18957. The value passed in must be 0x80 or higher.
  18958. */
  18959. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  18960. /** Returns the name of a midi note number.
  18961. E.g "C", "D#", etc.
  18962. @param noteNumber the midi note number, 0 to 127
  18963. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  18964. they'll be flattened, e.g. "Db"
  18965. @param includeOctaveNumber if true, the octave number will be appended to the string,
  18966. e.g. "C#4"
  18967. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  18968. number that will be used for middle C's octave
  18969. @see getMidiNoteInHertz
  18970. */
  18971. static const String getMidiNoteName (int noteNumber,
  18972. bool useSharps,
  18973. bool includeOctaveNumber,
  18974. int octaveNumForMiddleC) throw();
  18975. /** Returns the frequency of a midi note number.
  18976. @see getMidiNoteName
  18977. */
  18978. static const double getMidiNoteInHertz (int noteNumber) throw();
  18979. /** Returns the standard name of a GM instrument.
  18980. @param midiInstrumentNumber the program number 0 to 127
  18981. @see getProgramChangeNumber
  18982. */
  18983. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  18984. /** Returns the name of a bank of GM instruments.
  18985. @param midiBankNumber the bank, 0 to 15
  18986. */
  18987. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  18988. /** Returns the standard name of a channel 10 percussion sound.
  18989. @param midiNoteNumber the key number, 35 to 81
  18990. */
  18991. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  18992. /** Returns the name of a controller type number.
  18993. @see getControllerNumber
  18994. */
  18995. static const String getControllerName (int controllerNumber) throw();
  18996. juce_UseDebuggingNewOperator
  18997. private:
  18998. double timeStamp;
  18999. uint8* data;
  19000. int message, size;
  19001. };
  19002. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19003. /********* End of inlined file: juce_MidiMessage.h *********/
  19004. /**
  19005. Holds a sequence of time-stamped midi events.
  19006. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19007. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19008. @see MidiMessage
  19009. */
  19010. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19011. {
  19012. public:
  19013. /** Creates an empty MidiBuffer. */
  19014. MidiBuffer() throw();
  19015. /** Creates a copy of another MidiBuffer. */
  19016. MidiBuffer (const MidiBuffer& other) throw();
  19017. /** Makes a copy of another MidiBuffer. */
  19018. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19019. /** Destructor */
  19020. ~MidiBuffer() throw();
  19021. /** Removes all events from the buffer. */
  19022. void clear() throw();
  19023. /** Removes all events between two times from the buffer.
  19024. All events for which (start <= event position < start + numSamples) will
  19025. be removed.
  19026. */
  19027. void clear (const int start,
  19028. const int numSamples) throw();
  19029. /** Returns true if the buffer is empty.
  19030. To actually retrieve the events, use a MidiBuffer::Iterator object
  19031. */
  19032. bool isEmpty() const throw();
  19033. /** Counts the number of events in the buffer.
  19034. This is actually quite a slow operation, as it has to iterate through all
  19035. the events, so you might prefer to call isEmpty() if that's all you need
  19036. to know.
  19037. */
  19038. int getNumEvents() const throw();
  19039. /** Adds an event to the buffer.
  19040. The sample number will be used to determine the position of the event in
  19041. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19042. ignored.
  19043. If an event is added whose sample position is the same as one or more events
  19044. already in the buffer, the new event will be placed after the existing ones.
  19045. To retrieve events, use a MidiBuffer::Iterator object
  19046. */
  19047. void addEvent (const MidiMessage& midiMessage,
  19048. const int sampleNumber) throw();
  19049. /** Adds an event to the buffer from raw midi data.
  19050. The sample number will be used to determine the position of the event in
  19051. the buffer, which is always kept sorted.
  19052. If an event is added whose sample position is the same as one or more events
  19053. already in the buffer, the new event will be placed after the existing ones.
  19054. The event data will be inspected to calculate the number of bytes in length that
  19055. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19056. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19057. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19058. add an event at all.
  19059. To retrieve events, use a MidiBuffer::Iterator object
  19060. */
  19061. void addEvent (const uint8* const rawMidiData,
  19062. const int maxBytesOfMidiData,
  19063. const int sampleNumber) throw();
  19064. /** Adds some events from another buffer to this one.
  19065. @param otherBuffer the buffer containing the events you want to add
  19066. @param startSample the lowest sample number in the source buffer for which
  19067. events should be added. Any source events whose timestamp is
  19068. less than this will be ignored
  19069. @param numSamples the valid range of samples from the source buffer for which
  19070. events should be added - i.e. events in the source buffer whose
  19071. timestamp is greater than or equal to (startSample + numSamples)
  19072. will be ignored. If this value is less than 0, all events after
  19073. startSample will be taken.
  19074. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19075. that are added to this buffer
  19076. */
  19077. void addEvents (const MidiBuffer& otherBuffer,
  19078. const int startSample,
  19079. const int numSamples,
  19080. const int sampleDeltaToAdd) throw();
  19081. /** Returns the sample number of the first event in the buffer.
  19082. If the buffer's empty, this will just return 0.
  19083. */
  19084. int getFirstEventTime() const throw();
  19085. /** Returns the sample number of the last event in the buffer.
  19086. If the buffer's empty, this will just return 0.
  19087. */
  19088. int getLastEventTime() const throw();
  19089. /**
  19090. Used to iterate through the events in a MidiBuffer.
  19091. Note that altering the buffer while an iterator is using it isn't a
  19092. safe operation.
  19093. @see MidiBuffer
  19094. */
  19095. class Iterator
  19096. {
  19097. public:
  19098. /** Creates an Iterator for this MidiBuffer. */
  19099. Iterator (const MidiBuffer& buffer) throw();
  19100. /** Destructor. */
  19101. ~Iterator() throw();
  19102. /** Repositions the iterator so that the next event retrieved will be the first
  19103. one whose sample position is at greater than or equal to the given position.
  19104. */
  19105. void setNextSamplePosition (const int samplePosition) throw();
  19106. /** Retrieves a copy of the next event from the buffer.
  19107. @param result on return, this will be the message (the MidiMessage's timestamp
  19108. is not set)
  19109. @param samplePosition on return, this will be the position of the event
  19110. @returns true if an event was found, or false if the iterator has reached
  19111. the end of the buffer
  19112. */
  19113. bool getNextEvent (MidiMessage& result,
  19114. int& samplePosition) throw();
  19115. /** Retrieves the next event from the buffer.
  19116. @param midiData on return, this pointer will be set to a block of data containing
  19117. the midi message. Note that to make it fast, this is a pointer
  19118. directly into the MidiBuffer's internal data, so is only valid
  19119. temporarily until the MidiBuffer is altered.
  19120. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19121. midi message
  19122. @param samplePosition on return, this will be the position of the event
  19123. @returns true if an event was found, or false if the iterator has reached
  19124. the end of the buffer
  19125. */
  19126. bool getNextEvent (const uint8* &midiData,
  19127. int& numBytesOfMidiData,
  19128. int& samplePosition) throw();
  19129. juce_UseDebuggingNewOperator
  19130. private:
  19131. const MidiBuffer& buffer;
  19132. const uint8* data;
  19133. Iterator (const Iterator&);
  19134. const Iterator& operator= (const Iterator&);
  19135. };
  19136. juce_UseDebuggingNewOperator
  19137. private:
  19138. friend class MidiBuffer::Iterator;
  19139. int bytesUsed;
  19140. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19141. };
  19142. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19143. /********* End of inlined file: juce_MidiBuffer.h *********/
  19144. #endif
  19145. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19146. /********* Start of inlined file: juce_MidiFile.h *********/
  19147. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19148. #define __JUCE_MIDIFILE_JUCEHEADER__
  19149. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19150. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19151. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19152. /**
  19153. A sequence of timestamped midi messages.
  19154. This allows the sequence to be manipulated, and also to be read from and
  19155. written to a standard midi file.
  19156. @see MidiMessage, MidiFile
  19157. */
  19158. class JUCE_API MidiMessageSequence
  19159. {
  19160. public:
  19161. /** Creates an empty midi sequence object. */
  19162. MidiMessageSequence();
  19163. /** Creates a copy of another sequence. */
  19164. MidiMessageSequence (const MidiMessageSequence& other);
  19165. /** Replaces this sequence with another one. */
  19166. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19167. /** Destructor. */
  19168. ~MidiMessageSequence();
  19169. /** Structure used to hold midi events in the sequence.
  19170. These structures act as 'handles' on the events as they are moved about in
  19171. the list, and make it quick to find the matching note-offs for note-on events.
  19172. @see MidiMessageSequence::getEventPointer
  19173. */
  19174. class MidiEventHolder
  19175. {
  19176. public:
  19177. /** Destructor. */
  19178. ~MidiEventHolder();
  19179. /** The message itself, whose timestamp is used to specify the event's time.
  19180. */
  19181. MidiMessage message;
  19182. /** The matching note-off event (if this is a note-on event).
  19183. If this isn't a note-on, this pointer will be null.
  19184. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19185. note-offs up-to-date after events have been moved around in the sequence
  19186. or deleted.
  19187. */
  19188. MidiEventHolder* noteOffObject;
  19189. juce_UseDebuggingNewOperator
  19190. private:
  19191. friend class MidiMessageSequence;
  19192. MidiEventHolder (const MidiMessage& message);
  19193. };
  19194. /** Clears the sequence. */
  19195. void clear();
  19196. /** Returns the number of events in the sequence. */
  19197. int getNumEvents() const;
  19198. /** Returns a pointer to one of the events. */
  19199. MidiEventHolder* getEventPointer (const int index) const;
  19200. /** Returns the time of the note-up that matches the note-on at this index.
  19201. If the event at this index isn't a note-on, it'll just return 0.
  19202. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19203. */
  19204. double getTimeOfMatchingKeyUp (const int index) const;
  19205. /** Returns the index of the note-up that matches the note-on at this index.
  19206. If the event at this index isn't a note-on, it'll just return -1.
  19207. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19208. */
  19209. int getIndexOfMatchingKeyUp (const int index) const;
  19210. /** Returns the index of an event. */
  19211. int getIndexOf (MidiEventHolder* const event) const;
  19212. /** Returns the index of the first event on or after the given timestamp.
  19213. If the time is beyond the end of the sequence, this will return the
  19214. number of events.
  19215. */
  19216. int getNextIndexAtTime (const double timeStamp) const;
  19217. /** Returns the timestamp of the first event in the sequence.
  19218. @see getEndTime
  19219. */
  19220. double getStartTime() const;
  19221. /** Returns the timestamp of the last event in the sequence.
  19222. @see getStartTime
  19223. */
  19224. double getEndTime() const;
  19225. /** Returns the timestamp of the event at a given index.
  19226. If the index is out-of-range, this will return 0.0
  19227. */
  19228. double getEventTime (const int index) const;
  19229. /** Inserts a midi message into the sequence.
  19230. The index at which the new message gets inserted will depend on its timestamp,
  19231. because the sequence is kept sorted.
  19232. Remember to call updateMatchedPairs() after adding note-on events.
  19233. @param newMessage the new message to add (an internal copy will be made)
  19234. @param timeAdjustment an optional value to add to the timestamp of the message
  19235. that will be inserted
  19236. @see updateMatchedPairs
  19237. */
  19238. void addEvent (const MidiMessage& newMessage,
  19239. double timeAdjustment = 0);
  19240. /** Deletes one of the events in the sequence.
  19241. Remember to call updateMatchedPairs() after removing events.
  19242. @param index the index of the event to delete
  19243. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19244. if the event you're removing is a note-on
  19245. */
  19246. void deleteEvent (const int index,
  19247. const bool deleteMatchingNoteUp);
  19248. /** Merges another sequence into this one.
  19249. Remember to call updateMatchedPairs() after using this method.
  19250. @param other the sequence to add from
  19251. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19252. as they are read from the other sequence
  19253. @param firstAllowableDestTime events will not be added if their time is earlier
  19254. than this time. (This is after their time has been adjusted
  19255. by the timeAdjustmentDelta)
  19256. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19257. or greater than this time. (This is after their time has
  19258. been adjusted by the timeAdjustmentDelta)
  19259. */
  19260. void addSequence (const MidiMessageSequence& other,
  19261. double timeAdjustmentDelta,
  19262. double firstAllowableDestTime,
  19263. double endOfAllowableDestTimes);
  19264. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19265. Call this after moving messages about or deleting/adding messages, and it
  19266. will scan the list and make sure all the note-offs in the MidiEventHolder
  19267. structures are pointing at the correct ones.
  19268. */
  19269. void updateMatchedPairs();
  19270. /** Copies all the messages for a particular midi channel to another sequence.
  19271. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19272. @param destSequence the sequence that the chosen events should be copied to
  19273. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19274. channel) will also be copied across.
  19275. @see extractSysExMessages
  19276. */
  19277. void extractMidiChannelMessages (const int channelNumberToExtract,
  19278. MidiMessageSequence& destSequence,
  19279. const bool alsoIncludeMetaEvents) const;
  19280. /** Copies all midi sys-ex messages to another sequence.
  19281. @param destSequence this is the sequence to which any sys-exes in this sequence
  19282. will be added
  19283. @see extractMidiChannelMessages
  19284. */
  19285. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19286. /** Removes any messages in this sequence that have a specific midi channel.
  19287. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19288. */
  19289. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19290. /** Removes any sys-ex messages from this sequence.
  19291. */
  19292. void deleteSysExMessages();
  19293. /** Adds an offset to the timestamps of all events in the sequence.
  19294. @param deltaTime the amount to add to each timestamp.
  19295. */
  19296. void addTimeToMessages (const double deltaTime);
  19297. /** Scans through the sequence to determine the state of any midi controllers at
  19298. a given time.
  19299. This will create a sequence of midi controller changes that can be
  19300. used to set all midi controllers to the state they would be in at the
  19301. specified time within this sequence.
  19302. As well as controllers, it will also recreate the midi program number
  19303. and pitch bend position.
  19304. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19305. for other channels will be ignored.
  19306. @param time the time at which you want to find out the state - there are
  19307. no explicit units for this time measurement, it's the same units
  19308. as used for the timestamps of the messages
  19309. @param resultMessages an array to which midi controller-change messages will be added. This
  19310. will be the minimum number of controller changes to recreate the
  19311. state at the required time.
  19312. */
  19313. void createControllerUpdatesForTime (const int channelNumber,
  19314. const double time,
  19315. OwnedArray<MidiMessage>& resultMessages);
  19316. juce_UseDebuggingNewOperator
  19317. /** @internal */
  19318. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19319. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19320. private:
  19321. friend class MidiComparator;
  19322. friend class MidiFile;
  19323. OwnedArray <MidiEventHolder> list;
  19324. void sort();
  19325. };
  19326. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19327. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19328. /**
  19329. Reads/writes standard midi format files.
  19330. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19331. can then get the individual midi tracks from it using the getTrack() method.
  19332. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19333. to it using the addTrack() method, and then call its writeTo() method to stream
  19334. it out.
  19335. @see MidiMessageSequence
  19336. */
  19337. class JUCE_API MidiFile
  19338. {
  19339. public:
  19340. /** Creates an empty MidiFile object.
  19341. */
  19342. MidiFile() throw();
  19343. /** Destructor. */
  19344. ~MidiFile() throw();
  19345. /** Returns the number of tracks in the file.
  19346. @see getTrack, addTrack
  19347. */
  19348. int getNumTracks() const throw();
  19349. /** Returns a pointer to one of the tracks in the file.
  19350. @returns a pointer to the track, or 0 if the index is out-of-range
  19351. @see getNumTracks, addTrack
  19352. */
  19353. const MidiMessageSequence* getTrack (const int index) const throw();
  19354. /** Adds a midi track to the file.
  19355. This will make its own internal copy of the sequence that is passed-in.
  19356. @see getNumTracks, getTrack
  19357. */
  19358. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19359. /** Removes all midi tracks from the file.
  19360. @see getNumTracks
  19361. */
  19362. void clear() throw();
  19363. /** Returns the raw time format code that will be written to a stream.
  19364. After reading a midi file, this method will return the time-format that
  19365. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19366. or setSmpteTimeFormat() methods.
  19367. If the value returned is positive, it indicates the number of midi ticks
  19368. per quarter-note - see setTicksPerQuarterNote().
  19369. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19370. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19371. */
  19372. short getTimeFormat() const throw();
  19373. /** Sets the time format to use when this file is written to a stream.
  19374. If this is called, the file will be written as bars/beats using the
  19375. specified resolution, rather than SMPTE absolute times, as would be
  19376. used if setSmpteTimeFormat() had been called instead.
  19377. @param ticksPerQuarterNote e.g. 96, 960
  19378. @see setSmpteTimeFormat
  19379. */
  19380. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19381. /** Sets the time format to use when this file is written to a stream.
  19382. If this is called, the file will be written using absolute times, rather
  19383. than bars/beats as would be the case if setTicksPerBeat() had been called
  19384. instead.
  19385. @param framesPerSecond must be 24, 25, 29 or 30
  19386. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19387. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19388. timing, setSmpteTimeFormat (25, 40)
  19389. @see setTicksPerBeat
  19390. */
  19391. void setSmpteTimeFormat (const int framesPerSecond,
  19392. const int subframeResolution) throw();
  19393. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19394. Useful for finding the positions of all the tempo changes in a file.
  19395. @param tempoChangeEvents a list to which all the events will be added
  19396. */
  19397. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19398. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19399. Useful for finding the positions of all the tempo changes in a file.
  19400. @param timeSigEvents a list to which all the events will be added
  19401. */
  19402. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19403. /** Returns the latest timestamp in any of the tracks.
  19404. (Useful for finding the length of the file).
  19405. */
  19406. double getLastTimestamp() const;
  19407. /** Reads a midi file format stream.
  19408. After calling this, you can get the tracks that were read from the file by using the
  19409. getNumTracks() and getTrack() methods.
  19410. The timestamps of the midi events in the tracks will represent their positions in
  19411. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19412. method.
  19413. @returns true if the stream was read successfully
  19414. */
  19415. bool readFrom (InputStream& sourceStream);
  19416. /** Writes the midi tracks as a standard midi file.
  19417. @returns true if the operation succeeded.
  19418. */
  19419. bool writeTo (OutputStream& destStream);
  19420. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19421. This will use the midi time format and tempo/time signature info in the
  19422. tracks to convert all the timestamps to absolute values in seconds.
  19423. */
  19424. void convertTimestampTicksToSeconds();
  19425. juce_UseDebuggingNewOperator
  19426. /** @internal */
  19427. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19428. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19429. private:
  19430. MidiMessageSequence* tracks [128];
  19431. short numTracks, timeFormat;
  19432. MidiFile (const MidiFile&);
  19433. const MidiFile& operator= (const MidiFile&);
  19434. void readNextTrack (const char* data, int size);
  19435. void writeTrack (OutputStream& mainOut, const int trackNum);
  19436. };
  19437. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19438. /********* End of inlined file: juce_MidiFile.h *********/
  19439. #endif
  19440. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19441. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19442. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19443. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19444. class MidiKeyboardState;
  19445. /**
  19446. Receives events from a MidiKeyboardState object.
  19447. @see MidiKeyboardState
  19448. */
  19449. class JUCE_API MidiKeyboardStateListener
  19450. {
  19451. public:
  19452. MidiKeyboardStateListener() throw() {}
  19453. virtual ~MidiKeyboardStateListener() {}
  19454. /** Called when one of the MidiKeyboardState's keys is pressed.
  19455. This will be called synchronously when the state is either processing a
  19456. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19457. when a note is being played with its MidiKeyboardState::noteOn() method.
  19458. Note that this callback could happen from an audio callback thread, so be
  19459. careful not to block, and avoid any UI activity in the callback.
  19460. */
  19461. virtual void handleNoteOn (MidiKeyboardState* source,
  19462. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19463. /** Called when one of the MidiKeyboardState's keys is released.
  19464. This will be called synchronously when the state is either processing a
  19465. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19466. when a note is being played with its MidiKeyboardState::noteOff() method.
  19467. Note that this callback could happen from an audio callback thread, so be
  19468. careful not to block, and avoid any UI activity in the callback.
  19469. */
  19470. virtual void handleNoteOff (MidiKeyboardState* source,
  19471. int midiChannel, int midiNoteNumber) = 0;
  19472. };
  19473. /**
  19474. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19475. This object can parse a stream of midi events, using them to update its idea
  19476. of which keys are pressed for each individiual midi channel.
  19477. When keys go up or down, it can broadcast these events to listener objects.
  19478. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19479. methods, and midi messages for these events will be merged into the
  19480. midi stream that gets processed by processNextMidiBuffer().
  19481. */
  19482. class JUCE_API MidiKeyboardState
  19483. {
  19484. public:
  19485. MidiKeyboardState();
  19486. ~MidiKeyboardState();
  19487. /** Resets the state of the object.
  19488. All internal data for all the channels is reset, but no events are sent as a
  19489. result.
  19490. If you want to release any keys that are currently down, and to send out note-up
  19491. midi messages for this, use the allNotesOff() method instead.
  19492. */
  19493. void reset();
  19494. /** Returns true if the given midi key is currently held down for the given midi channel.
  19495. The channel number must be between 1 and 16. If you want to see if any notes are
  19496. on for a range of channels, use the isNoteOnForChannels() method.
  19497. */
  19498. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19499. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19500. The channel mask has a bit set for each midi channel you want to test for - bit
  19501. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19502. If a note is on for at least one of the specified channels, this returns true.
  19503. */
  19504. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19505. /** Turns a specified note on.
  19506. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19507. next call to processNextMidiBuffer().
  19508. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19509. gone down.
  19510. */
  19511. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19512. /** Turns a specified note off.
  19513. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19514. next call to processNextMidiBuffer().
  19515. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19516. gone up.
  19517. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19518. */
  19519. void noteOff (const int midiChannel, const int midiNoteNumber);
  19520. /** This will turn off any currently-down notes for the given midi channel.
  19521. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19522. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19523. and events being added to the midi stream.
  19524. */
  19525. void allNotesOff (const int midiChannel);
  19526. /** Looks at a key-up/down event and uses it to update the state of this object.
  19527. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19528. instead.
  19529. */
  19530. void processNextMidiEvent (const MidiMessage& message);
  19531. /** Scans a midi stream for up/down events and adds its own events to it.
  19532. This will look for any up/down events and use them to update the internal state,
  19533. synchronously making suitable callbacks to the listeners.
  19534. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19535. and noteOff() calls will be added into the buffer.
  19536. Only the section of the buffer whose timestamps are between startSample and
  19537. (startSample + numSamples) will be affected, and any events added will be placed
  19538. between these times.
  19539. If you're going to use this method, you'll need to keep calling it regularly for
  19540. it to work satisfactorily.
  19541. To process a single midi event at a time, use the processNextMidiEvent() method
  19542. instead.
  19543. */
  19544. void processNextMidiBuffer (MidiBuffer& buffer,
  19545. const int startSample,
  19546. const int numSamples,
  19547. const bool injectIndirectEvents);
  19548. /** Registers a listener for callbacks when keys go up or down.
  19549. @see removeListener
  19550. */
  19551. void addListener (MidiKeyboardStateListener* const listener) throw();
  19552. /** Deregisters a listener.
  19553. @see addListener
  19554. */
  19555. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19556. juce_UseDebuggingNewOperator
  19557. private:
  19558. CriticalSection lock;
  19559. uint16 noteStates [128];
  19560. MidiBuffer eventsToAdd;
  19561. VoidArray listeners;
  19562. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19563. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19564. MidiKeyboardState (const MidiKeyboardState&);
  19565. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19566. };
  19567. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19568. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19569. #endif
  19570. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19571. #endif
  19572. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19573. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19574. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19575. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19576. /********* Start of inlined file: juce_MidiInput.h *********/
  19577. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19578. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19579. class MidiInput;
  19580. /**
  19581. Receives midi messages from a midi input device.
  19582. This class is overridden to handle incoming midi messages. See the MidiInput
  19583. class for more details.
  19584. @see MidiInput
  19585. */
  19586. class JUCE_API MidiInputCallback
  19587. {
  19588. public:
  19589. /** Destructor. */
  19590. virtual ~MidiInputCallback() {}
  19591. /** Receives an incoming message.
  19592. A MidiInput object will call this method when a midi event arrives. It'll be
  19593. called on a high-priority system thread, so avoid doing anything time-consuming
  19594. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19595. for queueing incoming messages for use later.
  19596. @param source the MidiInput object that generated the message
  19597. @param message the incoming message. The message's timestamp is set to a value
  19598. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19599. time when the message arrived.
  19600. */
  19601. virtual void handleIncomingMidiMessage (MidiInput* source,
  19602. const MidiMessage& message) = 0;
  19603. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19604. If a long sysex message is broken up into multiple packets, this callback is made
  19605. for each packet that arrives until the message is finished, at which point
  19606. the normal handleIncomingMidiMessage() callback will be made with the entire
  19607. message.
  19608. The message passed in will contain the start of a sysex, but won't be finished
  19609. with the terminating 0xf7 byte.
  19610. */
  19611. virtual void handlePartialSysexMessage (MidiInput* source,
  19612. const uint8* messageData,
  19613. const int numBytesSoFar,
  19614. const double timestamp)
  19615. {
  19616. // (this bit is just to avoid compiler warnings about unused variables)
  19617. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19618. }
  19619. };
  19620. /**
  19621. Represents a midi input device.
  19622. To create one of these, use the static getDevices() method to find out what inputs are
  19623. available, and then use the openDevice() method to try to open one.
  19624. @see MidiOutput
  19625. */
  19626. class JUCE_API MidiInput
  19627. {
  19628. public:
  19629. /** Returns a list of the available midi input devices.
  19630. You can open one of the devices by passing its index into the
  19631. openDevice() method.
  19632. @see getDefaultDeviceIndex, openDevice
  19633. */
  19634. static const StringArray getDevices();
  19635. /** Returns the index of the default midi input device to use.
  19636. This refers to the index in the list returned by getDevices().
  19637. */
  19638. static int getDefaultDeviceIndex();
  19639. /** Tries to open one of the midi input devices.
  19640. This will return a MidiInput object if it manages to open it. You can then
  19641. call start() and stop() on this device, and delete it when no longer needed.
  19642. If the device can't be opened, this will return a null pointer.
  19643. @param deviceIndex the index of a device from the list returned by getDevices()
  19644. @param callback the object that will receive the midi messages from this device.
  19645. @see MidiInputCallback, getDevices
  19646. */
  19647. static MidiInput* openDevice (int deviceIndex,
  19648. MidiInputCallback* callback);
  19649. #if JUCE_LINUX || DOXYGEN
  19650. /** LINUX ONLY - This will try to create a new midi input device.
  19651. This will attempt to create a new midi input device with the specified name,
  19652. for other apps to connect to.
  19653. Returns 0 if a device can't be created.
  19654. @param deviceName the name to use for the new device
  19655. @param callback the object that will receive the midi messages from this device.
  19656. */
  19657. static MidiInput* createNewDevice (const String& deviceName,
  19658. MidiInputCallback* callback);
  19659. #endif
  19660. /** Destructor. */
  19661. ~MidiInput();
  19662. /** Returns the name of this device.
  19663. */
  19664. const String getName() const throw() { return name; }
  19665. /** Allows you to set a custom name for the device, in case you don't like the name
  19666. it was given when created.
  19667. */
  19668. void setName (const String& newName) throw() { name = newName; }
  19669. /** Starts the device running.
  19670. After calling this, the device will start sending midi messages to the
  19671. MidiInputCallback object that was specified when the openDevice() method
  19672. was called.
  19673. @see stop
  19674. */
  19675. void start();
  19676. /** Stops the device running.
  19677. @see start
  19678. */
  19679. void stop();
  19680. juce_UseDebuggingNewOperator
  19681. private:
  19682. String name;
  19683. void* internal;
  19684. MidiInput (const String& name);
  19685. MidiInput (const MidiInput&);
  19686. };
  19687. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19688. /********* End of inlined file: juce_MidiInput.h *********/
  19689. /**
  19690. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19691. processing by a block-based audio callback.
  19692. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19693. so it can easily use a midi input or keyboard component as its source.
  19694. @see MidiMessage, MidiInput
  19695. */
  19696. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19697. public MidiInputCallback
  19698. {
  19699. public:
  19700. /** Creates a MidiMessageCollector. */
  19701. MidiMessageCollector();
  19702. /** Destructor. */
  19703. ~MidiMessageCollector();
  19704. /** Clears any messages from the queue.
  19705. You need to call this method before starting to use the collector, so that
  19706. it knows the correct sample rate to use.
  19707. */
  19708. void reset (const double sampleRate);
  19709. /** Takes an incoming real-time message and adds it to the queue.
  19710. The message's timestamp is taken, and it will be ready for retrieval as part
  19711. of the block returned by the next call to removeNextBlockOfMessages().
  19712. This method is fully thread-safe when overlapping calls are made with
  19713. removeNextBlockOfMessages().
  19714. */
  19715. void addMessageToQueue (const MidiMessage& message);
  19716. /** Removes all the pending messages from the queue as a buffer.
  19717. This will also correct the messages' timestamps to make sure they're in
  19718. the range 0 to numSamples - 1.
  19719. This call should be made regularly by something like an audio processing
  19720. callback, because the time that it happens is used in calculating the
  19721. midi event positions.
  19722. This method is fully thread-safe when overlapping calls are made with
  19723. addMessageToQueue().
  19724. */
  19725. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19726. const int numSamples);
  19727. /** @internal */
  19728. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19729. /** @internal */
  19730. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19731. /** @internal */
  19732. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19733. juce_UseDebuggingNewOperator
  19734. private:
  19735. double lastCallbackTime;
  19736. CriticalSection midiCallbackLock;
  19737. MidiBuffer incomingMessages;
  19738. double sampleRate;
  19739. MidiMessageCollector (const MidiMessageCollector&);
  19740. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19741. };
  19742. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19743. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19744. #endif
  19745. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19746. #endif
  19747. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19748. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19749. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19750. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19751. /**
  19752. A set of routines to convert buffers of 32-bit floating point data to and from
  19753. various integer formats.
  19754. */
  19755. class JUCE_API AudioDataConverters
  19756. {
  19757. public:
  19758. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19759. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19760. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19761. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19762. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19763. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19764. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19765. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19766. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19767. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19768. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19769. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19770. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19771. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19772. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19773. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19774. enum DataFormat
  19775. {
  19776. int16LE,
  19777. int16BE,
  19778. int24LE,
  19779. int24BE,
  19780. int32LE,
  19781. int32BE,
  19782. float32LE,
  19783. float32BE,
  19784. };
  19785. static void convertFloatToFormat (const DataFormat destFormat,
  19786. const float* source, void* dest, int numSamples);
  19787. static void convertFormatToFloat (const DataFormat sourceFormat,
  19788. const void* source, float* dest, int numSamples);
  19789. static void interleaveSamples (const float** source, float* dest,
  19790. const int numSamples, const int numChannels);
  19791. static void deinterleaveSamples (const float* source, float** dest,
  19792. const int numSamples, const int numChannels);
  19793. };
  19794. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19795. /********* End of inlined file: juce_AudioDataConverters.h *********/
  19796. #endif
  19797. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19798. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  19799. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19800. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19801. class AudioFormatReader;
  19802. class AudioFormatWriter;
  19803. /**
  19804. A multi-channel buffer of 32-bit floating point audio samples.
  19805. */
  19806. class JUCE_API AudioSampleBuffer
  19807. {
  19808. public:
  19809. /** Creates a buffer with a specified number of channels and samples.
  19810. The contents of the buffer will initially be undefined, so use clear() to
  19811. set all the samples to zero.
  19812. The buffer will allocate its memory internally, and this will be released
  19813. when the buffer is deleted.
  19814. */
  19815. AudioSampleBuffer (const int numChannels,
  19816. const int numSamples) throw();
  19817. /** Creates a buffer using a pre-allocated block of memory.
  19818. Note that if the buffer is resized or its number of channels is changed, it
  19819. will re-allocate memory internally and copy the existing data to this new area,
  19820. so it will then stop directly addressing this memory.
  19821. @param dataToReferTo a pre-allocated array containing pointers to the data
  19822. for each channel that should be used by this buffer. The
  19823. buffer will only refer to this memory, it won't try to delete
  19824. it when the buffer is deleted or resized.
  19825. @param numChannels the number of channels to use - this must correspond to the
  19826. number of elements in the array passed in
  19827. @param numSamples the number of samples to use - this must correspond to the
  19828. size of the arrays passed in
  19829. */
  19830. AudioSampleBuffer (float** dataToReferTo,
  19831. const int numChannels,
  19832. const int numSamples) throw();
  19833. /** Copies another buffer.
  19834. This buffer will make its own copy of the other's data, unless the buffer was created
  19835. using an external data buffer, in which case boths buffers will just point to the same
  19836. shared block of data.
  19837. */
  19838. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  19839. /** Copies another buffer onto this one.
  19840. This buffer's size will be changed to that of the other buffer.
  19841. */
  19842. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  19843. /** Destructor.
  19844. This will free any memory allocated by the buffer.
  19845. */
  19846. virtual ~AudioSampleBuffer() throw();
  19847. /** Returns the number of channels of audio data that this buffer contains.
  19848. @see getSampleData
  19849. */
  19850. int getNumChannels() const throw() { return numChannels; }
  19851. /** Returns the number of samples allocated in each of the buffer's channels.
  19852. @see getSampleData
  19853. */
  19854. int getNumSamples() const throw() { return size; }
  19855. /** Returns a pointer to a sample in one of the buffer's channels.
  19856. For speed, this doesn't check whether the channel and sample number
  19857. are legal, so be careful when using it!
  19858. */
  19859. float* getSampleData (const int channelNumber,
  19860. const int sampleOffset = 0) const throw();
  19861. /** Chages the buffer's size or number of channels.
  19862. This can expand or contract the buffer's length, and add or remove channels.
  19863. If keepExistingContent is true, it will try to preserve as much of the
  19864. old data as it can in the new buffer.
  19865. If clearExtraSpace is true, then any extra channels or space that is
  19866. allocated will be also be cleared. If false, then this space is left
  19867. uninitialised.
  19868. If avoidReallocating is true, then changing the buffer's size won't reduce the
  19869. amount of memory that is currently allocated (but it will still increase it if
  19870. the new size is bigger than the amount it currently has). If this is false, then
  19871. a new allocation will be done so that the buffer uses takes up the minimum amount
  19872. of memory that it needs.
  19873. */
  19874. void setSize (const int newNumChannels,
  19875. const int newNumSamples,
  19876. const bool keepExistingContent = false,
  19877. const bool clearExtraSpace = false,
  19878. const bool avoidReallocating = false) throw();
  19879. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  19880. There's also a constructor that lets you specify arrays like this, but this
  19881. lets you change the channels dynamically.
  19882. Note that if the buffer is resized or its number of channels is changed, it
  19883. will re-allocate memory internally and copy the existing data to this new area,
  19884. so it will then stop directly addressing this memory.
  19885. @param dataToReferTo a pre-allocated array containing pointers to the data
  19886. for each channel that should be used by this buffer. The
  19887. buffer will only refer to this memory, it won't try to delete
  19888. it when the buffer is deleted or resized.
  19889. @param numChannels the number of channels to use - this must correspond to the
  19890. number of elements in the array passed in
  19891. @param numSamples the number of samples to use - this must correspond to the
  19892. size of the arrays passed in
  19893. */
  19894. void setDataToReferTo (float** dataToReferTo,
  19895. const int numChannels,
  19896. const int numSamples) throw();
  19897. /** Clears all the samples in all channels. */
  19898. void clear() throw();
  19899. /** Clears a specified region of all the channels.
  19900. For speed, this doesn't check whether the channel and sample number
  19901. are in-range, so be careful!
  19902. */
  19903. void clear (const int startSample,
  19904. const int numSamples) throw();
  19905. /** Clears a specified region of just one channel.
  19906. For speed, this doesn't check whether the channel and sample number
  19907. are in-range, so be careful!
  19908. */
  19909. void clear (const int channel,
  19910. const int startSample,
  19911. const int numSamples) throw();
  19912. /** Applies a gain multiple to a region of one channel.
  19913. For speed, this doesn't check whether the channel and sample number
  19914. are in-range, so be careful!
  19915. */
  19916. void applyGain (const int channel,
  19917. const int startSample,
  19918. int numSamples,
  19919. const float gain) throw();
  19920. /** Applies a gain multiple to a region of all the channels.
  19921. For speed, this doesn't check whether the sample numbers
  19922. are in-range, so be careful!
  19923. */
  19924. void applyGain (const int startSample,
  19925. const int numSamples,
  19926. const float gain) throw();
  19927. /** Applies a range of gains to a region of a channel.
  19928. The gain that is applied to each sample will vary from
  19929. startGain on the first sample to endGain on the last Sample,
  19930. so it can be used to do basic fades.
  19931. For speed, this doesn't check whether the sample numbers
  19932. are in-range, so be careful!
  19933. */
  19934. void applyGainRamp (const int channel,
  19935. const int startSample,
  19936. int numSamples,
  19937. float startGain,
  19938. float endGain) throw();
  19939. /** Adds samples from another buffer to this one.
  19940. @param destChannel the channel within this buffer to add the samples to
  19941. @param destStartSample the start sample within this buffer's channel
  19942. @param source the source buffer to add from
  19943. @param sourceChannel the channel within the source buffer to read from
  19944. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  19945. @param numSamples the number of samples to process
  19946. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  19947. added to this buffer's samples
  19948. @see copyFrom
  19949. */
  19950. void addFrom (const int destChannel,
  19951. const int destStartSample,
  19952. const AudioSampleBuffer& source,
  19953. const int sourceChannel,
  19954. const int sourceStartSample,
  19955. int numSamples,
  19956. const float gainToApplyToSource = 1.0f) throw();
  19957. /** Adds samples from an array of floats to one of the channels.
  19958. @param destChannel the channel within this buffer to add the samples to
  19959. @param destStartSample the start sample within this buffer's channel
  19960. @param source the source data to use
  19961. @param numSamples the number of samples to process
  19962. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  19963. added to this buffer's samples
  19964. @see copyFrom
  19965. */
  19966. void addFrom (const int destChannel,
  19967. const int destStartSample,
  19968. const float* source,
  19969. int numSamples,
  19970. const float gainToApplyToSource = 1.0f) throw();
  19971. /** Adds samples from an array of floats, applying a gain ramp to them.
  19972. @param destChannel the channel within this buffer to add the samples to
  19973. @param destStartSample the start sample within this buffer's channel
  19974. @param source the source data to use
  19975. @param numSamples the number of samples to process
  19976. @param startGain the gain to apply to the first sample (this is multiplied with
  19977. the source samples before they are added to this buffer)
  19978. @param endGain the gain to apply to the final sample. The gain is linearly
  19979. interpolated between the first and last samples.
  19980. */
  19981. void addFromWithRamp (const int destChannel,
  19982. const int destStartSample,
  19983. const float* source,
  19984. int numSamples,
  19985. float startGain,
  19986. float endGain) throw();
  19987. /** Copies samples from another buffer to this one.
  19988. @param destChannel the channel within this buffer to copy the samples to
  19989. @param destStartSample the start sample within this buffer's channel
  19990. @param source the source buffer to read from
  19991. @param sourceChannel the channel within the source buffer to read from
  19992. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  19993. @param numSamples the number of samples to process
  19994. @see addFrom
  19995. */
  19996. void copyFrom (const int destChannel,
  19997. const int destStartSample,
  19998. const AudioSampleBuffer& source,
  19999. const int sourceChannel,
  20000. const int sourceStartSample,
  20001. int numSamples) throw();
  20002. /** Copies samples from an array of floats into one of the channels.
  20003. @param destChannel the channel within this buffer to copy the samples to
  20004. @param destStartSample the start sample within this buffer's channel
  20005. @param source the source buffer to read from
  20006. @param numSamples the number of samples to process
  20007. @see addFrom
  20008. */
  20009. void copyFrom (const int destChannel,
  20010. const int destStartSample,
  20011. const float* source,
  20012. int numSamples) throw();
  20013. /** Finds the highest and lowest sample values in a given range.
  20014. @param channel the channel to read from
  20015. @param startSample the start sample within the channel
  20016. @param numSamples the number of samples to check
  20017. @param minVal on return, the lowest value that was found
  20018. @param maxVal on return, the highest value that was found
  20019. */
  20020. void findMinMax (const int channel,
  20021. const int startSample,
  20022. int numSamples,
  20023. float& minVal,
  20024. float& maxVal) const throw();
  20025. /** Finds the highest absolute sample value within a region of a channel.
  20026. */
  20027. float getMagnitude (const int channel,
  20028. const int startSample,
  20029. const int numSamples) const throw();
  20030. /** Finds the highest absolute sample value within a region on all channels.
  20031. */
  20032. float getMagnitude (const int startSample,
  20033. const int numSamples) const throw();
  20034. /** Returns the root mean squared level for a region of a channel.
  20035. */
  20036. float getRMSLevel (const int channel,
  20037. const int startSample,
  20038. const int numSamples) const throw();
  20039. /** Fills a section of the buffer using an AudioReader as its source.
  20040. This will convert the reader's fixed- or floating-point data to
  20041. the buffer's floating-point format, and will try to intelligently
  20042. cope with mismatches between the number of channels in the reader
  20043. and the buffer.
  20044. @see writeToAudioWriter
  20045. */
  20046. void readFromAudioReader (AudioFormatReader* reader,
  20047. const int startSample,
  20048. const int numSamples,
  20049. const int readerStartSample,
  20050. const bool useReaderLeftChan,
  20051. const bool useReaderRightChan) throw();
  20052. /** Writes a section of this buffer to an audio writer.
  20053. This saves you having to mess about with channels or floating/fixed
  20054. point conversion.
  20055. @see readFromAudioReader
  20056. */
  20057. void writeToAudioWriter (AudioFormatWriter* writer,
  20058. const int startSample,
  20059. const int numSamples) const throw();
  20060. juce_UseDebuggingNewOperator
  20061. private:
  20062. int numChannels, size, allocatedBytes;
  20063. float** channels;
  20064. float* allocatedData;
  20065. };
  20066. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20067. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20068. #endif
  20069. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20070. /********* Start of inlined file: juce_IIRFilter.h *********/
  20071. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20072. #define __JUCE_IIRFILTER_JUCEHEADER__
  20073. /**
  20074. An IIR filter that can perform low, high, or band-pass filtering on an
  20075. audio signal.
  20076. @see IIRFilterAudioSource
  20077. */
  20078. class JUCE_API IIRFilter
  20079. {
  20080. public:
  20081. /** Creates a filter.
  20082. Initially the filter is inactive, so will have no effect on samples that
  20083. you process with it. Use the appropriate method to turn it into the type
  20084. of filter needed.
  20085. */
  20086. IIRFilter() throw();
  20087. /** Creates a copy of another filter. */
  20088. IIRFilter (const IIRFilter& other) throw();
  20089. /** Destructor. */
  20090. ~IIRFilter() throw();
  20091. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20092. Note that this clears the processing state, but the type of filter and
  20093. its coefficients aren't changed. To put a filter into an inactive state, use
  20094. the makeInactive() method.
  20095. */
  20096. void reset() throw();
  20097. /** Performs the filter operation on the given set of samples.
  20098. */
  20099. void processSamples (float* const samples,
  20100. const int numSamples) throw();
  20101. /** Processes a single sample, without any locking or checking.
  20102. Use this if you need fast processing of a single value, but be aware that
  20103. this isn't thread-safe in the way that processSamples() is.
  20104. */
  20105. float processSingleSampleRaw (const float sample) throw();
  20106. /** Sets the filter up to act as a low-pass filter.
  20107. */
  20108. void makeLowPass (const double sampleRate,
  20109. const double frequency) throw();
  20110. /** Sets the filter up to act as a high-pass filter.
  20111. */
  20112. void makeHighPass (const double sampleRate,
  20113. const double frequency) throw();
  20114. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20115. The gain is a scale factor that the low frequencies are multiplied by, so values
  20116. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20117. attenuate them.
  20118. */
  20119. void makeLowShelf (const double sampleRate,
  20120. const double cutOffFrequency,
  20121. const double Q,
  20122. const float gainFactor) throw();
  20123. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20124. The gain is a scale factor that the high frequencies are multiplied by, so values
  20125. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20126. attenuate them.
  20127. */
  20128. void makeHighShelf (const double sampleRate,
  20129. const double cutOffFrequency,
  20130. const double Q,
  20131. const float gainFactor) throw();
  20132. /** Sets the filter up to act as a band pass filter centred around a
  20133. frequency, with a variable Q and gain.
  20134. The gain is a scale factor that the centre frequencies are multiplied by, so
  20135. values greater than 1.0 will boost the centre frequencies, values less than
  20136. 1.0 will attenuate them.
  20137. */
  20138. void makeBandPass (const double sampleRate,
  20139. const double centreFrequency,
  20140. const double Q,
  20141. const float gainFactor) throw();
  20142. /** Clears the filter's coefficients so that it becomes inactive.
  20143. */
  20144. void makeInactive() throw();
  20145. /** Makes this filter duplicate the set-up of another one.
  20146. */
  20147. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20148. juce_UseDebuggingNewOperator
  20149. protected:
  20150. CriticalSection processLock;
  20151. void setCoefficients (double c1, double c2, double c3,
  20152. double c4, double c5, double c6) throw();
  20153. bool active;
  20154. float coefficients[6];
  20155. float x1, x2, y1, y2;
  20156. // (use the copyCoefficientsFrom() method instead of this operator)
  20157. const IIRFilter& operator= (const IIRFilter&);
  20158. };
  20159. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20160. /********* End of inlined file: juce_IIRFilter.h *********/
  20161. #endif
  20162. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20163. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20164. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20165. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20166. /**
  20167. A subclass of AudioPlayHead can supply information about the position and
  20168. status of a moving play head during audio playback.
  20169. One of these can be supplied to an AudioProcessor object so that it can find
  20170. out about the position of the audio that it is rendering.
  20171. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20172. */
  20173. class JUCE_API AudioPlayHead
  20174. {
  20175. protected:
  20176. AudioPlayHead() {}
  20177. public:
  20178. virtual ~AudioPlayHead() {}
  20179. /** Frame rate types. */
  20180. enum FrameRateType
  20181. {
  20182. fps24 = 0,
  20183. fps25 = 1,
  20184. fps2997 = 2,
  20185. fps30 = 3,
  20186. fps2997drop = 4,
  20187. fps30drop = 5,
  20188. fpsUnknown = 99
  20189. };
  20190. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20191. */
  20192. struct CurrentPositionInfo
  20193. {
  20194. /** The tempo in BPM */
  20195. double bpm;
  20196. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20197. int timeSigNumerator;
  20198. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20199. int timeSigDenominator;
  20200. /** The current play position, in seconds from the start of the edit. */
  20201. double timeInSeconds;
  20202. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20203. double editOriginTime;
  20204. /** The current play position in pulses-per-quarter-note.
  20205. This is the number of quarter notes since the edit start.
  20206. */
  20207. double ppqPosition;
  20208. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20209. This is the number of quarter notes from the start of the edit to the
  20210. start of the current bar.
  20211. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20212. it's not available, the value will be 0.
  20213. */
  20214. double ppqPositionOfLastBarStart;
  20215. /** The video frame rate, if applicable. */
  20216. FrameRateType frameRate;
  20217. /** True if the transport is currently playing. */
  20218. bool isPlaying;
  20219. /** True if the transport is currently recording.
  20220. (When isRecording is true, then isPlaying will also be true).
  20221. */
  20222. bool isRecording;
  20223. };
  20224. /** Fills-in the given structure with details about the transport's
  20225. position at the start of the current processing block.
  20226. */
  20227. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20228. };
  20229. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20230. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20231. #endif
  20232. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20233. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20234. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20235. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20236. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20237. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20238. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20239. class AudioProcessor;
  20240. /**
  20241. Base class for the component that acts as the GUI for an AudioProcessor.
  20242. Derive your editor component from this class, and create an instance of it
  20243. by overriding the AudioProcessor::createEditor() method.
  20244. @see AudioProcessor, GenericAudioProcessorEditor
  20245. */
  20246. class JUCE_API AudioProcessorEditor : public Component
  20247. {
  20248. protected:
  20249. /** Creates an editor for the specified processor.
  20250. */
  20251. AudioProcessorEditor (AudioProcessor* const owner);
  20252. public:
  20253. /** Destructor. */
  20254. ~AudioProcessorEditor();
  20255. /** Returns a pointer to the processor that this editor represents. */
  20256. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20257. private:
  20258. AudioProcessor* const owner;
  20259. };
  20260. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20261. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20262. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20263. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20264. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20265. class AudioProcessor;
  20266. /**
  20267. Base class for listeners that want to know about changes to an AudioProcessor.
  20268. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20269. @see AudioProcessor
  20270. */
  20271. class JUCE_API AudioProcessorListener
  20272. {
  20273. public:
  20274. /** Destructor. */
  20275. virtual ~AudioProcessorListener() {}
  20276. /** Receives a callback when a parameter is changed.
  20277. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20278. many audio processors will change their parameter during their audio callback.
  20279. This means that not only has your handler code got to be completely thread-safe,
  20280. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20281. this event on your message thread, use this callback to trigger an AsyncUpdater
  20282. or ChangeBroadcaster which you can respond to on the message thread.
  20283. */
  20284. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20285. int parameterIndex,
  20286. float newValue) = 0;
  20287. /** Called to indicate that something else in the plugin has changed, like its
  20288. program, number of parameters, etc.
  20289. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20290. call it during their audio callback. This means that not only has your handler code
  20291. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20292. blocking. If you need to handle this event on your message thread, use this callback
  20293. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20294. message thread.
  20295. */
  20296. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20297. /** Indicates that a parameter change gesture has started.
  20298. E.g. if the user is dragging a slider, this would be called when they first
  20299. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20300. called when they release it.
  20301. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20302. call it during their audio callback. This means that not only has your handler code
  20303. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20304. blocking. If you need to handle this event on your message thread, use this callback
  20305. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20306. message thread.
  20307. @see audioProcessorParameterChangeGestureEnd
  20308. */
  20309. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20310. int parameterIndex);
  20311. /** Indicates that a parameter change gesture has finished.
  20312. E.g. if the user is dragging a slider, this would be called when they release
  20313. the mouse button.
  20314. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20315. call it during their audio callback. This means that not only has your handler code
  20316. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20317. blocking. If you need to handle this event on your message thread, use this callback
  20318. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20319. message thread.
  20320. @see audioPluginParameterChangeGestureStart
  20321. */
  20322. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20323. int parameterIndex);
  20324. };
  20325. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20326. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20327. /**
  20328. Base class for audio processing filters or plugins.
  20329. This is intended to act as a base class of audio filter that is general enough to
  20330. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20331. It is also used by the plugin hosting code as the wrapper around an instance
  20332. of a loaded plugin.
  20333. Derive your filter class from this base class, and if you're building a plugin,
  20334. you should implement a global function called createPluginFilter() which creates
  20335. and returns a new instance of your subclass.
  20336. */
  20337. class JUCE_API AudioProcessor
  20338. {
  20339. protected:
  20340. /** Constructor.
  20341. You can also do your initialisation tasks in the initialiseFilterInfo()
  20342. call, which will be made after this object has been created.
  20343. */
  20344. AudioProcessor();
  20345. public:
  20346. /** Destructor. */
  20347. virtual ~AudioProcessor();
  20348. /** Returns the name of this processor.
  20349. */
  20350. virtual const String getName() const = 0;
  20351. /** Called before playback starts, to let the filter prepare itself.
  20352. The sample rate is the target sample rate, and will remain constant until
  20353. playback stops.
  20354. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20355. samples that will be processed for each callback, but isn't any kind
  20356. of guarantee. The actual block sizes that the host uses may be different
  20357. each time the callback happens, and may be more or less than this value.
  20358. */
  20359. virtual void prepareToPlay (double sampleRate,
  20360. int estimatedSamplesPerBlock) = 0;
  20361. /** Called after playback has stopped, to let the filter free up any resources it
  20362. no longer needs.
  20363. */
  20364. virtual void releaseResources() = 0;
  20365. /** Renders the next block.
  20366. When this method is called, the buffer contains a number of channels which is
  20367. at least as great as the maximum number of input and output channels that
  20368. this filter is using. It will be filled with the filter's input data and
  20369. should be replaced with the filter's output.
  20370. So for example if your filter has 2 input channels and 4 output channels, then
  20371. the buffer will contain 4 channels, the first two being filled with the
  20372. input data. Your filter should read these, do its processing, and replace
  20373. the contents of all 4 channels with its output.
  20374. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20375. all filled with data, and your filter should overwrite the first 2 of these
  20376. with its output. But be VERY careful not to write anything to the last 3
  20377. channels, as these might be mapped to memory that the host assumes is read-only!
  20378. Note that if you have more outputs than inputs, then only those channels that
  20379. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20380. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20381. but the last two channels may contain garbage, so you should be careful not to
  20382. let this pass through without being overwritten or cleared.
  20383. Also note that the buffer may have more channels than are strictly necessary,
  20384. but your should only read/write from the ones that your filter is supposed to
  20385. be using.
  20386. The number of samples in these buffers is NOT guaranteed to be the same for every
  20387. callback, and may be more or less than the estimated value given to prepareToPlay().
  20388. Your code must be able to cope with variable-sized blocks, or you're going to get
  20389. clicks and crashes!
  20390. If the filter is receiving a midi input, then the midiMessages array will be filled
  20391. with the midi messages for this block. Each message's timestamp will indicate the
  20392. message's time, as a number of samples from the start of the block.
  20393. Any messages left in the midi buffer when this method has finished are assumed to
  20394. be the filter's midi output. This means that your filter should be careful to
  20395. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20396. Be very careful about what you do in this callback - it's going to be called by
  20397. the audio thread, so any kind of interaction with the UI is absolutely
  20398. out of the question. If you change a parameter in here and need to tell your UI to
  20399. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20400. the UI components register as listeners, and then call sendChangeMessage() inside the
  20401. processBlock() method to send out an asynchronous message. You could also use
  20402. the AsyncUpdater class in a similar way.
  20403. */
  20404. virtual void processBlock (AudioSampleBuffer& buffer,
  20405. MidiBuffer& midiMessages) = 0;
  20406. /** Returns the current AudioPlayHead object that should be used to find
  20407. out the state and position of the playhead.
  20408. You can call this from your processBlock() method, and use the AudioPlayHead
  20409. object to get the details about the time of the start of the block currently
  20410. being processed.
  20411. If the host hasn't supplied a playhead object, this will return 0.
  20412. */
  20413. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20414. /** Returns the current sample rate.
  20415. This can be called from your processBlock() method - it's not guaranteed
  20416. to be valid at any other time, and may return 0 if it's unknown.
  20417. */
  20418. double getSampleRate() const throw() { return sampleRate; }
  20419. /** Returns the current typical block size that is being used.
  20420. This can be called from your processBlock() method - it's not guaranteed
  20421. to be valid at any other time.
  20422. Remember it's not the ONLY block size that may be used when calling
  20423. processBlock, it's just the normal one. The actual block sizes used may be
  20424. larger or smaller than this, and will vary between successive calls.
  20425. */
  20426. int getBlockSize() const throw() { return blockSize; }
  20427. /** Returns the number of input channels that the host will be sending the filter.
  20428. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20429. number of channels that your filter would prefer to have, and this method lets
  20430. you know how many the host is actually using.
  20431. Note that this method is only valid during or after the prepareToPlay()
  20432. method call. Until that point, the number of channels will be unknown.
  20433. */
  20434. int getNumInputChannels() const throw() { return numInputChannels; }
  20435. /** Returns the number of output channels that the host will be sending the filter.
  20436. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20437. number of channels that your filter would prefer to have, and this method lets
  20438. you know how many the host is actually using.
  20439. Note that this method is only valid during or after the prepareToPlay()
  20440. method call. Until that point, the number of channels will be unknown.
  20441. */
  20442. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20443. /** Returns the name of one of the input channels, as returned by the host.
  20444. The host might not supply very useful names for channels, and this might be
  20445. something like "1", "2", "left", "right", etc.
  20446. */
  20447. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20448. /** Returns the name of one of the output channels, as returned by the host.
  20449. The host might not supply very useful names for channels, and this might be
  20450. something like "1", "2", "left", "right", etc.
  20451. */
  20452. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20453. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20454. virtual bool isInputChannelStereoPair (int index) const = 0;
  20455. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20456. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20457. /** This returns the number of samples delay that the filter imposes on the audio
  20458. passing through it.
  20459. The host will call this to find the latency - the filter itself should set this value
  20460. by calling setLatencySamples() as soon as it can during its initialisation.
  20461. */
  20462. int getLatencySamples() const throw() { return latencySamples; }
  20463. /** The filter should call this to set the number of samples delay that it introduces.
  20464. The filter should call this as soon as it can during initialisation, and can call it
  20465. later if the value changes.
  20466. */
  20467. void setLatencySamples (const int newLatency);
  20468. /** Returns true if the processor wants midi messages. */
  20469. virtual bool acceptsMidi() const = 0;
  20470. /** Returns true if the processor produces midi messages. */
  20471. virtual bool producesMidi() const = 0;
  20472. /** This returns a critical section that will automatically be locked while the host
  20473. is calling the processBlock() method.
  20474. Use it from your UI or other threads to lock access to variables that are used
  20475. by the process callback, but obviously be careful not to keep it locked for
  20476. too long, because that could cause stuttering playback. If you need to do something
  20477. that'll take a long time and need the processing to stop while it happens, use the
  20478. suspendProcessing() method instead.
  20479. @see suspendProcessing
  20480. */
  20481. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20482. /** Enables and disables the processing callback.
  20483. If you need to do something time-consuming on a thread and would like to make sure
  20484. the audio processing callback doesn't happen until you've finished, use this
  20485. to disable the callback and re-enable it again afterwards.
  20486. E.g.
  20487. @code
  20488. void loadNewPatch()
  20489. {
  20490. suspendProcessing (true);
  20491. ..do something that takes ages..
  20492. suspendProcessing (false);
  20493. }
  20494. @endcode
  20495. If the host tries to make an audio callback while processing is suspended, the
  20496. filter will return an empty buffer, but won't block the audio thread like it would
  20497. do if you use the getCallbackLock() critical section to synchronise access.
  20498. @see getCallbackLock
  20499. */
  20500. void suspendProcessing (const bool shouldBeSuspended);
  20501. /** Returns true if processing is currently suspended.
  20502. @see suspendProcessing
  20503. */
  20504. bool isSuspended() const throw() { return suspended; }
  20505. /** A plugin can override this to be told when it should reset any playing voices.
  20506. The default implementation does nothing, but a host may call this to tell the
  20507. plugin that it should stop any tails or sounds that have been left running.
  20508. */
  20509. virtual void reset();
  20510. /** Returns true if the processor is being run in an offline mode for rendering.
  20511. If the processor is being run live on realtime signals, this returns false.
  20512. If the mode is unknown, this will assume it's realtime and return false.
  20513. This value may be unreliable until the prepareToPlay() method has been called,
  20514. and could change each time prepareToPlay() is called.
  20515. @see setNonRealtime()
  20516. */
  20517. bool isNonRealtime() const throw() { return nonRealtime; }
  20518. /** Called by the host to tell this processor whether it's being used in a non-realime
  20519. capacity for offline rendering or bouncing.
  20520. Whatever value is passed-in will be
  20521. */
  20522. void setNonRealtime (const bool isNonRealtime) throw();
  20523. /** Creates the filter's UI.
  20524. This can return 0 if you want a UI-less filter, in which case the host may create
  20525. a generic UI that lets the user twiddle the parameters directly.
  20526. If you do want to pass back a component, the component should be created and set to
  20527. the correct size before returning it.
  20528. Remember not to do anything silly like allowing your filter to keep a pointer to
  20529. the component that gets created - it could be deleted later without any warning, which
  20530. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20531. The correct way to handle the connection between an editor component and its
  20532. filter is to use something like a ChangeBroadcaster so that the editor can
  20533. register itself as a listener, and be told when a change occurs. This lets them
  20534. safely unregister themselves when they are deleted.
  20535. Here are a few things to bear in mind when writing an editor:
  20536. - Initially there won't be an editor, until the user opens one, or they might
  20537. not open one at all. Your filter mustn't rely on it being there.
  20538. - An editor object may be deleted and a replacement one created again at any time.
  20539. - It's safe to assume that an editor will be deleted before its filter.
  20540. */
  20541. virtual AudioProcessorEditor* createEditor() = 0;
  20542. /** Returns the active editor, if there is one.
  20543. Bear in mind this can return 0, even if an editor has previously been
  20544. opened.
  20545. */
  20546. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20547. /** Returns the active editor, or if there isn't one, it will create one.
  20548. This may call createEditor() internally to create the component.
  20549. */
  20550. AudioProcessorEditor* createEditorIfNeeded();
  20551. /** This must return the correct value immediately after the object has been
  20552. created, and mustn't change the number of parameters later.
  20553. */
  20554. virtual int getNumParameters() = 0;
  20555. /** Returns the name of a particular parameter. */
  20556. virtual const String getParameterName (int parameterIndex) = 0;
  20557. /** Called by the host to find out the value of one of the filter's parameters.
  20558. The host will expect the value returned to be between 0 and 1.0.
  20559. This could be called quite frequently, so try to make your code efficient.
  20560. It's also likely to be called by non-UI threads, so the code in here should
  20561. be thread-aware.
  20562. */
  20563. virtual float getParameter (int parameterIndex) = 0;
  20564. /** Returns the value of a parameter as a text string. */
  20565. virtual const String getParameterText (int parameterIndex) = 0;
  20566. /** The host will call this method to change the value of one of the filter's parameters.
  20567. The host may call this at any time, including during the audio processing
  20568. callback, so the filter has to process this very fast and avoid blocking.
  20569. If you want to set the value of a parameter internally, e.g. from your
  20570. editor component, then don't call this directly - instead, use the
  20571. setParameterNotifyingHost() method, which will also send a message to
  20572. the host telling it about the change. If the message isn't sent, the host
  20573. won't be able to automate your parameters properly.
  20574. The value passed will be between 0 and 1.0.
  20575. */
  20576. virtual void setParameter (int parameterIndex,
  20577. float newValue) = 0;
  20578. /** Your filter can call this when it needs to change one of its parameters.
  20579. This could happen when the editor or some other internal operation changes
  20580. a parameter. This method will call the setParameter() method to change the
  20581. value, and will then send a message to the host telling it about the change.
  20582. Note that to make sure the host correctly handles automation, you should call
  20583. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20584. tell the host when the user has started and stopped changing the parameter.
  20585. */
  20586. void setParameterNotifyingHost (int parameterIndex,
  20587. float newValue);
  20588. /** Returns true if the host can automate this parameter.
  20589. By default, this returns true for all parameters.
  20590. */
  20591. virtual bool isParameterAutomatable (int parameterIndex) const;
  20592. /** Should return true if this parameter is a "meta" parameter.
  20593. A meta-parameter is a parameter that changes other params. It is used
  20594. by some hosts (e.g. AudioUnit hosts).
  20595. By default this returns false.
  20596. */
  20597. virtual bool isMetaParameter (int parameterIndex) const;
  20598. /** Sends a signal to the host to tell it that the user is about to start changing this
  20599. parameter.
  20600. This allows the host to know when a parameter is actively being held by the user, and
  20601. it may use this information to help it record automation.
  20602. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20603. */
  20604. void beginParameterChangeGesture (int parameterIndex);
  20605. /** Tells the host that the user has finished changing this parameter.
  20606. This allows the host to know when a parameter is actively being held by the user, and
  20607. it may use this information to help it record automation.
  20608. A call to this method must follow a call to beginParameterChangeGesture().
  20609. */
  20610. void endParameterChangeGesture (int parameterIndex);
  20611. /** The filter can call this when something (apart from a parameter value) has changed.
  20612. It sends a hint to the host that something like the program, number of parameters,
  20613. etc, has changed, and that it should update itself.
  20614. */
  20615. void updateHostDisplay();
  20616. /** Returns the number of preset programs the filter supports.
  20617. The value returned must be valid as soon as this object is created, and
  20618. must not change over its lifetime.
  20619. This value shouldn't be less than 1.
  20620. */
  20621. virtual int getNumPrograms() = 0;
  20622. /** Returns the number of the currently active program.
  20623. */
  20624. virtual int getCurrentProgram() = 0;
  20625. /** Called by the host to change the current program.
  20626. */
  20627. virtual void setCurrentProgram (int index) = 0;
  20628. /** Must return the name of a given program. */
  20629. virtual const String getProgramName (int index) = 0;
  20630. /** Called by the host to rename a program.
  20631. */
  20632. virtual void changeProgramName (int index, const String& newName) = 0;
  20633. /** The host will call this method when it wants to save the filter's internal state.
  20634. This must copy any info about the filter's state into the block of memory provided,
  20635. so that the host can store this and later restore it using setStateInformation().
  20636. Note that there's also a getCurrentProgramStateInformation() method, which only
  20637. stores the current program, not the state of the entire filter.
  20638. See also the helper function copyXmlToBinary() for storing settings as XML.
  20639. @see getCurrentProgramStateInformation
  20640. */
  20641. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20642. /** The host will call this method if it wants to save the state of just the filter's
  20643. current program.
  20644. Unlike getStateInformation, this should only return the current program's state.
  20645. Not all hosts support this, and if you don't implement it, the base class
  20646. method just calls getStateInformation() instead. If you do implement it, be
  20647. sure to also implement getCurrentProgramStateInformation.
  20648. @see getStateInformation, setCurrentProgramStateInformation
  20649. */
  20650. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20651. /** This must restore the filter's state from a block of data previously created
  20652. using getStateInformation().
  20653. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20654. to restore just the current program, not the state of the entire filter.
  20655. See also the helper function getXmlFromBinary() for loading settings as XML.
  20656. @see setCurrentProgramStateInformation
  20657. */
  20658. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20659. /** The host will call this method if it wants to restore the state of just the filter's
  20660. current program.
  20661. Not all hosts support this, and if you don't implement it, the base class
  20662. method just calls setStateInformation() instead. If you do implement it, be
  20663. sure to also implement getCurrentProgramStateInformation.
  20664. @see setStateInformation, getCurrentProgramStateInformation
  20665. */
  20666. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20667. /** Adds a listener that will be called when an aspect of this processor changes. */
  20668. void addListener (AudioProcessorListener* const newListener) throw();
  20669. /** Removes a previously added listener. */
  20670. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20671. /** Not for public use - this is called before deleting an editor component. */
  20672. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20673. /** Not for public use - this is called to initialise the processor. */
  20674. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20675. /** Not for public use - this is called to initialise the processor before playing. */
  20676. void setPlayConfigDetails (const int numIns, const int numOuts,
  20677. const double sampleRate,
  20678. const int blockSize) throw();
  20679. juce_UseDebuggingNewOperator
  20680. protected:
  20681. /** Helper function that just converts an xml element into a binary blob.
  20682. Use this in your filter's getStateInformation() method if you want to
  20683. store its state as xml.
  20684. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20685. from a binary blob.
  20686. */
  20687. static void copyXmlToBinary (const XmlElement& xml,
  20688. JUCE_NAMESPACE::MemoryBlock& destData);
  20689. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20690. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20691. an XmlElement object that the caller must delete when no longer needed.
  20692. */
  20693. static XmlElement* getXmlFromBinary (const void* data,
  20694. const int sizeInBytes);
  20695. /** @internal */
  20696. AudioPlayHead* playHead;
  20697. /** @internal */
  20698. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20699. private:
  20700. VoidArray listeners;
  20701. AudioProcessorEditor* activeEditor;
  20702. double sampleRate;
  20703. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20704. bool suspended, nonRealtime;
  20705. CriticalSection callbackLock, listenerLock;
  20706. #ifdef JUCE_DEBUG
  20707. BitArray changingParams;
  20708. #endif
  20709. AudioProcessor (const AudioProcessor&);
  20710. const AudioProcessor& operator= (const AudioProcessor&);
  20711. };
  20712. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20713. /********* End of inlined file: juce_AudioProcessor.h *********/
  20714. #endif
  20715. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20716. #endif
  20717. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20718. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20719. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20720. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20721. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20722. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20723. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20724. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20725. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20726. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20727. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20728. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20729. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20730. /********* Start of inlined file: juce_PluginDescription.h *********/
  20731. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20732. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20733. /**
  20734. A small class to represent some facts about a particular type of plugin.
  20735. This class is for storing and managing the details about a plugin without
  20736. actually having to load an instance of it.
  20737. A KnownPluginList contains a list of PluginDescription objects.
  20738. @see KnownPluginList
  20739. */
  20740. class JUCE_API PluginDescription
  20741. {
  20742. public:
  20743. PluginDescription() throw();
  20744. PluginDescription (const PluginDescription& other) throw();
  20745. const PluginDescription& operator= (const PluginDescription& other) throw();
  20746. ~PluginDescription() throw();
  20747. /** The name of the plugin. */
  20748. String name;
  20749. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  20750. */
  20751. String pluginFormatName;
  20752. /** A category, such as "Dynamics", "Reverbs", etc.
  20753. */
  20754. String category;
  20755. /** The manufacturer. */
  20756. String manufacturerName;
  20757. /** The version. This string doesn't have any particular format. */
  20758. String version;
  20759. /** The binary module file containing the plugin. */
  20760. File file;
  20761. /** The last time the plugin file was changed.
  20762. This is handy when scanning for new or changed plugins.
  20763. */
  20764. Time lastFileModTime;
  20765. /** A unique ID for the plugin.
  20766. Note that this might not be unique between formats, e.g. a VST and some
  20767. other format might actually have the same id.
  20768. @see createIdentifierString
  20769. */
  20770. int uid;
  20771. /** True if the plugin identifies itself as a synthesiser. */
  20772. bool isInstrument;
  20773. /** The number of inputs. */
  20774. int numInputChannels;
  20775. /** The number of outputs. */
  20776. int numOutputChannels;
  20777. /** Returns true if the two descriptions refer the the same plugin.
  20778. This isn't quite as simple as them just having the same file (because of
  20779. shell plugins).
  20780. */
  20781. bool isDuplicateOf (const PluginDescription& other) const;
  20782. /** Returns a string that can be saved and used to uniquely identify the
  20783. plugin again.
  20784. This contains less info than the XML encoding, and is independent of the
  20785. plugin's file location, so can be used to store a plugin ID for use
  20786. across different machines.
  20787. */
  20788. const String createIdentifierString() const throw();
  20789. /** Creates an XML object containing these details.
  20790. @see loadFromXml
  20791. */
  20792. XmlElement* createXml() const;
  20793. /** Reloads the info in this structure from an XML record that was previously
  20794. saved with createXML().
  20795. Returns true if the XML was a valid plugin description.
  20796. */
  20797. bool loadFromXml (const XmlElement& xml);
  20798. juce_UseDebuggingNewOperator
  20799. };
  20800. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20801. /********* End of inlined file: juce_PluginDescription.h *********/
  20802. /**
  20803. Base class for an active instance of a plugin.
  20804. This derives from the AudioProcessor class, and adds some extra functionality
  20805. that helps when wrapping dynamically loaded plugins.
  20806. @see AudioProcessor, AudioPluginFormat
  20807. */
  20808. class JUCE_API AudioPluginInstance : public AudioProcessor
  20809. {
  20810. public:
  20811. /** Destructor.
  20812. Make sure that you delete any UI components that belong to this plugin before
  20813. deleting the plugin.
  20814. */
  20815. virtual ~AudioPluginInstance();
  20816. /** Fills-in the appropriate parts of this plugin description object.
  20817. */
  20818. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  20819. juce_UseDebuggingNewOperator
  20820. protected:
  20821. AudioPluginInstance();
  20822. AudioPluginInstance (const AudioPluginInstance&);
  20823. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  20824. };
  20825. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20826. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  20827. class PluginDescription;
  20828. /**
  20829. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  20830. Use the static getNumFormats() and getFormat() calls to find the types
  20831. of format that are available.
  20832. */
  20833. class JUCE_API AudioPluginFormat
  20834. {
  20835. public:
  20836. /** Destructor. */
  20837. virtual ~AudioPluginFormat();
  20838. /** Returns the format name.
  20839. E.g. "VST", "AudioUnit", etc.
  20840. */
  20841. virtual const String getName() const = 0;
  20842. /** This tries to create descriptions for all the plugin types available in
  20843. a binary module file.
  20844. The file will be some kind of DLL or bundle.
  20845. Normally there will only be one type returned, but some plugins
  20846. (e.g. VST shells) can use a single DLL to create a set of different plugin
  20847. subtypes, so in that case, each subtype is returned as a separate object.
  20848. */
  20849. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  20850. const File& file) = 0;
  20851. /** Tries to recreate a type from a previously generated PluginDescription.
  20852. @see PluginDescription::createInstance
  20853. */
  20854. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  20855. /** Should do a quick check to see if this file or directory might be a plugin of
  20856. this format.
  20857. This is for searching for potential files, so it shouldn't actually try to
  20858. load the plugin or do anything time-consuming.
  20859. */
  20860. virtual bool fileMightContainThisPluginType (const File& file) = 0;
  20861. /** Returns the typical places to look for this kind of plugin.
  20862. Note that if this returns no paths, it means that the format can't be scanned-for
  20863. (i.e. it's an internal format that doesn't live in files)
  20864. */
  20865. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  20866. juce_UseDebuggingNewOperator
  20867. protected:
  20868. AudioPluginFormat() throw();
  20869. AudioPluginFormat (const AudioPluginFormat&);
  20870. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  20871. };
  20872. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20873. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  20874. /**
  20875. This maintains a list of known AudioPluginFormats.
  20876. @see AudioPluginFormat
  20877. */
  20878. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  20879. {
  20880. public:
  20881. AudioPluginFormatManager() throw();
  20882. /** Destructor. */
  20883. ~AudioPluginFormatManager() throw();
  20884. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  20885. /** Adds any formats that it knows about, e.g. VST.
  20886. */
  20887. void addDefaultFormats();
  20888. /** Returns the number of types of format that are available.
  20889. Use getFormat() to get one of them.
  20890. */
  20891. int getNumFormats() throw();
  20892. /** Returns one of the available formats.
  20893. @see getNumFormats
  20894. */
  20895. AudioPluginFormat* getFormat (const int index) throw();
  20896. /** Adds a format to the list.
  20897. The object passed in will be owned and deleted by the manager.
  20898. */
  20899. void addFormat (AudioPluginFormat* const format) throw();
  20900. /** Tries to load the type for this description, by trying all the formats
  20901. that this manager knows about.
  20902. The caller is responsible for deleting the object that is returned.
  20903. If it can't load the plugin, it returns 0 and leaves a message in the
  20904. errorMessage string.
  20905. */
  20906. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  20907. String& errorMessage) const;
  20908. juce_UseDebuggingNewOperator
  20909. private:
  20910. OwnedArray <AudioPluginFormat> formats;
  20911. AudioPluginFormatManager (const AudioPluginFormatManager&);
  20912. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  20913. };
  20914. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20915. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  20916. /********* Start of inlined file: juce_KnownPluginList.h *********/
  20917. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  20918. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  20919. /********* Start of inlined file: juce_PopupMenu.h *********/
  20920. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  20921. #define __JUCE_POPUPMENU_JUCEHEADER__
  20922. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  20923. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20924. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20925. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  20926. @see PopupMenu::addCustomItem
  20927. */
  20928. class JUCE_API PopupMenuCustomComponent : public Component
  20929. {
  20930. public:
  20931. /** Destructor. */
  20932. ~PopupMenuCustomComponent();
  20933. /** Chooses the size that this component would like to have.
  20934. Note that the size which this method returns isn't necessarily the one that
  20935. the menu will give it, as it will be stretched to fit the other items in
  20936. the menu.
  20937. */
  20938. virtual void getIdealSize (int& idealWidth,
  20939. int& idealHeight) = 0;
  20940. /** Dismisses the menu indicating that this item has been chosen.
  20941. This will cause the menu to exit from its modal state, returning
  20942. this item's id as the result.
  20943. */
  20944. void triggerMenuItem();
  20945. /** Returns true if this item should be highlighted because the mouse is
  20946. over it.
  20947. You can call this method in your paint() method to find out whether
  20948. to draw a highlight.
  20949. */
  20950. bool isItemHighlighted() const throw() { return isHighlighted; }
  20951. protected:
  20952. /** Constructor.
  20953. If isTriggeredAutomatically is true, then the menu will automatically detect
  20954. a click on this component and use that to trigger it. If it's false, then it's
  20955. up to your class to manually trigger the item if it wants to.
  20956. */
  20957. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  20958. private:
  20959. friend class MenuItemInfo;
  20960. friend class MenuItemComponent;
  20961. friend class PopupMenuWindow;
  20962. int refCount_;
  20963. bool isHighlighted, isTriggeredAutomatically;
  20964. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  20965. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  20966. };
  20967. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20968. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  20969. /** Creates and displays a popup-menu.
  20970. To show a popup-menu, you create one of these, add some items to it, then
  20971. call its show() method, which returns the id of the item the user selects.
  20972. E.g. @code
  20973. void MyWidget::mouseDown (const MouseEvent& e)
  20974. {
  20975. PopupMenu m;
  20976. m.addItem (1, "item 1");
  20977. m.addItem (2, "item 2");
  20978. const int result = m.show();
  20979. if (result == 0)
  20980. {
  20981. // user dismissed the menu without picking anything
  20982. }
  20983. else if (result == 1)
  20984. {
  20985. // user picked item 1
  20986. }
  20987. else if (result == 2)
  20988. {
  20989. // user picked item 2
  20990. }
  20991. }
  20992. @endcode
  20993. Submenus are easy too: @code
  20994. void MyWidget::mouseDown (const MouseEvent& e)
  20995. {
  20996. PopupMenu subMenu;
  20997. subMenu.addItem (1, "item 1");
  20998. subMenu.addItem (2, "item 2");
  20999. PopupMenu mainMenu;
  21000. mainMenu.addItem (3, "item 3");
  21001. mainMenu.addSubMenu ("other choices", subMenu);
  21002. const int result = m.show();
  21003. ...etc
  21004. }
  21005. @endcode
  21006. */
  21007. class JUCE_API PopupMenu
  21008. {
  21009. public:
  21010. /** Creates an empty popup menu. */
  21011. PopupMenu() throw();
  21012. /** Creates a copy of another menu. */
  21013. PopupMenu (const PopupMenu& other) throw();
  21014. /** Destructor. */
  21015. ~PopupMenu() throw();
  21016. /** Copies this menu from another one. */
  21017. const PopupMenu& operator= (const PopupMenu& other) throw();
  21018. /** Resets the menu, removing all its items. */
  21019. void clear() throw();
  21020. /** Appends a new text item for this menu to show.
  21021. @param itemResultId the number that will be returned from the show() method
  21022. if the user picks this item. The value should never be
  21023. zero, because that's used to indicate that the user didn't
  21024. select anything.
  21025. @param itemText the text to show.
  21026. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21027. picked
  21028. @param isTicked if true, the item will be shown with a tick next to it
  21029. @param iconToUse if this is non-zero, it should be an image that will be
  21030. displayed to the left of the item. This method will take its
  21031. own copy of the image passed-in, so there's no need to keep
  21032. it hanging around.
  21033. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21034. */
  21035. void addItem (const int itemResultId,
  21036. const String& itemText,
  21037. const bool isActive = true,
  21038. const bool isTicked = false,
  21039. const Image* const iconToUse = 0) throw();
  21040. /** Adds an item that represents one of the commands in a command manager object.
  21041. @param commandManager the manager to use to trigger the command and get information
  21042. about it
  21043. @param commandID the ID of the command
  21044. @param displayName if this is non-empty, then this string will be used instead of
  21045. the command's registered name
  21046. */
  21047. void addCommandItem (ApplicationCommandManager* commandManager,
  21048. const int commandID,
  21049. const String& displayName = String::empty) throw();
  21050. /** Appends a text item with a special colour.
  21051. This is the same as addItem(), but specifies a colour to use for the
  21052. text, which will override the default colours that are used by the
  21053. current look-and-feel. See addItem() for a description of the parameters.
  21054. */
  21055. void addColouredItem (const int itemResultId,
  21056. const String& itemText,
  21057. const Colour& itemTextColour,
  21058. const bool isActive = true,
  21059. const bool isTicked = false,
  21060. const Image* const iconToUse = 0) throw();
  21061. /** Appends a custom menu item.
  21062. This will add a user-defined component to use as a menu item. The component
  21063. passed in will be deleted by this menu when it's no longer needed.
  21064. @see PopupMenuCustomComponent
  21065. */
  21066. void addCustomItem (const int itemResultId,
  21067. PopupMenuCustomComponent* const customComponent) throw();
  21068. /** Appends a custom menu item that can't be used to trigger a result.
  21069. This will add a user-defined component to use as a menu item. Unlike the
  21070. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21071. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21072. delete the component when it's finished, so it's the caller's responsibility
  21073. to manage the component that is passed-in.
  21074. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21075. detection of a mouse-click on your component, and use that to trigger the
  21076. menu ID specified in itemResultId. If this is false, the menu item can't
  21077. be triggered, so itemResultId is not used.
  21078. @see PopupMenuCustomComponent
  21079. */
  21080. void addCustomItem (const int itemResultId,
  21081. Component* customComponent,
  21082. int idealWidth, int idealHeight,
  21083. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21084. /** Appends a sub-menu.
  21085. If the menu that's passed in is empty, it will appear as an inactive item.
  21086. */
  21087. void addSubMenu (const String& subMenuName,
  21088. const PopupMenu& subMenu,
  21089. const bool isActive = true,
  21090. Image* const iconToUse = 0) throw();
  21091. /** Appends a separator to the menu, to help break it up into sections.
  21092. The menu class is smart enough not to display separators at the top or bottom
  21093. of the menu, and it will replace mutliple adjacent separators with a single
  21094. one, so your code can be quite free and easy about adding these, and it'll
  21095. always look ok.
  21096. */
  21097. void addSeparator() throw();
  21098. /** Adds a non-clickable text item to the menu.
  21099. This is a bold-font items which can be used as a header to separate the items
  21100. into named groups.
  21101. */
  21102. void addSectionHeader (const String& title) throw();
  21103. /** Returns the number of items that the menu currently contains.
  21104. (This doesn't count separators).
  21105. */
  21106. int getNumItems() const throw();
  21107. /** Returns true if the menu contains a command item that triggers the given command. */
  21108. bool containsCommandItem (const int commandID) const throw();
  21109. /** Returns true if the menu contains any items that can be used. */
  21110. bool containsAnyActiveItems() const throw();
  21111. /** Displays the menu and waits for the user to pick something.
  21112. This will display the menu modally, and return the ID of the item that the
  21113. user picks. If they click somewhere off the menu to get rid of it without
  21114. choosing anything, this will return 0.
  21115. The current location of the mouse will be used as the position to show the
  21116. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21117. on where this point is on the screen, the menu will appear above, below or
  21118. to the side of the point.
  21119. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21120. then when the menu first appears, it will make sure
  21121. that this item is visible. So if the menu has too many
  21122. items to fit on the screen, it will be scrolled to a
  21123. position where this item is visible.
  21124. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21125. than this if some items are too long to fit.
  21126. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21127. vertical column, the menu may be laid out as a series of
  21128. columns - this is the maximum number allowed. To use the
  21129. default value for this (probably about 7), you can pass
  21130. in zero.
  21131. @param standardItemHeight if this is non-zero, it will be used as the standard
  21132. height for menu items (apart from custom items)
  21133. @see showAt
  21134. */
  21135. int show (const int itemIdThatMustBeVisible = 0,
  21136. const int minimumWidth = 0,
  21137. const int maximumNumColumns = 0,
  21138. const int standardItemHeight = 0);
  21139. /** Displays the menu at a specific location.
  21140. This is the same as show(), but uses a specific location (in global screen
  21141. co-ordinates) rather than the current mouse position.
  21142. Note that the co-ordinates don't specify the top-left of the menu - they
  21143. indicate a point of interest, and the menu will position itself nearby to
  21144. this point, trying to keep it fully on-screen.
  21145. @see show()
  21146. */
  21147. int showAt (const int screenX,
  21148. const int screenY,
  21149. const int itemIdThatMustBeVisible = 0,
  21150. const int minimumWidth = 0,
  21151. const int maximumNumColumns = 0,
  21152. const int standardItemHeight = 0);
  21153. /** Displays the menu as if it's attached to a component such as a button.
  21154. This is similar to showAt(), but will position it next to the given component, e.g.
  21155. so that the menu's edge is aligned with that of the component. This is intended for
  21156. things like buttons that trigger a pop-up menu.
  21157. */
  21158. int showAt (Component* componentToAttachTo,
  21159. const int itemIdThatMustBeVisible = 0,
  21160. const int minimumWidth = 0,
  21161. const int maximumNumColumns = 0,
  21162. const int standardItemHeight = 0);
  21163. /** Closes any menus that are currently open.
  21164. This might be useful if you have a situation where your window is being closed
  21165. by some means other than a user action, and you'd like to make sure that menus
  21166. aren't left hanging around.
  21167. */
  21168. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21169. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21170. This can be called before show() if you need a customised menu. Be careful
  21171. not to delete the LookAndFeel object before the menu has been deleted.
  21172. */
  21173. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21174. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21175. These constants can be used either via the LookAndFeel::setColour()
  21176. method for the look and feel that is set for this menu with setLookAndFeel()
  21177. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21178. */
  21179. enum ColourIds
  21180. {
  21181. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21182. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21183. colour is specified when the item is added). */
  21184. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21185. addSectionHeader() method). */
  21186. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21187. highlighted menu item. */
  21188. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21189. highlighted item. */
  21190. };
  21191. /**
  21192. Allows you to iterate through the items in a pop-up menu, and examine
  21193. their properties.
  21194. To use this, just create one and repeatedly call its next() method. When this
  21195. returns true, all the member variables of the iterator are filled-out with
  21196. information describing the menu item. When it returns false, the end of the
  21197. list has been reached.
  21198. */
  21199. class JUCE_API MenuItemIterator
  21200. {
  21201. public:
  21202. /** Creates an iterator that will scan through the items in the specified
  21203. menu.
  21204. Be careful not to add any items to a menu while it is being iterated,
  21205. or things could get out of step.
  21206. */
  21207. MenuItemIterator (const PopupMenu& menu) throw();
  21208. /** Destructor. */
  21209. ~MenuItemIterator() throw();
  21210. /** Returns true if there is another item, and sets up all this object's
  21211. member variables to reflect that item's properties.
  21212. */
  21213. bool next() throw();
  21214. String itemName;
  21215. const PopupMenu* subMenu;
  21216. int itemId;
  21217. bool isSeparator;
  21218. bool isTicked;
  21219. bool isEnabled;
  21220. bool isCustomComponent;
  21221. bool isSectionHeader;
  21222. const Colour* customColour;
  21223. const Image* customImage;
  21224. ApplicationCommandManager* commandManager;
  21225. juce_UseDebuggingNewOperator
  21226. private:
  21227. const PopupMenu& menu;
  21228. int index;
  21229. MenuItemIterator (const MenuItemIterator&);
  21230. const MenuItemIterator& operator= (const MenuItemIterator&);
  21231. };
  21232. juce_UseDebuggingNewOperator
  21233. private:
  21234. friend class PopupMenuWindow;
  21235. friend class MenuItemIterator;
  21236. VoidArray items;
  21237. LookAndFeel* lookAndFeel;
  21238. bool separatorPending;
  21239. void addSeparatorIfPending();
  21240. int showMenu (const int x, const int y, const int w, const int h,
  21241. const int itemIdThatMustBeVisible,
  21242. const int minimumWidth,
  21243. const int maximumNumColumns,
  21244. const int standardItemHeight,
  21245. const bool alignToRectangle,
  21246. Component* const componentAttachedTo) throw();
  21247. friend class MenuBarComponent;
  21248. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21249. const int itemIdThatMustBeVisible,
  21250. const int minimumWidth,
  21251. const int maximumNumColumns,
  21252. const int standardItemHeight,
  21253. const bool alignToRectangle,
  21254. Component* menuBarComponent,
  21255. ApplicationCommandManager** managerOfChosenCommand,
  21256. Component* const componentAttachedTo) throw();
  21257. };
  21258. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21259. /********* End of inlined file: juce_PopupMenu.h *********/
  21260. /**
  21261. Manages a list of plugin types.
  21262. This can be easily edited, saved and loaded, and used to create instances of
  21263. the plugin types in it.
  21264. @see PluginListComponent
  21265. */
  21266. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21267. {
  21268. public:
  21269. /** Creates an empty list.
  21270. */
  21271. KnownPluginList();
  21272. /** Destructor. */
  21273. ~KnownPluginList();
  21274. /** Clears the list. */
  21275. void clear();
  21276. /** Returns the number of types currently in the list.
  21277. @see getType
  21278. */
  21279. int getNumTypes() const throw() { return types.size(); }
  21280. /** Returns one of the types.
  21281. @see getNumTypes
  21282. */
  21283. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21284. /** Looks for a type in the list which comes from this file.
  21285. */
  21286. PluginDescription* getTypeForFile (const File& file) const throw();
  21287. /** Looks for a type in the list which matches a plugin type ID.
  21288. The identifierString parameter must have been created by
  21289. PluginDescription::createIdentifierString().
  21290. */
  21291. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21292. /** Adds a type manually from its description. */
  21293. bool addType (const PluginDescription& type);
  21294. /** Removes a type. */
  21295. void removeType (const int index) throw();
  21296. /** Looks for all types that can be loaded from a given file, and adds them
  21297. to the list.
  21298. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21299. re-tested if it's not already in the list, or if the file's modification
  21300. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21301. false, the file will always be reloaded and tested.
  21302. Returns true if any new types were added, and all the types found in this
  21303. file (even if it was already known and hasn't been re-scanned) get returned
  21304. in the array.
  21305. */
  21306. bool scanAndAddFile (const File& possiblePluginFile,
  21307. const bool dontRescanIfAlreadyInList,
  21308. OwnedArray <PluginDescription>& typesFound);
  21309. /** Returns true if the specified file is already known about and if it
  21310. hasn't been modified since our entry was created.
  21311. */
  21312. bool isListingUpToDate (const File& possiblePluginFile) const throw();
  21313. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21314. If any types are found in the files, their descriptions are returned in the array.
  21315. */
  21316. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21317. OwnedArray <PluginDescription>& typesFound);
  21318. /** Sort methods used to change the order of the plugins in the list.
  21319. */
  21320. enum SortMethod
  21321. {
  21322. defaultOrder = 0,
  21323. sortAlphabetically,
  21324. sortByCategory,
  21325. sortByManufacturer,
  21326. sortByFileSystemLocation
  21327. };
  21328. /** Adds all the plugin types to a popup menu so that the user can select one.
  21329. Depending on the sort method, it may add sub-menus for categories,
  21330. manufacturers, etc.
  21331. Use getIndexChosenByMenu() to find out the type that was chosen.
  21332. */
  21333. void addToMenu (PopupMenu& menu,
  21334. const SortMethod sortMethod) const;
  21335. /** Converts a menu item index that has been chosen into its index in this list.
  21336. Returns -1 if it's not an ID that was used.
  21337. @see addToMenu
  21338. */
  21339. int getIndexChosenByMenu (const int menuResultCode) const;
  21340. /** Sorts the list. */
  21341. void sort (const SortMethod method);
  21342. /** Creates some XML that can be used to store the state of this list.
  21343. */
  21344. XmlElement* createXml() const;
  21345. /** Recreates the state of this list from its stored XML format.
  21346. */
  21347. void recreateFromXml (const XmlElement& xml);
  21348. juce_UseDebuggingNewOperator
  21349. private:
  21350. OwnedArray <PluginDescription> types;
  21351. KnownPluginList (const KnownPluginList&);
  21352. const KnownPluginList& operator= (const KnownPluginList&);
  21353. };
  21354. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21355. /********* End of inlined file: juce_KnownPluginList.h *********/
  21356. /**
  21357. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21358. Use one of these objects if you want to wire-up a set of AudioProcessors
  21359. and play back the result.
  21360. Processors can be added to the graph as "nodes" using addNode(), and once
  21361. added, you can connect any of their input or output channels to other
  21362. nodes using addConnection().
  21363. To play back a graph through an audio device, you might want to use an
  21364. AudioProcessorPlayer object.
  21365. */
  21366. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21367. public AsyncUpdater
  21368. {
  21369. public:
  21370. /** Creates an empty graph.
  21371. */
  21372. AudioProcessorGraph();
  21373. /** Destructor.
  21374. Any processor objects that have been added to the graph will also be deleted.
  21375. */
  21376. ~AudioProcessorGraph();
  21377. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21378. To create a node, call AudioProcessorGraph::addNode().
  21379. */
  21380. class Node : public ReferenceCountedObject
  21381. {
  21382. public:
  21383. /** Destructor.
  21384. */
  21385. ~Node();
  21386. /** The ID number assigned to this node.
  21387. This is assigned by the graph that owns it, and can't be changed.
  21388. */
  21389. const uint32 id;
  21390. /** The actual processor object that this node represents.
  21391. */
  21392. AudioProcessor* const processor;
  21393. /** A set of user-definable properties that are associated with this node.
  21394. This can be used to attach values to the node for whatever purpose seems
  21395. useful. For example, you might store an x and y position if your application
  21396. is displaying the nodes on-screen.
  21397. */
  21398. PropertySet properties;
  21399. /** A convenient typedef for referring to a pointer to a node object.
  21400. */
  21401. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21402. juce_UseDebuggingNewOperator
  21403. private:
  21404. friend class AudioProcessorGraph;
  21405. bool isPrepared;
  21406. Node (const uint32 id, AudioProcessor* const processor) throw();
  21407. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21408. void unprepare();
  21409. Node (const Node&);
  21410. const Node& operator= (const Node&);
  21411. };
  21412. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21413. To create a connection, use AudioProcessorGraph::addConnection().
  21414. */
  21415. struct Connection
  21416. {
  21417. public:
  21418. /** The ID number of the node which is the input source for this connection.
  21419. @see AudioProcessorGraph::getNodeForId
  21420. */
  21421. uint32 sourceNodeId;
  21422. /** The index of the output channel of the source node from which this
  21423. connection takes its data.
  21424. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21425. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21426. index of an audio output channel in the source node.
  21427. */
  21428. int sourceChannelIndex;
  21429. /** The ID number of the node which is the destination for this connection.
  21430. @see AudioProcessorGraph::getNodeForId
  21431. */
  21432. uint32 destNodeId;
  21433. /** The index of the input channel of the destination node to which this
  21434. connection delivers its data.
  21435. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21436. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21437. index of an audio input channel in the destination node.
  21438. */
  21439. int destChannelIndex;
  21440. juce_UseDebuggingNewOperator
  21441. private:
  21442. };
  21443. /** Deletes all nodes and connections from this graph.
  21444. Any processor objects in the graph will be deleted.
  21445. */
  21446. void clear();
  21447. /** Returns the number of nodes in the graph. */
  21448. int getNumNodes() const throw() { return nodes.size(); }
  21449. /** Returns a pointer to one of the nodes in the graph.
  21450. This will return 0 if the index is out of range.
  21451. @see getNodeForId
  21452. */
  21453. Node* getNode (const int index) const throw() { return nodes [index]; }
  21454. /** Searches the graph for a node with the given ID number and returns it.
  21455. If no such node was found, this returns 0.
  21456. @see getNode
  21457. */
  21458. Node* getNodeForId (const uint32 nodeId) const throw();
  21459. /** Adds a node to the graph.
  21460. This creates a new node in the graph, for the specified processor. Once you have
  21461. added a processor to the graph, the graph owns it and will delete it later when
  21462. it is no longer needed.
  21463. The optional nodeId parameter lets you specify an ID to use for the node, but
  21464. if the value is already in use, this new node will overwrite the old one.
  21465. If this succeeds, it returns a pointer to the newly-created node.
  21466. */
  21467. Node* addNode (AudioProcessor* const newProcessor,
  21468. uint32 nodeId = 0);
  21469. /** Deletes a node within the graph which has the specified ID.
  21470. This will also delete any connections that are attached to this node.
  21471. */
  21472. bool removeNode (const uint32 nodeId);
  21473. /** Returns the number of connections in the graph. */
  21474. int getNumConnections() const throw() { return connections.size(); }
  21475. /** Returns a pointer to one of the connections in the graph. */
  21476. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21477. /** Searches for a connection between some specified channels.
  21478. If no such connection is found, this returns 0.
  21479. */
  21480. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21481. const int sourceChannelIndex,
  21482. const uint32 destNodeId,
  21483. const int destChannelIndex) const throw();
  21484. /** Returns true if there is a connection between any of the channels of
  21485. two specified nodes.
  21486. */
  21487. bool isConnected (const uint32 possibleSourceNodeId,
  21488. const uint32 possibleDestNodeId) const throw();
  21489. /** Returns true if it would be legal to connect the specified points.
  21490. */
  21491. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21492. const uint32 destNodeId, const int destChannelIndex) const throw();
  21493. /** Attempts to connect two specified channels of two nodes.
  21494. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21495. to an audio one or other such nonsense), then it'll return false.
  21496. */
  21497. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21498. const uint32 destNodeId, const int destChannelIndex);
  21499. /** Deletes the connection with the specified index.
  21500. Returns true if a connection was actually deleted.
  21501. */
  21502. void removeConnection (const int index);
  21503. /** Deletes any connection between two specified points.
  21504. Returns true if a connection was actually deleted.
  21505. */
  21506. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21507. const uint32 destNodeId, const int destChannelIndex);
  21508. /** Removes all connections from the specified node.
  21509. */
  21510. bool disconnectNode (const uint32 nodeId);
  21511. /** Performs a sanity checks of all the connections.
  21512. This might be useful if some of the processors are doing things like changing
  21513. their channel counts, which could render some connections obsolete.
  21514. */
  21515. bool removeIllegalConnections();
  21516. /** A special number that represents the midi channel of a node.
  21517. This is used as a channel index value if you want to refer to the midi input
  21518. or output instead of an audio channel.
  21519. */
  21520. static const int midiChannelIndex;
  21521. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21522. in order to use the audio that comes into and out of the graph itself.
  21523. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21524. node in the graph which delivers the audio that is coming into the parent
  21525. graph. This allows you to stream the data to other nodes and process the
  21526. incoming audio.
  21527. Likewise, one of these in "output" mode can be sent data which it will add to
  21528. the sum of data being sent to the graph's output.
  21529. @see AudioProcessorGraph
  21530. */
  21531. class AudioGraphIOProcessor : public AudioPluginInstance
  21532. {
  21533. public:
  21534. /** Specifies the mode in which this processor will operate.
  21535. */
  21536. enum IODeviceType
  21537. {
  21538. audioInputNode, /**< In this mode, the processor has output channels
  21539. representing all the audio input channels that are
  21540. coming into its parent audio graph. */
  21541. audioOutputNode, /**< In this mode, the processor has input channels
  21542. representing all the audio output channels that are
  21543. going out of its parent audio graph. */
  21544. midiInputNode, /**< In this mode, the processor has a midi output which
  21545. delivers the same midi data that is arriving at its
  21546. parent graph. */
  21547. midiOutputNode /**< In this mode, the processor has a midi input and
  21548. any data sent to it will be passed out of the parent
  21549. graph. */
  21550. };
  21551. /** Returns the mode of this processor. */
  21552. IODeviceType getType() const throw() { return type; }
  21553. /** Returns the parent graph to which this processor belongs, or 0 if it
  21554. hasn't yet been added to one. */
  21555. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21556. /** True if this is an audio or midi input. */
  21557. bool isInput() const throw();
  21558. /** True if this is an audio or midi output. */
  21559. bool isOutput() const throw();
  21560. AudioGraphIOProcessor (const IODeviceType type);
  21561. ~AudioGraphIOProcessor();
  21562. const String getName() const;
  21563. void fillInPluginDescription (PluginDescription& d) const;
  21564. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21565. void releaseResources();
  21566. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21567. const String getInputChannelName (const int channelIndex) const;
  21568. const String getOutputChannelName (const int channelIndex) const;
  21569. bool isInputChannelStereoPair (int index) const;
  21570. bool isOutputChannelStereoPair (int index) const;
  21571. bool acceptsMidi() const;
  21572. bool producesMidi() const;
  21573. AudioProcessorEditor* createEditor();
  21574. int getNumParameters();
  21575. const String getParameterName (int);
  21576. float getParameter (int);
  21577. const String getParameterText (int);
  21578. void setParameter (int, float);
  21579. int getNumPrograms();
  21580. int getCurrentProgram();
  21581. void setCurrentProgram (int);
  21582. const String getProgramName (int);
  21583. void changeProgramName (int, const String&);
  21584. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21585. void setStateInformation (const void* data, int sizeInBytes);
  21586. /** @internal */
  21587. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21588. juce_UseDebuggingNewOperator
  21589. private:
  21590. const IODeviceType type;
  21591. AudioProcessorGraph* graph;
  21592. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21593. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21594. };
  21595. // AudioProcessor methods:
  21596. const String getName() const;
  21597. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21598. void releaseResources();
  21599. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21600. const String getInputChannelName (const int channelIndex) const;
  21601. const String getOutputChannelName (const int channelIndex) const;
  21602. bool isInputChannelStereoPair (int index) const;
  21603. bool isOutputChannelStereoPair (int index) const;
  21604. bool acceptsMidi() const;
  21605. bool producesMidi() const;
  21606. AudioProcessorEditor* createEditor() { return 0; }
  21607. int getNumParameters() { return 0; }
  21608. const String getParameterName (int) { return String::empty; }
  21609. float getParameter (int) { return 0; }
  21610. const String getParameterText (int) { return String::empty; }
  21611. void setParameter (int, float) { }
  21612. int getNumPrograms() { return 0; }
  21613. int getCurrentProgram() { return 0; }
  21614. void setCurrentProgram (int) { }
  21615. const String getProgramName (int) { return String::empty; }
  21616. void changeProgramName (int, const String&) { }
  21617. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21618. void setStateInformation (const void* data, int sizeInBytes);
  21619. /** @internal */
  21620. void handleAsyncUpdate();
  21621. juce_UseDebuggingNewOperator
  21622. private:
  21623. ReferenceCountedArray <Node> nodes;
  21624. OwnedArray <Connection> connections;
  21625. int lastNodeId;
  21626. AudioSampleBuffer renderingBuffers;
  21627. OwnedArray <MidiBuffer> midiBuffers;
  21628. CriticalSection renderLock;
  21629. VoidArray renderingOps;
  21630. friend class AudioGraphIOProcessor;
  21631. AudioSampleBuffer* currentAudioInputBuffer;
  21632. AudioSampleBuffer currentAudioOutputBuffer;
  21633. MidiBuffer* currentMidiInputBuffer;
  21634. MidiBuffer currentMidiOutputBuffer;
  21635. void clearRenderingSequence();
  21636. void buildRenderingSequence();
  21637. bool isAnInputTo (const uint32 possibleInputId,
  21638. const uint32 possibleDestinationId,
  21639. const int recursionCheck) const throw();
  21640. AudioProcessorGraph (const AudioProcessorGraph&);
  21641. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21642. };
  21643. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21644. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21645. #endif
  21646. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21647. #endif
  21648. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21649. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21650. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21651. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21652. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21653. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21654. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21655. class AudioIODevice;
  21656. /**
  21657. One of these is passed to an AudioIODevice object to stream the audio data
  21658. in and out.
  21659. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21660. method on its own high-priority audio thread, when it needs to send or receive
  21661. the next block of data.
  21662. @see AudioIODevice, AudioDeviceManager
  21663. */
  21664. class JUCE_API AudioIODeviceCallback
  21665. {
  21666. public:
  21667. /** Destructor. */
  21668. virtual ~AudioIODeviceCallback() {}
  21669. /** Processes a block of incoming and outgoing audio data.
  21670. The subclass's implementation should use the incoming audio for whatever
  21671. purposes it needs to, and must fill all the output channels with the next
  21672. block of output data before returning.
  21673. The channel data is arranged with the same array indices as the channel name
  21674. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21675. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21676. associated channel, so remember to check for this.
  21677. @param inputChannelData a set of arrays containing the audio data for each
  21678. incoming channel - this data is valid until the function
  21679. returns. There will be one channel of data for each input
  21680. channel that was enabled when the audio device was opened
  21681. (see AudioIODevice::open())
  21682. @param numInputChannels the number of pointers to channel data in the
  21683. inputChannelData array.
  21684. @param outputChannelData a set of arrays which need to be filled with the data
  21685. that should be sent to each outgoing channel of the device.
  21686. There will be one channel of data for each output channel
  21687. that was enabled when the audio device was opened (see
  21688. AudioIODevice::open())
  21689. The initial contents of the array is undefined, so the
  21690. callback function must fill all the channels with zeros if
  21691. its output is silence. Failing to do this could cause quite
  21692. an unpleasant noise!
  21693. @param numOutputChannels the number of pointers to channel data in the
  21694. outputChannelData array.
  21695. @param numSamples the number of samples in each channel of the input and
  21696. output arrays. The number of samples will depend on the
  21697. audio device's buffer size and will usually remain constant,
  21698. although this isn't guaranteed, so make sure your code can
  21699. cope with reasonable changes in the buffer size from one
  21700. callback to the next.
  21701. */
  21702. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21703. int numInputChannels,
  21704. float** outputChannelData,
  21705. int numOutputChannels,
  21706. int numSamples) = 0;
  21707. /** Called to indicate that the device is about to start calling back.
  21708. This will be called just before the audio callbacks begin, either when this
  21709. callback has just been added to an audio device, or after the device has been
  21710. restarted because of a sample-rate or block-size change.
  21711. You can use this opportunity to find out the sample rate and block size
  21712. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21713. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21714. @param device the audio IO device that will be used to drive the callback.
  21715. Note that if you're going to store this this pointer, it is
  21716. only valid until the next time that audioDeviceStopped is called.
  21717. */
  21718. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21719. /** Called to indicate that the device has stopped.
  21720. */
  21721. virtual void audioDeviceStopped() = 0;
  21722. };
  21723. /**
  21724. Base class for an audio device with synchronised input and output channels.
  21725. Subclasses of this are used to implement different protocols such as DirectSound,
  21726. ASIO, CoreAudio, etc.
  21727. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21728. documentation for that class for more info.
  21729. For an easier way of managing audio devices and their settings, have a look at the
  21730. AudioDeviceManager class.
  21731. @see AudioIODeviceType, AudioDeviceManager
  21732. */
  21733. class JUCE_API AudioIODevice
  21734. {
  21735. public:
  21736. /** Destructor. */
  21737. virtual ~AudioIODevice();
  21738. /** Returns the device's name, (as set in the constructor). */
  21739. const String& getName() const throw() { return name; }
  21740. /** Returns the type of the device.
  21741. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21742. */
  21743. const String& getTypeName() const throw() { return typeName; }
  21744. /** Returns the names of all the available output channels on this device.
  21745. To find out which of these are currently in use, call getActiveOutputChannels().
  21746. */
  21747. virtual const StringArray getOutputChannelNames() = 0;
  21748. /** Returns the names of all the available input channels on this device.
  21749. To find out which of these are currently in use, call getActiveInputChannels().
  21750. */
  21751. virtual const StringArray getInputChannelNames() = 0;
  21752. /** Returns the number of sample-rates this device supports.
  21753. To find out which rates are available on this device, use this method to
  21754. find out how many there are, and getSampleRate() to get the rates.
  21755. @see getSampleRate
  21756. */
  21757. virtual int getNumSampleRates() = 0;
  21758. /** Returns one of the sample-rates this device supports.
  21759. To find out which rates are available on this device, use getNumSampleRates() to
  21760. find out how many there are, and getSampleRate() to get the individual rates.
  21761. The sample rate is set by the open() method.
  21762. (Note that for DirectSound some rates might not work, depending on combinations
  21763. of i/o channels that are being opened).
  21764. @see getNumSampleRates
  21765. */
  21766. virtual double getSampleRate (int index) = 0;
  21767. /** Returns the number of sizes of buffer that are available.
  21768. @see getBufferSizeSamples, getDefaultBufferSize
  21769. */
  21770. virtual int getNumBufferSizesAvailable() = 0;
  21771. /** Returns one of the possible buffer-sizes.
  21772. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21773. @returns a number of samples
  21774. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21775. */
  21776. virtual int getBufferSizeSamples (int index) = 0;
  21777. /** Returns the default buffer-size to use.
  21778. @returns a number of samples
  21779. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21780. */
  21781. virtual int getDefaultBufferSize() = 0;
  21782. /** Tries to open the device ready to play.
  21783. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21784. input channel should be enabled
  21785. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  21786. output channel should be enabled
  21787. @param sampleRate the sample rate to try to use - to find out which rates are
  21788. available, see getNumSampleRates() and getSampleRate()
  21789. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  21790. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  21791. @returns an error description if there's a problem, or an empty string if it succeeds in
  21792. opening the device
  21793. @see close
  21794. */
  21795. virtual const String open (const BitArray& inputChannels,
  21796. const BitArray& outputChannels,
  21797. double sampleRate,
  21798. int bufferSizeSamples) = 0;
  21799. /** Closes and releases the device if it's open. */
  21800. virtual void close() = 0;
  21801. /** Returns true if the device is still open.
  21802. A device might spontaneously close itself if something goes wrong, so this checks if
  21803. it's still open.
  21804. */
  21805. virtual bool isOpen() = 0;
  21806. /** Starts the device actually playing.
  21807. This must be called after the device has been opened.
  21808. @param callback the callback to use for streaming the data.
  21809. @see AudioIODeviceCallback, open
  21810. */
  21811. virtual void start (AudioIODeviceCallback* callback) = 0;
  21812. /** Stops the device playing.
  21813. Once a device has been started, this will stop it. Any pending calls to the
  21814. callback class will be flushed before this method returns.
  21815. */
  21816. virtual void stop() = 0;
  21817. /** Returns true if the device is still calling back.
  21818. The device might mysteriously stop, so this checks whether it's
  21819. still playing.
  21820. */
  21821. virtual bool isPlaying() = 0;
  21822. /** Returns the last error that happened if anything went wrong. */
  21823. virtual const String getLastError() = 0;
  21824. /** Returns the buffer size that the device is currently using.
  21825. If the device isn't actually open, this value doesn't really mean much.
  21826. */
  21827. virtual int getCurrentBufferSizeSamples() = 0;
  21828. /** Returns the sample rate that the device is currently using.
  21829. If the device isn't actually open, this value doesn't really mean much.
  21830. */
  21831. virtual double getCurrentSampleRate() = 0;
  21832. /** Returns the device's current physical bit-depth.
  21833. If the device isn't actually open, this value doesn't really mean much.
  21834. */
  21835. virtual int getCurrentBitDepth() = 0;
  21836. /** Returns a mask showing which of the available output channels are currently
  21837. enabled.
  21838. @see getOutputChannelNames
  21839. */
  21840. virtual const BitArray getActiveOutputChannels() const = 0;
  21841. /** Returns a mask showing which of the available input channels are currently
  21842. enabled.
  21843. @see getInputChannelNames
  21844. */
  21845. virtual const BitArray getActiveInputChannels() const = 0;
  21846. /** Returns the device's output latency.
  21847. This is the delay in samples between a callback getting a block of data, and
  21848. that data actually getting played.
  21849. */
  21850. virtual int getOutputLatencyInSamples() = 0;
  21851. /** Returns the device's input latency.
  21852. This is the delay in samples between some audio actually arriving at the soundcard,
  21853. and the callback getting passed this block of data.
  21854. */
  21855. virtual int getInputLatencyInSamples() = 0;
  21856. /** True if this device can show a pop-up control panel for editing its settings.
  21857. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  21858. to display it.
  21859. */
  21860. virtual bool hasControlPanel() const;
  21861. /** Shows a device-specific control panel if there is one.
  21862. This should only be called for devices which return true from hasControlPanel().
  21863. */
  21864. virtual bool showControlPanel();
  21865. protected:
  21866. /** Creates a device, setting its name and type member variables. */
  21867. AudioIODevice (const String& deviceName,
  21868. const String& typeName);
  21869. /** @internal */
  21870. String name, typeName;
  21871. };
  21872. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21873. /********* End of inlined file: juce_AudioIODevice.h *********/
  21874. /**
  21875. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  21876. To use one of these, just make it the callback used by your AudioIODevice, and
  21877. give it a processor to use by calling setProcessor().
  21878. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  21879. input to send both streams through the processor.
  21880. @see AudioProcessor, AudioProcessorGraph
  21881. */
  21882. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  21883. public MidiInputCallback
  21884. {
  21885. public:
  21886. /**
  21887. */
  21888. AudioProcessorPlayer();
  21889. /** Destructor. */
  21890. virtual ~AudioProcessorPlayer();
  21891. /** Sets the processor that should be played.
  21892. The processor that is passed in will not be deleted or owned by this object.
  21893. To stop anything playing, pass in 0 to this method.
  21894. */
  21895. void setProcessor (AudioProcessor* const processorToPlay);
  21896. /** Returns the current audio processor that is being played.
  21897. */
  21898. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  21899. /** Returns a midi message collector that you can pass midi messages to if you
  21900. want them to be injected into the midi stream that is being sent to the
  21901. processor.
  21902. */
  21903. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  21904. /** @internal */
  21905. void audioDeviceIOCallback (const float** inputChannelData,
  21906. int totalNumInputChannels,
  21907. float** outputChannelData,
  21908. int totalNumOutputChannels,
  21909. int numSamples);
  21910. /** @internal */
  21911. void audioDeviceAboutToStart (AudioIODevice* device);
  21912. /** @internal */
  21913. void audioDeviceStopped();
  21914. /** @internal */
  21915. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  21916. juce_UseDebuggingNewOperator
  21917. private:
  21918. AudioProcessor* processor;
  21919. CriticalSection lock;
  21920. double sampleRate;
  21921. int blockSize;
  21922. bool isPrepared;
  21923. int numInputChans, numOutputChans;
  21924. float* channels [128];
  21925. AudioSampleBuffer tempBuffer;
  21926. MidiBuffer incomingMidi;
  21927. MidiMessageCollector messageCollector;
  21928. AudioProcessorPlayer (const AudioProcessorPlayer&);
  21929. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  21930. };
  21931. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21932. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  21933. #endif
  21934. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  21935. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  21936. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  21937. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  21938. /********* Start of inlined file: juce_PropertyPanel.h *********/
  21939. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  21940. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  21941. /********* Start of inlined file: juce_PropertyComponent.h *********/
  21942. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  21943. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  21944. class EditableProperty;
  21945. /**
  21946. A base class for a component that goes in a PropertyPanel and displays one of
  21947. an item's properties.
  21948. Subclasses of this are used to display a property in various forms, e.g. a
  21949. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  21950. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  21951. A subclass must implement the refresh() method which will be called to tell the
  21952. component to update itself, and is also responsible for calling this it when the
  21953. item that it refers to is changed.
  21954. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  21955. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  21956. */
  21957. class JUCE_API PropertyComponent : public Component
  21958. {
  21959. public:
  21960. /** Creates a PropertyComponent.
  21961. @param propertyName the name is stored as this component's name, and is
  21962. used as the name displayed next to this component in
  21963. a property panel
  21964. @param preferredHeight the height that the component should be given - some
  21965. items may need to be larger than a normal row height.
  21966. This value can also be set if a subclass changes the
  21967. preferredHeight member variable.
  21968. */
  21969. PropertyComponent (const String& propertyName,
  21970. const int preferredHeight = 25);
  21971. /** Destructor. */
  21972. ~PropertyComponent();
  21973. /** Returns this item's preferred height.
  21974. This value is specified either in the constructor or by a subclass changing the
  21975. preferredHeight member variable.
  21976. */
  21977. int getPreferredHeight() const throw() { return preferredHeight; }
  21978. /** Updates the property component if the item it refers to has changed.
  21979. A subclass must implement this method, and other objects may call it to
  21980. force it to refresh itself.
  21981. The subclass should be economical in the amount of work is done, so for
  21982. example it should check whether it really needs to do a repaint rather than
  21983. just doing one every time this method is called, as it may be called when
  21984. the value being displayed hasn't actually changed.
  21985. */
  21986. virtual void refresh() = 0;
  21987. /** The default paint method fills the background and draws a label for the
  21988. item's name.
  21989. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  21990. */
  21991. void paint (Graphics& g);
  21992. /** The default resize method positions any child component to the right of this
  21993. one, based on the look and feel's default label size.
  21994. */
  21995. void resized();
  21996. /** By default, this just repaints the component. */
  21997. void enablementChanged();
  21998. juce_UseDebuggingNewOperator
  21999. protected:
  22000. /** Used by the PropertyPanel to determine how high this component needs to be.
  22001. A subclass can update this value in its constructor but shouldn't alter it later
  22002. as changes won't necessarily be picked up.
  22003. */
  22004. int preferredHeight;
  22005. };
  22006. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22007. /********* End of inlined file: juce_PropertyComponent.h *********/
  22008. /********* Start of inlined file: juce_Viewport.h *********/
  22009. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22010. #define __JUCE_VIEWPORT_JUCEHEADER__
  22011. /********* Start of inlined file: juce_ScrollBar.h *********/
  22012. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22013. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22014. /********* Start of inlined file: juce_Button.h *********/
  22015. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22016. #define __JUCE_BUTTON_JUCEHEADER__
  22017. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22018. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22019. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22020. /********* Start of inlined file: juce_TooltipClient.h *********/
  22021. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22022. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22023. /**
  22024. Components that want to use pop-up tooltips should implement this interface.
  22025. A TooltipWindow will wait for the mouse to hover over a component that
  22026. implements the TooltipClient interface, and when it finds one, it will display
  22027. the tooltip returned by its getTooltip() method.
  22028. @see TooltipWindow, SettableTooltipClient
  22029. */
  22030. class JUCE_API TooltipClient
  22031. {
  22032. public:
  22033. /** Destructor. */
  22034. virtual ~TooltipClient() {}
  22035. /** Returns the string that this object wants to show as its tooltip. */
  22036. virtual const String getTooltip() = 0;
  22037. };
  22038. /**
  22039. An implementation of TooltipClient that stores the tooltip string and a method
  22040. for changing it.
  22041. This makes it easy to add a tooltip to a custom component, by simply adding this
  22042. as a base class and calling setTooltip().
  22043. Many of the Juce widgets already use this as a base class to implement their
  22044. tooltips.
  22045. @see TooltipClient, TooltipWindow
  22046. */
  22047. class JUCE_API SettableTooltipClient : public TooltipClient
  22048. {
  22049. public:
  22050. /** Destructor. */
  22051. virtual ~SettableTooltipClient() {}
  22052. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22053. virtual const String getTooltip() { return tooltipString; }
  22054. juce_UseDebuggingNewOperator
  22055. protected:
  22056. String tooltipString;
  22057. };
  22058. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22059. /********* End of inlined file: juce_TooltipClient.h *********/
  22060. /**
  22061. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22062. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22063. object.
  22064. The TooltipWindow object will then stay invisible, waiting until the mouse
  22065. hovers for the specified length of time - it will then see if it's currently
  22066. over a component which implements the TooltipClient interface, and if so,
  22067. it will make itself visible to show the tooltip in the appropriate place.
  22068. @see TooltipClient, SettableTooltipClient
  22069. */
  22070. class JUCE_API TooltipWindow : public Component,
  22071. private Timer
  22072. {
  22073. public:
  22074. /** Creates a tooltip window.
  22075. Make sure your app only creates one instance of this class, otherwise you'll
  22076. get multiple overlaid tooltips appearing. The window will initially be invisible
  22077. and will make itself visible when it needs to display a tip.
  22078. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22079. methods.
  22080. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22081. otherwise the tooltip will be added to the given parent
  22082. component.
  22083. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22084. before a tooltip will be shown
  22085. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22086. */
  22087. TooltipWindow (Component* parentComponent = 0,
  22088. const int millisecondsBeforeTipAppears = 700);
  22089. /** Destructor. */
  22090. ~TooltipWindow();
  22091. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22092. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22093. methods.
  22094. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22095. */
  22096. enum ColourIds
  22097. {
  22098. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22099. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22100. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22101. };
  22102. juce_UseDebuggingNewOperator
  22103. private:
  22104. const int millisecondsBeforeTipAppears;
  22105. int mouseX, mouseY, mouseClicks;
  22106. unsigned int lastMouseMoveTime, lastHideTime;
  22107. Component* lastComponentUnderMouse;
  22108. bool changedCompsSinceShown;
  22109. String tip;
  22110. void paint (Graphics& g);
  22111. void mouseEnter (const MouseEvent& e);
  22112. void timerCallback();
  22113. void showFor (Component* const c);
  22114. void hide();
  22115. TooltipWindow (const TooltipWindow&);
  22116. const TooltipWindow& operator= (const TooltipWindow&);
  22117. };
  22118. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22119. /********* End of inlined file: juce_TooltipWindow.h *********/
  22120. class Button;
  22121. /**
  22122. Used to receive callbacks when a button is clicked.
  22123. @see Button::addButtonListener, Button::removeButtonListener
  22124. */
  22125. class JUCE_API ButtonListener
  22126. {
  22127. public:
  22128. /** Destructor. */
  22129. virtual ~ButtonListener() {}
  22130. /** Called when the button is clicked. */
  22131. virtual void buttonClicked (Button* button) = 0;
  22132. /** Called when the button's state changes. */
  22133. virtual void buttonStateChanged (Button*) {}
  22134. };
  22135. /**
  22136. A base class for buttons.
  22137. This contains all the logic for button behaviours such as enabling/disabling,
  22138. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22139. and radio groups, etc.
  22140. @see TextButton, DrawableButton, ToggleButton
  22141. */
  22142. class JUCE_API Button : public Component,
  22143. public SettableTooltipClient,
  22144. public ApplicationCommandManagerListener,
  22145. private KeyListener
  22146. {
  22147. protected:
  22148. /** Creates a button.
  22149. @param buttonName the text to put in the button (the component's name is also
  22150. initially set to this string, but these can be changed later
  22151. using the setName() and setButtonText() methods)
  22152. */
  22153. Button (const String& buttonName);
  22154. public:
  22155. /** Destructor. */
  22156. virtual ~Button();
  22157. /** Changes the button's text.
  22158. @see getButtonText
  22159. */
  22160. void setButtonText (const String& newText) throw();
  22161. /** Returns the text displayed in the button.
  22162. @see setButtonText
  22163. */
  22164. const String getButtonText() const throw() { return text; }
  22165. /** Returns true if the button is currently being held down by the mouse.
  22166. @see isOver
  22167. */
  22168. bool isDown() const throw();
  22169. /** Returns true if the mouse is currently over the button.
  22170. This will be also be true if the mouse is being held down.
  22171. @see isDown
  22172. */
  22173. bool isOver() const throw();
  22174. /** A button has an on/off state associated with it, and this changes that.
  22175. By default buttons are 'off' and for simple buttons that you click to perform
  22176. an action you won't change this. Toggle buttons, however will want to
  22177. change their state when turned on or off.
  22178. @param shouldBeOn whether to set the button's toggle state to be on or
  22179. off. If it's a member of a button group, this will
  22180. always try to turn it on, and to turn off any other
  22181. buttons in the group
  22182. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22183. the button will be repainted but no notification will
  22184. be sent
  22185. @see getToggleState, setRadioGroupId
  22186. */
  22187. void setToggleState (const bool shouldBeOn,
  22188. const bool sendChangeNotification);
  22189. /** Returns true if the button in 'on'.
  22190. By default buttons are 'off' and for simple buttons that you click to perform
  22191. an action you won't change this. Toggle buttons, however will want to
  22192. change their state when turned on or off.
  22193. @see setToggleState
  22194. */
  22195. bool getToggleState() const throw() { return isOn; }
  22196. /** This tells the button to automatically flip the toggle state when
  22197. the button is clicked.
  22198. If set to true, then before the clicked() callback occurs, the toggle-state
  22199. of the button is flipped.
  22200. */
  22201. void setClickingTogglesState (const bool shouldToggle) throw();
  22202. /** Returns true if this button is set to be an automatic toggle-button.
  22203. This returns the last value that was passed to setClickingTogglesState().
  22204. */
  22205. bool getClickingTogglesState() const throw();
  22206. /** Enables the button to act as a member of a mutually-exclusive group
  22207. of 'radio buttons'.
  22208. If the group ID is set to a non-zero number, then this button will
  22209. act as part of a group of buttons with the same ID, only one of
  22210. which can be 'on' at the same time. Note that when it's part of
  22211. a group, clicking a toggle-button that's 'on' won't turn it off.
  22212. To find other buttons with the same ID, this button will search through
  22213. its sibling components for ToggleButtons, so all the buttons for a
  22214. particular group must be placed inside the same parent component.
  22215. Set the group ID back to zero if you want it to act as a normal toggle
  22216. button again.
  22217. @see getRadioGroupId
  22218. */
  22219. void setRadioGroupId (const int newGroupId);
  22220. /** Returns the ID of the group to which this button belongs.
  22221. (See setRadioGroupId() for an explanation of this).
  22222. */
  22223. int getRadioGroupId() const throw() { return radioGroupId; }
  22224. /** Registers a listener to receive events when this button's state changes.
  22225. If the listener is already registered, this will not register it again.
  22226. @see removeButtonListener
  22227. */
  22228. void addButtonListener (ButtonListener* const newListener) throw();
  22229. /** Removes a previously-registered button listener
  22230. @see addButtonListener
  22231. */
  22232. void removeButtonListener (ButtonListener* const listener) throw();
  22233. /** Causes the button to act as if it's been clicked.
  22234. This will asynchronously make the button draw itself going down and up, and
  22235. will then call back the clicked() method as if mouse was clicked on it.
  22236. @see clicked
  22237. */
  22238. virtual void triggerClick();
  22239. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22240. When the button is pressed, it will use the given manager to trigger the
  22241. command ID.
  22242. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22243. before this button is. To disable the command triggering, call this method and
  22244. pass 0 for the parameters.
  22245. If generateTooltip is true, then the button's tooltip will be automatically
  22246. generated based on the name of this command and its current shortcut key.
  22247. @see addShortcut, getCommandID
  22248. */
  22249. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22250. const int commandID,
  22251. const bool generateTooltip);
  22252. /** Returns the command ID that was set by setCommandToTrigger().
  22253. */
  22254. int getCommandID() const throw() { return commandID; }
  22255. /** Assigns a shortcut key to trigger the button.
  22256. The button registers itself with its top-level parent component for keypresses.
  22257. Note that a different way of linking buttons to keypresses is by using the
  22258. setKeyPressToTrigger() method to invoke a command - the difference being that
  22259. setting a shortcut allows the button to be temporarily linked to a keypress
  22260. only while it's on-screen.
  22261. @see clearShortcuts
  22262. */
  22263. void addShortcut (const KeyPress& key);
  22264. /** Removes all key shortcuts that had been set for this button.
  22265. @see addShortcut
  22266. */
  22267. void clearShortcuts();
  22268. /** Returns true if the given keypress is a shortcut for this button.
  22269. @see addShortcut
  22270. */
  22271. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22272. /** Sets an auto-repeat speed for the button when it is held down.
  22273. (Auto-repeat is disabled by default).
  22274. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22275. triggering the next click. If this is zero, auto-repeat
  22276. is disabled
  22277. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22278. triggered
  22279. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22280. get faster, the longer the button is held down, up to the
  22281. minimum interval specified here
  22282. */
  22283. void setRepeatSpeed (const int initialDelayInMillisecs,
  22284. const int repeatDelayInMillisecs,
  22285. const int minimumDelayInMillisecs = -1) throw();
  22286. /** Sets whether the button click should happen when the mouse is pressed or released.
  22287. By default the button is only considered to have been clicked when the mouse is
  22288. released, but setting this to true will make it call the clicked() method as soon
  22289. as the button is pressed.
  22290. This is useful if the button is being used to show a pop-up menu, as it allows
  22291. the click to be used as a drag onto the menu.
  22292. */
  22293. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22294. /** Returns the number of milliseconds since the last time the button
  22295. went into the 'down' state.
  22296. */
  22297. uint32 getMillisecondsSinceButtonDown() const throw();
  22298. /** (overridden from Component to do special stuff). */
  22299. void setVisible (bool shouldBeVisible);
  22300. /** Sets the tooltip for this button.
  22301. @see TooltipClient, TooltipWindow
  22302. */
  22303. void setTooltip (const String& newTooltip);
  22304. // (implementation of the TooltipClient method)
  22305. const String getTooltip();
  22306. /** A combination of these flags are used by setConnectedEdges().
  22307. */
  22308. enum ConnectedEdgeFlags
  22309. {
  22310. ConnectedOnLeft = 1,
  22311. ConnectedOnRight = 2,
  22312. ConnectedOnTop = 4,
  22313. ConnectedOnBottom = 8
  22314. };
  22315. /** Hints about which edges of the button might be connected to adjoining buttons.
  22316. The value passed in is a bitwise combination of any of the values in the
  22317. ConnectedEdgeFlags enum.
  22318. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22319. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22320. without rounded corners on the edges that connect. It's only a hint, so the
  22321. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22322. button.
  22323. */
  22324. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22325. /** Returns the set of flags passed into setConnectedEdges(). */
  22326. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22327. /** Indicates whether the button adjoins another one on its left edge.
  22328. @see setConnectedEdges
  22329. */
  22330. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22331. /** Indicates whether the button adjoins another one on its right edge.
  22332. @see setConnectedEdges
  22333. */
  22334. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22335. /** Indicates whether the button adjoins another one on its top edge.
  22336. @see setConnectedEdges
  22337. */
  22338. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22339. /** Indicates whether the button adjoins another one on its bottom edge.
  22340. @see setConnectedEdges
  22341. */
  22342. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22343. /** Used by setState(). */
  22344. enum ButtonState
  22345. {
  22346. buttonNormal,
  22347. buttonOver,
  22348. buttonDown
  22349. };
  22350. /** Can be used to force the button into a particular state.
  22351. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22352. from happening.
  22353. The state that you set here will only last until it is automatically changed when the mouse
  22354. enters or exits the button, or the mouse-button is pressed or released.
  22355. */
  22356. void setState (const ButtonState newState);
  22357. juce_UseDebuggingNewOperator
  22358. protected:
  22359. /** This method is called when the button has been clicked.
  22360. Subclasses can override this to perform whatever they actions they need
  22361. to do.
  22362. Alternatively, a ButtonListener can be added to the button, and these listeners
  22363. will be called when the click occurs.
  22364. @see triggerClick
  22365. */
  22366. virtual void clicked();
  22367. /** This method is called when the button has been clicked.
  22368. By default it just calls clicked(), but you might want to override it to handle
  22369. things like clicking when a modifier key is pressed, etc.
  22370. @see ModifierKeys
  22371. */
  22372. virtual void clicked (const ModifierKeys& modifiers);
  22373. /** Subclasses should override this to actually paint the button's contents.
  22374. It's better to use this than the paint method, because it gives you information
  22375. about the over/down state of the button.
  22376. @param g the graphics context to use
  22377. @param isMouseOverButton true if the button is either in the 'over' or
  22378. 'down' state
  22379. @param isButtonDown true if the button should be drawn in the 'down' position
  22380. */
  22381. virtual void paintButton (Graphics& g,
  22382. bool isMouseOverButton,
  22383. bool isButtonDown) = 0;
  22384. /** Called when the button's up/down/over state changes.
  22385. Subclasses can override this if they need to do something special when the button
  22386. goes up or down.
  22387. @see isDown, isOver
  22388. */
  22389. virtual void buttonStateChanged();
  22390. /** @internal */
  22391. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22392. /** @internal */
  22393. void handleCommandMessage (int commandId);
  22394. /** @internal */
  22395. void mouseEnter (const MouseEvent& e);
  22396. /** @internal */
  22397. void mouseExit (const MouseEvent& e);
  22398. /** @internal */
  22399. void mouseDown (const MouseEvent& e);
  22400. /** @internal */
  22401. void mouseDrag (const MouseEvent& e);
  22402. /** @internal */
  22403. void mouseUp (const MouseEvent& e);
  22404. /** @internal */
  22405. bool keyPressed (const KeyPress& key);
  22406. /** @internal */
  22407. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22408. /** @internal */
  22409. bool keyStateChanged (Component* originatingComponent);
  22410. /** @internal */
  22411. void paint (Graphics& g);
  22412. /** @internal */
  22413. void parentHierarchyChanged();
  22414. /** @internal */
  22415. void focusGained (FocusChangeType cause);
  22416. /** @internal */
  22417. void focusLost (FocusChangeType cause);
  22418. /** @internal */
  22419. void enablementChanged();
  22420. /** @internal */
  22421. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22422. /** @internal */
  22423. void applicationCommandListChanged();
  22424. private:
  22425. Array <KeyPress> shortcuts;
  22426. Component* keySource;
  22427. String text;
  22428. SortedSet <void*> buttonListeners;
  22429. friend class InternalButtonRepeatTimer;
  22430. Timer* repeatTimer;
  22431. uint32 buttonPressTime, lastTimeCallbackTime;
  22432. ApplicationCommandManager* commandManagerToUse;
  22433. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22434. int radioGroupId, commandID, connectedEdgeFlags;
  22435. ButtonState buttonState;
  22436. bool isOn : 1;
  22437. bool clickTogglesState : 1;
  22438. bool needsToRelease : 1;
  22439. bool needsRepainting : 1;
  22440. bool isKeyDown : 1;
  22441. bool triggerOnMouseDown : 1;
  22442. bool generateTooltip : 1;
  22443. void repeatTimerCallback() throw();
  22444. Timer& getRepeatTimer() throw();
  22445. ButtonState updateState (const MouseEvent* const e) throw();
  22446. bool isShortcutPressed() const throw();
  22447. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22448. void flashButtonState() throw();
  22449. void sendClickMessage (const ModifierKeys& modifiers);
  22450. void sendStateMessage();
  22451. Button (const Button&);
  22452. const Button& operator= (const Button&);
  22453. };
  22454. #endif // __JUCE_BUTTON_JUCEHEADER__
  22455. /********* End of inlined file: juce_Button.h *********/
  22456. class ScrollBar;
  22457. /**
  22458. A class for receiving events from a ScrollBar.
  22459. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22460. method, and it will be called when the bar's position changes.
  22461. @see ScrollBar::addListener, ScrollBar::removeListener
  22462. */
  22463. class JUCE_API ScrollBarListener
  22464. {
  22465. public:
  22466. /** Destructor. */
  22467. virtual ~ScrollBarListener() {}
  22468. /** Called when a ScrollBar is moved.
  22469. @param scrollBarThatHasMoved the bar that has moved
  22470. @param newRangeStart the new range start of this bar
  22471. */
  22472. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22473. const double newRangeStart) = 0;
  22474. };
  22475. /**
  22476. A scrollbar component.
  22477. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22478. sets the range of values it can represent. Then you can use setCurrentRange() to
  22479. change the position and size of the scrollbar's 'thumb'.
  22480. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22481. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22482. they moved it to.
  22483. The scrollbar will adjust its own visibility according to whether its thumb size
  22484. allows it to actually be scrolled.
  22485. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22486. instead of handling a scrollbar directly.
  22487. @see ScrollBarListener
  22488. */
  22489. class JUCE_API ScrollBar : public Component,
  22490. public AsyncUpdater,
  22491. private Timer
  22492. {
  22493. public:
  22494. /** Creates a Scrollbar.
  22495. @param isVertical whether it should be a vertical or horizontal bar
  22496. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22497. */
  22498. ScrollBar (const bool isVertical,
  22499. const bool buttonsAreVisible = true);
  22500. /** Destructor. */
  22501. ~ScrollBar();
  22502. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22503. bool isVertical() const throw() { return vertical; }
  22504. /** Changes the scrollbar's direction.
  22505. You'll also need to resize the bar appropriately - this just changes its internal
  22506. layout.
  22507. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22508. */
  22509. void setOrientation (const bool shouldBeVertical) throw();
  22510. /** Shows or hides the scrollbar's buttons. */
  22511. void setButtonVisibility (const bool buttonsAreVisible);
  22512. /** Tells the scrollbar whether to make itself invisible when not needed.
  22513. The default behaviour is for a scrollbar to become invisible when the thumb
  22514. fills the whole of its range (i.e. when it can't be moved). Setting this
  22515. value to false forces the bar to always be visible.
  22516. */
  22517. void setAutoHide (const bool shouldHideWhenFullRange);
  22518. /** Sets the minimum and maximum values that the bar will move between.
  22519. The bar's thumb will always be constrained so that the top of the thumb
  22520. will be >= minimum, and the bottom of the thumb <= maximum.
  22521. @see setCurrentRange
  22522. */
  22523. void setRangeLimits (const double minimum,
  22524. const double maximum) throw();
  22525. /** Returns the lower value that the thumb can be set to.
  22526. This is the value set by setRangeLimits().
  22527. */
  22528. double getMinimumRangeLimit() const throw() { return minimum; }
  22529. /** Returns the upper value that the thumb can be set to.
  22530. This is the value set by setRangeLimits().
  22531. */
  22532. double getMaximumRangeLimit() const throw() { return maximum; }
  22533. /** Changes the position of the scrollbar's 'thumb'.
  22534. This sets both the position and size of the thumb - to just set the position without
  22535. changing the size, you can use setCurrentRangeStart().
  22536. If this method call actually changes the scrollbar's position, it will trigger an
  22537. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22538. are registered.
  22539. @param newStart the top (or left) of the thumb, in the range
  22540. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22541. value is beyond these limits, it will be clipped.
  22542. @param newSize the size of the thumb, such that
  22543. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22544. size is beyond these limits, it will be clipped.
  22545. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22546. */
  22547. void setCurrentRange (double newStart,
  22548. double newSize) throw();
  22549. /** Moves the bar's thumb position.
  22550. This will move the thumb position without changing the thumb size. Note
  22551. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22552. If this method call actually changes the scrollbar's position, it will trigger an
  22553. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22554. are registered.
  22555. @see setCurrentRange
  22556. */
  22557. void setCurrentRangeStart (double newStart) throw();
  22558. /** Returns the position of the top of the thumb.
  22559. @see setCurrentRangeStart
  22560. */
  22561. double getCurrentRangeStart() const throw() { return rangeStart; }
  22562. /** Returns the current size of the thumb.
  22563. @see setCurrentRange
  22564. */
  22565. double getCurrentRangeSize() const throw() { return rangeSize; }
  22566. /** Sets the amount by which the up and down buttons will move the bar.
  22567. The value here is in terms of the total range, and is added or subtracted
  22568. from the thumb position when the user clicks an up/down (or left/right) button.
  22569. */
  22570. void setSingleStepSize (const double newSingleStepSize) throw();
  22571. /** Moves the scrollbar by a number of single-steps.
  22572. This will move the bar by a multiple of its single-step interval (as
  22573. specified using the setSingleStepSize() method).
  22574. A positive value here will move the bar down or to the right, a negative
  22575. value moves it up or to the left.
  22576. */
  22577. void moveScrollbarInSteps (const int howManySteps) throw();
  22578. /** Moves the scroll bar up or down in pages.
  22579. This will move the bar by a multiple of its current thumb size, effectively
  22580. doing a page-up or down.
  22581. A positive value here will move the bar down or to the right, a negative
  22582. value moves it up or to the left.
  22583. */
  22584. void moveScrollbarInPages (const int howManyPages) throw();
  22585. /** Scrolls to the top (or left).
  22586. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22587. */
  22588. void scrollToTop() throw();
  22589. /** Scrolls to the bottom (or right).
  22590. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22591. */
  22592. void scrollToBottom() throw();
  22593. /** Changes the delay before the up and down buttons autorepeat when they are held
  22594. down.
  22595. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22596. @see Button::setRepeatSpeed
  22597. */
  22598. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22599. const int repeatDelayInMillisecs,
  22600. const int minimumDelayInMillisecs = -1) throw();
  22601. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22602. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22603. methods.
  22604. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22605. */
  22606. enum ColourIds
  22607. {
  22608. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22609. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22610. 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. */
  22611. };
  22612. /** Registers a listener that will be called when the scrollbar is moved. */
  22613. void addListener (ScrollBarListener* const listener) throw();
  22614. /** Deregisters a previously-registered listener. */
  22615. void removeListener (ScrollBarListener* const listener) throw();
  22616. /** @internal */
  22617. bool keyPressed (const KeyPress& key);
  22618. /** @internal */
  22619. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22620. /** @internal */
  22621. void lookAndFeelChanged();
  22622. /** @internal */
  22623. void handleAsyncUpdate();
  22624. /** @internal */
  22625. void mouseDown (const MouseEvent& e);
  22626. /** @internal */
  22627. void mouseDrag (const MouseEvent& e);
  22628. /** @internal */
  22629. void mouseUp (const MouseEvent& e);
  22630. /** @internal */
  22631. void paint (Graphics& g);
  22632. /** @internal */
  22633. void resized();
  22634. juce_UseDebuggingNewOperator
  22635. private:
  22636. double minimum, maximum;
  22637. double rangeStart, rangeSize;
  22638. double singleStepSize, dragStartRange;
  22639. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22640. int dragStartMousePos, lastMousePos;
  22641. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22642. bool vertical, isDraggingThumb, alwaysVisible;
  22643. Button* upButton;
  22644. Button* downButton;
  22645. SortedSet <void*> listeners;
  22646. void updateThumbPosition() throw();
  22647. void timerCallback();
  22648. ScrollBar (const ScrollBar&);
  22649. const ScrollBar& operator= (const ScrollBar&);
  22650. };
  22651. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22652. /********* End of inlined file: juce_ScrollBar.h *********/
  22653. /**
  22654. A Viewport is used to contain a larger child component, and allows the child
  22655. to be automatically scrolled around.
  22656. To use a Viewport, just create one and set the component that goes inside it
  22657. using the setViewedComponent() method. When the child component changes size,
  22658. the Viewport will adjust its scrollbars accordingly.
  22659. A subclass of the viewport can be created which will receive calls to its
  22660. visibleAreaChanged() method when the subcomponent changes position or size.
  22661. */
  22662. class JUCE_API Viewport : public Component,
  22663. private ComponentListener,
  22664. private ScrollBarListener
  22665. {
  22666. public:
  22667. /** Creates a Viewport.
  22668. The viewport is initially empty - use the setViewedComponent() method to
  22669. add a child component for it to manage.
  22670. */
  22671. Viewport (const String& componentName = String::empty);
  22672. /** Destructor. */
  22673. ~Viewport();
  22674. /** Sets the component that this viewport will contain and scroll around.
  22675. This will add the given component to this Viewport and position it at
  22676. (0, 0).
  22677. (Don't add or remove any child components directly using the normal
  22678. Component::addChildComponent() methods).
  22679. @param newViewedComponent the component to add to this viewport (this pointer
  22680. may be null). The component passed in will be deleted
  22681. by the Viewport when it's no longer needed
  22682. @see getViewedComponent
  22683. */
  22684. void setViewedComponent (Component* const newViewedComponent);
  22685. /** Returns the component that's currently being used inside the Viewport.
  22686. @see setViewedComponent
  22687. */
  22688. Component* getViewedComponent() const throw() { return contentComp; }
  22689. /** Changes the position of the viewed component.
  22690. The inner component will be moved so that the pixel at the top left of
  22691. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22692. within the inner component.
  22693. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22694. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22695. */
  22696. void setViewPosition (const int xPixelsOffset,
  22697. const int yPixelsOffset);
  22698. /** Changes the view position as a proportion of the distance it can move.
  22699. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22700. visible area in the top-left, and (1, 1) would put it as far down and
  22701. to the right as it's possible to go whilst keeping the child component
  22702. on-screen.
  22703. */
  22704. void setViewPositionProportionately (const double proportionX,
  22705. const double proportionY);
  22706. /** Returns the position within the child component of the top-left of its visible area.
  22707. @see getViewWidth, setViewPosition
  22708. */
  22709. int getViewPositionX() const throw() { return lastVX; }
  22710. /** Returns the position within the child component of the top-left of its visible area.
  22711. @see getViewHeight, setViewPosition
  22712. */
  22713. int getViewPositionY() const throw() { return lastVY; }
  22714. /** Returns the width of the visible area of the child component.
  22715. This may be less than the width of this Viewport if there's a vertical scrollbar
  22716. or if the child component is itself smaller.
  22717. */
  22718. int getViewWidth() const throw() { return lastVW; }
  22719. /** Returns the height of the visible area of the child component.
  22720. This may be less than the height of this Viewport if there's a horizontal scrollbar
  22721. or if the child component is itself smaller.
  22722. */
  22723. int getViewHeight() const throw() { return lastVH; }
  22724. /** Returns the width available within this component for the contents.
  22725. This will be the width of the viewport component minus the width of a
  22726. vertical scrollbar (if visible).
  22727. */
  22728. int getMaximumVisibleWidth() const throw();
  22729. /** Returns the height available within this component for the contents.
  22730. This will be the height of the viewport component minus the space taken up
  22731. by a horizontal scrollbar (if visible).
  22732. */
  22733. int getMaximumVisibleHeight() const throw();
  22734. /** Callback method that is called when the visible area changes.
  22735. This will be called when the visible area is moved either be scrolling or
  22736. by calls to setViewPosition(), etc.
  22737. */
  22738. virtual void visibleAreaChanged (int visibleX, int visibleY,
  22739. int visibleW, int visibleH);
  22740. /** Turns scrollbars on or off.
  22741. If set to false, the scrollbars won't ever appear. When true (the default)
  22742. they will appear only when needed.
  22743. */
  22744. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  22745. const bool showHorizontalScrollbarIfNeeded);
  22746. /** True if the vertical scrollbar is enabled.
  22747. @see setScrollBarsShown
  22748. */
  22749. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  22750. /** True if the horizontal scrollbar is enabled.
  22751. @see setScrollBarsShown
  22752. */
  22753. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  22754. /** Changes the width of the scrollbars.
  22755. If this isn't specified, the default width from the LookAndFeel class will be used.
  22756. @see LookAndFeel::getDefaultScrollbarWidth
  22757. */
  22758. void setScrollBarThickness (const int thickness);
  22759. /** Returns the thickness of the scrollbars.
  22760. @see setScrollBarThickness
  22761. */
  22762. int getScrollBarThickness() const throw();
  22763. /** Changes the distance that a single-step click on a scrollbar button
  22764. will move the viewport.
  22765. */
  22766. void setSingleStepSizes (const int stepX, const int stepY);
  22767. /** Shows or hides the buttons on any scrollbars that are used.
  22768. @see ScrollBar::setButtonVisibility
  22769. */
  22770. void setScrollBarButtonVisibility (const bool buttonsVisible);
  22771. /** Returns a pointer to the scrollbar component being used.
  22772. Handy if you need to customise the bar somehow.
  22773. */
  22774. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  22775. /** Returns a pointer to the scrollbar component being used.
  22776. Handy if you need to customise the bar somehow.
  22777. */
  22778. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  22779. juce_UseDebuggingNewOperator
  22780. /** @internal */
  22781. void resized();
  22782. /** @internal */
  22783. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  22784. /** @internal */
  22785. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22786. /** @internal */
  22787. bool keyPressed (const KeyPress& key);
  22788. /** @internal */
  22789. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  22790. /** @internal */
  22791. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22792. private:
  22793. Component* contentComp;
  22794. int lastVX, lastVY, lastVW, lastVH;
  22795. int scrollBarThickness;
  22796. int singleStepX, singleStepY;
  22797. bool showHScrollbar, showVScrollbar;
  22798. Component* contentHolder;
  22799. ScrollBar* verticalScrollBar;
  22800. ScrollBar* horizontalScrollBar;
  22801. void updateVisibleRegion();
  22802. Viewport (const Viewport&);
  22803. const Viewport& operator= (const Viewport&);
  22804. };
  22805. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  22806. /********* End of inlined file: juce_Viewport.h *********/
  22807. /**
  22808. A panel that holds a list of PropertyComponent objects.
  22809. This panel displays a list of PropertyComponents, and allows them to be organised
  22810. into collapsible sections.
  22811. To use, simply create one of these and add your properties to it with addProperties()
  22812. or addSection().
  22813. @see PropertyComponent
  22814. */
  22815. class JUCE_API PropertyPanel : public Component
  22816. {
  22817. public:
  22818. /** Creates an empty property panel. */
  22819. PropertyPanel();
  22820. /** Destructor. */
  22821. ~PropertyPanel();
  22822. /** Deletes all property components from the panel.
  22823. */
  22824. void clear();
  22825. /** Adds a set of properties to the panel.
  22826. The components in the list will be owned by this object and will be automatically
  22827. deleted later on when no longer needed.
  22828. These properties are added without them being inside a named section. If you
  22829. want them to be kept together in a collapsible section, use addSection() instead.
  22830. */
  22831. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  22832. /** Adds a set of properties to the panel.
  22833. These properties are added at the bottom of the list, under a section heading with
  22834. a plus/minus button that allows it to be opened and closed.
  22835. The components in the list will be owned by this object and will be automatically
  22836. deleted later on when no longer needed.
  22837. To add properies without them being in a section, use addProperties().
  22838. */
  22839. void addSection (const String& sectionTitle,
  22840. const Array <PropertyComponent*>& newPropertyComponents,
  22841. const bool shouldSectionInitiallyBeOpen = true);
  22842. /** Calls the refresh() method of all PropertyComponents in the panel */
  22843. void refreshAll() const;
  22844. /** Returns a list of all the names of sections in the panel.
  22845. These are the sections that have been added with addSection().
  22846. */
  22847. const StringArray getSectionNames() const;
  22848. /** Returns true if the section at this index is currently open.
  22849. The index is from 0 up to the number of items returned by getSectionNames().
  22850. */
  22851. bool isSectionOpen (const int sectionIndex) const;
  22852. /** Opens or closes one of the sections.
  22853. The index is from 0 up to the number of items returned by getSectionNames().
  22854. */
  22855. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  22856. /** Enables or disables one of the sections.
  22857. The index is from 0 up to the number of items returned by getSectionNames().
  22858. */
  22859. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  22860. /** Saves the current state of open/closed sections so it can be restored later.
  22861. The caller is responsible for deleting the object that is returned.
  22862. To restore this state, use restoreOpennessState().
  22863. @see restoreOpennessState
  22864. */
  22865. XmlElement* getOpennessState() const;
  22866. /** Restores a previously saved arrangement of open/closed sections.
  22867. This will try to restore a snapshot of the panel's state that was created by
  22868. the getOpennessState() method. If any of the sections named in the original
  22869. XML aren't present, they will be ignored.
  22870. @see getOpennessState
  22871. */
  22872. void restoreOpennessState (const XmlElement& newState);
  22873. /** Sets a message to be displayed when there are no properties in the panel.
  22874. The default message is "nothing selected".
  22875. */
  22876. void setMessageWhenEmpty (const String& newMessage);
  22877. /** Returns the message that is displayed when there are no properties.
  22878. @see setMessageWhenEmpty
  22879. */
  22880. const String& getMessageWhenEmpty() const throw();
  22881. /** @internal */
  22882. void paint (Graphics& g);
  22883. /** @internal */
  22884. void resized();
  22885. juce_UseDebuggingNewOperator
  22886. private:
  22887. Viewport* viewport;
  22888. Component* propertyHolderComponent;
  22889. String messageWhenEmpty;
  22890. void updatePropHolderLayout() const;
  22891. void updatePropHolderLayout (const int width) const;
  22892. };
  22893. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  22894. /********* End of inlined file: juce_PropertyPanel.h *********/
  22895. /**
  22896. A type of UI component that displays the parameters of an AudioProcessor as
  22897. a simple list of sliders.
  22898. This can be used for showing an editor for a processor that doesn't supply
  22899. its own custom editor.
  22900. @see AudioProcessor
  22901. */
  22902. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  22903. {
  22904. public:
  22905. GenericAudioProcessorEditor (AudioProcessor* const owner);
  22906. ~GenericAudioProcessorEditor();
  22907. void paint (Graphics& g);
  22908. void resized();
  22909. juce_UseDebuggingNewOperator
  22910. private:
  22911. PropertyPanel* panel;
  22912. };
  22913. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22914. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22915. #endif
  22916. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22917. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  22918. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22919. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22920. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  22921. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22922. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22923. /********* Start of inlined file: juce_AudioSource.h *********/
  22924. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22925. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  22926. /**
  22927. Used by AudioSource::getNextAudioBlock().
  22928. */
  22929. struct JUCE_API AudioSourceChannelInfo
  22930. {
  22931. /** The destination buffer to fill with audio data.
  22932. When the AudioSource::getNextAudioBlock() method is called, the active section
  22933. of this buffer should be filled with whatever output the source produces.
  22934. Only the samples specified by the startSample and numSamples members of this structure
  22935. should be affected by the call.
  22936. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22937. method can be treated as the input if the source is performing some kind of filter operation,
  22938. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22939. a handy way of doing this.
  22940. The number of channels in the buffer could be anything, so the AudioSource
  22941. must cope with this in whatever way is appropriate for its function.
  22942. */
  22943. AudioSampleBuffer* buffer;
  22944. /** The first sample in the buffer from which the callback is expected
  22945. to write data. */
  22946. int startSample;
  22947. /** The number of samples in the buffer which the callback is expected to
  22948. fill with data. */
  22949. int numSamples;
  22950. /** Convenient method to clear the buffer if the source is not producing any data. */
  22951. void clearActiveBufferRegion() const
  22952. {
  22953. if (buffer != 0)
  22954. buffer->clear (startSample, numSamples);
  22955. }
  22956. };
  22957. /**
  22958. Base class for objects that can produce a continuous stream of audio.
  22959. @see AudioFormatReaderSource, ResamplingAudioSource
  22960. */
  22961. class JUCE_API AudioSource
  22962. {
  22963. protected:
  22964. /** Creates an AudioSource. */
  22965. AudioSource() throw() {}
  22966. public:
  22967. /** Destructor. */
  22968. virtual ~AudioSource() {}
  22969. /** Tells the source to prepare for playing.
  22970. The source can use this opportunity to initialise anything it needs to.
  22971. Note that this method could be called more than once in succession without
  22972. a matching call to releaseResources(), so make sure your code is robust and
  22973. can handle that kind of situation.
  22974. @param samplesPerBlockExpected the number of samples that the source
  22975. will be expected to supply each time its
  22976. getNextAudioBlock() method is called. This
  22977. number may vary slightly, because it will be dependent
  22978. on audio hardware callbacks, and these aren't
  22979. guaranteed to always use a constant block size, so
  22980. the source should be able to cope with small variations.
  22981. @param sampleRate the sample rate that the output will be used at - this
  22982. is needed by sources such as tone generators.
  22983. @see releaseResources, getNextAudioBlock
  22984. */
  22985. virtual void prepareToPlay (int samplesPerBlockExpected,
  22986. double sampleRate) = 0;
  22987. /** Allows the source to release anything it no longer needs after playback has stopped.
  22988. This will be called when the source is no longer going to have its getNextAudioBlock()
  22989. method called, so it should release any spare memory, etc. that it might have
  22990. allocated during the prepareToPlay() call.
  22991. Note that there's no guarantee that prepareToPlay() will actually have been called before
  22992. releaseResources(), and it may be called more than once in succession, so make sure your
  22993. code is robust and doesn't make any assumptions about when it will be called.
  22994. @see prepareToPlay, getNextAudioBlock
  22995. */
  22996. virtual void releaseResources() = 0;
  22997. /** Called repeatedly to fetch subsequent blocks of audio data.
  22998. After calling the prepareToPlay() method, this callback will be made each
  22999. time the audio playback hardware (or whatever other destination the audio
  23000. data is going to) needs another block of data.
  23001. It will generally be called on a high-priority system thread, or possibly even
  23002. an interrupt, so be careful not to do too much work here, as that will cause
  23003. audio glitches!
  23004. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23005. */
  23006. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23007. };
  23008. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23009. /********* End of inlined file: juce_AudioSource.h *********/
  23010. /**
  23011. A type of AudioSource which can be repositioned.
  23012. The basic AudioSource just streams continuously with no idea of a current
  23013. time or length, so the PositionableAudioSource is used for a finite stream
  23014. that has a current read position.
  23015. @see AudioSource, AudioTransportSource
  23016. */
  23017. class JUCE_API PositionableAudioSource : public AudioSource
  23018. {
  23019. protected:
  23020. /** Creates the PositionableAudioSource. */
  23021. PositionableAudioSource() throw() {}
  23022. public:
  23023. /** Destructor */
  23024. ~PositionableAudioSource() {}
  23025. /** Tells the stream to move to a new position.
  23026. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23027. should return samples from this position.
  23028. Note that this may be called on a different thread to getNextAudioBlock(),
  23029. so the subclass should make sure it's synchronised.
  23030. */
  23031. virtual void setNextReadPosition (int newPosition) = 0;
  23032. /** Returns the position from which the next block will be returned.
  23033. @see setNextReadPosition
  23034. */
  23035. virtual int getNextReadPosition() const = 0;
  23036. /** Returns the total length of the stream (in samples). */
  23037. virtual int getTotalLength() const = 0;
  23038. /** Returns true if this source is actually playing in a loop. */
  23039. virtual bool isLooping() const = 0;
  23040. };
  23041. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23042. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23043. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23044. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23045. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23046. class AudioFormat;
  23047. /**
  23048. Reads samples from an audio file stream.
  23049. A subclass that reads a specific type of audio format will be created by
  23050. an AudioFormat object.
  23051. @see AudioFormat, AudioFormatWriter
  23052. */
  23053. class JUCE_API AudioFormatReader
  23054. {
  23055. protected:
  23056. /** Creates an AudioFormatReader object.
  23057. @param sourceStream the stream to read from - this will be deleted
  23058. by this object when it is no longer needed. (Some
  23059. specialised readers might not use this parameter and
  23060. can leave it as 0).
  23061. @param formatName the description that will be returned by the getFormatName()
  23062. method
  23063. */
  23064. AudioFormatReader (InputStream* const sourceStream,
  23065. const String& formatName);
  23066. public:
  23067. /** Destructor. */
  23068. virtual ~AudioFormatReader();
  23069. /** Returns a description of what type of format this is.
  23070. E.g. "AIFF"
  23071. */
  23072. const String getFormatName() const throw() { return formatName; }
  23073. /** Reads samples from the stream.
  23074. @param destSamples an array of buffers into which the sample data for each
  23075. channel will be written.
  23076. If the format is fixed-point, each channel will be written
  23077. as an array of 32-bit signed integers using the full
  23078. range -0x80000000 to 0x7fffffff, regardless of the source's
  23079. bit-depth. If it is a floating-point format, you should cast
  23080. the resulting array to a (float**) to get the values (in the
  23081. range -1.0 to 1.0 or beyond)
  23082. If the format is stereo, then destSamples[0] is the left channel
  23083. data, and destSamples[1] is the right channel.
  23084. The array passed in should be zero-terminated, and it's ok to
  23085. pass in an array with a different number of channels than
  23086. the number in the stream, so if you pass in an array with only
  23087. one channel and the stream is stereo, the reader will
  23088. put a merged sum of the stereo channels into the single
  23089. destination channel.
  23090. @param startSample the offset into the audio stream from which the samples
  23091. should be read, as a number of samples from the start of the
  23092. stream. It's ok for this to be beyond the start or end of the
  23093. available data - any samples that can't be read will be padded
  23094. with zeros.
  23095. @param numSamples the number of samples to read. If this is greater than the
  23096. number of samples available, the result will be padded with
  23097. zeros
  23098. @returns true if the operation succeeded, false if there was an error. Note
  23099. that reading sections of data beyond the extent of the stream isn't an
  23100. error - the reader should just return zeros for these regions
  23101. @see readMaxLevels
  23102. */
  23103. virtual bool read (int** destSamples,
  23104. int64 startSample,
  23105. int numSamples) = 0;
  23106. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23107. This will read a block of samples from the stream, and measure the
  23108. highest and lowest sample levels from the channels in that section, returning
  23109. these as normalised floating-point levels.
  23110. @param startSample the offset into the audio stream to start reading from. It's
  23111. ok for this to be beyond the start or end of the stream.
  23112. @param numSamples how many samples to read
  23113. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23114. @param highestLeft on return, this is the highest absolute sample from the left channel
  23115. @param lowestRight on return, this is the lowest absolute sample from the right
  23116. channel (if there is one)
  23117. @param highestRight on return, this is the highest absolute sample from the right
  23118. channel (if there is one)
  23119. @see read
  23120. */
  23121. virtual void readMaxLevels (int64 startSample,
  23122. int64 numSamples,
  23123. float& lowestLeft,
  23124. float& highestLeft,
  23125. float& lowestRight,
  23126. float& highestRight);
  23127. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23128. This will read from the source, either forwards or backwards between two sample
  23129. positions, until it finds a sample whose magnitude lies between two specified levels.
  23130. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23131. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23132. points when you're searching for a continuous range of samples
  23133. @param startSample the first sample to look at
  23134. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23135. the search will go backwards
  23136. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23137. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23138. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23139. of this many consecutive samples, all of which lie
  23140. within the target range. When it finds such a sequence,
  23141. it returns the position of the first in-range sample
  23142. it found (i.e. the earliest one if scanning forwards, the
  23143. latest one if scanning backwards)
  23144. */
  23145. int64 searchForLevel (int64 startSample,
  23146. int64 numSamplesToSearch,
  23147. const double magnitudeRangeMinimum,
  23148. const double magnitudeRangeMaximum,
  23149. const int minimumConsecutiveSamples);
  23150. /** The sample-rate of the stream. */
  23151. double sampleRate;
  23152. /** The number of bits per sample, e.g. 16, 24, 32. */
  23153. unsigned int bitsPerSample;
  23154. /** The total number of samples in the audio stream. */
  23155. int64 lengthInSamples;
  23156. /** The total number of channels in the audio stream. */
  23157. unsigned int numChannels;
  23158. /** Indicates whether the data is floating-point or fixed. */
  23159. bool usesFloatingPointData;
  23160. /** A set of metadata values that the reader has pulled out of the stream.
  23161. Exactly what these values are depends on the format, so you can
  23162. check out the format implementation code to see what kind of stuff
  23163. they understand.
  23164. */
  23165. StringPairArray metadataValues;
  23166. /** The input stream, for use by subclasses. */
  23167. InputStream* input;
  23168. juce_UseDebuggingNewOperator
  23169. private:
  23170. String formatName;
  23171. AudioFormatReader (const AudioFormatReader&);
  23172. const AudioFormatReader& operator= (const AudioFormatReader&);
  23173. };
  23174. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23175. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23176. /**
  23177. A type of AudioSource that will read from an AudioFormatReader.
  23178. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23179. */
  23180. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23181. {
  23182. public:
  23183. /** Creates an AudioFormatReaderSource for a given reader.
  23184. @param sourceReader the reader to use as the data source
  23185. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23186. when this object is deleted; if false it will be
  23187. left up to the caller to manage its lifetime
  23188. */
  23189. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23190. const bool deleteReaderWhenThisIsDeleted);
  23191. /** Destructor. */
  23192. ~AudioFormatReaderSource();
  23193. /** Toggles loop-mode.
  23194. If set to true, it will continuously loop the input source. If false,
  23195. it will just emit silence after the source has finished.
  23196. @see isLooping
  23197. */
  23198. void setLooping (const bool shouldLoop) throw();
  23199. /** Returns whether loop-mode is turned on or not. */
  23200. bool isLooping() const { return looping; }
  23201. /** Returns the reader that's being used. */
  23202. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23203. /** Implementation of the AudioSource method. */
  23204. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23205. /** Implementation of the AudioSource method. */
  23206. void releaseResources();
  23207. /** Implementation of the AudioSource method. */
  23208. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23209. /** Implements the PositionableAudioSource method. */
  23210. void setNextReadPosition (int newPosition);
  23211. /** Implements the PositionableAudioSource method. */
  23212. int getNextReadPosition() const;
  23213. /** Implements the PositionableAudioSource method. */
  23214. int getTotalLength() const;
  23215. juce_UseDebuggingNewOperator
  23216. private:
  23217. AudioFormatReader* reader;
  23218. bool deleteReader;
  23219. int volatile nextPlayPos;
  23220. bool volatile looping;
  23221. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23222. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23223. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23224. };
  23225. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23226. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23227. #endif
  23228. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23229. #endif
  23230. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23231. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23232. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23233. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23234. /**
  23235. Wrapper class to continuously stream audio from an audio source to an
  23236. AudioIODevice.
  23237. This object acts as an AudioIODeviceCallback, so can be attached to an
  23238. output device, and will stream audio from an AudioSource.
  23239. */
  23240. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23241. {
  23242. public:
  23243. /** Creates an empty AudioSourcePlayer. */
  23244. AudioSourcePlayer();
  23245. /** Destructor.
  23246. Make sure this object isn't still being used by an AudioIODevice before
  23247. deleting it!
  23248. */
  23249. virtual ~AudioSourcePlayer();
  23250. /** Changes the current audio source to play from.
  23251. If the source passed in is already being used, this method will do nothing.
  23252. If the source is not null, its prepareToPlay() method will be called
  23253. before it starts being used for playback.
  23254. If there's another source currently playing, its releaseResources() method
  23255. will be called after it has been swapped for the new one.
  23256. @param newSource the new source to use - this will NOT be deleted
  23257. by this object when no longer needed, so it's the
  23258. caller's responsibility to manage it.
  23259. */
  23260. void setSource (AudioSource* newSource);
  23261. /** Returns the source that's playing.
  23262. May return 0 if there's no source.
  23263. */
  23264. AudioSource* getCurrentSource() const throw() { return source; }
  23265. /** Sets a gain to apply to the audio data. */
  23266. void setGain (const float newGain) throw();
  23267. /** Implementation of the AudioIODeviceCallback method. */
  23268. void audioDeviceIOCallback (const float** inputChannelData,
  23269. int totalNumInputChannels,
  23270. float** outputChannelData,
  23271. int totalNumOutputChannels,
  23272. int numSamples);
  23273. /** Implementation of the AudioIODeviceCallback method. */
  23274. void audioDeviceAboutToStart (AudioIODevice* device);
  23275. /** Implementation of the AudioIODeviceCallback method. */
  23276. void audioDeviceStopped();
  23277. juce_UseDebuggingNewOperator
  23278. private:
  23279. CriticalSection readLock;
  23280. AudioSource* source;
  23281. double sampleRate;
  23282. int bufferSize;
  23283. float* channels [128];
  23284. float* outputChans [128];
  23285. const float* inputChans [128];
  23286. AudioSampleBuffer tempBuffer;
  23287. float lastGain, gain;
  23288. AudioSourcePlayer (const AudioSourcePlayer&);
  23289. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23290. };
  23291. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23292. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23293. #endif
  23294. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23295. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23296. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23297. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23298. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23299. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23300. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23301. /**
  23302. An AudioSource which takes another source as input, and buffers it using a thread.
  23303. Create this as a wrapper around another thread, and it will read-ahead with
  23304. a background thread to smooth out playback. You can either create one of these
  23305. directly, or use it indirectly using an AudioTransportSource.
  23306. @see PositionableAudioSource, AudioTransportSource
  23307. */
  23308. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23309. {
  23310. public:
  23311. /** Creates a BufferingAudioSource.
  23312. @param source the input source to read from
  23313. @param deleteSourceWhenDeleted if true, then the input source object will
  23314. be deleted when this object is deleted
  23315. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23316. */
  23317. BufferingAudioSource (PositionableAudioSource* source,
  23318. const bool deleteSourceWhenDeleted,
  23319. int numberOfSamplesToBuffer);
  23320. /** Destructor.
  23321. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23322. flag was set in the constructor.
  23323. */
  23324. ~BufferingAudioSource();
  23325. /** Implementation of the AudioSource method. */
  23326. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23327. /** Implementation of the AudioSource method. */
  23328. void releaseResources();
  23329. /** Implementation of the AudioSource method. */
  23330. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23331. /** Implements the PositionableAudioSource method. */
  23332. void setNextReadPosition (int newPosition);
  23333. /** Implements the PositionableAudioSource method. */
  23334. int getNextReadPosition() const;
  23335. /** Implements the PositionableAudioSource method. */
  23336. int getTotalLength() const { return source->getTotalLength(); }
  23337. /** Implements the PositionableAudioSource method. */
  23338. bool isLooping() const { return source->isLooping(); }
  23339. juce_UseDebuggingNewOperator
  23340. private:
  23341. PositionableAudioSource* source;
  23342. bool deleteSourceWhenDeleted;
  23343. int numberOfSamplesToBuffer;
  23344. AudioSampleBuffer buffer;
  23345. CriticalSection bufferStartPosLock;
  23346. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23347. bool wasSourceLooping;
  23348. double volatile sampleRate;
  23349. friend class SharedBufferingAudioSourceThread;
  23350. bool readNextBufferChunk();
  23351. void readBufferSection (int start, int length, int bufferOffset);
  23352. BufferingAudioSource (const BufferingAudioSource&);
  23353. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23354. };
  23355. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23356. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23357. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23358. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23359. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23360. /**
  23361. A type of AudioSource that takes an input source and changes its sample rate.
  23362. @see AudioSource
  23363. */
  23364. class JUCE_API ResamplingAudioSource : public AudioSource
  23365. {
  23366. public:
  23367. /** Creates a ResamplingAudioSource for a given input source.
  23368. @param inputSource the input source to read from
  23369. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23370. this object is deleted
  23371. */
  23372. ResamplingAudioSource (AudioSource* const inputSource,
  23373. const bool deleteInputWhenDeleted);
  23374. /** Destructor. */
  23375. ~ResamplingAudioSource();
  23376. /** Changes the resampling ratio.
  23377. (This value can be changed at any time, even while the source is running).
  23378. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23379. values will speed it up; lower values will slow it
  23380. down. The ratio must be greater than 0
  23381. */
  23382. void setResamplingRatio (const double samplesInPerOutputSample);
  23383. /** Returns the current resampling ratio.
  23384. This is the value that was set by setResamplingRatio().
  23385. */
  23386. double getResamplingRatio() const throw() { return ratio; }
  23387. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23388. void releaseResources();
  23389. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23390. juce_UseDebuggingNewOperator
  23391. private:
  23392. AudioSource* const input;
  23393. const bool deleteInputWhenDeleted;
  23394. double ratio, lastRatio;
  23395. AudioSampleBuffer buffer;
  23396. int bufferPos, sampsInBuffer;
  23397. double subSampleOffset;
  23398. double coefficients[6];
  23399. CriticalSection ratioLock;
  23400. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23401. void createLowPass (const double proportionalRate);
  23402. struct FilterState
  23403. {
  23404. double x1, x2, y1, y2;
  23405. };
  23406. FilterState filterStates[2];
  23407. void resetFilters();
  23408. void applyFilter (float* samples, int num, FilterState& fs);
  23409. ResamplingAudioSource (const ResamplingAudioSource&);
  23410. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23411. };
  23412. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23413. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23414. /**
  23415. An AudioSource that takes a PositionableAudioSource and allows it to be
  23416. played, stopped, started, etc.
  23417. This can also be told use a buffer and background thread to read ahead, and
  23418. if can correct for different sample-rates.
  23419. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23420. to control playback of an audio file.
  23421. @see AudioSource, AudioSourcePlayer
  23422. */
  23423. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23424. public ChangeBroadcaster
  23425. {
  23426. public:
  23427. /** Creates an AudioTransportSource.
  23428. After creating one of these, use the setSource() method to select an input source.
  23429. */
  23430. AudioTransportSource();
  23431. /** Destructor. */
  23432. ~AudioTransportSource();
  23433. /** Sets the reader that is being used as the input source.
  23434. This will stop playback, reset the position to 0 and change to the new reader.
  23435. The source passed in will not be deleted by this object, so must be managed by
  23436. the caller.
  23437. @param newSource the new input source to use. This may be zero
  23438. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23439. is zero, no reading ahead will be done; if it's
  23440. greater than zero, a BufferingAudioSource will be used
  23441. to do the reading-ahead
  23442. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23443. rate of the source, and playback will be sample-rate
  23444. adjusted to maintain playback at the correct pitch. If
  23445. this is 0, no sample-rate adjustment will be performed
  23446. */
  23447. void setSource (PositionableAudioSource* const newSource,
  23448. int readAheadBufferSize = 0,
  23449. double sourceSampleRateToCorrectFor = 0.0);
  23450. /** Changes the current playback position in the source stream.
  23451. The next time the getNextAudioBlock() method is called, this
  23452. is the time from which it'll read data.
  23453. @see getPosition
  23454. */
  23455. void setPosition (double newPosition);
  23456. /** Returns the position that the next data block will be read from
  23457. This is a time in seconds.
  23458. */
  23459. double getCurrentPosition() const;
  23460. /** Returns true if the player has stopped because its input stream ran out of data.
  23461. */
  23462. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23463. /** Starts playing (if a source has been selected).
  23464. If it starts playing, this will send a message to any ChangeListeners
  23465. that are registered with this object.
  23466. */
  23467. void start();
  23468. /** Stops playing.
  23469. If it's actually playing, this will send a message to any ChangeListeners
  23470. that are registered with this object.
  23471. */
  23472. void stop();
  23473. /** Returns true if it's currently playing. */
  23474. bool isPlaying() const throw() { return playing; }
  23475. /** Changes the gain to apply to the output.
  23476. @param newGain a factor by which to multiply the outgoing samples,
  23477. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23478. */
  23479. void setGain (const float newGain) throw();
  23480. /** Returns the current gain setting.
  23481. @see setGain
  23482. */
  23483. float getGain() const throw() { return gain; }
  23484. /** Implementation of the AudioSource method. */
  23485. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23486. /** Implementation of the AudioSource method. */
  23487. void releaseResources();
  23488. /** Implementation of the AudioSource method. */
  23489. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23490. /** Implements the PositionableAudioSource method. */
  23491. void setNextReadPosition (int newPosition);
  23492. /** Implements the PositionableAudioSource method. */
  23493. int getNextReadPosition() const;
  23494. /** Implements the PositionableAudioSource method. */
  23495. int getTotalLength() const;
  23496. /** Implements the PositionableAudioSource method. */
  23497. bool isLooping() const;
  23498. juce_UseDebuggingNewOperator
  23499. private:
  23500. PositionableAudioSource* source;
  23501. ResamplingAudioSource* resamplerSource;
  23502. BufferingAudioSource* bufferingSource;
  23503. PositionableAudioSource* positionableSource;
  23504. AudioSource* masterSource;
  23505. CriticalSection callbackLock;
  23506. float volatile gain, lastGain;
  23507. bool volatile playing, stopped;
  23508. double sampleRate, sourceSampleRate;
  23509. int blockSize, readAheadBufferSize;
  23510. bool isPrepared, inputStreamEOF;
  23511. AudioTransportSource (const AudioTransportSource&);
  23512. const AudioTransportSource& operator= (const AudioTransportSource&);
  23513. };
  23514. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23515. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23516. #endif
  23517. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23518. #endif
  23519. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23520. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23521. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23522. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23523. /**
  23524. An AudioSource that takes the audio from another source, and re-maps its
  23525. input and output channels to a different arrangement.
  23526. You can use this to increase or decrease the number of channels that an
  23527. audio source uses, or to re-order those channels.
  23528. Call the reset() method before using it to set up a default mapping, and then
  23529. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23530. create an appropriate mapping, otherwise no channels will be connected and
  23531. it'll produce silence.
  23532. @see AudioSource
  23533. */
  23534. class ChannelRemappingAudioSource : public AudioSource
  23535. {
  23536. public:
  23537. /** Creates a remapping source that will pass on audio from the given input.
  23538. @param source the input source to use. Make sure that this doesn't
  23539. get deleted before the ChannelRemappingAudioSource object
  23540. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23541. when this object is deleted, if false, the caller is
  23542. responsible for its deletion
  23543. */
  23544. ChannelRemappingAudioSource (AudioSource* const source,
  23545. const bool deleteSourceWhenDeleted);
  23546. /** Destructor. */
  23547. ~ChannelRemappingAudioSource();
  23548. /** Specifies a number of channels that this audio source must produce from its
  23549. getNextAudioBlock() callback.
  23550. */
  23551. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23552. /** Clears any mapped channels.
  23553. After this, no channels are mapped, so this object will produce silence. Create
  23554. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23555. */
  23556. void clearAllMappings() throw();
  23557. /** Creates an input channel mapping.
  23558. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23559. data will be sent to destChannelIndex of our input source.
  23560. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23561. source specified when this object was created).
  23562. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23563. during our getNextAudioBlock() callback
  23564. */
  23565. void setInputChannelMapping (const int destChannelIndex,
  23566. const int sourceChannelIndex) throw();
  23567. /** Creates an output channel mapping.
  23568. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23569. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23570. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23571. (i.e. the source specified when this object was created).
  23572. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23573. during our getNextAudioBlock() callback
  23574. */
  23575. void setOutputChannelMapping (const int sourceChannelIndex,
  23576. const int destChannelIndex) throw();
  23577. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23578. our input audio source.
  23579. */
  23580. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23581. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23582. source will be sent to.
  23583. */
  23584. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23585. /** Returns an XML object to encapsulate the state of the mappings.
  23586. @see restoreFromXml
  23587. */
  23588. XmlElement* createXml() const throw();
  23589. /** Restores the mappings from an XML object created by createXML().
  23590. @see createXml
  23591. */
  23592. void restoreFromXml (const XmlElement& e) throw();
  23593. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23594. void releaseResources();
  23595. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23596. juce_UseDebuggingNewOperator
  23597. private:
  23598. int requiredNumberOfChannels;
  23599. Array <int> remappedInputs, remappedOutputs;
  23600. AudioSource* const source;
  23601. const bool deleteSourceWhenDeleted;
  23602. AudioSampleBuffer buffer;
  23603. AudioSourceChannelInfo remappedInfo;
  23604. CriticalSection lock;
  23605. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23606. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23607. };
  23608. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23609. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23610. #endif
  23611. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23612. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23613. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23614. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23615. /**
  23616. An AudioSource that performs an IIR filter on another source.
  23617. */
  23618. class JUCE_API IIRFilterAudioSource : public AudioSource
  23619. {
  23620. public:
  23621. /** Creates a IIRFilterAudioSource for a given input source.
  23622. @param inputSource the input source to read from
  23623. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23624. this object is deleted
  23625. */
  23626. IIRFilterAudioSource (AudioSource* const inputSource,
  23627. const bool deleteInputWhenDeleted);
  23628. /** Destructor. */
  23629. ~IIRFilterAudioSource();
  23630. /** Changes the filter to use the same parameters as the one being passed in.
  23631. */
  23632. void setFilterParameters (const IIRFilter& newSettings);
  23633. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23634. void releaseResources();
  23635. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23636. juce_UseDebuggingNewOperator
  23637. private:
  23638. AudioSource* const input;
  23639. const bool deleteInputWhenDeleted;
  23640. OwnedArray <IIRFilter> iirFilters;
  23641. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23642. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23643. };
  23644. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23645. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23646. #endif
  23647. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23648. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23649. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23650. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23651. /**
  23652. An AudioSource that mixes together the output of a set of other AudioSources.
  23653. Input sources can be added and removed while the mixer is running as long as their
  23654. prepareToPlay() and releaseResources() methods are called before and after adding
  23655. them to the mixer.
  23656. */
  23657. class JUCE_API MixerAudioSource : public AudioSource
  23658. {
  23659. public:
  23660. /** Creates a MixerAudioSource.
  23661. */
  23662. MixerAudioSource();
  23663. /** Destructor. */
  23664. ~MixerAudioSource();
  23665. /** Adds an input source to the mixer.
  23666. If the mixer is running you'll need to make sure that the input source
  23667. is ready to play by calling its prepareToPlay() method before adding it.
  23668. If the mixer is stopped, then its input sources will be automatically
  23669. prepared when the mixer's prepareToPlay() method is called.
  23670. @param newInput the source to add to the mixer
  23671. @param deleteWhenRemoved if true, then this source will be deleted when
  23672. the mixer is deleted or when removeAllInputs() is
  23673. called (unless the source is previously removed
  23674. with the removeInputSource method)
  23675. */
  23676. void addInputSource (AudioSource* newInput,
  23677. const bool deleteWhenRemoved);
  23678. /** Removes an input source.
  23679. If the mixer is running, this will remove the source but not call its
  23680. releaseResources() method, so the caller might want to do this manually.
  23681. @param input the source to remove
  23682. @param deleteSource whether to delete this source after it's been removed
  23683. */
  23684. void removeInputSource (AudioSource* input,
  23685. const bool deleteSource);
  23686. /** Removes all the input sources.
  23687. If the mixer is running, this will remove the sources but not call their
  23688. releaseResources() method, so the caller might want to do this manually.
  23689. Any sources which were added with the deleteWhenRemoved flag set will be
  23690. deleted by this method.
  23691. */
  23692. void removeAllInputs();
  23693. /** Implementation of the AudioSource method.
  23694. This will call prepareToPlay() on all its input sources.
  23695. */
  23696. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23697. /** Implementation of the AudioSource method.
  23698. This will call releaseResources() on all its input sources.
  23699. */
  23700. void releaseResources();
  23701. /** Implementation of the AudioSource method. */
  23702. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23703. juce_UseDebuggingNewOperator
  23704. private:
  23705. VoidArray inputs;
  23706. BitArray inputsToDelete;
  23707. CriticalSection lock;
  23708. AudioSampleBuffer tempBuffer;
  23709. double currentSampleRate;
  23710. int bufferSizeExpected;
  23711. MixerAudioSource (const MixerAudioSource&);
  23712. const MixerAudioSource& operator= (const MixerAudioSource&);
  23713. };
  23714. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23715. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23716. #endif
  23717. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23718. #endif
  23719. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23720. #endif
  23721. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23722. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23723. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23724. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23725. /**
  23726. A simple AudioSource that generates a sine wave.
  23727. */
  23728. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  23729. {
  23730. public:
  23731. /** Creates a ToneGeneratorAudioSource. */
  23732. ToneGeneratorAudioSource();
  23733. /** Destructor. */
  23734. ~ToneGeneratorAudioSource();
  23735. /** Sets the signal's amplitude. */
  23736. void setAmplitude (const float newAmplitude);
  23737. /** Sets the signal's frequency. */
  23738. void setFrequency (const double newFrequencyHz);
  23739. /** Implementation of the AudioSource method. */
  23740. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23741. /** Implementation of the AudioSource method. */
  23742. void releaseResources();
  23743. /** Implementation of the AudioSource method. */
  23744. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23745. juce_UseDebuggingNewOperator
  23746. private:
  23747. double frequency, sampleRate;
  23748. double currentPhase, phasePerSample;
  23749. float amplitude;
  23750. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  23751. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  23752. };
  23753. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23754. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23755. #endif
  23756. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23757. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  23758. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23759. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23760. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  23761. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23762. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23763. class AudioDeviceManager;
  23764. class Component;
  23765. /**
  23766. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  23767. To get a list of available audio driver types, use the createDeviceTypes()
  23768. method. Each of the objects returned can then be used to list the available
  23769. devices of that type. E.g.
  23770. @code
  23771. OwnedArray <AudioIODeviceType> types;
  23772. AudioIODeviceType::createDeviceTypes (types);
  23773. for (int i = 0; i < types.size(); ++i)
  23774. {
  23775. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  23776. types[i]->scanForDevices(); // This must be called before getting the list of devices
  23777. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  23778. for (int j = 0; j < deviceNames.size(); ++j)
  23779. {
  23780. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  23781. ...
  23782. }
  23783. }
  23784. @endcode
  23785. For an easier way of managing audio devices and their settings, have a look at the
  23786. AudioDeviceManager class.
  23787. @see AudioIODevice, AudioDeviceManager
  23788. */
  23789. class JUCE_API AudioIODeviceType
  23790. {
  23791. public:
  23792. /** Returns the name of this type of driver that this object manages.
  23793. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  23794. */
  23795. const String& getTypeName() const throw() { return typeName; }
  23796. /** Refreshes the object's cached list of known devices.
  23797. This must be called at least once before calling getDeviceNames() or any of
  23798. the other device creation methods.
  23799. */
  23800. virtual void scanForDevices() = 0;
  23801. /** Returns the list of available devices of this type.
  23802. The scanForDevices() method must have been called to create this list.
  23803. @param wantInputNames only really used by DirectSound where devices are split up
  23804. into inputs and outputs, this indicates whether to use
  23805. the input or output name to refer to a pair of devices.
  23806. */
  23807. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  23808. /** Returns the name of the default device.
  23809. This will be one of the names from the getDeviceNames() list.
  23810. @param forInput if true, this means that a default input device should be
  23811. returned; if false, it should return the default output
  23812. */
  23813. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  23814. /** Returns the index of a given device in the list of device names.
  23815. If asInput is true, it shows the index in the inputs list, otherwise it
  23816. looks for it in the outputs list.
  23817. */
  23818. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  23819. /** Returns true if two different devices can be used for the input and output.
  23820. */
  23821. virtual bool hasSeparateInputsAndOutputs() const = 0;
  23822. /** Creates one of the devices of this type.
  23823. The deviceName must be one of the strings returned by getDeviceNames(), and
  23824. scanForDevices() must have been called before this method is used.
  23825. */
  23826. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  23827. const String& inputDeviceName) = 0;
  23828. struct DeviceSetupDetails
  23829. {
  23830. AudioDeviceManager* manager;
  23831. int minNumInputChannels, maxNumInputChannels;
  23832. int minNumOutputChannels, maxNumOutputChannels;
  23833. bool useStereoPairs;
  23834. };
  23835. /** Destructor. */
  23836. virtual ~AudioIODeviceType();
  23837. protected:
  23838. AudioIODeviceType (const tchar* const typeName);
  23839. private:
  23840. String typeName;
  23841. AudioIODeviceType (const AudioIODeviceType&);
  23842. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  23843. };
  23844. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23845. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  23846. /********* Start of inlined file: juce_MidiOutput.h *********/
  23847. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  23848. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  23849. /**
  23850. Represents a midi output device.
  23851. To create one of these, use the static getDevices() method to find out what
  23852. outputs are available, then use the openDevice() method to try to open one.
  23853. @see MidiInput
  23854. */
  23855. class JUCE_API MidiOutput : private Thread
  23856. {
  23857. public:
  23858. /** Returns a list of the available midi output devices.
  23859. You can open one of the devices by passing its index into the
  23860. openDevice() method.
  23861. @see getDefaultDeviceIndex, openDevice
  23862. */
  23863. static const StringArray getDevices();
  23864. /** Returns the index of the default midi output device to use.
  23865. This refers to the index in the list returned by getDevices().
  23866. */
  23867. static int getDefaultDeviceIndex();
  23868. /** Tries to open one of the midi output devices.
  23869. This will return a MidiOutput object if it manages to open it. You can then
  23870. send messages to this device, and delete it when no longer needed.
  23871. If the device can't be opened, this will return a null pointer.
  23872. @param deviceIndex the index of a device from the list returned by getDevices()
  23873. @see getDevices
  23874. */
  23875. static MidiOutput* openDevice (int deviceIndex);
  23876. #if JUCE_LINUX || DOXYGEN
  23877. /** LINUX ONLY - This will try to create a new midi output device.
  23878. This will attempt to create a new midi output device that other apps can connect
  23879. to and use as their midi input.
  23880. Returns 0 if a device can't be created.
  23881. @param deviceName the name to use for the new device
  23882. */
  23883. static MidiOutput* createNewDevice (const String& deviceName);
  23884. #endif
  23885. /** Destructor. */
  23886. ~MidiOutput();
  23887. /** Makes this device output a midi message.
  23888. @see MidiMessage
  23889. */
  23890. void sendMessageNow (const MidiMessage& message);
  23891. /** Sends a midi reset to the device. */
  23892. void reset();
  23893. /** Returns the current volume setting for this device. */
  23894. bool getVolume (float& leftVol,
  23895. float& rightVol);
  23896. /** Changes the overall volume for this device. */
  23897. void setVolume (float leftVol,
  23898. float rightVol);
  23899. /** This lets you supply a block of messages that will be sent out at some point
  23900. in the future.
  23901. The MidiOutput class has an internal thread that can send out timestamped
  23902. messages - this appends a set of messages to its internal buffer, ready for
  23903. sending.
  23904. This will only work if you've already started the thread with startBackgroundThread().
  23905. A time is supplied, at which the block of messages should be sent. This time uses
  23906. the same time base as Time::getMillisecondCounter(), and must be in the future.
  23907. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  23908. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  23909. samplesPerSecondForBuffer value is needed to convert this sample position to a
  23910. real time.
  23911. */
  23912. void sendBlockOfMessages (const MidiBuffer& buffer,
  23913. const double millisecondCounterToStartAt,
  23914. double samplesPerSecondForBuffer) throw();
  23915. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  23916. */
  23917. void clearAllPendingMessages() throw();
  23918. /** Starts up a background thread so that the device can send blocks of data.
  23919. Call this to get the device ready, before using sendBlockOfMessages().
  23920. */
  23921. void startBackgroundThread() throw();
  23922. /** Stops the background thread, and clears any pending midi events.
  23923. @see startBackgroundThread
  23924. */
  23925. void stopBackgroundThread() throw();
  23926. juce_UseDebuggingNewOperator
  23927. private:
  23928. void* internal;
  23929. struct PendingMessage
  23930. {
  23931. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  23932. MidiMessage message;
  23933. PendingMessage* next;
  23934. juce_UseDebuggingNewOperator
  23935. };
  23936. CriticalSection lock;
  23937. PendingMessage* firstMessage;
  23938. MidiOutput() throw();
  23939. MidiOutput (const MidiOutput&);
  23940. void run();
  23941. };
  23942. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  23943. /********* End of inlined file: juce_MidiOutput.h *********/
  23944. /********* Start of inlined file: juce_ComboBox.h *********/
  23945. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  23946. #define __JUCE_COMBOBOX_JUCEHEADER__
  23947. /********* Start of inlined file: juce_Label.h *********/
  23948. #ifndef __JUCE_LABEL_JUCEHEADER__
  23949. #define __JUCE_LABEL_JUCEHEADER__
  23950. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  23951. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23952. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23953. /**
  23954. Object for monitoring a component, and later testing whether it's still valid.
  23955. Slightly obscure, this one, but it's used internally for making sure that
  23956. after some callbacks, a component hasn't been deleted. It's more reliable than
  23957. just using isValidComponent(), which can provide false-positives if a new
  23958. component is created at the same memory location as an old one.
  23959. */
  23960. class JUCE_API ComponentDeletionWatcher
  23961. {
  23962. public:
  23963. /** Creates a watcher for a given component.
  23964. The component must be valid at the time it's passed in.
  23965. */
  23966. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  23967. /** Destructor. */
  23968. ~ComponentDeletionWatcher() throw();
  23969. /** Returns true if the component has been deleted since the time that this
  23970. object was created.
  23971. */
  23972. bool hasBeenDeleted() const throw();
  23973. /** Returns the component that's being watched, or null if it has been deleted. */
  23974. const Component* getComponent() const throw();
  23975. juce_UseDebuggingNewOperator
  23976. private:
  23977. const Component* const componentToWatch;
  23978. const uint32 componentUID;
  23979. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  23980. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  23981. };
  23982. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23983. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  23984. /********* Start of inlined file: juce_TextEditor.h *********/
  23985. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  23986. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  23987. /********* Start of inlined file: juce_UndoManager.h *********/
  23988. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  23989. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  23990. /********* Start of inlined file: juce_UndoableAction.h *********/
  23991. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  23992. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  23993. /**
  23994. Used by the UndoManager class to store an action which can be done
  23995. and undone.
  23996. @see UndoManager
  23997. */
  23998. class JUCE_API UndoableAction
  23999. {
  24000. protected:
  24001. /** Creates an action. */
  24002. UndoableAction() throw() {}
  24003. public:
  24004. /** Destructor. */
  24005. virtual ~UndoableAction() {}
  24006. /** Overridden by a subclass to perform the action.
  24007. This method is called by the UndoManager, and shouldn't be used directly by
  24008. applications.
  24009. Be careful not to make any calls in a perform() method that could call
  24010. recursively back into the UndoManager::perform() method
  24011. @returns true if the action could be performed.
  24012. @see UndoManager::perform
  24013. */
  24014. virtual bool perform() = 0;
  24015. /** Overridden by a subclass to undo the action.
  24016. This method is called by the UndoManager, and shouldn't be used directly by
  24017. applications.
  24018. Be careful not to make any calls in an undo() method that could call
  24019. recursively back into the UndoManager::perform() method
  24020. @returns true if the action could be undone without any errors.
  24021. @see UndoManager::perform
  24022. */
  24023. virtual bool undo() = 0;
  24024. /** Returns a value to indicate how much memory this object takes up.
  24025. Because the UndoManager keeps a list of UndoableActions, this is used
  24026. to work out how much space each one will take up, so that the UndoManager
  24027. can work out how many to keep.
  24028. The default value returned here is 10 - units are arbitrary and
  24029. don't have to be accurate.
  24030. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24031. UndoManager::setMaxNumberOfStoredUnits
  24032. */
  24033. virtual int getSizeInUnits() { return 10; }
  24034. };
  24035. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24036. /********* End of inlined file: juce_UndoableAction.h *********/
  24037. /**
  24038. Manages a list of undo/redo commands.
  24039. An UndoManager object keeps a list of past actions and can use these actions
  24040. to move backwards and forwards through an undo history.
  24041. To use it, create subclasses of UndoableAction which perform all the
  24042. actions you need, then when you need to actually perform an action, create one
  24043. and pass it to the UndoManager's perform() method.
  24044. The manager also uses the concept of 'transactions' to group the actions
  24045. together - all actions performed between calls to beginNewTransaction() are
  24046. grouped together and are all undone/redone as a group.
  24047. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24048. when actions are performed or undone.
  24049. @see UndoableAction
  24050. */
  24051. class JUCE_API UndoManager : public ChangeBroadcaster
  24052. {
  24053. public:
  24054. /** Creates an UndoManager.
  24055. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24056. to indicate how much storage it takes up
  24057. (UndoableAction::getSizeInUnits()), so this
  24058. lets you specify the maximum total number of
  24059. units that the undomanager is allowed to
  24060. keep in memory before letting the older actions
  24061. drop off the end of the list.
  24062. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24063. that will be kept, even if this involves exceeding
  24064. the amount of space specified in maxNumberOfUnitsToKeep
  24065. */
  24066. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24067. const int minimumTransactionsToKeep = 30);
  24068. /** Destructor. */
  24069. ~UndoManager();
  24070. /** Deletes all stored actions in the list. */
  24071. void clearUndoHistory();
  24072. /** Returns the current amount of space to use for storing UndoableAction objects.
  24073. @see setMaxNumberOfStoredUnits
  24074. */
  24075. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24076. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24077. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24078. to indicate how much storage it takes up
  24079. (UndoableAction::getSizeInUnits()), so this
  24080. lets you specify the maximum total number of
  24081. units that the undomanager is allowed to
  24082. keep in memory before letting the older actions
  24083. drop off the end of the list.
  24084. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24085. that will be kept, even if this involves exceeding
  24086. the amount of space specified in maxNumberOfUnitsToKeep
  24087. @see getNumberOfUnitsTakenUpByStoredCommands
  24088. */
  24089. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24090. const int minimumTransactionsToKeep);
  24091. /** Performs an action and adds it to the undo history list.
  24092. @param action the action to perform - this will be deleted by the UndoManager
  24093. when no longer needed
  24094. @param actionName if this string is non-empty, the current transaction will be
  24095. given this name; if it's empty, the current transaction name will
  24096. be left unchanged. See setCurrentTransactionName()
  24097. @returns true if the command succeeds - see UndoableAction::perform
  24098. @see beginNewTransaction
  24099. */
  24100. bool perform (UndoableAction* const action,
  24101. const String& actionName = String::empty);
  24102. /** Starts a new group of actions that together will be treated as a single transaction.
  24103. All actions that are passed to the perform() method between calls to this
  24104. method are grouped together and undone/redone together by a single call to
  24105. undo() or redo().
  24106. @param actionName a description of the transaction that is about to be
  24107. performed
  24108. */
  24109. void beginNewTransaction (const String& actionName = String::empty);
  24110. /** Changes the name stored for the current transaction.
  24111. Each transaction is given a name when the beginNewTransaction() method is
  24112. called, but this can be used to change that name without starting a new
  24113. transaction.
  24114. */
  24115. void setCurrentTransactionName (const String& newName);
  24116. /** Returns true if there's at least one action in the list to undo.
  24117. @see getUndoDescription, undo, canRedo
  24118. */
  24119. bool canUndo() const;
  24120. /** Returns the description of the transaction that would be next to get undone.
  24121. The description returned is the one that was passed into beginNewTransaction
  24122. before the set of actions was performed.
  24123. @see undo
  24124. */
  24125. const String getUndoDescription() const;
  24126. /** Tries to roll-back the last transaction.
  24127. @returns true if the transaction can be undone, and false if it fails, or
  24128. if there aren't any transactions to undo
  24129. */
  24130. bool undo();
  24131. /** Tries to roll-back any actions that were added to the current transaction.
  24132. This will perform an undo() only if there are some actions in the undo list
  24133. that were added after the last call to beginNewTransaction().
  24134. This is useful because it lets you call beginNewTransaction(), then
  24135. perform an operation which may or may not actually perform some actions, and
  24136. then call this method to get rid of any actions that might have been done
  24137. without it rolling back the previous transaction if nothing was actually
  24138. done.
  24139. @returns true if any actions were undone.
  24140. */
  24141. bool undoCurrentTransactionOnly();
  24142. /** Returns a list of the UndoableAction objects that have been performed during the
  24143. transaction that is currently open.
  24144. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24145. were to be called now.
  24146. The first item in the list is the earliest action performed.
  24147. */
  24148. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24149. /** Returns true if there's at least one action in the list to redo.
  24150. @see getRedoDescription, redo, canUndo
  24151. */
  24152. bool canRedo() const;
  24153. /** Returns the description of the transaction that would be next to get redone.
  24154. The description returned is the one that was passed into beginNewTransaction
  24155. before the set of actions was performed.
  24156. @see redo
  24157. */
  24158. const String getRedoDescription() const;
  24159. /** Tries to redo the last transaction that was undone.
  24160. @returns true if the transaction can be redone, and false if it fails, or
  24161. if there aren't any transactions to redo
  24162. */
  24163. bool redo();
  24164. juce_UseDebuggingNewOperator
  24165. private:
  24166. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24167. StringArray transactionNames;
  24168. String currentTransactionName;
  24169. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24170. bool newTransaction, reentrancyCheck;
  24171. // disallow copy constructor
  24172. UndoManager (const UndoManager&);
  24173. const UndoManager& operator= (const UndoManager&);
  24174. };
  24175. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24176. /********* End of inlined file: juce_UndoManager.h *********/
  24177. class TextEditor;
  24178. class TextHolderComponent;
  24179. /**
  24180. Receives callbacks from a TextEditor component when it changes.
  24181. @see TextEditor::addListener
  24182. */
  24183. class JUCE_API TextEditorListener
  24184. {
  24185. public:
  24186. /** Destructor. */
  24187. virtual ~TextEditorListener() {}
  24188. /** Called when the user changes the text in some way. */
  24189. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24190. /** Called when the user presses the return key. */
  24191. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24192. /** Called when the user presses the escape key. */
  24193. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24194. /** Called when the text editor loses focus. */
  24195. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24196. };
  24197. /**
  24198. A component containing text that can be edited.
  24199. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24200. fonts and colours.
  24201. @see TextEditorListener, Label
  24202. */
  24203. class JUCE_API TextEditor : public Component,
  24204. public SettableTooltipClient
  24205. {
  24206. public:
  24207. /** Creates a new, empty text editor.
  24208. @param componentName the name to pass to the component for it to use as its name
  24209. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24210. for all characters that are drawn on screen - e.g. to create
  24211. a password-style textbox containing circular blobs instead of text,
  24212. you could set this value to 0x25cf, which is the unicode character
  24213. for a black splodge (not all fonts include this, though), or 0x2022,
  24214. which is a bullet (probably the best choice for linux).
  24215. */
  24216. TextEditor (const String& componentName = String::empty,
  24217. const tchar passwordCharacter = 0);
  24218. /** Destructor. */
  24219. virtual ~TextEditor();
  24220. /** Puts the editor into either multi- or single-line mode.
  24221. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24222. editor.
  24223. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24224. on if you want a multi-line editor with line-breaks.
  24225. @see isMultiLine, setReturnKeyStartsNewLine
  24226. */
  24227. void setMultiLine (const bool shouldBeMultiLine,
  24228. const bool shouldWordWrap = true);
  24229. /** Returns true if the editor is in multi-line mode.
  24230. */
  24231. bool isMultiLine() const throw();
  24232. /** Changes the behaviour of the return key.
  24233. If set to true, the return key will insert a new-line into the text; if false
  24234. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24235. method. By default this is set to false, and when true it will only insert
  24236. new-lines when in multi-line mode (see setMultiLine()).
  24237. */
  24238. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24239. /** Returns the value set by setReturnKeyStartsNewLine().
  24240. See setReturnKeyStartsNewLine() for more info.
  24241. */
  24242. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24243. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24244. or whether it gets ignored.
  24245. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24246. between components.
  24247. */
  24248. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24249. /** Returns true if the tab key is being used for input.
  24250. @see setTabKeyUsedAsCharacter
  24251. */
  24252. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24253. /** Changes the editor to read-only mode.
  24254. By default, the text editor is not read-only. If you're making it read-only, you
  24255. might also want to call setCaretVisible (false) to get rid of the caret.
  24256. The text can still be highlighted and copied when in read-only mode.
  24257. @see isReadOnly, setCaretVisible
  24258. */
  24259. void setReadOnly (const bool shouldBeReadOnly);
  24260. /** Returns true if the editor is in read-only mode.
  24261. */
  24262. bool isReadOnly() const throw();
  24263. /** Makes the caret visible or invisible.
  24264. By default the caret is visible.
  24265. @see setCaretColour, setCaretPosition
  24266. */
  24267. void setCaretVisible (const bool shouldBeVisible) throw();
  24268. /** Returns true if the caret is enabled.
  24269. @see setCaretVisible
  24270. */
  24271. bool isCaretVisible() const throw() { return caretVisible; }
  24272. /** Enables/disables a vertical scrollbar.
  24273. (This only applies when in multi-line mode). When the text gets too long to fit
  24274. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24275. this is enabled, the scrollbar will be hidden unless it's needed.
  24276. By default the scrollbar is enabled.
  24277. */
  24278. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24279. /** Returns true if scrollbars are enabled.
  24280. @see setScrollbarsShown
  24281. */
  24282. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24283. /** Changes the password character used to disguise the text.
  24284. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24285. for all characters that are drawn on screen - e.g. to create
  24286. a password-style textbox containing circular blobs instead of text,
  24287. you could set this value to 0x25cf, which is the unicode character
  24288. for a black splodge (not all fonts include this, though), or 0x2022,
  24289. which is a bullet (probably the best choice for linux).
  24290. */
  24291. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24292. /** Returns the current password character.
  24293. @see setPasswordCharacter
  24294. l */
  24295. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24296. /** Allows a right-click menu to appear for the editor.
  24297. (This defaults to being enabled).
  24298. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24299. of options such as cut/copy/paste, undo/redo, etc.
  24300. */
  24301. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24302. /** Returns true if the right-click menu is enabled.
  24303. @see setPopupMenuEnabled
  24304. */
  24305. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24306. /** Returns true if a popup-menu is currently being displayed.
  24307. */
  24308. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24309. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24310. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24311. methods.
  24312. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24313. */
  24314. enum ColourIds
  24315. {
  24316. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24317. transparent if necessary. */
  24318. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24319. that because the editor can contain multiple colours, calling this
  24320. method won't change the colour of existing text - to do that, call
  24321. applyFontToAllText() after calling this method.*/
  24322. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24323. the text - this can be transparent if you don't want to show any
  24324. highlighting.*/
  24325. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24326. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24327. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24328. the edge of the component. */
  24329. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24330. the edge of the component when it has focus. */
  24331. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24332. around the edge of the editor. */
  24333. };
  24334. /** Sets the font to use for newly added text.
  24335. This will change the font that will be used next time any text is added or entered
  24336. into the editor. It won't change the font of any existing text - to do that, use
  24337. applyFontToAllText() instead.
  24338. @see applyFontToAllText
  24339. */
  24340. void setFont (const Font& newFont) throw();
  24341. /** Applies a font to all the text in the editor.
  24342. This will also set the current font to use for any new text that's added.
  24343. @see setFont
  24344. */
  24345. void applyFontToAllText (const Font& newFont);
  24346. /** Returns the font that's currently being used for new text.
  24347. @see setFont
  24348. */
  24349. const Font getFont() const throw();
  24350. /** If set to true, focusing on the editor will highlight all its text.
  24351. (Set to false by default).
  24352. This is useful for boxes where you expect the user to re-enter all the
  24353. text when they focus on the component, rather than editing what's already there.
  24354. */
  24355. void setSelectAllWhenFocused (const bool b) throw();
  24356. /** Sets limits on the characters that can be entered.
  24357. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24358. limit is set
  24359. @param allowedCharacters if this is non-empty, then only characters that occur in
  24360. this string are allowed to be entered into the editor.
  24361. */
  24362. void setInputRestrictions (const int maxTextLength,
  24363. const String& allowedCharacters = String::empty) throw();
  24364. /** When the text editor is empty, it can be set to display a message.
  24365. This is handy for things like telling the user what to type in the box - the
  24366. string is only displayed, it's not taken to actually be the contents of
  24367. the editor.
  24368. */
  24369. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24370. /** Changes the size of the scrollbars that are used.
  24371. Handy if you need smaller scrollbars for a small text box.
  24372. */
  24373. void setScrollBarThickness (const int newThicknessPixels);
  24374. /** Shows or hides the buttons on any scrollbars that are used.
  24375. @see ScrollBar::setButtonVisibility
  24376. */
  24377. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24378. /** Registers a listener to be told when things happen to the text.
  24379. @see removeListener
  24380. */
  24381. void addListener (TextEditorListener* const newListener) throw();
  24382. /** Deregisters a listener.
  24383. @see addListener
  24384. */
  24385. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24386. /** Returns the entire contents of the editor. */
  24387. const String getText() const throw();
  24388. /** Returns a section of the contents of the editor. */
  24389. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24390. /** Returns true if there are no characters in the editor.
  24391. This is more efficient than calling getText().isEmpty().
  24392. */
  24393. bool isEmpty() const throw();
  24394. /** Sets the entire content of the editor.
  24395. This will clear the editor and insert the given text (using the current text colour
  24396. and font). You can set the current text colour using
  24397. @code setColour (TextEditor::textColourId, ...);
  24398. @endcode
  24399. @param newText the text to add
  24400. @param sendTextChangeMessage if true, this will cause a change message to
  24401. be sent to all the listeners.
  24402. @see insertText
  24403. */
  24404. void setText (const String& newText,
  24405. const bool sendTextChangeMessage = true);
  24406. /** Inserts some text at the current cursor position.
  24407. If a section of the text is highlighted, it will be replaced by
  24408. this string, otherwise it will be inserted.
  24409. To delete a section of text, you can use setHighlightedRegion() to
  24410. highlight it, and call insertTextAtCursor (String::empty).
  24411. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24412. */
  24413. void insertTextAtCursor (String textToInsert);
  24414. /** Deletes all the text from the editor. */
  24415. void clear();
  24416. /** Deletes the currently selected region, and puts it on the clipboard.
  24417. @see copy, paste, SystemClipboard
  24418. */
  24419. void cut();
  24420. /** Copies any currently selected region to the clipboard.
  24421. @see cut, paste, SystemClipboard
  24422. */
  24423. void copy();
  24424. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24425. @see cut, copy, SystemClipboard
  24426. */
  24427. void paste();
  24428. /** Moves the caret to be in front of a given character.
  24429. @see getCaretPosition
  24430. */
  24431. void setCaretPosition (const int newIndex) throw();
  24432. /** Returns the current index of the caret.
  24433. @see setCaretPosition
  24434. */
  24435. int getCaretPosition() const throw();
  24436. /** Attempts to scroll the text editor so that the caret ends up at
  24437. a specified position.
  24438. This won't affect the caret's position within the text, it tries to scroll
  24439. the entire editor vertically and horizontally so that the caret is sitting
  24440. at the given position (relative to the top-left of this component).
  24441. Depending on the amount of text available, it might not be possible to
  24442. scroll far enough for the caret to reach this exact position, but it
  24443. will go as far as it can in that direction.
  24444. */
  24445. void scrollEditorToPositionCaret (const int desiredCaretX,
  24446. const int desiredCaretY) throw();
  24447. /** Get the graphical position of the caret.
  24448. The rectangle returned is relative to the component's top-left corner.
  24449. @see scrollEditorToPositionCaret
  24450. */
  24451. const Rectangle getCaretRectangle() throw();
  24452. /** Selects a section of the text.
  24453. */
  24454. void setHighlightedRegion (int startIndex,
  24455. int numberOfCharactersToHighlight) throw();
  24456. /** Returns the first character that is selected.
  24457. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24458. will return 0.
  24459. @see setHighlightedRegion, getHighlightedRegionLength
  24460. */
  24461. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24462. /** Returns the number of characters that are selected.
  24463. @see setHighlightedRegion, getHighlightedRegionStart
  24464. */
  24465. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24466. /** Returns the section of text that is currently selected. */
  24467. const String getHighlightedText() const throw();
  24468. /** Finds the index of the character at a given position.
  24469. The co-ordinates are relative to the component's top-left.
  24470. */
  24471. int getTextIndexAt (const int x, const int y) throw();
  24472. /** Returns the total width of the text, as it is currently laid-out.
  24473. This may be larger than the size of the TextEditor, and can change when
  24474. the TextEditor is resized or the text changes.
  24475. */
  24476. int getTextWidth() const throw();
  24477. /** Returns the maximum height of the text, as it is currently laid-out.
  24478. This may be larger than the size of the TextEditor, and can change when
  24479. the TextEditor is resized or the text changes.
  24480. */
  24481. int getTextHeight() const throw();
  24482. /** Changes the size of the gap at the top and left-edge of the editor.
  24483. By default there's a gap of 4 pixels.
  24484. */
  24485. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24486. /** Changes the size of border left around the edge of the component.
  24487. @see getBorder
  24488. */
  24489. void setBorder (const BorderSize& border) throw();
  24490. /** Returns the size of border around the edge of the component.
  24491. @see setBorder
  24492. */
  24493. const BorderSize getBorder() const throw();
  24494. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24495. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24496. set to false, it won't.
  24497. */
  24498. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24499. /** @internal */
  24500. void paint (Graphics& g);
  24501. /** @internal */
  24502. void paintOverChildren (Graphics& g);
  24503. /** @internal */
  24504. void mouseDown (const MouseEvent& e);
  24505. /** @internal */
  24506. void mouseUp (const MouseEvent& e);
  24507. /** @internal */
  24508. void mouseDrag (const MouseEvent& e);
  24509. /** @internal */
  24510. void mouseDoubleClick (const MouseEvent& e);
  24511. /** @internal */
  24512. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24513. /** @internal */
  24514. bool keyPressed (const KeyPress& key);
  24515. /** @internal */
  24516. bool keyStateChanged();
  24517. /** @internal */
  24518. void focusGained (FocusChangeType cause);
  24519. /** @internal */
  24520. void focusLost (FocusChangeType cause);
  24521. /** @internal */
  24522. void resized();
  24523. /** @internal */
  24524. void enablementChanged();
  24525. /** @internal */
  24526. void colourChanged();
  24527. juce_UseDebuggingNewOperator
  24528. protected:
  24529. /** This adds the items to the popup menu.
  24530. By default it adds the cut/copy/paste items, but you can override this if
  24531. you need to replace these with your own items.
  24532. If you want to add your own items to the existing ones, you can override this,
  24533. call the base class's addPopupMenuItems() method, then append your own items.
  24534. When the menu has been shown, performPopupMenuAction() will be called to
  24535. perform the item that the user has chosen.
  24536. The default menu items will be added using item IDs in the range
  24537. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24538. menu IDs.
  24539. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24540. a pointer to the info about it, or may be null if the menu is being triggered
  24541. by some other means.
  24542. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24543. */
  24544. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24545. const MouseEvent* mouseClickEvent);
  24546. /** This is called to perform one of the items that was shown on the popup menu.
  24547. If you've overridden addPopupMenuItems(), you should also override this
  24548. to perform the actions that you've added.
  24549. If you've overridden addPopupMenuItems() but have still left the default items
  24550. on the menu, remember to call the superclass's performPopupMenuAction()
  24551. so that it can perform the default actions if that's what the user clicked on.
  24552. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24553. */
  24554. virtual void performPopupMenuAction (const int menuItemID);
  24555. /** Scrolls the minimum distance needed to get the caret into view. */
  24556. void scrollToMakeSureCursorIsVisible() throw();
  24557. /** @internal */
  24558. void moveCaret (int newCaretPos) throw();
  24559. /** @internal */
  24560. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24561. /** Used internally to dispatch a text-change message. */
  24562. void textChanged() throw();
  24563. /** Counts the number of characters in the text.
  24564. This is quicker than getting the text as a string if you just need to know
  24565. the length.
  24566. */
  24567. int getTotalNumChars() throw();
  24568. /** Begins a new transaction in the UndoManager.
  24569. */
  24570. void newTransaction() throw();
  24571. /** Used internally to trigger an undo or redo. */
  24572. void doUndoRedo (const bool isRedo);
  24573. /** Can be overridden to intercept return key presses directly */
  24574. virtual void returnPressed();
  24575. /** Can be overridden to intercept escape key presses directly */
  24576. virtual void escapePressed();
  24577. /** @internal */
  24578. void handleCommandMessage (int commandId);
  24579. private:
  24580. Viewport* viewport;
  24581. TextHolderComponent* textHolder;
  24582. BorderSize borderSize;
  24583. bool readOnly : 1;
  24584. bool multiline : 1;
  24585. bool wordWrap : 1;
  24586. bool returnKeyStartsNewLine : 1;
  24587. bool caretVisible : 1;
  24588. bool popupMenuEnabled : 1;
  24589. bool selectAllTextWhenFocused : 1;
  24590. bool scrollbarVisible : 1;
  24591. bool wasFocused : 1;
  24592. bool caretFlashState : 1;
  24593. bool keepCursorOnScreen : 1;
  24594. bool tabKeyUsed : 1;
  24595. bool menuActive : 1;
  24596. UndoManager undoManager;
  24597. float cursorX, cursorY, cursorHeight;
  24598. int maxTextLength;
  24599. int selectionStart, selectionEnd;
  24600. int leftIndent, topIndent;
  24601. unsigned int lastTransactionTime;
  24602. Font currentFont;
  24603. int totalNumChars, caretPosition;
  24604. VoidArray sections;
  24605. String textToShowWhenEmpty;
  24606. Colour colourForTextWhenEmpty;
  24607. tchar passwordCharacter;
  24608. enum
  24609. {
  24610. notDragging,
  24611. draggingSelectionStart,
  24612. draggingSelectionEnd
  24613. } dragType;
  24614. String allowedCharacters;
  24615. SortedSet <void*> listeners;
  24616. friend class TextEditorInsertAction;
  24617. friend class TextEditorRemoveAction;
  24618. void coalesceSimilarSections() throw();
  24619. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24620. void clearInternal (UndoManager* const um) throw();
  24621. void insert (const String& text,
  24622. const int insertIndex,
  24623. const Font& font,
  24624. const Colour& colour,
  24625. UndoManager* const um,
  24626. const int caretPositionToMoveTo) throw();
  24627. void reinsert (const int insertIndex,
  24628. const VoidArray& sections) throw();
  24629. void remove (const int startIndex,
  24630. int endIndex,
  24631. UndoManager* const um,
  24632. const int caretPositionToMoveTo) throw();
  24633. void getCharPosition (const int index,
  24634. float& x, float& y,
  24635. float& lineHeight) const throw();
  24636. void updateCaretPosition() throw();
  24637. int indexAtPosition (const float x,
  24638. const float y) throw();
  24639. int findWordBreakAfter (const int position) const throw();
  24640. int findWordBreakBefore (const int position) const throw();
  24641. friend class TextHolderComponent;
  24642. friend class TextEditorViewport;
  24643. void drawContent (Graphics& g);
  24644. void updateTextHolderSize() throw();
  24645. float getWordWrapWidth() const throw();
  24646. void timerCallbackInt();
  24647. void repaintCaret();
  24648. void repaintText (int textStartIndex, int textEndIndex);
  24649. TextEditor (const TextEditor&);
  24650. const TextEditor& operator= (const TextEditor&);
  24651. };
  24652. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24653. /********* End of inlined file: juce_TextEditor.h *********/
  24654. class Label;
  24655. /**
  24656. A class for receiving events from a Label.
  24657. You can register a LabelListener with a Label using the Label::addListener()
  24658. method, and it will be called when the text of the label changes, either because
  24659. of a call to Label::setText() or by the user editing the text (if the label is
  24660. editable).
  24661. @see Label::addListener, Label::removeListener
  24662. */
  24663. class JUCE_API LabelListener
  24664. {
  24665. public:
  24666. /** Destructor. */
  24667. virtual ~LabelListener() {}
  24668. /** Called when a Label's text has changed.
  24669. */
  24670. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24671. };
  24672. /**
  24673. A component that displays a text string, and can optionally become a text
  24674. editor when clicked.
  24675. */
  24676. class JUCE_API Label : public Component,
  24677. public SettableTooltipClient,
  24678. protected TextEditorListener,
  24679. private ComponentListener,
  24680. private AsyncUpdater
  24681. {
  24682. public:
  24683. /** Creates a Label.
  24684. @param componentName the name to give the component
  24685. @param labelText the text to show in the label
  24686. */
  24687. Label (const String& componentName,
  24688. const String& labelText);
  24689. /** Destructor. */
  24690. ~Label();
  24691. /** Changes the label text.
  24692. If broadcastChangeMessage is true and the new text is different to the current
  24693. text, then the class will broadcast a change message to any LabelListeners that
  24694. are registered.
  24695. */
  24696. void setText (const String& newText,
  24697. const bool broadcastChangeMessage);
  24698. /** Returns the label's current text.
  24699. @param returnActiveEditorContents if this is true and the label is currently
  24700. being edited, then this method will return the
  24701. text as it's being shown in the editor. If false,
  24702. then the value returned here won't be updated until
  24703. the user has finished typing and pressed the return
  24704. key.
  24705. */
  24706. const String getText (const bool returnActiveEditorContents = false) const throw();
  24707. /** Changes the font to use to draw the text.
  24708. @see getFont
  24709. */
  24710. void setFont (const Font& newFont) throw();
  24711. /** Returns the font currently being used.
  24712. @see setFont
  24713. */
  24714. const Font& getFont() const throw();
  24715. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24716. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24717. methods.
  24718. Note that you can also use the constants from TextEditor::ColourIds to change the
  24719. colour of the text editor that is opened when a label is editable.
  24720. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24721. */
  24722. enum ColourIds
  24723. {
  24724. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  24725. textColourId = 0x1000281, /**< The colour for the text. */
  24726. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  24727. Leave this transparent to not have an outline. */
  24728. };
  24729. /** Sets the style of justification to be used for positioning the text.
  24730. (The default is Justification::centredLeft)
  24731. */
  24732. void setJustificationType (const Justification& justification) throw();
  24733. /** Returns the type of justification, as set in setJustificationType(). */
  24734. const Justification getJustificationType() const throw() { return justification; }
  24735. /** Changes the gap that is left between the edge of the component and the text.
  24736. By default there's a small gap left at the sides of the component to allow for
  24737. the drawing of the border, but you can change this if necessary.
  24738. */
  24739. void setBorderSize (int horizontalBorder, int verticalBorder);
  24740. /** Returns the size of the horizontal gap being left around the text.
  24741. */
  24742. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  24743. /** Returns the size of the vertical gap being left around the text.
  24744. */
  24745. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  24746. /** Makes this label "stick to" another component.
  24747. This will cause the label to follow another component around, staying
  24748. either to its left or above it.
  24749. @param owner the component to follow
  24750. @param onLeft if true, the label will stay on the left of its component; if
  24751. false, it will stay above it.
  24752. */
  24753. void attachToComponent (Component* owner,
  24754. const bool onLeft);
  24755. /** If this label has been attached to another component using attachToComponent, this
  24756. returns the other component.
  24757. Returns 0 if the label is not attached.
  24758. */
  24759. Component* getAttachedComponent() const throw() { return ownerComponent; }
  24760. /** If the label is attached to the left of another component, this returns true.
  24761. Returns false if the label is above the other component. This is only relevent if
  24762. attachToComponent() has been called.
  24763. */
  24764. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  24765. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  24766. using ellipsis.
  24767. @see Graphics::drawFittedText
  24768. */
  24769. void setMinimumHorizontalScale (const float newScale);
  24770. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  24771. /** Registers a listener that will be called when the label's text changes. */
  24772. void addListener (LabelListener* const listener) throw();
  24773. /** Deregisters a previously-registered listener. */
  24774. void removeListener (LabelListener* const listener) throw();
  24775. /** Makes the label turn into a TextEditor when clicked.
  24776. By default this is turned off.
  24777. If turned on, then single- or double-clicking will turn the label into
  24778. an editor. If the user then changes the text, then the ChangeBroadcaster
  24779. base class will be used to send change messages to any listeners that
  24780. have registered.
  24781. If the user changes the text, the textWasEdited() method will be called
  24782. afterwards, and subclasses can override this if they need to do anything
  24783. special.
  24784. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  24785. @param editOnDoubleClick if true, a double-click is needed to start editing
  24786. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  24787. edited will discard any changes; if false, then this will
  24788. commit the changes.
  24789. @see showEditor, setEditorColours, TextEditor
  24790. */
  24791. void setEditable (const bool editOnSingleClick,
  24792. const bool editOnDoubleClick = false,
  24793. const bool lossOfFocusDiscardsChanges = false) throw();
  24794. /** Returns true if this option was set using setEditable(). */
  24795. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  24796. /** Returns true if this option was set using setEditable(). */
  24797. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  24798. /** Returns true if this option has been set in a call to setEditable(). */
  24799. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  24800. /** Returns true if the user can edit this label's text. */
  24801. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  24802. /** Makes the editor appear as if the label had been clicked by the user.
  24803. @see textWasEdited, setEditable
  24804. */
  24805. void showEditor();
  24806. /** Hides the editor if it was being shown.
  24807. @param discardCurrentEditorContents if true, the label's text will be
  24808. reset to whatever it was before the editor
  24809. was shown; if false, the current contents of the
  24810. editor will be used to set the label's text
  24811. before it is hidden.
  24812. */
  24813. void hideEditor (const bool discardCurrentEditorContents);
  24814. /** Returns true if the editor is currently focused and active. */
  24815. bool isBeingEdited() const throw();
  24816. juce_UseDebuggingNewOperator
  24817. protected:
  24818. /** @internal */
  24819. void paint (Graphics& g);
  24820. /** @internal */
  24821. void resized();
  24822. /** @internal */
  24823. void mouseUp (const MouseEvent& e);
  24824. /** @internal */
  24825. void mouseDoubleClick (const MouseEvent& e);
  24826. /** @internal */
  24827. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24828. /** @internal */
  24829. void componentParentHierarchyChanged (Component& component);
  24830. /** @internal */
  24831. void componentVisibilityChanged (Component& component);
  24832. /** @internal */
  24833. void inputAttemptWhenModal();
  24834. /** @internal */
  24835. void focusGained (FocusChangeType);
  24836. /** @internal */
  24837. void enablementChanged();
  24838. /** @internal */
  24839. KeyboardFocusTraverser* createFocusTraverser();
  24840. /** @internal */
  24841. void textEditorTextChanged (TextEditor& editor);
  24842. /** @internal */
  24843. void textEditorReturnKeyPressed (TextEditor& editor);
  24844. /** @internal */
  24845. void textEditorEscapeKeyPressed (TextEditor& editor);
  24846. /** @internal */
  24847. void textEditorFocusLost (TextEditor& editor);
  24848. /** @internal */
  24849. void handleAsyncUpdate();
  24850. /** @internal */
  24851. void colourChanged();
  24852. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  24853. Subclasses can override this if they need to customise this component in some way.
  24854. */
  24855. virtual TextEditor* createEditorComponent();
  24856. /** Called after the user changes the text.
  24857. */
  24858. virtual void textWasEdited();
  24859. private:
  24860. String text;
  24861. Font font;
  24862. Justification justification;
  24863. TextEditor* editor;
  24864. SortedSet <void*> listeners;
  24865. Component* ownerComponent;
  24866. ComponentDeletionWatcher* deletionWatcher;
  24867. int horizontalBorderSize, verticalBorderSize;
  24868. float minimumHorizontalScale;
  24869. bool editSingleClick : 1;
  24870. bool editDoubleClick : 1;
  24871. bool lossOfFocusDiscardsChanges : 1;
  24872. bool leftOfOwnerComp : 1;
  24873. bool updateFromTextEditorContents();
  24874. Label (const Label&);
  24875. const Label& operator= (const Label&);
  24876. };
  24877. #endif // __JUCE_LABEL_JUCEHEADER__
  24878. /********* End of inlined file: juce_Label.h *********/
  24879. class ComboBox;
  24880. /**
  24881. A class for receiving events from a ComboBox.
  24882. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  24883. method, and it will be called when the selected item in the box changes.
  24884. @see ComboBox::addListener, ComboBox::removeListener
  24885. */
  24886. class JUCE_API ComboBoxListener
  24887. {
  24888. public:
  24889. /** Destructor. */
  24890. virtual ~ComboBoxListener() {}
  24891. /** Called when a ComboBox has its selected item changed.
  24892. */
  24893. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  24894. };
  24895. /**
  24896. A component that lets the user choose from a drop-down list of choices.
  24897. The combo-box has a list of text strings, each with an associated id number,
  24898. that will be shown in the drop-down list when the user clicks on the component.
  24899. The currently selected choice is displayed in the combo-box, and this can
  24900. either be read-only text, or editable.
  24901. To find out when the user selects a different item or edits the text, you
  24902. can register a ComboBoxListener to receive callbacks.
  24903. @see ComboBoxListener
  24904. */
  24905. class JUCE_API ComboBox : public Component,
  24906. public SettableTooltipClient,
  24907. private LabelListener,
  24908. private AsyncUpdater
  24909. {
  24910. public:
  24911. /** Creates a combo-box.
  24912. On construction, the text field will be empty, so you should call the
  24913. setSelectedId() or setText() method to choose the initial value before
  24914. displaying it.
  24915. @param componentName the name to set for the component (see Component::setName())
  24916. */
  24917. ComboBox (const String& componentName);
  24918. /** Destructor. */
  24919. ~ComboBox();
  24920. /** Sets whether the test in the combo-box is editable.
  24921. The default state for a new ComboBox is non-editable, and can only be changed
  24922. by choosing from the drop-down list.
  24923. */
  24924. void setEditableText (const bool isEditable);
  24925. /** Returns true if the text is directly editable.
  24926. @see setEditableText
  24927. */
  24928. bool isTextEditable() const throw();
  24929. /** Sets the style of justification to be used for positioning the text.
  24930. The default is Justification::centredLeft. The text is displayed using a
  24931. Label component inside the ComboBox.
  24932. */
  24933. void setJustificationType (const Justification& justification) throw();
  24934. /** Returns the current justification for the text box.
  24935. @see setJustificationType
  24936. */
  24937. const Justification getJustificationType() const throw();
  24938. /** Adds an item to be shown in the drop-down list.
  24939. @param newItemText the text of the item to show in the list
  24940. @param newItemId an associated ID number that can be set or retrieved - see
  24941. getSelectedId() and setSelectedId()
  24942. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  24943. */
  24944. void addItem (const String& newItemText,
  24945. const int newItemId) throw();
  24946. /** Adds a separator line to the drop-down list.
  24947. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  24948. */
  24949. void addSeparator() throw();
  24950. /** Adds a heading to the drop-down list, so that you can group the items into
  24951. different sections.
  24952. The headings are indented slightly differently to set them apart from the
  24953. items on the list, and obviously can't be selected. You might want to add
  24954. separators between your sections too.
  24955. @see addItem, addSeparator
  24956. */
  24957. void addSectionHeading (const String& headingName) throw();
  24958. /** This allows items in the drop-down list to be selectively disabled.
  24959. When you add an item, it's enabled by default, but you can call this
  24960. method to change its status.
  24961. If you disable an item which is already selected, this won't change the
  24962. current selection - it just stops the user choosing that item from the list.
  24963. */
  24964. void setItemEnabled (const int itemId,
  24965. const bool isEnabled) throw();
  24966. /** Changes the text for an existing item.
  24967. */
  24968. void changeItemText (const int itemId,
  24969. const String& newText) throw();
  24970. /** Removes all the items from the drop-down list.
  24971. If this call causes the content to be cleared, then a change-message
  24972. will be broadcast unless dontSendChangeMessage is true.
  24973. @see addItem, removeItem, getNumItems
  24974. */
  24975. void clear (const bool dontSendChangeMessage = false);
  24976. /** Returns the number of items that have been added to the list.
  24977. Note that this doesn't include headers or separators.
  24978. */
  24979. int getNumItems() const throw();
  24980. /** Returns the text for one of the items in the list.
  24981. Note that this doesn't include headers or separators.
  24982. @param index the item's index from 0 to (getNumItems() - 1)
  24983. */
  24984. const String getItemText (const int index) const throw();
  24985. /** Returns the ID for one of the items in the list.
  24986. Note that this doesn't include headers or separators.
  24987. @param index the item's index from 0 to (getNumItems() - 1)
  24988. */
  24989. int getItemId (const int index) const throw();
  24990. /** Returns the ID of the item that's currently shown in the box.
  24991. If no item is selected, or if the text is editable and the user
  24992. has entered something which isn't one of the items in the list, then
  24993. this will return 0.
  24994. @see setSelectedId, getSelectedItemIndex, getText
  24995. */
  24996. int getSelectedId() const throw();
  24997. /** Sets one of the items to be the current selection.
  24998. This will set the ComboBox's text to that of the item that matches
  24999. this ID.
  25000. @param newItemId the new item to select
  25001. @param dontSendChangeMessage if set to true, this method won't trigger a
  25002. change notification
  25003. @see getSelectedId, setSelectedItemIndex, setText
  25004. */
  25005. void setSelectedId (const int newItemId,
  25006. const bool dontSendChangeMessage = false) throw();
  25007. /** Returns the index of the item that's currently shown in the box.
  25008. If no item is selected, or if the text is editable and the user
  25009. has entered something which isn't one of the items in the list, then
  25010. this will return -1.
  25011. @see setSelectedItemIndex, getSelectedId, getText
  25012. */
  25013. int getSelectedItemIndex() const throw();
  25014. /** Sets one of the items to be the current selection.
  25015. This will set the ComboBox's text to that of the item at the given
  25016. index in the list.
  25017. @param newItemIndex the new item to select
  25018. @param dontSendChangeMessage if set to true, this method won't trigger a
  25019. change notification
  25020. @see getSelectedItemIndex, setSelectedId, setText
  25021. */
  25022. void setSelectedItemIndex (const int newItemIndex,
  25023. const bool dontSendChangeMessage = false) throw();
  25024. /** Returns the text that is currently shown in the combo-box's text field.
  25025. If the ComboBox has editable text, then this text may have been edited
  25026. by the user; otherwise it will be one of the items from the list, or
  25027. possibly an empty string if nothing was selected.
  25028. @see setText, getSelectedId, getSelectedItemIndex
  25029. */
  25030. const String getText() const throw();
  25031. /** Sets the contents of the combo-box's text field.
  25032. The text passed-in will be set as the current text regardless of whether
  25033. it is one of the items in the list. If the current text isn't one of the
  25034. items, then getSelectedId() will return -1, otherwise it wil return
  25035. the approriate ID.
  25036. @param newText the text to select
  25037. @param dontSendChangeMessage if set to true, this method won't trigger a
  25038. change notification
  25039. @see getText
  25040. */
  25041. void setText (const String& newText,
  25042. const bool dontSendChangeMessage = false) throw();
  25043. /** Programmatically opens the text editor to allow the user to edit the current item.
  25044. This is the same effect as when the box is clicked-on.
  25045. @see Label::showEditor();
  25046. */
  25047. void showEditor();
  25048. /** Registers a listener that will be called when the box's content changes. */
  25049. void addListener (ComboBoxListener* const listener) throw();
  25050. /** Deregisters a previously-registered listener. */
  25051. void removeListener (ComboBoxListener* const listener) throw();
  25052. /** Sets a message to display when there is no item currently selected.
  25053. @see getTextWhenNothingSelected
  25054. */
  25055. void setTextWhenNothingSelected (const String& newMessage) throw();
  25056. /** Returns the text that is shown when no item is selected.
  25057. @see setTextWhenNothingSelected
  25058. */
  25059. const String getTextWhenNothingSelected() const throw();
  25060. /** Sets the message to show when there are no items in the list, and the user clicks
  25061. on the drop-down box.
  25062. By default it just says "no choices", but this lets you change it to something more
  25063. meaningful.
  25064. */
  25065. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25066. /** Returns the text shown when no items have been added to the list.
  25067. @see setTextWhenNoChoicesAvailable
  25068. */
  25069. const String getTextWhenNoChoicesAvailable() const throw();
  25070. /** Gives the ComboBox a tooltip. */
  25071. void setTooltip (const String& newTooltip);
  25072. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25073. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25074. methods.
  25075. To change the colours of the menu that pops up
  25076. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25077. */
  25078. enum ColourIds
  25079. {
  25080. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25081. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25082. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25083. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25084. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25085. };
  25086. /** @internal */
  25087. void labelTextChanged (Label*);
  25088. /** @internal */
  25089. void enablementChanged();
  25090. /** @internal */
  25091. void colourChanged();
  25092. /** @internal */
  25093. void focusGained (Component::FocusChangeType cause);
  25094. /** @internal */
  25095. void focusLost (Component::FocusChangeType cause);
  25096. /** @internal */
  25097. void handleAsyncUpdate();
  25098. /** @internal */
  25099. const String getTooltip() { return label->getTooltip(); }
  25100. /** @internal */
  25101. void mouseDown (const MouseEvent&);
  25102. /** @internal */
  25103. void mouseDrag (const MouseEvent&);
  25104. /** @internal */
  25105. void mouseUp (const MouseEvent&);
  25106. /** @internal */
  25107. void lookAndFeelChanged();
  25108. /** @internal */
  25109. void paint (Graphics&);
  25110. /** @internal */
  25111. void resized();
  25112. /** @internal */
  25113. bool keyStateChanged();
  25114. /** @internal */
  25115. bool keyPressed (const KeyPress&);
  25116. juce_UseDebuggingNewOperator
  25117. private:
  25118. struct ItemInfo
  25119. {
  25120. String name;
  25121. int itemId;
  25122. bool isEnabled : 1, isHeading : 1;
  25123. bool isSeparator() const throw();
  25124. bool isRealItem() const throw();
  25125. };
  25126. OwnedArray <ItemInfo> items;
  25127. int currentIndex;
  25128. bool isButtonDown;
  25129. bool separatorPending;
  25130. bool menuActive;
  25131. SortedSet <void*> listeners;
  25132. Label* label;
  25133. String textWhenNothingSelected, noChoicesMessage;
  25134. void showPopup();
  25135. ItemInfo* getItemForId (const int itemId) const throw();
  25136. ItemInfo* getItemForIndex (const int index) const throw();
  25137. ComboBox (const ComboBox&);
  25138. const ComboBox& operator= (const ComboBox&);
  25139. };
  25140. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25141. /********* End of inlined file: juce_ComboBox.h *********/
  25142. /**
  25143. Manages the state of some audio and midi i/o devices.
  25144. This class keeps tracks of a currently-selected audio device, through
  25145. with which it continuously streams data from an audio callback, as well as
  25146. one or more midi inputs.
  25147. The idea is that your application will create one global instance of this object,
  25148. and let it take care of creating and deleting specific types of audio devices
  25149. internally. So when the device is changed, your callbacks will just keep running
  25150. without having to worry about this.
  25151. The manager can save and reload all of its device settings as XML, which
  25152. makes it very easy for you to save and reload the audio setup of your
  25153. application.
  25154. And to make it easy to let the user change its settings, there's a component
  25155. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25156. device selection/sample-rate/latency controls.
  25157. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25158. call setAudioCallback() to register your audio callback with it, and use that to process
  25159. your audio data.
  25160. The manager also acts as a handy hub for incoming midi messages, allowing a
  25161. listener to register for messages from either a specific midi device, or from whatever
  25162. the current default midi input device is. The listener then doesn't have to worry about
  25163. re-registering with different midi devices if they are changed or deleted.
  25164. And yet another neat trick is that amount of CPU time being used is measured and
  25165. available with the getCpuUsage() method.
  25166. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25167. listeners whenever one of its settings is changed.
  25168. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25169. */
  25170. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25171. {
  25172. public:
  25173. /** Creates a default AudioDeviceManager.
  25174. Initially no audio device will be selected. You should call the initialise() method
  25175. and register an audio callback with setAudioCallback() before it'll be able to
  25176. actually make any noise.
  25177. */
  25178. AudioDeviceManager();
  25179. /** Destructor. */
  25180. ~AudioDeviceManager();
  25181. /** Opens a set of audio devices ready for use.
  25182. This will attempt to open either a default audio device, or one that was
  25183. previously saved as XML.
  25184. @param numInputChannelsNeeded a minimum number of input channels needed
  25185. by your app.
  25186. @param numOutputChannelsNeeded a minimum number of output channels to open
  25187. @param savedState either a previously-saved state that was produced
  25188. by createStateXml(), or 0 if you want the manager
  25189. to choose the best device to open.
  25190. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25191. fails to open, then a default device will be used
  25192. instead. If false, then on failure, no device is
  25193. opened.
  25194. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25195. name, then that will be used as the default device
  25196. (assuming that there wasn't one specified in the XML).
  25197. The string can actually be a simple wildcard, containing "*"
  25198. and "?" characters
  25199. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25200. */
  25201. const String initialise (const int numInputChannelsNeeded,
  25202. const int numOutputChannelsNeeded,
  25203. const XmlElement* const savedState,
  25204. const bool selectDefaultDeviceOnFailure,
  25205. const String& preferredDefaultDeviceName = String::empty);
  25206. /** Returns some XML representing the current state of the manager.
  25207. This stores the current device, its samplerate, block size, etc, and
  25208. can be restored later with initialise().
  25209. */
  25210. XmlElement* createStateXml() const;
  25211. /**
  25212. */
  25213. struct AudioDeviceSetup
  25214. {
  25215. AudioDeviceSetup();
  25216. bool operator== (const AudioDeviceSetup& other) const;
  25217. /**
  25218. */
  25219. String outputDeviceName;
  25220. /**
  25221. */
  25222. String inputDeviceName;
  25223. /**
  25224. */
  25225. double sampleRate;
  25226. /**
  25227. */
  25228. int bufferSize;
  25229. /**
  25230. */
  25231. BitArray inputChannels;
  25232. bool useDefaultInputChannels;
  25233. /**
  25234. */
  25235. BitArray outputChannels;
  25236. bool useDefaultOutputChannels;
  25237. };
  25238. /**
  25239. */
  25240. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25241. /**
  25242. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25243. settings will be taken as having been explicitly chosen by the
  25244. user, and the next time createStateXml() is called, these settings
  25245. will be returned. If it's false, then the device is treated as a
  25246. temporary or default device, and a call to createStateXml() will
  25247. return either the last settings that were made with treatAsChosenDevice
  25248. as true, or the last XML settings that were passed into initialise().
  25249. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25250. */
  25251. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25252. const bool treatAsChosenDevice);
  25253. /** Returns the currently-active audio device. */
  25254. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25255. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25256. void setCurrentAudioDeviceType (const String& type,
  25257. const bool treatAsChosenDevice);
  25258. /** Closes the currently-open device.
  25259. You can call restartLastAudioDevice() later to reopen it in the same state
  25260. that it was just in.
  25261. */
  25262. void closeAudioDevice();
  25263. /** Tries to reload the last audio device that was running.
  25264. Note that this only reloads the last device that was running before
  25265. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25266. and can only be called after a device has been opened with SetAudioDevice().
  25267. If a device is already open, this call will do nothing.
  25268. */
  25269. void restartLastAudioDevice();
  25270. /** Gives the manager an audio callback to use.
  25271. The manager will redirect callbacks from whatever audio device is currently
  25272. in use to this callback object.
  25273. You can pass 0 in here to stop callbacks being made.
  25274. */
  25275. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25276. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25277. Returns a value between 0 and 1.0
  25278. */
  25279. double getCpuUsage() const;
  25280. /** Enables or disables a midi input device.
  25281. The list of devices can be obtained with the MidiInput::getDevices() method.
  25282. Any incoming messages from enabled input devices will be forwarded on to all the
  25283. listeners that have been registered with the addMidiInputCallback() method. They
  25284. can either register for messages from a particular device, or from just the
  25285. "default" midi input.
  25286. Routing the midi input via an AudioDeviceManager means that when a listener
  25287. registers for the default midi input, this default device can be changed by the
  25288. manager without the listeners having to know about it or re-register.
  25289. It also means that a listener can stay registered for a midi input that is disabled
  25290. or not present, so that when the input is re-enabled, the listener will start
  25291. receiving messages again.
  25292. @see addMidiInputCallback, isMidiInputEnabled
  25293. */
  25294. void setMidiInputEnabled (const String& midiInputDeviceName,
  25295. const bool enabled);
  25296. /** Returns true if a given midi input device is being used.
  25297. @see setMidiInputEnabled
  25298. */
  25299. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25300. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25301. The device name can be empty to indicate that it wants events from whatever the
  25302. current "default" device is. Or it can be the name of one of the midi input devices
  25303. (see MidiInput::getDevices() for the names).
  25304. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25305. events forwarded on to listeners.
  25306. */
  25307. void addMidiInputCallback (const String& midiInputDeviceName,
  25308. MidiInputCallback* callback);
  25309. /** Removes a listener that was previously registered with addMidiInputCallback().
  25310. */
  25311. void removeMidiInputCallback (const String& midiInputDeviceName,
  25312. MidiInputCallback* callback);
  25313. /** Sets a midi output device to use as the default.
  25314. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25315. The specified device will be opened automatically and can be retrieved with the
  25316. getDefaultMidiOutput() method.
  25317. Pass in an empty string to deselect all devices. For the default device, you
  25318. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25319. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25320. */
  25321. void setDefaultMidiOutput (const String& deviceName);
  25322. /** Returns the name of the default midi output.
  25323. @see setDefaultMidiOutput, getDefaultMidiOutput
  25324. */
  25325. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25326. /** Returns the current default midi output device.
  25327. If no device has been selected, or the device can't be opened, this will
  25328. return 0.
  25329. @see getDefaultMidiOutputName
  25330. */
  25331. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25332. /**
  25333. */
  25334. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25335. /** Creates a list of available types.
  25336. This will add a set of new AudioIODeviceType objects to the specified list, to
  25337. represent each available types of device.
  25338. You can override this if your app needs to do something specific, like avoid
  25339. using DirectSound devices, etc.
  25340. */
  25341. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25342. /** Plays a beep through the current audio device.
  25343. This is here to allow the audio setup UI panels to easily include a "test"
  25344. button so that the user can check where the audio is coming from.
  25345. */
  25346. void playTestSound();
  25347. /** Turns on level-measuring.
  25348. When enabled, the device manager will measure the peak input level
  25349. across all channels, and you can get this level by calling getCurrentInputLevel().
  25350. This is mainly intended for audio setup UI panels to use to create a mic
  25351. level display, so that the user can check that they've selected the right
  25352. device.
  25353. A simple filter is used to make the level decay smoothly, but this is
  25354. only intended for giving rough feedback, and not for any kind of accurate
  25355. measurement.
  25356. */
  25357. void enableInputLevelMeasurement (const bool enableMeasurement);
  25358. /** Returns the current input level.
  25359. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25360. See enableInputLevelMeasurement() for more info.
  25361. */
  25362. double getCurrentInputLevel() const;
  25363. juce_UseDebuggingNewOperator
  25364. private:
  25365. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25366. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25367. AudioDeviceSetup currentSetup;
  25368. AudioIODevice* currentAudioDevice;
  25369. AudioIODeviceCallback* currentCallback;
  25370. int numInputChansNeeded, numOutputChansNeeded;
  25371. String currentDeviceType;
  25372. BitArray inputChannels, outputChannels;
  25373. XmlElement* lastExplicitSettings;
  25374. mutable bool listNeedsScanning;
  25375. bool useInputNames, inputLevelMeasurementEnabled;
  25376. double inputLevel;
  25377. AudioSampleBuffer* testSound;
  25378. int testSoundPosition;
  25379. StringArray midiInsFromXml;
  25380. OwnedArray <MidiInput> enabledMidiInputs;
  25381. Array <MidiInputCallback*> midiCallbacks;
  25382. Array <MidiInput*> midiCallbackDevices;
  25383. String defaultMidiOutputName;
  25384. MidiOutput* defaultMidiOutput;
  25385. CriticalSection audioCallbackLock, midiCallbackLock;
  25386. double cpuUsageMs, timeToCpuScale;
  25387. class CallbackHandler : public AudioIODeviceCallback,
  25388. public MidiInputCallback
  25389. {
  25390. public:
  25391. AudioDeviceManager* owner;
  25392. void audioDeviceIOCallback (const float** inputChannelData,
  25393. int totalNumInputChannels,
  25394. float** outputChannelData,
  25395. int totalNumOutputChannels,
  25396. int numSamples);
  25397. void audioDeviceAboutToStart (AudioIODevice*);
  25398. void audioDeviceStopped();
  25399. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25400. };
  25401. CallbackHandler callbackHandler;
  25402. friend class CallbackHandler;
  25403. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25404. int totalNumInputChannels,
  25405. float** outputChannelData,
  25406. int totalNumOutputChannels,
  25407. int numSamples);
  25408. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25409. void audioDeviceStoppedInt();
  25410. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25411. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25412. const BitArray& ins, const BitArray& outs);
  25413. void stopDevice();
  25414. void updateXml();
  25415. void createDeviceTypesIfNeeded();
  25416. void scanDevicesIfNeeded();
  25417. void deleteCurrentDevice();
  25418. double chooseBestSampleRate (double preferred) const;
  25419. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25420. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25421. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25422. AudioDeviceManager (const AudioDeviceManager&);
  25423. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25424. };
  25425. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25426. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25427. #endif
  25428. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25429. #endif
  25430. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25431. #endif
  25432. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25433. #endif
  25434. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25435. #endif
  25436. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25437. /********* Start of inlined file: juce_Sampler.h *********/
  25438. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25439. #define __JUCE_SAMPLER_JUCEHEADER__
  25440. /********* Start of inlined file: juce_Synthesiser.h *********/
  25441. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25442. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25443. /**
  25444. Describes one of the sounds that a Synthesiser can play.
  25445. A synthesiser can contain one or more sounds, and a sound can choose which
  25446. midi notes and channels can trigger it.
  25447. The SynthesiserSound is a passive class that just describes what the sound is -
  25448. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25449. more than one SynthesiserVoice to play the same sound at the same time.
  25450. @see Synthesiser, SynthesiserVoice
  25451. */
  25452. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25453. {
  25454. protected:
  25455. SynthesiserSound();
  25456. public:
  25457. /** Destructor. */
  25458. virtual ~SynthesiserSound();
  25459. /** Returns true if this sound should be played when a given midi note is pressed.
  25460. The Synthesiser will use this information when deciding which sounds to trigger
  25461. for a given note.
  25462. */
  25463. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25464. /** Returns true if the sound should be triggered by midi events on a given channel.
  25465. The Synthesiser will use this information when deciding which sounds to trigger
  25466. for a given note.
  25467. */
  25468. virtual bool appliesToChannel (const int midiChannel) = 0;
  25469. /**
  25470. */
  25471. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25472. juce_UseDebuggingNewOperator
  25473. };
  25474. /**
  25475. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25476. A voice plays a single sound at a time, and a synthesiser holds an array of
  25477. voices so that it can play polyphonically.
  25478. @see Synthesiser, SynthesiserSound
  25479. */
  25480. class JUCE_API SynthesiserVoice
  25481. {
  25482. public:
  25483. /** Creates a voice. */
  25484. SynthesiserVoice();
  25485. /** Destructor. */
  25486. virtual ~SynthesiserVoice();
  25487. /** Returns the midi note that this voice is currently playing.
  25488. Returns a value less than 0 if no note is playing.
  25489. */
  25490. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25491. /** Returns the sound that this voice is currently playing.
  25492. Returns 0 if it's not playing.
  25493. */
  25494. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25495. /** Must return true if this voice object is capable of playing the given sound.
  25496. If there are different classes of sound, and different classes of voice, a voice can
  25497. choose which ones it wants to take on.
  25498. A typical implementation of this method may just return true if there's only one type
  25499. of voice and sound, or it might check the type of the sound object passed-in and
  25500. see if it's one that it understands.
  25501. */
  25502. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25503. /** Called to start a new note.
  25504. This will be called during the rendering callback, so must be fast and thread-safe.
  25505. */
  25506. virtual void startNote (const int midiNoteNumber,
  25507. const float velocity,
  25508. SynthesiserSound* sound,
  25509. const int currentPitchWheelPosition) = 0;
  25510. /** Called to stop a note.
  25511. This will be called during the rendering callback, so must be fast and thread-safe.
  25512. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25513. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25514. and allow the synth to reassign it another sound.
  25515. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25516. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25517. finishes playing (during the rendering callback), it must make sure that it calls
  25518. clearCurrentNote().
  25519. */
  25520. virtual void stopNote (const bool allowTailOff) = 0;
  25521. /** Called to let the voice know that the pitch wheel has been moved.
  25522. This will be called during the rendering callback, so must be fast and thread-safe.
  25523. */
  25524. virtual void pitchWheelMoved (const int newValue) = 0;
  25525. /** Called to let the voice know that a midi controller has been moved.
  25526. This will be called during the rendering callback, so must be fast and thread-safe.
  25527. */
  25528. virtual void controllerMoved (const int controllerNumber,
  25529. const int newValue) = 0;
  25530. /** Renders the next block of data for this voice.
  25531. The output audio data must be added to the current contents of the buffer provided.
  25532. Only the region of the buffer between startSample and (startSample + numSamples)
  25533. should be altered by this method.
  25534. If the voice is currently silent, it should just return without doing anything.
  25535. If the sound that the voice is playing finishes during the course of this rendered
  25536. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25537. The size of the blocks that are rendered can change each time it is called, and may
  25538. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25539. the voice's methods will be called to tell it about note and controller events.
  25540. */
  25541. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25542. int startSample,
  25543. int numSamples) = 0;
  25544. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25545. midi channel.
  25546. If it's not currently playing, this will return false.
  25547. */
  25548. bool isPlayingChannel (const int midiChannel) const;
  25549. /** Changes the voice's reference sample rate.
  25550. The rate is set so that subclasses know the output rate and can set their pitch
  25551. accordingly.
  25552. This method is called by the synth, and subclasses can access the current rate with
  25553. the currentSampleRate member.
  25554. */
  25555. void setCurrentPlaybackSampleRate (const double newRate);
  25556. juce_UseDebuggingNewOperator
  25557. protected:
  25558. /** Returns the current target sample rate at which rendering is being done.
  25559. This is available for subclasses so they can pitch things correctly.
  25560. */
  25561. double getSampleRate() const throw() { return currentSampleRate; }
  25562. /** Resets the state of this voice after a sound has finished playing.
  25563. The subclass must call this when it finishes playing a note and becomes available
  25564. to play new ones.
  25565. It must either call it in the stopNote() method, or if the voice is tailing off,
  25566. then it should call it later during the renderNextBlock method, as soon as it
  25567. finishes its tail-off.
  25568. It can also be called at any time during the render callback if the sound happens
  25569. to have finished, e.g. if it's playing a sample and the sample finishes.
  25570. */
  25571. void clearCurrentNote();
  25572. private:
  25573. friend class Synthesiser;
  25574. double currentSampleRate;
  25575. int currentlyPlayingNote;
  25576. uint32 noteOnTime;
  25577. SynthesiserSound::Ptr currentlyPlayingSound;
  25578. };
  25579. /**
  25580. Base class for a musical device that can play sounds.
  25581. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25582. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25583. which can play back one of these sounds.
  25584. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25585. set of sounds, and a set of voices it can use to play them. If you only give it
  25586. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25587. have available.
  25588. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25589. events that go in will be scanned for note on/off messages, and these are used to
  25590. start and stop the voices playing the appropriate sounds.
  25591. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25592. noteOff() and other controller methods.
  25593. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25594. what the target playback rate is. This value is passed on to the voices so that
  25595. they can pitch their output correctly.
  25596. */
  25597. class JUCE_API Synthesiser
  25598. {
  25599. public:
  25600. /** Creates a new synthesiser.
  25601. You'll need to add some sounds and voices before it'll make any sound..
  25602. */
  25603. Synthesiser();
  25604. /** Destructor. */
  25605. virtual ~Synthesiser();
  25606. /** Deletes all voices. */
  25607. void clearVoices();
  25608. /** Returns the number of voices that have been added. */
  25609. int getNumVoices() const throw() { return voices.size(); }
  25610. /** Returns one of the voices that have been added. */
  25611. SynthesiserVoice* getVoice (const int index) const throw();
  25612. /** Adds a new voice to the synth.
  25613. All the voices should be the same class of object and are treated equally.
  25614. The object passed in will be managed by the synthesiser, which will delete
  25615. it later on when no longer needed. The caller should not retain a pointer to the
  25616. voice.
  25617. */
  25618. void addVoice (SynthesiserVoice* const newVoice);
  25619. /** Deletes one of the voices. */
  25620. void removeVoice (const int index);
  25621. /** Deletes all sounds. */
  25622. void clearSounds();
  25623. /** Returns the number of sounds that have been added to the synth. */
  25624. int getNumSounds() const throw() { return sounds.size(); }
  25625. /** Returns one of the sounds. */
  25626. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25627. /** Adds a new sound to the synthesiser.
  25628. The object passed in is reference counted, so will be deleted when it is removed
  25629. from the synthesiser, and when no voices are still using it.
  25630. */
  25631. void addSound (const SynthesiserSound::Ptr& newSound);
  25632. /** Removes and deletes one of the sounds. */
  25633. void removeSound (const int index);
  25634. /** If set to true, then the synth will try to take over an existing voice if
  25635. it runs out and needs to play another note.
  25636. The value of this boolean is passed into findFreeVoice(), so the result will
  25637. depend on the implementation of this method.
  25638. */
  25639. void setNoteStealingEnabled (const bool shouldStealNotes);
  25640. /** Returns true if note-stealing is enabled.
  25641. @see setNoteStealingEnabled
  25642. */
  25643. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25644. /** Triggers a note-on event.
  25645. The default method here will find all the sounds that want to be triggered by
  25646. this note/channel. For each sound, it'll try to find a free voice, and use the
  25647. voice to start playing the sound.
  25648. Subclasses might want to override this if they need a more complex algorithm.
  25649. This method will be called automatically according to the midi data passed into
  25650. renderNextBlock(), but may be called explicitly too.
  25651. */
  25652. virtual void noteOn (const int midiChannel,
  25653. const int midiNoteNumber,
  25654. const float velocity);
  25655. /** Triggers a note-off event.
  25656. This will turn off any voices that are playing a sound for the given note/channel.
  25657. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25658. (if they can do). If this is false, the notes will all be cut off immediately.
  25659. This method will be called automatically according to the midi data passed into
  25660. renderNextBlock(), but may be called explicitly too.
  25661. */
  25662. virtual void noteOff (const int midiChannel,
  25663. const int midiNoteNumber,
  25664. const bool allowTailOff);
  25665. /** Turns off all notes.
  25666. This will turn off any voices that are playing a sound on the given midi channel.
  25667. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25668. which channel they're playing.
  25669. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25670. (if they can do). If this is false, the notes will all be cut off immediately.
  25671. This method will be called automatically according to the midi data passed into
  25672. renderNextBlock(), but may be called explicitly too.
  25673. */
  25674. virtual void allNotesOff (const int midiChannel,
  25675. const bool allowTailOff);
  25676. /** Sends a pitch-wheel message.
  25677. This will send a pitch-wheel message to any voices that are playing sounds on
  25678. the given midi channel.
  25679. This method will be called automatically according to the midi data passed into
  25680. renderNextBlock(), but may be called explicitly too.
  25681. @param midiChannel the midi channel for the event
  25682. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25683. */
  25684. virtual void handlePitchWheel (const int midiChannel,
  25685. const int wheelValue);
  25686. /** Sends a midi controller message.
  25687. This will send a midi controller message to any voices that are playing sounds on
  25688. the given midi channel.
  25689. This method will be called automatically according to the midi data passed into
  25690. renderNextBlock(), but may be called explicitly too.
  25691. @param midiChannel the midi channel for the event
  25692. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  25693. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  25694. */
  25695. virtual void handleController (const int midiChannel,
  25696. const int controllerNumber,
  25697. const int controllerValue);
  25698. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  25699. render.
  25700. This value is propagated to the voices so that they can use it to render the correct
  25701. pitches.
  25702. */
  25703. void setCurrentPlaybackSampleRate (const double sampleRate);
  25704. /** Creates the next block of audio output.
  25705. This will process the next numSamples of data from all the voices, and add that output
  25706. to the audio block supplied, starting from the offset specified. Note that the
  25707. data will be added to the current contents of the buffer, so you should clear it
  25708. before calling this method if necessary.
  25709. The midi events in the inputMidi buffer are parsed for note and controller events,
  25710. and these are used to trigger the voices. Note that the startSample offset applies
  25711. both to the audio output buffer and the midi input buffer, so any midi events
  25712. with timestamps outside the specified region will be ignored.
  25713. */
  25714. void renderNextBlock (AudioSampleBuffer& outputAudio,
  25715. const MidiBuffer& inputMidi,
  25716. int startSample,
  25717. int numSamples);
  25718. juce_UseDebuggingNewOperator
  25719. protected:
  25720. /** This is used to control access to the rendering callback and the note trigger methods. */
  25721. CriticalSection lock;
  25722. OwnedArray <SynthesiserVoice> voices;
  25723. ReferenceCountedArray <SynthesiserSound> sounds;
  25724. /** The last pitch-wheel values for each midi channel. */
  25725. int lastPitchWheelValues [16];
  25726. /** Searches through the voices to find one that's not currently playing, and which
  25727. can play the given sound.
  25728. Returns 0 if all voices are busy and stealing isn't enabled.
  25729. This can be overridden to implement custom voice-stealing algorithms.
  25730. */
  25731. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  25732. const bool stealIfNoneAvailable) const;
  25733. /** Starts a specified voice playing a particular sound.
  25734. You'll probably never need to call this, it's used internally by noteOn(), but
  25735. may be needed by subclasses for custom behaviours.
  25736. */
  25737. void startVoice (SynthesiserVoice* const voice,
  25738. SynthesiserSound* const sound,
  25739. const int midiChannel,
  25740. const int midiNoteNumber,
  25741. const float velocity);
  25742. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  25743. int findFreeVoice (const bool) const { return 0; }
  25744. private:
  25745. double sampleRate;
  25746. uint32 lastNoteOnCounter;
  25747. bool shouldStealNotes;
  25748. Synthesiser (const Synthesiser&);
  25749. const Synthesiser& operator= (const Synthesiser&);
  25750. };
  25751. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  25752. /********* End of inlined file: juce_Synthesiser.h *********/
  25753. /**
  25754. A subclass of SynthesiserSound that represents a sampled audio clip.
  25755. This is a pretty basic sampler, and just attempts to load the whole audio stream
  25756. into memory.
  25757. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25758. give it some SampledSound objects to play.
  25759. @see SamplerVoice, Synthesiser, SynthesiserSound
  25760. */
  25761. class JUCE_API SamplerSound : public SynthesiserSound
  25762. {
  25763. public:
  25764. /** Creates a sampled sound from an audio reader.
  25765. This will attempt to load the audio from the source into memory and store
  25766. it in this object.
  25767. @param name a name for the sample
  25768. @param source the audio to load. This object can be safely deleted by the
  25769. caller after this constructor returns
  25770. @param midiNotes the set of midi keys that this sound should be played on. This
  25771. is used by the SynthesiserSound::appliesToNote() method
  25772. @param midiNoteForNormalPitch the midi note at which the sample should be played
  25773. with its natural rate. All other notes will be pitched
  25774. up or down relative to this one
  25775. @param attackTimeSecs the attack (fade-in) time, in seconds
  25776. @param releaseTimeSecs the decay (fade-out) time, in seconds
  25777. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  25778. source, in seconds
  25779. */
  25780. SamplerSound (const String& name,
  25781. AudioFormatReader& source,
  25782. const BitArray& midiNotes,
  25783. const int midiNoteForNormalPitch,
  25784. const double attackTimeSecs,
  25785. const double releaseTimeSecs,
  25786. const double maxSampleLengthSeconds);
  25787. /** Destructor. */
  25788. ~SamplerSound();
  25789. /** Returns the sample's name */
  25790. const String& getName() const throw() { return name; }
  25791. /** Returns the audio sample data.
  25792. This could be 0 if there was a problem loading it.
  25793. */
  25794. AudioSampleBuffer* getAudioData() const throw() { return data; }
  25795. bool appliesToNote (const int midiNoteNumber);
  25796. bool appliesToChannel (const int midiChannel);
  25797. juce_UseDebuggingNewOperator
  25798. private:
  25799. friend class SamplerVoice;
  25800. String name;
  25801. AudioSampleBuffer* data;
  25802. double sourceSampleRate;
  25803. BitArray midiNotes;
  25804. int length, attackSamples, releaseSamples;
  25805. int midiRootNote;
  25806. };
  25807. /**
  25808. A subclass of SynthesiserVoice that can play a SamplerSound.
  25809. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25810. give it some SampledSound objects to play.
  25811. @see SamplerSound, Synthesiser, SynthesiserVoice
  25812. */
  25813. class JUCE_API SamplerVoice : public SynthesiserVoice
  25814. {
  25815. public:
  25816. /** Creates a SamplerVoice.
  25817. */
  25818. SamplerVoice();
  25819. /** Destructor. */
  25820. ~SamplerVoice();
  25821. bool canPlaySound (SynthesiserSound* sound);
  25822. void startNote (const int midiNoteNumber,
  25823. const float velocity,
  25824. SynthesiserSound* sound,
  25825. const int currentPitchWheelPosition);
  25826. void stopNote (const bool allowTailOff);
  25827. void pitchWheelMoved (const int newValue);
  25828. void controllerMoved (const int controllerNumber,
  25829. const int newValue);
  25830. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  25831. juce_UseDebuggingNewOperator
  25832. private:
  25833. double pitchRatio;
  25834. double sourceSamplePosition;
  25835. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  25836. bool isInAttack, isInRelease;
  25837. };
  25838. #endif // __JUCE_SAMPLER_JUCEHEADER__
  25839. /********* End of inlined file: juce_Sampler.h *********/
  25840. #endif
  25841. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25842. #endif
  25843. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25844. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  25845. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25846. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25847. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  25848. /**
  25849. Implements a plugin format manager for AudioUnits.
  25850. */
  25851. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  25852. {
  25853. public:
  25854. AudioUnitPluginFormat();
  25855. ~AudioUnitPluginFormat();
  25856. const String getName() const { return "AudioUnit"; }
  25857. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25858. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25859. bool fileMightContainThisPluginType (const File& file);
  25860. const FileSearchPath getDefaultLocationsToSearch();
  25861. juce_UseDebuggingNewOperator
  25862. private:
  25863. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  25864. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  25865. };
  25866. #endif
  25867. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25868. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  25869. #endif
  25870. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25871. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  25872. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25873. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25874. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  25875. // Sorry, this file is just a placeholder at the moment!...
  25876. /**
  25877. Implements a plugin format manager for DirectX plugins.
  25878. */
  25879. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  25880. {
  25881. public:
  25882. DirectXPluginFormat();
  25883. ~DirectXPluginFormat();
  25884. const String getName() const { return "DirectX"; }
  25885. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25886. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25887. bool fileMightContainThisPluginType (const File& file);
  25888. const FileSearchPath getDefaultLocationsToSearch();
  25889. juce_UseDebuggingNewOperator
  25890. private:
  25891. DirectXPluginFormat (const DirectXPluginFormat&);
  25892. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  25893. };
  25894. #endif
  25895. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25896. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  25897. #endif
  25898. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25899. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  25900. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25901. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25902. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  25903. // Sorry, this file is just a placeholder at the moment!...
  25904. /**
  25905. Implements a plugin format manager for DirectX plugins.
  25906. */
  25907. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  25908. {
  25909. public:
  25910. LADSPAPluginFormat();
  25911. ~LADSPAPluginFormat();
  25912. const String getName() const { return "LADSPA"; }
  25913. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25914. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25915. bool fileMightContainThisPluginType (const File& file);
  25916. const FileSearchPath getDefaultLocationsToSearch();
  25917. juce_UseDebuggingNewOperator
  25918. private:
  25919. LADSPAPluginFormat (const LADSPAPluginFormat&);
  25920. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  25921. };
  25922. #endif
  25923. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25924. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  25925. #endif
  25926. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25927. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  25928. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25929. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25930. #if JUCE_PLUGINHOST_VST
  25931. /**
  25932. Implements a plugin format manager for VSTs.
  25933. */
  25934. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  25935. {
  25936. public:
  25937. VSTPluginFormat();
  25938. ~VSTPluginFormat();
  25939. const String getName() const { return "VST"; }
  25940. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25941. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25942. bool fileMightContainThisPluginType (const File& file);
  25943. const FileSearchPath getDefaultLocationsToSearch();
  25944. juce_UseDebuggingNewOperator
  25945. private:
  25946. VSTPluginFormat (const VSTPluginFormat&);
  25947. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  25948. };
  25949. #endif
  25950. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25951. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  25952. #endif
  25953. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  25954. #endif
  25955. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  25956. #endif
  25957. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  25958. #endif
  25959. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  25960. #endif
  25961. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  25962. #endif
  25963. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  25964. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  25965. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  25966. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  25967. /**
  25968. Scans a directory for plugins, and adds them to a KnownPluginList.
  25969. To use one of these, create it and call scanNextFile() repeatedly, until
  25970. it returns false.
  25971. */
  25972. class JUCE_API PluginDirectoryScanner
  25973. {
  25974. public:
  25975. /**
  25976. Creates a scanner.
  25977. @param listToAddResultsTo this will get the new types added to it.
  25978. @param formatToLookFor this is the type of format that you want to look for
  25979. @param directoriesToSearch the path to search
  25980. @param searchRecursively true to search recursively
  25981. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  25982. be used as a file to store the names of any plugins
  25983. that crash during initialisation. If there are
  25984. any plugins listed in it, then these will always
  25985. be scanned after all other possible files have
  25986. been tried - in this way, even if there's a few
  25987. dodgy plugins in your path, then a couple of rescans
  25988. will still manage to find all the proper plugins.
  25989. It's probably best to choose a file in the user's
  25990. application data directory (alongside your app's
  25991. settings file) for this. The file format it uses
  25992. is just a list of filenames of the modules that
  25993. failed.
  25994. */
  25995. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  25996. AudioPluginFormat& formatToLookFor,
  25997. FileSearchPath directoriesToSearch,
  25998. const bool searchRecursively,
  25999. const File& deadMansPedalFile);
  26000. /** Destructor. */
  26001. ~PluginDirectoryScanner();
  26002. /** Tries the next likely-looking file.
  26003. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26004. re-tested if it's not already in the list, or if the file's modification
  26005. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26006. false, the file will always be reloaded and tested.
  26007. Returns false when there are no more files to try.
  26008. */
  26009. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26010. /** Returns the file that will be scanned during the next call to scanNextFile().
  26011. This is handy if you want to show the user which file is currently getting
  26012. scanned.
  26013. */
  26014. const File getNextPluginFileThatWillBeScanned() const throw();
  26015. /** Returns the estimated progress, between 0 and 1.
  26016. */
  26017. float getProgress() const { return progress; }
  26018. /** This returns a list of all the filenames of things that looked like being
  26019. a plugin file, but which failed to open for some reason.
  26020. */
  26021. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26022. juce_UseDebuggingNewOperator
  26023. private:
  26024. KnownPluginList& list;
  26025. AudioPluginFormat& format;
  26026. OwnedArray <File> filesToScan;
  26027. File deadMansPedalFile;
  26028. StringArray failedFiles;
  26029. int nextIndex;
  26030. float progress;
  26031. void recursiveFileSearch (const File& dir, const bool recursive);
  26032. const StringArray getDeadMansPedalFile() throw();
  26033. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26034. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26035. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26036. };
  26037. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26038. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26039. #endif
  26040. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26041. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26042. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26043. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26044. /********* Start of inlined file: juce_ListBox.h *********/
  26045. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26046. #define __JUCE_LISTBOX_JUCEHEADER__
  26047. class ListViewport;
  26048. /**
  26049. A subclass of this is used to drive a ListBox.
  26050. @see ListBox
  26051. */
  26052. class JUCE_API ListBoxModel
  26053. {
  26054. public:
  26055. /** Destructor. */
  26056. virtual ~ListBoxModel() {}
  26057. /** This has to return the number of items in the list.
  26058. @see ListBox::getNumRows()
  26059. */
  26060. virtual int getNumRows() = 0;
  26061. /** This method must be implemented to draw a row of the list.
  26062. */
  26063. virtual void paintListBoxItem (int rowNumber,
  26064. Graphics& g,
  26065. int width, int height,
  26066. bool rowIsSelected) = 0;
  26067. /** This is used to create or update a custom component to go in a row of the list.
  26068. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26069. and handle mouse clicks with listBoxItemClicked().
  26070. This method will be called whenever a custom component might need to be updated - e.g.
  26071. when the table is changed, or TableListBox::updateContent() is called.
  26072. If you don't need a custom component for the specified row, then return 0.
  26073. If you do want a custom component, and the existingComponentToUpdate is null, then
  26074. this method must create a suitable new component and return it.
  26075. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26076. by this method. In this case, the method must either update it to make sure it's correctly representing
  26077. the given row (which may be different from the one that the component was created for), or it can
  26078. delete this component and return a new one.
  26079. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26080. */
  26081. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26082. Component* existingComponentToUpdate);
  26083. /** This can be overridden to react to the user clicking on a row.
  26084. @see listBoxItemDoubleClicked
  26085. */
  26086. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26087. /** This can be overridden to react to the user double-clicking on a row.
  26088. @see listBoxItemClicked
  26089. */
  26090. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26091. /** This can be overridden to react to the user double-clicking on a part of the list where
  26092. there are no rows.
  26093. @see listBoxItemClicked
  26094. */
  26095. virtual void backgroundClicked();
  26096. /** Override this to be informed when rows are selected or deselected.
  26097. This will be called whenever a row is selected or deselected. If a range of
  26098. rows is selected all at once, this will just be called once for that event.
  26099. @param lastRowSelected the last row that the user selected. If no
  26100. rows are currently selected, this may be -1.
  26101. */
  26102. virtual void selectedRowsChanged (int lastRowSelected);
  26103. /** Override this to be informed when the delete key is pressed.
  26104. If no rows are selected when they press the key, this won't be called.
  26105. @param lastRowSelected the last row that had been selected when they pressed the
  26106. key - if there are multiple selections, this might not be
  26107. very useful
  26108. */
  26109. virtual void deleteKeyPressed (int lastRowSelected);
  26110. /** Override this to be informed when the return key is pressed.
  26111. If no rows are selected when they press the key, this won't be called.
  26112. @param lastRowSelected the last row that had been selected when they pressed the
  26113. key - if there are multiple selections, this might not be
  26114. very useful
  26115. */
  26116. virtual void returnKeyPressed (int lastRowSelected);
  26117. /** Override this to be informed when the list is scrolled.
  26118. This might be caused by the user moving the scrollbar, or by programmatic changes
  26119. to the list position.
  26120. */
  26121. virtual void listWasScrolled();
  26122. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26123. If this returns a non-empty name then when the user drags a row, the listbox will
  26124. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26125. a drag-and-drop operation, using this string as the source description, with the listbox
  26126. itself as the source component.
  26127. @see DragAndDropContainer::startDragging
  26128. */
  26129. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26130. };
  26131. /**
  26132. A list of items that can be scrolled vertically.
  26133. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26134. either paint each row of the list and respond to events via callbacks, or for
  26135. more specialised tasks, it can supply a custom component to fill each row.
  26136. @see ComboBox, TableListBox
  26137. */
  26138. class JUCE_API ListBox : public Component,
  26139. public SettableTooltipClient
  26140. {
  26141. public:
  26142. /** Creates a ListBox.
  26143. The model pointer passed-in can be null, in which case you can set it later
  26144. with setModel().
  26145. */
  26146. ListBox (const String& componentName,
  26147. ListBoxModel* const model);
  26148. /** Destructor. */
  26149. ~ListBox();
  26150. /** Changes the current data model to display. */
  26151. void setModel (ListBoxModel* const newModel);
  26152. /** Returns the current list model. */
  26153. ListBoxModel* getModel() const throw() { return model; }
  26154. /** Causes the list to refresh its content.
  26155. Call this when the number of rows in the list changes, or if you want it
  26156. to call refreshComponentForRow() on all the row components.
  26157. Be careful not to call it from a different thread, though, as it's not
  26158. thread-safe.
  26159. */
  26160. void updateContent();
  26161. /** Turns on multiple-selection of rows.
  26162. By default this is disabled.
  26163. When your row component gets clicked you'll need to call the
  26164. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26165. clicked and to get it to do the appropriate selection based on whether
  26166. the ctrl/shift keys are held down.
  26167. */
  26168. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26169. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26170. This function is here primarily for the ComboBox class to use, but might be
  26171. useful for some other purpose too.
  26172. */
  26173. void setMouseMoveSelectsRows (bool shouldSelect);
  26174. /** Selects a row.
  26175. If the row is already selected, this won't do anything.
  26176. @param rowNumber the row to select
  26177. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26178. the selected row is off-screen, it'll scroll to make
  26179. sure that row is on-screen
  26180. @param deselectOthersFirst if true and there are multiple selections, these will
  26181. first be deselected before this item is selected
  26182. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26183. deselectAllRows, selectRangeOfRows
  26184. */
  26185. void selectRow (const int rowNumber,
  26186. bool dontScrollToShowThisRow = false,
  26187. bool deselectOthersFirst = true);
  26188. /** Selects a set of rows.
  26189. This will add these rows to the current selection, so you might need to
  26190. clear the current selection first with deselectAllRows()
  26191. @param firstRow the first row to select (inclusive)
  26192. @param lastRow the last row to select (inclusive)
  26193. */
  26194. void selectRangeOfRows (int firstRow,
  26195. int lastRow);
  26196. /** Deselects a row.
  26197. If it's not currently selected, this will do nothing.
  26198. @see selectRow, deselectAllRows
  26199. */
  26200. void deselectRow (const int rowNumber);
  26201. /** Deselects any currently selected rows.
  26202. @see deselectRow
  26203. */
  26204. void deselectAllRows();
  26205. /** Selects or deselects a row.
  26206. If the row's currently selected, this deselects it, and vice-versa.
  26207. */
  26208. void flipRowSelection (const int rowNumber);
  26209. /** Returns a sparse set indicating the rows that are currently selected.
  26210. @see setSelectedRows
  26211. */
  26212. const SparseSet<int> getSelectedRows() const;
  26213. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26214. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26215. method will be called. If it's false, no notification will be sent to the model.
  26216. @see getSelectedRows
  26217. */
  26218. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26219. const bool sendNotificationEventToModel = true);
  26220. /** Checks whether a row is selected.
  26221. */
  26222. bool isRowSelected (const int rowNumber) const;
  26223. /** Returns the number of rows that are currently selected.
  26224. @see getSelectedRow, isRowSelected, getLastRowSelected
  26225. */
  26226. int getNumSelectedRows() const;
  26227. /** Returns the row number of a selected row.
  26228. This will return the row number of the Nth selected row. The row numbers returned will
  26229. be sorted in order from low to high.
  26230. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26231. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26232. selected
  26233. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26234. */
  26235. int getSelectedRow (const int index = 0) const;
  26236. /** Returns the last row that the user selected.
  26237. This isn't the same as the highest row number that is currently selected - if the user
  26238. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26239. If nothing is selected, it will return -1.
  26240. */
  26241. int getLastRowSelected() const;
  26242. /** Multiply-selects rows based on the modifier keys.
  26243. If no modifier keys are down, this will select the given row and
  26244. deselect any others.
  26245. If the ctrl (or command on the Mac) key is down, it'll flip the
  26246. state of the selected row.
  26247. If the shift key is down, it'll select up to the given row from the
  26248. last row selected.
  26249. @see selectRow
  26250. */
  26251. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26252. const ModifierKeys& modifiers);
  26253. /** Scrolls the list to a particular position.
  26254. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26255. 1.0 scrolls to the bottom.
  26256. If the total number of rows all fit onto the screen at once, then this
  26257. method won't do anything.
  26258. @see getVerticalPosition
  26259. */
  26260. void setVerticalPosition (const double newProportion);
  26261. /** Returns the current vertical position as a proportion of the total.
  26262. This can be used in conjunction with setVerticalPosition() to save and restore
  26263. the list's position. It returns a value in the range 0 to 1.
  26264. @see setVerticalPosition
  26265. */
  26266. double getVerticalPosition() const;
  26267. /** Scrolls if necessary to make sure that a particular row is visible.
  26268. */
  26269. void scrollToEnsureRowIsOnscreen (const int row);
  26270. /** Returns a pointer to the scrollbar.
  26271. (Unlikely to be useful for most people).
  26272. */
  26273. ScrollBar* getVerticalScrollBar() const throw();
  26274. /** Returns a pointer to the scrollbar.
  26275. (Unlikely to be useful for most people).
  26276. */
  26277. ScrollBar* getHorizontalScrollBar() const throw();
  26278. /** Finds the row index that contains a given x,y position.
  26279. The position is relative to the ListBox's top-left.
  26280. If no row exists at this position, the method will return -1.
  26281. @see getComponentForRowNumber
  26282. */
  26283. int getRowContainingPosition (const int x, const int y) const throw();
  26284. /** Finds a row index that would be the most suitable place to insert a new
  26285. item for a given position.
  26286. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26287. because it lets you easily choose the best position to insert the item that
  26288. they drop, based on where they drop it.
  26289. If the position is out of range, this will return -1. If the position is
  26290. beyond the end of the list, it will return getNumRows() to indicate the end
  26291. of the list.
  26292. @see getComponentForRowNumber
  26293. */
  26294. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26295. /** Returns the position of one of the rows, relative to the top-left of
  26296. the listbox.
  26297. This may be off-screen, and the range of the row number that is passed-in is
  26298. not checked to see if it's a valid row.
  26299. */
  26300. const Rectangle getRowPosition (const int rowNumber,
  26301. const bool relativeToComponentTopLeft) const throw();
  26302. /** Finds the row component for a given row in the list.
  26303. The component returned will have been created using createRowComponent().
  26304. If the component for this row is off-screen or if the row is out-of-range,
  26305. this will return 0.
  26306. @see getRowContainingPosition
  26307. */
  26308. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26309. /** Returns the row number that the given component represents.
  26310. If the component isn't one of the list's rows, this will return -1.
  26311. */
  26312. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26313. /** Returns the width of a row (which may be less than the width of this component
  26314. if there's a scrollbar).
  26315. */
  26316. int getVisibleRowWidth() const throw();
  26317. /** Sets the height of each row in the list.
  26318. The default height is 22 pixels.
  26319. @see getRowHeight
  26320. */
  26321. void setRowHeight (const int newHeight);
  26322. /** Returns the height of a row in the list.
  26323. @see setRowHeight
  26324. */
  26325. int getRowHeight() const throw() { return rowHeight; }
  26326. /** Returns the number of rows actually visible.
  26327. This is the number of whole rows which will fit on-screen, so the value might
  26328. be more than the actual number of rows in the list.
  26329. */
  26330. int getNumRowsOnScreen() const throw();
  26331. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26332. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26333. methods.
  26334. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26335. */
  26336. enum ColourIds
  26337. {
  26338. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26339. Make this transparent if you don't want the background to be filled. */
  26340. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26341. Make this transparent to not have an outline. */
  26342. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26343. };
  26344. /** Sets the thickness of a border that will be drawn around the box.
  26345. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26346. @see outlineColourId
  26347. */
  26348. void setOutlineThickness (const int outlineThickness);
  26349. /** Returns the thickness of outline that will be drawn around the listbox.
  26350. @see setOutlineColour
  26351. */
  26352. int getOutlineThickness() const throw() { return outlineThickness; }
  26353. /** Sets a component that the list should use as a header.
  26354. This will position the given component at the top of the list, maintaining the
  26355. height of the component passed-in, but rescaling it horizontally to match the
  26356. width of the items in the listbox.
  26357. The component will be deleted when setHeaderComponent() is called with a
  26358. different component, or when the listbox is deleted.
  26359. */
  26360. void setHeaderComponent (Component* const newHeaderComponent);
  26361. /** Changes the width of the rows in the list.
  26362. This can be used to make the list's row components wider than the list itself - the
  26363. width of the rows will be either the width of the list or this value, whichever is
  26364. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26365. appear.
  26366. The default value for this is 0, which means that the rows will always
  26367. be the same width as the list.
  26368. */
  26369. void setMinimumContentWidth (const int newMinimumWidth);
  26370. /** Returns the space currently available for the row items, taking into account
  26371. borders, scrollbars, etc.
  26372. */
  26373. int getVisibleContentWidth() const throw();
  26374. /** Repaints one of the rows.
  26375. This is a lightweight alternative to calling updateContent, and just causes a
  26376. repaint of the row's area.
  26377. */
  26378. void repaintRow (const int rowNumber) throw();
  26379. /** This fairly obscure method creates an image that just shows the currently
  26380. selected row components.
  26381. It's a handy method for doing drag-and-drop, as it can be passed to the
  26382. DragAndDropContainer for use as the drag image.
  26383. Note that it will make the row components temporarily invisible, so if you're
  26384. using custom components this could affect them if they're sensitive to that
  26385. sort of thing.
  26386. @see Component::createComponentSnapshot
  26387. */
  26388. Image* createSnapshotOfSelectedRows();
  26389. /** Returns the viewport that this ListBox uses.
  26390. You may need to use this to change parameters such as whether scrollbars
  26391. are shown, etc.
  26392. */
  26393. Viewport* getViewport() const throw();
  26394. /** @internal */
  26395. bool keyPressed (const KeyPress& key);
  26396. /** @internal */
  26397. bool keyStateChanged();
  26398. /** @internal */
  26399. void paint (Graphics& g);
  26400. /** @internal */
  26401. void paintOverChildren (Graphics& g);
  26402. /** @internal */
  26403. void resized();
  26404. /** @internal */
  26405. void visibilityChanged();
  26406. /** @internal */
  26407. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26408. /** @internal */
  26409. void mouseMove (const MouseEvent&);
  26410. /** @internal */
  26411. void mouseExit (const MouseEvent&);
  26412. /** @internal */
  26413. void mouseUp (const MouseEvent&);
  26414. /** @internal */
  26415. void colourChanged();
  26416. juce_UseDebuggingNewOperator
  26417. private:
  26418. friend class ListViewport;
  26419. friend class TableListBox;
  26420. ListBoxModel* model;
  26421. ListViewport* viewport;
  26422. Component* headerComponent;
  26423. int totalItems, rowHeight, minimumRowWidth;
  26424. int outlineThickness;
  26425. int lastMouseX, lastMouseY, lastRowSelected;
  26426. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26427. SparseSet <int> selected;
  26428. void selectRowInternal (const int rowNumber,
  26429. bool dontScrollToShowThisRow,
  26430. bool deselectOthersFirst,
  26431. bool isMouseClick);
  26432. ListBox (const ListBox&);
  26433. const ListBox& operator= (const ListBox&);
  26434. };
  26435. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26436. /********* End of inlined file: juce_ListBox.h *********/
  26437. /********* Start of inlined file: juce_TextButton.h *********/
  26438. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26439. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26440. /**
  26441. A button that uses the standard lozenge-shaped background with a line of
  26442. text on it.
  26443. @see Button, DrawableButton
  26444. */
  26445. class JUCE_API TextButton : public Button
  26446. {
  26447. public:
  26448. /** Creates a TextButton.
  26449. @param buttonName the text to put in the button (the component's name is also
  26450. initially set to this string, but these can be changed later
  26451. using the setName() and setButtonText() methods)
  26452. @param toolTip an optional string to use as a toolip
  26453. @see Button
  26454. */
  26455. TextButton (const String& buttonName,
  26456. const String& toolTip = String::empty);
  26457. /** Destructor. */
  26458. ~TextButton();
  26459. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26460. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26461. methods.
  26462. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26463. */
  26464. enum ColourIds
  26465. {
  26466. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26467. 'off'). The look-and-feel class might re-interpret this to add
  26468. effects, etc. */
  26469. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26470. 'on'). The look-and-feel class might re-interpret this to add
  26471. effects, etc. */
  26472. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26473. };
  26474. /** Resizes the button to fit neatly around its current text.
  26475. If newHeight is >= 0, the button's height will be changed to this
  26476. value. If it's less than zero, its height will be unaffected.
  26477. */
  26478. void changeWidthToFitText (const int newHeight = -1);
  26479. /** This can be overridden to use different fonts than the default one.
  26480. Note that you'll need to set the font's size appropriately, too.
  26481. */
  26482. virtual const Font getFont();
  26483. juce_UseDebuggingNewOperator
  26484. protected:
  26485. /** @internal */
  26486. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26487. /** @internal */
  26488. void colourChanged();
  26489. private:
  26490. TextButton (const TextButton&);
  26491. const TextButton& operator= (const TextButton&);
  26492. };
  26493. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26494. /********* End of inlined file: juce_TextButton.h *********/
  26495. /**
  26496. A component displaying a list of plugins, with options to scan for them,
  26497. add, remove and sort them.
  26498. */
  26499. class JUCE_API PluginListComponent : public Component,
  26500. public ListBoxModel,
  26501. public ChangeListener,
  26502. public ButtonListener,
  26503. public Timer
  26504. {
  26505. public:
  26506. /**
  26507. Creates the list component.
  26508. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26509. The properties file, if supplied, is used to store the user's last search paths.
  26510. */
  26511. PluginListComponent (KnownPluginList& listToRepresent,
  26512. const File& deadMansPedalFile,
  26513. PropertiesFile* const propertiesToUse);
  26514. /** Destructor. */
  26515. ~PluginListComponent();
  26516. /** @internal */
  26517. void resized();
  26518. /** @internal */
  26519. bool isInterestedInFileDrag (const StringArray& files);
  26520. /** @internal */
  26521. void filesDropped (const StringArray& files, int, int);
  26522. /** @internal */
  26523. int getNumRows();
  26524. /** @internal */
  26525. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26526. /** @internal */
  26527. void deleteKeyPressed (int lastRowSelected);
  26528. /** @internal */
  26529. void buttonClicked (Button* b);
  26530. /** @internal */
  26531. void changeListenerCallback (void*);
  26532. /** @internal */
  26533. void timerCallback();
  26534. juce_UseDebuggingNewOperator
  26535. private:
  26536. KnownPluginList& list;
  26537. File deadMansPedalFile;
  26538. ListBox* listBox;
  26539. TextButton* optionsButton;
  26540. PropertiesFile* propertiesToUse;
  26541. int typeToScan;
  26542. void scanFor (AudioPluginFormat* format);
  26543. PluginListComponent (const PluginListComponent&);
  26544. const PluginListComponent& operator= (const PluginListComponent&);
  26545. };
  26546. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26547. /********* End of inlined file: juce_PluginListComponent.h *********/
  26548. #endif
  26549. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26550. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  26551. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26552. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26553. /********* Start of inlined file: juce_AudioFormat.h *********/
  26554. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26555. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26556. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  26557. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26558. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26559. /**
  26560. Writes samples to an audio file stream.
  26561. A subclass that writes a specific type of audio format will be created by
  26562. an AudioFormat object.
  26563. After creating one of these with the AudioFormat::createWriterFor() method
  26564. you can call its write() method to store the samples, and then delete it.
  26565. @see AudioFormat, AudioFormatReader
  26566. */
  26567. class JUCE_API AudioFormatWriter
  26568. {
  26569. protected:
  26570. /** Creates an AudioFormatWriter object.
  26571. @param destStream the stream to write to - this will be deleted
  26572. by this object when it is no longer needed
  26573. @param formatName the description that will be returned by the getFormatName()
  26574. method
  26575. @param sampleRate the sample rate to use - the base class just stores
  26576. this value, it doesn't do anything with it
  26577. @param numberOfChannels the number of channels to write - the base class just stores
  26578. this value, it doesn't do anything with it
  26579. @param bitsPerSample the bit depth of the stream - the base class just stores
  26580. this value, it doesn't do anything with it
  26581. */
  26582. AudioFormatWriter (OutputStream* const destStream,
  26583. const String& formatName,
  26584. const double sampleRate,
  26585. const unsigned int numberOfChannels,
  26586. const unsigned int bitsPerSample);
  26587. public:
  26588. /** Destructor. */
  26589. virtual ~AudioFormatWriter();
  26590. /** Returns a description of what type of format this is.
  26591. E.g. "AIFF file"
  26592. */
  26593. const String getFormatName() const throw() { return formatName; }
  26594. /** Writes a set of samples to the audio stream.
  26595. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  26596. can use AudioSampleBuffer::writeToAudioWriter().
  26597. @param samplesToWrite an array of arrays containing the sample data for
  26598. each channel to write. This is a zero-terminated
  26599. array of arrays, and can contain a different number
  26600. of channels than the actual stream uses, and the
  26601. writer should do its best to cope with this.
  26602. If the format is fixed-point, each channel will be formatted
  26603. as an array of signed integers using the full 32-bit
  26604. range -0x80000000 to 0x7fffffff, regardless of the source's
  26605. bit-depth. If it is a floating-point format, you should treat
  26606. the arrays as arrays of floats, and just cast it to an (int**)
  26607. to pass it into the method.
  26608. @param numSamples the number of samples to write
  26609. */
  26610. virtual bool write (const int** samplesToWrite,
  26611. int numSamples) = 0;
  26612. /** Reads a section of samples from an AudioFormatReader, and writes these to
  26613. the output.
  26614. This will take care of any floating-point conversion that's required to convert
  26615. between the two formats. It won't deal with sample-rate conversion, though.
  26616. @returns false if it can't read or write properly during the operation
  26617. */
  26618. bool writeFromAudioReader (AudioFormatReader& reader,
  26619. int64 startSample,
  26620. int numSamplesToRead);
  26621. /** Reads some samples from an AudioSource, and writes these to the output.
  26622. The source must already have been initialised with the AudioSource::prepareToPlay() method
  26623. @param source the source to read from
  26624. @param numSamplesToRead total number of samples to read and write
  26625. @param samplesPerBlock the maximum number of samples to fetch from the source
  26626. @returns false if it can't read or write properly during the operation
  26627. */
  26628. bool writeFromAudioSource (AudioSource& source,
  26629. int numSamplesToRead,
  26630. const int samplesPerBlock = 2048);
  26631. /** Returns the sample rate being used. */
  26632. double getSampleRate() const throw() { return sampleRate; }
  26633. /** Returns the number of channels being written. */
  26634. int getNumChannels() const throw() { return numChannels; }
  26635. /** Returns the bit-depth of the data being written. */
  26636. int getBitsPerSample() const throw() { return bitsPerSample; }
  26637. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  26638. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  26639. juce_UseDebuggingNewOperator
  26640. protected:
  26641. /** The sample rate of the stream. */
  26642. double sampleRate;
  26643. /** The number of channels being written to the stream. */
  26644. unsigned int numChannels;
  26645. /** The bit depth of the file. */
  26646. unsigned int bitsPerSample;
  26647. /** True if it's a floating-point format, false if it's fixed-point. */
  26648. bool usesFloatingPointData;
  26649. /** The output stream for Use by subclasses. */
  26650. OutputStream* output;
  26651. private:
  26652. String formatName;
  26653. };
  26654. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26655. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  26656. /**
  26657. Subclasses of AudioFormat are used to read and write different audio
  26658. file formats.
  26659. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  26660. */
  26661. class JUCE_API AudioFormat
  26662. {
  26663. public:
  26664. /** Destructor. */
  26665. virtual ~AudioFormat();
  26666. /** Returns the name of this format.
  26667. e.g. "WAV file" or "AIFF file"
  26668. */
  26669. const String& getFormatName() const;
  26670. /** Returns all the file extensions that might apply to a file of this format.
  26671. The first item will be the one that's preferred when creating a new file.
  26672. So for a wav file this might just return ".wav"; for an AIFF file it might
  26673. return two items, ".aif" and ".aiff"
  26674. */
  26675. const StringArray& getFileExtensions() const;
  26676. /** Returns true if this the given file can be read by this format.
  26677. Subclasses shouldn't do too much work here, just check the extension or
  26678. file type. The base class implementation just checks the file's extension
  26679. against one of the ones that was registered in the constructor.
  26680. */
  26681. virtual bool canHandleFile (const File& fileToTest);
  26682. /** Returns a set of sample rates that the format can read and write. */
  26683. virtual const Array <int> getPossibleSampleRates() = 0;
  26684. /** Returns a set of bit depths that the format can read and write. */
  26685. virtual const Array <int> getPossibleBitDepths() = 0;
  26686. /** Returns true if the format can do 2-channel audio. */
  26687. virtual bool canDoStereo() = 0;
  26688. /** Returns true if the format can do 1-channel audio. */
  26689. virtual bool canDoMono() = 0;
  26690. /** Returns true if the format uses compressed data. */
  26691. virtual bool isCompressed();
  26692. /** Returns a list of different qualities that can be used when writing.
  26693. Non-compressed formats will just return an empty array, but for something
  26694. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  26695. When calling createWriterFor(), an index from this array is passed in to
  26696. tell the format which option is required.
  26697. */
  26698. virtual const StringArray getQualityOptions();
  26699. /** Tries to create an object that can read from a stream containing audio
  26700. data in this format.
  26701. The reader object that is returned can be used to read from the stream, and
  26702. should then be deleted by the caller.
  26703. @param sourceStream the stream to read from - the AudioFormatReader object
  26704. that is returned will delete this stream when it no longer
  26705. needs it.
  26706. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  26707. should delete the stream object that was passed-in. (If a valid
  26708. reader is returned, it will always be in charge of deleting the
  26709. stream, so this parameter is ignored)
  26710. @see AudioFormatReader
  26711. */
  26712. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26713. const bool deleteStreamIfOpeningFails) = 0;
  26714. /** Tries to create an object that can write to a stream with this audio format.
  26715. The writer object that is returned can be used to write to the stream, and
  26716. should then be deleted by the caller.
  26717. If the stream can't be created for some reason (e.g. the parameters passed in
  26718. here aren't suitable), this will return 0.
  26719. @param streamToWriteTo the stream that the data will go to - this will be
  26720. deleted by the AudioFormatWriter object when it's no longer
  26721. needed. If no AudioFormatWriter can be created by this method,
  26722. the stream will NOT be deleted, so that the caller can re-use it
  26723. to try to open a different format, etc
  26724. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  26725. returned by getPossibleSampleRates()
  26726. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  26727. the choice will depend on the results of canDoMono() and
  26728. canDoStereo()
  26729. @param bitsPerSample the bits per sample to use - this must be one of the values
  26730. returned by getPossibleBitDepths()
  26731. @param metadataValues a set of metadata values that the writer should try to write
  26732. to the stream. Exactly what these are depends on the format,
  26733. and the subclass doesn't actually have to do anything with
  26734. them if it doesn't want to. Have a look at the specific format
  26735. implementation classes to see possible values that can be
  26736. used
  26737. @param qualityOptionIndex the index of one of compression qualities returned by the
  26738. getQualityOptions() method. If there aren't any quality options
  26739. for this format, just pass 0 in this parameter, as it'll be
  26740. ignored
  26741. @see AudioFormatWriter
  26742. */
  26743. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26744. double sampleRateToUse,
  26745. unsigned int numberOfChannels,
  26746. int bitsPerSample,
  26747. const StringPairArray& metadataValues,
  26748. int qualityOptionIndex) = 0;
  26749. protected:
  26750. /** Creates an AudioFormat object.
  26751. @param formatName this sets the value that will be returned by getFormatName()
  26752. @param fileExtensions a zero-terminated list of file extensions - this is what will
  26753. be returned by getFileExtension()
  26754. */
  26755. AudioFormat (const String& formatName,
  26756. const tchar** const fileExtensions);
  26757. private:
  26758. String formatName;
  26759. StringArray fileExtensions;
  26760. };
  26761. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  26762. /********* End of inlined file: juce_AudioFormat.h *********/
  26763. /**
  26764. Reads and Writes AIFF format audio files.
  26765. @see AudioFormat
  26766. */
  26767. class JUCE_API AiffAudioFormat : public AudioFormat
  26768. {
  26769. public:
  26770. /** Creates an format object. */
  26771. AiffAudioFormat();
  26772. /** Destructor. */
  26773. ~AiffAudioFormat();
  26774. const Array <int> getPossibleSampleRates();
  26775. const Array <int> getPossibleBitDepths();
  26776. bool canDoStereo();
  26777. bool canDoMono();
  26778. #if JUCE_MAC
  26779. bool canHandleFile (const File& fileToTest);
  26780. #endif
  26781. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26782. const bool deleteStreamIfOpeningFails);
  26783. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26784. double sampleRateToUse,
  26785. unsigned int numberOfChannels,
  26786. int bitsPerSample,
  26787. const StringPairArray& metadataValues,
  26788. int qualityOptionIndex);
  26789. juce_UseDebuggingNewOperator
  26790. };
  26791. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26792. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  26793. #endif
  26794. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26795. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  26796. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26797. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26798. /**
  26799. */
  26800. class AudioCDBurner
  26801. {
  26802. public:
  26803. /** Returns a list of available optical drives.
  26804. Use openDevice() to open one of the items from this list.
  26805. */
  26806. static const StringArray findAvailableDevices();
  26807. /** Tries to open one of the optical drives.
  26808. The deviceIndex is an index into the array returned by findAvailableDevices().
  26809. */
  26810. static AudioCDBurner* openDevice (const int deviceIndex);
  26811. /** Destructor. */
  26812. ~AudioCDBurner();
  26813. /** Returns true if there's a writable disk in the drive.
  26814. */
  26815. bool isDiskPresent() const;
  26816. /** Returns the number of free blocks on the disk.
  26817. There are 75 blocks per second, at 44100Hz.
  26818. */
  26819. int getNumAvailableAudioBlocks() const;
  26820. /** Adds a track to be written.
  26821. The source passed-in here will be kept by this object, and it will
  26822. be used and deleted at some point in the future, either during the
  26823. burn() method or when this AudioCDBurner object is deleted. Your caller
  26824. method shouldn't keep a reference to it or use it again after passing
  26825. it in here.
  26826. */
  26827. bool addAudioTrack (AudioSource* source, int numSamples);
  26828. /**
  26829. Return true to cancel the current burn operation
  26830. */
  26831. class BurnProgressListener
  26832. {
  26833. public:
  26834. BurnProgressListener() throw() {}
  26835. virtual ~BurnProgressListener() {}
  26836. /** Called at intervals to report on the progress of the AudioCDBurner.
  26837. To cancel the burn, return true from this.
  26838. */
  26839. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  26840. };
  26841. const String burn (BurnProgressListener* listener,
  26842. const bool ejectDiscAfterwards,
  26843. const bool peformFakeBurnForTesting);
  26844. juce_UseDebuggingNewOperator
  26845. private:
  26846. AudioCDBurner (const int deviceIndex);
  26847. void* internal;
  26848. };
  26849. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26850. /********* End of inlined file: juce_AudioCDBurner.h *********/
  26851. #endif
  26852. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26853. /********* Start of inlined file: juce_AudioCDReader.h *********/
  26854. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26855. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  26856. #if JUCE_MAC
  26857. #endif
  26858. /**
  26859. A type of AudioFormatReader that reads from an audio CD.
  26860. One of these can be used to read a CD as if it's one big audio stream. Use the
  26861. getPositionOfTrackStart() method to find where the individual tracks are
  26862. within the stream.
  26863. @see AudioFormatReader
  26864. */
  26865. class JUCE_API AudioCDReader : public AudioFormatReader
  26866. {
  26867. public:
  26868. /** Returns a list of names of Audio CDs currently available for reading.
  26869. If there's a CD drive but no CD in it, this might return an empty list, or
  26870. possibly a device that can be opened but which has no tracks, depending
  26871. on the platform.
  26872. @see createReaderForCD
  26873. */
  26874. static const StringArray getAvailableCDNames();
  26875. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  26876. @param index the index of one of the available CDs - use getAvailableCDNames()
  26877. to find out how many there are.
  26878. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  26879. caller will be responsible for deleting the object returned.
  26880. */
  26881. static AudioCDReader* createReaderForCD (const int index);
  26882. /** Destructor. */
  26883. ~AudioCDReader();
  26884. /** Implementation of the AudioFormatReader method. */
  26885. bool read (int** destSamples,
  26886. int64 startSampleInFile,
  26887. int numSamples);
  26888. /** Checks whether the CD has been removed from the drive.
  26889. */
  26890. bool isCDStillPresent() const;
  26891. /** Returns the total number of tracks (audio + data).
  26892. */
  26893. int getNumTracks() const;
  26894. /** Finds the sample offset of the start of a track.
  26895. @param trackNum the track number, where 0 is the first track.
  26896. */
  26897. int getPositionOfTrackStart (int trackNum) const;
  26898. /** Returns true if a given track is an audio track.
  26899. @param trackNum the track number, where 0 is the first track.
  26900. */
  26901. bool isTrackAudio (int trackNum) const;
  26902. /** Refreshes the object's table of contents.
  26903. If the disc has been ejected and a different one put in since this
  26904. object was created, this will cause it to update its idea of how many tracks
  26905. there are, etc.
  26906. */
  26907. void refreshTrackLengths();
  26908. /** Enables scanning for indexes within tracks.
  26909. @see getLastIndex
  26910. */
  26911. void enableIndexScanning (bool enabled);
  26912. /** Returns the index number found during the last read() call.
  26913. Index scanning is turned off by default - turn it on with enableIndexScanning().
  26914. Then when the read() method is called, if it comes across an index within that
  26915. block, the index number is stored and returned by this method.
  26916. Some devices might not support indexes, of course.
  26917. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  26918. @see enableIndexScanning
  26919. */
  26920. int getLastIndex() const;
  26921. /** Scans a track to find the position of any indexes within it.
  26922. @param trackNumber the track to look in, where 0 is the first track on the disc
  26923. @returns an array of sample positions of any index points found (not including
  26924. the index that marks the start of the track)
  26925. */
  26926. const Array <int> findIndexesInTrack (const int trackNumber);
  26927. /** Returns the CDDB id number for the CD.
  26928. It's not a great way of identifying a disc, but it's traditional.
  26929. */
  26930. int getCDDBId();
  26931. /** Tries to eject the disk.
  26932. Of course this might not be possible, if some other process is using it.
  26933. */
  26934. void ejectDisk();
  26935. juce_UseDebuggingNewOperator
  26936. private:
  26937. #if JUCE_MAC
  26938. File volumeDir;
  26939. OwnedArray<File> tracks;
  26940. Array <int> trackStartSamples;
  26941. int currentReaderTrack;
  26942. AudioFormatReader* reader;
  26943. AudioCDReader (const File& volume);
  26944. public:
  26945. static int compareElements (const File* const, const File* const) throw();
  26946. private:
  26947. #elif JUCE_WIN32
  26948. int numTracks;
  26949. int trackStarts[100];
  26950. bool audioTracks [100];
  26951. void* handle;
  26952. bool indexingEnabled;
  26953. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  26954. MemoryBlock buffer;
  26955. AudioCDReader (void* handle);
  26956. int getIndexAt (int samplePos);
  26957. #elif JUCE_LINUX
  26958. AudioCDReader();
  26959. #endif
  26960. AudioCDReader (const AudioCDReader&);
  26961. const AudioCDReader& operator= (const AudioCDReader&);
  26962. };
  26963. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  26964. /********* End of inlined file: juce_AudioCDReader.h *********/
  26965. #endif
  26966. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26967. #endif
  26968. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  26969. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  26970. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  26971. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  26972. /**
  26973. A class for keeping a list of available audio formats, and for deciding which
  26974. one to use to open a given file.
  26975. You can either use this class as a singleton object, or create instances of it
  26976. yourself. Once created, use its registerFormat() method to tell it which
  26977. formats it should use.
  26978. @see AudioFormat
  26979. */
  26980. class JUCE_API AudioFormatManager
  26981. {
  26982. public:
  26983. /** Creates an empty format manager.
  26984. Before it'll be any use, you'll need to call registerFormat() with all the
  26985. formats you want it to be able to recognise.
  26986. */
  26987. AudioFormatManager();
  26988. /** Destructor. */
  26989. ~AudioFormatManager();
  26990. juce_DeclareSingleton (AudioFormatManager, false);
  26991. /** Adds a format to the manager's list of available file types.
  26992. The object passed-in will be deleted by this object, so don't keep a pointer
  26993. to it!
  26994. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  26995. return this one when called.
  26996. */
  26997. void registerFormat (AudioFormat* newFormat,
  26998. const bool makeThisTheDefaultFormat);
  26999. /** Handy method to make it easy to register the formats that come with Juce.
  27000. Currently, this will add WAV and AIFF to the list.
  27001. */
  27002. void registerBasicFormats();
  27003. /** Clears the list of known formats. */
  27004. void clearFormats();
  27005. /** Returns the number of currently registered file formats. */
  27006. int getNumKnownFormats() const;
  27007. /** Returns one of the registered file formats. */
  27008. AudioFormat* getKnownFormat (const int index) const;
  27009. /** Looks for which of the known formats is listed as being for a given file
  27010. extension.
  27011. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27012. */
  27013. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27014. /** Returns the format which has been set as the default one.
  27015. You can set a format as being the default when it is registered. It's useful
  27016. when you want to write to a file, because the best format may change between
  27017. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27018. If none has been set as the default, this method will just return the first
  27019. one in the list.
  27020. */
  27021. AudioFormat* getDefaultFormat() const;
  27022. /** Returns a set of wildcards for file-matching that contains the extensions for
  27023. all known formats.
  27024. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27025. */
  27026. const String getWildcardForAllFormats() const;
  27027. /** Searches through the known formats to try to create a suitable reader for
  27028. this file.
  27029. If none of the registered formats can open the file, it'll return 0. If it
  27030. returns a reader, it's the caller's responsibility to delete the reader.
  27031. */
  27032. AudioFormatReader* createReaderFor (const File& audioFile);
  27033. /** Searches through the known formats to try to create a suitable reader for
  27034. this stream.
  27035. The stream object that is passed-in will be deleted by this method or by the
  27036. reader that is returned, so the caller should not keep any references to it.
  27037. The stream that is passed-in must be capable of being repositioned so
  27038. that all the formats can have a go at opening it.
  27039. If none of the registered formats can open the stream, it'll return 0. If it
  27040. returns a reader, it's the caller's responsibility to delete the reader.
  27041. */
  27042. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27043. juce_UseDebuggingNewOperator
  27044. private:
  27045. VoidArray knownFormats;
  27046. int defaultFormatIndex;
  27047. };
  27048. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27049. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27050. #endif
  27051. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27052. #endif
  27053. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27054. #endif
  27055. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27056. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27057. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27058. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27059. /**
  27060. This class is used to wrap an AudioFormatReader and only read from a
  27061. subsection of the file.
  27062. So if you have a reader which can read a 1000 sample file, you could wrap it
  27063. in one of these to only access, e.g. samples 100 to 200, and any samples
  27064. outside that will come back as 0. Accessing sample 0 from this reader will
  27065. actually read the first sample from the other's subsection, which might
  27066. be at a non-zero position.
  27067. @see AudioFormatReader
  27068. */
  27069. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27070. {
  27071. public:
  27072. /** Creates a AudioSubsectionReader for a given data source.
  27073. @param sourceReader the source reader from which we'll be taking data
  27074. @param subsectionStartSample the sample within the source reader which will be
  27075. mapped onto sample 0 for this reader.
  27076. @param subsectionLength the number of samples from the source that will
  27077. make up the subsection. If this reader is asked for
  27078. any samples beyond this region, it will return zero.
  27079. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27080. this object is deleted.
  27081. */
  27082. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27083. const int64 subsectionStartSample,
  27084. const int64 subsectionLength,
  27085. const bool deleteSourceWhenDeleted);
  27086. /** Destructor. */
  27087. ~AudioSubsectionReader();
  27088. bool read (int** destSamples,
  27089. int64 startSample,
  27090. int numSamples);
  27091. void readMaxLevels (int64 startSample,
  27092. int64 numSamples,
  27093. float& lowestLeft,
  27094. float& highestLeft,
  27095. float& lowestRight,
  27096. float& highestRight);
  27097. juce_UseDebuggingNewOperator
  27098. private:
  27099. AudioFormatReader* const source;
  27100. int64 startSample, length;
  27101. const bool deleteSourceWhenDeleted;
  27102. AudioSubsectionReader (const AudioSubsectionReader&);
  27103. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27104. };
  27105. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27106. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27107. #endif
  27108. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27109. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27110. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27111. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27112. class AudioThumbnailCache;
  27113. /**
  27114. Makes it easy to quickly draw scaled views of the waveform shape of an
  27115. audio file.
  27116. To use this class, just create an AudioThumbNail class for the file you want
  27117. to draw, call setSource to tell it which file or resource to use, then call
  27118. drawChannel() to draw it.
  27119. The class will asynchronously scan the wavefile to create its scaled-down view,
  27120. so you should make your UI repaint itself as this data comes in. To do this, the
  27121. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27122. listeners should repaint themselves.
  27123. The thumbnail stores an internal low-res version of the wave data, and this can
  27124. be loaded and saved to avoid having to scan the file again.
  27125. @see AudioThumbnailCache
  27126. */
  27127. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27128. public TimeSliceClient,
  27129. private Timer
  27130. {
  27131. public:
  27132. /** Creates an audio thumbnail.
  27133. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27134. of the audio data, this is the scale at which it should be done
  27135. @param formatManagerToUse the audio format manager that is used to open the file
  27136. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27137. thread and storage that is used to by the thumbnail, and the cache
  27138. object can be shared between multiple thumbnails
  27139. */
  27140. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27141. AudioFormatManager& formatManagerToUse,
  27142. AudioThumbnailCache& cacheToUse);
  27143. /** Destructor. */
  27144. ~AudioThumbnail();
  27145. /** Specifies the file or stream that contains the audio file.
  27146. For a file, just call
  27147. @code
  27148. setSource (new FileInputSource (file))
  27149. @endcode
  27150. You can pass a zero in here to clear the thumbnail.
  27151. The source that is passed in will be deleted by this object when it is no
  27152. longer needed
  27153. */
  27154. void setSource (InputSource* const newSource);
  27155. /** Reloads the low res thumbnail data from an input stream.
  27156. The thumb will automatically attempt to reload itself from its
  27157. AudioThumbnailCache.
  27158. */
  27159. void loadFrom (InputStream& input);
  27160. /** Saves the low res thumbnail data to an output stream.
  27161. The thumb will automatically attempt to save itself to its
  27162. AudioThumbnailCache after it finishes scanning the wave file.
  27163. */
  27164. void saveTo (OutputStream& output) const;
  27165. /** Returns the number of channels in the file.
  27166. */
  27167. int getNumChannels() const throw();
  27168. /** Returns the length of the audio file.
  27169. */
  27170. double getTotalLength() const throw();
  27171. /** Renders the waveform shape for a channel.
  27172. The waveform will be drawn within the specified rectangle, where startTime
  27173. and endTime specify the times within the audio file that should be positioned
  27174. at the left and right edges of the rectangle.
  27175. The waveform will be scaled vertically so that a full-volume sample will fill
  27176. the rectangle vertically, but you can also specify an extra vertical scale factor
  27177. with the verticalZoomFactor parameter.
  27178. */
  27179. void drawChannel (Graphics& g,
  27180. int x, int y, int w, int h,
  27181. double startTime,
  27182. double endTime,
  27183. int channelNum,
  27184. const float verticalZoomFactor);
  27185. /** Returns true if the low res preview is fully generated.
  27186. */
  27187. bool isFullyLoaded() const throw();
  27188. /** @internal */
  27189. bool useTimeSlice();
  27190. /** @internal */
  27191. void timerCallback();
  27192. juce_UseDebuggingNewOperator
  27193. private:
  27194. AudioFormatManager& formatManagerToUse;
  27195. AudioThumbnailCache& cache;
  27196. InputSource* source;
  27197. CriticalSection readerLock;
  27198. AudioFormatReader* reader;
  27199. MemoryBlock data, cachedLevels;
  27200. int orginalSamplesPerThumbnailSample;
  27201. int numChannelsCached, numSamplesCached;
  27202. double cachedStart, cachedTimePerPixel;
  27203. bool cacheNeedsRefilling;
  27204. void clear();
  27205. AudioFormatReader* createReader() const;
  27206. void generateSection (AudioFormatReader& reader,
  27207. int64 startSample,
  27208. int numSamples);
  27209. char* getChannelData (int channel) const;
  27210. void refillCache (const int numSamples,
  27211. double startTime,
  27212. const double timePerPixel);
  27213. friend class AudioThumbnailCache;
  27214. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27215. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27216. // returns true if more needs to be read
  27217. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27218. };
  27219. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27220. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27221. #endif
  27222. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27223. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27224. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27225. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27226. struct ThumbnailCacheEntry;
  27227. /**
  27228. An instance of this class is used to manage multiple AudioThumbnail objects.
  27229. The cache runs a single background thread that is shared by all the thumbnails
  27230. that need it, and it maintains a set of low-res previews in memory, to avoid
  27231. having to re-scan audio files too often.
  27232. @see AudioThumbnail
  27233. */
  27234. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27235. {
  27236. public:
  27237. /** Creates a cache object.
  27238. The maxNumThumbsToStore parameter lets you specify how many previews should
  27239. be kept in memory at once.
  27240. */
  27241. AudioThumbnailCache (const int maxNumThumbsToStore);
  27242. /** Destructor. */
  27243. ~AudioThumbnailCache();
  27244. /** Clears out any stored thumbnails.
  27245. */
  27246. void clear();
  27247. /** Reloads the specified thumb if this cache contains the appropriate stored
  27248. data.
  27249. This is called automatically by the AudioThumbnail class, so you shouldn't
  27250. normally need to call it directly.
  27251. */
  27252. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27253. /** Stores the cachable data from the specified thumb in this cache.
  27254. This is called automatically by the AudioThumbnail class, so you shouldn't
  27255. normally need to call it directly.
  27256. */
  27257. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27258. juce_UseDebuggingNewOperator
  27259. private:
  27260. OwnedArray <ThumbnailCacheEntry> thumbs;
  27261. int maxNumThumbsToStore;
  27262. friend class AudioThumbnail;
  27263. void addThumbnail (AudioThumbnail* const thumb);
  27264. void removeThumbnail (AudioThumbnail* const thumb);
  27265. };
  27266. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27267. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27268. #endif
  27269. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27270. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27271. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27272. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27273. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27274. /**
  27275. Reads and writes the lossless-compression FLAC audio format.
  27276. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27277. and make sure your include search path and library search path are set up to find
  27278. the FLAC header files and static libraries.
  27279. @see AudioFormat
  27280. */
  27281. class JUCE_API FlacAudioFormat : public AudioFormat
  27282. {
  27283. public:
  27284. FlacAudioFormat();
  27285. ~FlacAudioFormat();
  27286. const Array <int> getPossibleSampleRates();
  27287. const Array <int> getPossibleBitDepths();
  27288. bool canDoStereo();
  27289. bool canDoMono();
  27290. bool isCompressed();
  27291. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27292. const bool deleteStreamIfOpeningFails);
  27293. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27294. double sampleRateToUse,
  27295. unsigned int numberOfChannels,
  27296. int bitsPerSample,
  27297. const StringPairArray& metadataValues,
  27298. int qualityOptionIndex);
  27299. juce_UseDebuggingNewOperator
  27300. };
  27301. #endif
  27302. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27303. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27304. #endif
  27305. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27306. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27307. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27308. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27309. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27310. /**
  27311. Reads and writes the Ogg-Vorbis audio format.
  27312. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27313. and make sure your include search path and library search path are set up to find
  27314. the Vorbis and Ogg header files and static libraries.
  27315. @see AudioFormat,
  27316. */
  27317. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27318. {
  27319. public:
  27320. OggVorbisAudioFormat();
  27321. ~OggVorbisAudioFormat();
  27322. const Array <int> getPossibleSampleRates();
  27323. const Array <int> getPossibleBitDepths();
  27324. bool canDoStereo();
  27325. bool canDoMono();
  27326. bool isCompressed();
  27327. const StringArray getQualityOptions();
  27328. /** Tries to estimate the quality level of an ogg file based on its size.
  27329. If it can't read the file for some reason, this will just return 1 (medium quality),
  27330. otherwise it will return the approximate quality setting that would have been used
  27331. to create the file.
  27332. @see getQualityOptions
  27333. */
  27334. int estimateOggFileQuality (const File& source);
  27335. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27336. const bool deleteStreamIfOpeningFails);
  27337. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27338. double sampleRateToUse,
  27339. unsigned int numberOfChannels,
  27340. int bitsPerSample,
  27341. const StringPairArray& metadataValues,
  27342. int qualityOptionIndex);
  27343. juce_UseDebuggingNewOperator
  27344. };
  27345. #endif
  27346. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27347. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27348. #endif
  27349. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27350. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27351. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27352. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27353. #if JUCE_QUICKTIME
  27354. /**
  27355. Uses QuickTime to read the audio track a movie or media file.
  27356. As well as QuickTime movies, this should also manage to open other audio
  27357. files that quicktime can understand, like mp3, m4a, etc.
  27358. @see AudioFormat
  27359. */
  27360. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27361. {
  27362. public:
  27363. /** Creates a format object. */
  27364. QuickTimeAudioFormat();
  27365. /** Destructor. */
  27366. ~QuickTimeAudioFormat();
  27367. const Array <int> getPossibleSampleRates();
  27368. const Array <int> getPossibleBitDepths();
  27369. bool canDoStereo();
  27370. bool canDoMono();
  27371. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27372. const bool deleteStreamIfOpeningFails);
  27373. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27374. double sampleRateToUse,
  27375. unsigned int numberOfChannels,
  27376. int bitsPerSample,
  27377. const StringPairArray& metadataValues,
  27378. int qualityOptionIndex);
  27379. juce_UseDebuggingNewOperator
  27380. };
  27381. #endif
  27382. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27383. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27384. #endif
  27385. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27386. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27387. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27388. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27389. /**
  27390. Reads and Writes WAV format audio files.
  27391. @see AudioFormat
  27392. */
  27393. class JUCE_API WavAudioFormat : public AudioFormat
  27394. {
  27395. public:
  27396. /** Creates a format object. */
  27397. WavAudioFormat();
  27398. /** Destructor. */
  27399. ~WavAudioFormat();
  27400. /** Metadata property name used by wav readers and writers for adding
  27401. a BWAV chunk to the file.
  27402. @see AudioFormatReader::metadataValues, createWriterFor
  27403. */
  27404. static const tchar* const bwavDescription;
  27405. /** Metadata property name used by wav readers and writers for adding
  27406. a BWAV chunk to the file.
  27407. @see AudioFormatReader::metadataValues, createWriterFor
  27408. */
  27409. static const tchar* const bwavOriginator;
  27410. /** Metadata property name used by wav readers and writers for adding
  27411. a BWAV chunk to the file.
  27412. @see AudioFormatReader::metadataValues, createWriterFor
  27413. */
  27414. static const tchar* const bwavOriginatorRef;
  27415. /** Metadata property name used by wav readers and writers for adding
  27416. a BWAV chunk to the file.
  27417. Date format is: yyyy-mm-dd
  27418. @see AudioFormatReader::metadataValues, createWriterFor
  27419. */
  27420. static const tchar* const bwavOriginationDate;
  27421. /** Metadata property name used by wav readers and writers for adding
  27422. a BWAV chunk to the file.
  27423. Time format is: hh-mm-ss
  27424. @see AudioFormatReader::metadataValues, createWriterFor
  27425. */
  27426. static const tchar* const bwavOriginationTime;
  27427. /** Metadata property name used by wav readers and writers for adding
  27428. a BWAV chunk to the file.
  27429. This is the number of samples from the start of an edit that the
  27430. file is supposed to begin at. Seems like an obvious mistake to
  27431. only allow a file to occur in an edit once, but that's the way
  27432. it is..
  27433. @see AudioFormatReader::metadataValues, createWriterFor
  27434. */
  27435. static const tchar* const bwavTimeReference;
  27436. /** Metadata property name used by wav readers and writers for adding
  27437. a BWAV chunk to the file.
  27438. This is a
  27439. @see AudioFormatReader::metadataValues, createWriterFor
  27440. */
  27441. static const tchar* const bwavCodingHistory;
  27442. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27443. This just makes it easier than using the property names directly, and it
  27444. fills out the time and date in the right format.
  27445. */
  27446. static const StringPairArray createBWAVMetadata (const String& description,
  27447. const String& originator,
  27448. const String& originatorRef,
  27449. const Time& dateAndTime,
  27450. const int64 timeReferenceSamples,
  27451. const String& codingHistory);
  27452. const Array <int> getPossibleSampleRates();
  27453. const Array <int> getPossibleBitDepths();
  27454. bool canDoStereo();
  27455. bool canDoMono();
  27456. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27457. const bool deleteStreamIfOpeningFails);
  27458. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27459. double sampleRateToUse,
  27460. unsigned int numberOfChannels,
  27461. int bitsPerSample,
  27462. const StringPairArray& metadataValues,
  27463. int qualityOptionIndex);
  27464. juce_UseDebuggingNewOperator
  27465. };
  27466. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27467. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27468. #endif
  27469. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27470. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  27471. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27472. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27473. /********* Start of inlined file: juce_ActionListenerList.h *********/
  27474. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27475. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27476. /**
  27477. A set of ActionListeners.
  27478. Listeners can be added and removed from the list, and messages can be
  27479. broadcast to all the listeners.
  27480. @see ActionListener, ActionBroadcaster
  27481. */
  27482. class JUCE_API ActionListenerList : public MessageListener
  27483. {
  27484. public:
  27485. /** Creates an empty list. */
  27486. ActionListenerList() throw();
  27487. /** Destructor. */
  27488. ~ActionListenerList() throw();
  27489. /** Adds a listener to the list.
  27490. (Trying to add a listener that's already on the list will have no effect).
  27491. */
  27492. void addActionListener (ActionListener* const listener) throw();
  27493. /** Removes a listener from the list.
  27494. If the listener isn't on the list, this won't have any effect.
  27495. */
  27496. void removeActionListener (ActionListener* const listener) throw();
  27497. /** Removes all listeners from the list. */
  27498. void removeAllActionListeners() throw();
  27499. /** Broadcasts a message to all the registered listeners.
  27500. This sends the message asynchronously.
  27501. If a listener is on the list when this method is called but is removed from
  27502. the list before the message arrives, it won't receive the message. Similarly
  27503. listeners that are added to the list after the message is sent but before it
  27504. arrives won't get the message either.
  27505. */
  27506. void sendActionMessage (const String& message) const;
  27507. /** @internal */
  27508. void handleMessage (const Message&);
  27509. juce_UseDebuggingNewOperator
  27510. private:
  27511. SortedSet <void*> actionListeners_;
  27512. CriticalSection actionListenerLock_;
  27513. ActionListenerList (const ActionListenerList&);
  27514. const ActionListenerList& operator= (const ActionListenerList&);
  27515. };
  27516. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27517. /********* End of inlined file: juce_ActionListenerList.h *********/
  27518. /** Manages a list of ActionListeners, and can send them messages.
  27519. To quickly add methods to your class that can add/remove action
  27520. listeners and broadcast to them, you can derive from this.
  27521. @see ActionListenerList, ActionListener
  27522. */
  27523. class JUCE_API ActionBroadcaster
  27524. {
  27525. public:
  27526. /** Creates an ActionBroadcaster. */
  27527. ActionBroadcaster() throw();
  27528. /** Destructor. */
  27529. virtual ~ActionBroadcaster();
  27530. /** Adds a listener to the list.
  27531. (Trying to add a listener that's already on the list will have no effect).
  27532. */
  27533. void addActionListener (ActionListener* const listener);
  27534. /** Removes a listener from the list.
  27535. If the listener isn't on the list, this won't have any effect.
  27536. */
  27537. void removeActionListener (ActionListener* const listener);
  27538. /** Removes all listeners from the list. */
  27539. void removeAllActionListeners();
  27540. /** Broadcasts a message to all the registered listeners.
  27541. @see ActionListenerList::sendActionMessage
  27542. */
  27543. void sendActionMessage (const String& message) const;
  27544. private:
  27545. ActionListenerList actionListenerList;
  27546. ActionBroadcaster (const ActionBroadcaster&);
  27547. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  27548. };
  27549. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27550. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  27551. #endif
  27552. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  27553. #endif
  27554. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27555. #endif
  27556. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  27557. #endif
  27558. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  27559. #endif
  27560. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  27561. #endif
  27562. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  27563. #endif
  27564. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27565. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  27566. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27567. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27568. class InterprocessConnectionServer;
  27569. /**
  27570. Manages a simple two-way messaging connection to another process, using either
  27571. a socket or a named pipe as the transport medium.
  27572. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  27573. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27574. and incoming messages will result in a callback via the messageReceived()
  27575. method.
  27576. To open a pipe and wait for another client to connect to it, use the createPipe()
  27577. method.
  27578. To act as a socket server and create connections for one or more client, see the
  27579. InterprocessConnectionServer class.
  27580. @see InterprocessConnectionServer, Socket, NamedPipe
  27581. */
  27582. class JUCE_API InterprocessConnection : public Thread,
  27583. private MessageListener
  27584. {
  27585. public:
  27586. /** Creates a connection.
  27587. Connections are created manually, connecting them with the connectToSocket()
  27588. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  27589. when a client wants to connect.
  27590. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  27591. connectionLost() and messageReceived() methods will
  27592. always be made using the message thread; if false,
  27593. these will be called immediately on the connection's
  27594. own thread.
  27595. @param magicMessageHeaderNumber a magic number to use in the header to check the
  27596. validity of the data blocks being sent and received. This
  27597. can be any number, but the sender and receiver must obviously
  27598. use matching values or they won't recognise each other.
  27599. */
  27600. InterprocessConnection (const bool callbacksOnMessageThread = true,
  27601. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  27602. /** Destructor. */
  27603. ~InterprocessConnection();
  27604. /** Tries to connect this object to a socket.
  27605. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  27606. object waiting to receive client connections on this port number.
  27607. @param hostName the host computer, either a network address or name
  27608. @param portNumber the socket port number to try to connect to
  27609. @param timeOutMillisecs how long to keep trying before giving up
  27610. @returns true if the connection is established successfully
  27611. @see Socket
  27612. */
  27613. bool connectToSocket (const String& hostName,
  27614. const int portNumber,
  27615. const int timeOutMillisecs);
  27616. /** Tries to connect the object to an existing named pipe.
  27617. For this to work, another process on the same computer must already have opened
  27618. an InterprocessConnection object and used createPipe() to create a pipe for this
  27619. to connect to.
  27620. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27621. @returns true if it connects successfully.
  27622. @see createPipe, NamedPipe
  27623. */
  27624. bool connectToPipe (const String& pipeName,
  27625. const int pipeReceiveMessageTimeoutMs = -1);
  27626. /** Tries to create a new pipe for other processes to connect to.
  27627. This creates a pipe with the given name, so that other processes can use
  27628. connectToPipe() to connect to the other end.
  27629. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27630. If another process is already using this pipe, this will fail and return false.
  27631. */
  27632. bool createPipe (const String& pipeName,
  27633. const int pipeReceiveMessageTimeoutMs = -1);
  27634. /** Disconnects and closes any currently-open sockets or pipes. */
  27635. void disconnect();
  27636. /** True if a socket or pipe is currently active. */
  27637. bool isConnected() const;
  27638. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  27639. StreamingSocket* getSocket() const throw() { return socket; }
  27640. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  27641. NamedPipe* getPipe() const throw() { return pipe; }
  27642. /** Returns the name of the machine at the other end of this connection.
  27643. This will return an empty string if the other machine isn't known for
  27644. some reason.
  27645. */
  27646. const String getConnectedHostName() const;
  27647. /** Tries to send a message to the other end of this connection.
  27648. This will fail if it's not connected, or if there's some kind of write error. If
  27649. it succeeds, the connection object at the other end will receive the message by
  27650. a callback to its messageReceived() method.
  27651. @see messageReceived
  27652. */
  27653. bool sendMessage (const MemoryBlock& message);
  27654. /** Called when the connection is first connected.
  27655. If the connection was created with the callbacksOnMessageThread flag set, then
  27656. this will be called on the message thread; otherwise it will be called on a server
  27657. thread.
  27658. */
  27659. virtual void connectionMade() = 0;
  27660. /** Called when the connection is broken.
  27661. If the connection was created with the callbacksOnMessageThread flag set, then
  27662. this will be called on the message thread; otherwise it will be called on a server
  27663. thread.
  27664. */
  27665. virtual void connectionLost() = 0;
  27666. /** Called when a message arrives.
  27667. When the object at the other end of this connection sends us a message with sendMessage(),
  27668. this callback is used to deliver it to us.
  27669. If the connection was created with the callbacksOnMessageThread flag set, then
  27670. this will be called on the message thread; otherwise it will be called on a server
  27671. thread.
  27672. @see sendMessage
  27673. */
  27674. virtual void messageReceived (const MemoryBlock& message) = 0;
  27675. juce_UseDebuggingNewOperator
  27676. private:
  27677. CriticalSection pipeAndSocketLock;
  27678. StreamingSocket* socket;
  27679. NamedPipe* pipe;
  27680. bool callbackConnectionState;
  27681. const bool useMessageThread;
  27682. const uint32 magicMessageHeader;
  27683. int pipeReceiveMessageTimeout;
  27684. friend class InterprocessConnectionServer;
  27685. void initialiseWithSocket (StreamingSocket* const socket_);
  27686. void initialiseWithPipe (NamedPipe* const pipe_);
  27687. void handleMessage (const Message& message);
  27688. void connectionMadeInt();
  27689. void connectionLostInt();
  27690. void deliverDataInt (const MemoryBlock& data);
  27691. bool readNextMessageInt();
  27692. void run();
  27693. InterprocessConnection (const InterprocessConnection&);
  27694. const InterprocessConnection& operator= (const InterprocessConnection&);
  27695. };
  27696. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27697. /********* End of inlined file: juce_InterprocessConnection.h *********/
  27698. #endif
  27699. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27700. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  27701. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27702. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27703. /**
  27704. An object that waits for client sockets to connect to a port on this host, and
  27705. creates InterprocessConnection objects for each one.
  27706. To use this, create a class derived from it which implements the createConnectionObject()
  27707. method, so that it creates suitable connection objects for each client that tries
  27708. to connect.
  27709. @see InterprocessConnection
  27710. */
  27711. class JUCE_API InterprocessConnectionServer : private Thread
  27712. {
  27713. public:
  27714. /** Creates an uninitialised server object.
  27715. */
  27716. InterprocessConnectionServer();
  27717. /** Destructor. */
  27718. ~InterprocessConnectionServer();
  27719. /** Starts an internal thread which listens on the given port number.
  27720. While this is running, in another process tries to connect with the
  27721. InterprocessConnection::connectToSocket() method, this object will call
  27722. createConnectionObject() to create a connection to that client.
  27723. Use stop() to stop the thread running.
  27724. @see createConnectionObject, stop
  27725. */
  27726. bool beginWaitingForSocket (const int portNumber);
  27727. /** Terminates the listener thread, if it's active.
  27728. @see beginWaitingForSocket
  27729. */
  27730. void stop();
  27731. protected:
  27732. /** Creates a suitable connection object for a client process that wants to
  27733. connect to this one.
  27734. This will be called by the listener thread when a client process tries
  27735. to connect, and must return a new InterprocessConnection object that will
  27736. then run as this end of the connection.
  27737. @see InterprocessConnection
  27738. */
  27739. virtual InterprocessConnection* createConnectionObject() = 0;
  27740. public:
  27741. juce_UseDebuggingNewOperator
  27742. private:
  27743. StreamingSocket* volatile socket;
  27744. void run();
  27745. InterprocessConnectionServer (const InterprocessConnectionServer&);
  27746. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  27747. };
  27748. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27749. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  27750. #endif
  27751. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  27752. #endif
  27753. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  27754. #endif
  27755. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27756. /********* Start of inlined file: juce_MessageManager.h *********/
  27757. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27758. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27759. class Thread;
  27760. class Component;
  27761. class MessageManagerLock;
  27762. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  27763. */
  27764. typedef void* (MessageCallbackFunction) (void* userData);
  27765. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  27766. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  27767. */
  27768. class JUCE_API MessageManager : private DeletedAtShutdown
  27769. {
  27770. public:
  27771. /** Returns the global instance of the MessageManager. */
  27772. static MessageManager* getInstance() throw();
  27773. void runDispatchLoop();
  27774. void stopDispatchLoop();
  27775. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  27776. /** Synchronously dispatches messages until a given time has elapsed.
  27777. Returns false if a quit message has been posted, otherwise returns true.
  27778. */
  27779. bool runDispatchLoopUntil (int millisecondsToRunFor);
  27780. /*int runModalLoop (Component* componentToBeModal);
  27781. bool makeComponentModal (Component* componentToBeModal);
  27782. bool isComponentModal (const Component* component) const;
  27783. Component* getCurrentModalComponent() const;
  27784. void exitModalLoop (int returnValue);*/
  27785. /** Calls a function using the message-thread.
  27786. This can be used by any thread to cause this function to be called-back
  27787. by the message thread. If it's the message-thread that's calling this method,
  27788. then the function will just be called; if another thread is calling, a message
  27789. will be posted to the queue, and this method will block until that message
  27790. is delivered, the function is called, and the result is returned.
  27791. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  27792. thread has a critical section locked, which an unrelated message callback then tries to lock
  27793. before the message thread gets round to processing this callback.
  27794. @param callback the function to call - its signature must be @code
  27795. void* myCallbackFunction (void*) @endcode
  27796. @param userData a user-defined pointer that will be passed to the function that gets called
  27797. @returns the value that the callback function returns.
  27798. @see MessageManagerLock
  27799. */
  27800. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  27801. void* userData);
  27802. /** Returns true if the caller-thread is the message thread. */
  27803. bool isThisTheMessageThread() const throw();
  27804. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  27805. (Best to ignore this method unless you really know what you're doing..)
  27806. @see getCurrentMessageThread
  27807. */
  27808. void setCurrentMessageThread (const int threadId) throw();
  27809. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  27810. (Best to ignore this method unless you really know what you're doing..)
  27811. @see setCurrentMessageThread
  27812. */
  27813. int64 getCurrentMessageThread() const throw() { return messageThreadId; }
  27814. /** Returns true if the caller thread has currenltly got the message manager locked.
  27815. see the MessageManagerLock class for more info about this.
  27816. This will be true if the caller is the message thread, because that automatically
  27817. gains a lock while a message is being dispatched.
  27818. */
  27819. bool currentThreadHasLockedMessageManager() const throw();
  27820. /** Sends a message to all other JUCE applications that are running.
  27821. @param messageText the string that will be passed to the actionListenerCallback()
  27822. method of the broadcast listeners in the other app.
  27823. @see registerBroadcastListener, ActionListener
  27824. */
  27825. static void broadcastMessage (const String& messageText) throw();
  27826. /** Registers a listener to get told about broadcast messages.
  27827. The actionListenerCallback() callback's string parameter
  27828. is the message passed into broadcastMessage().
  27829. @see broadcastMessage
  27830. */
  27831. void registerBroadcastListener (ActionListener* listener) throw();
  27832. /** Deregisters a broadcast listener. */
  27833. void deregisterBroadcastListener (ActionListener* listener) throw();
  27834. /** @internal */
  27835. void deliverMessage (void*);
  27836. /** @internal */
  27837. void deliverBroadcastMessage (const String&);
  27838. juce_UseDebuggingNewOperator
  27839. private:
  27840. MessageManager() throw();
  27841. ~MessageManager() throw();
  27842. friend class MessageListener;
  27843. friend class ChangeBroadcaster;
  27844. friend class ActionBroadcaster;
  27845. static MessageManager* instance;
  27846. SortedSet<const MessageListener*> messageListeners;
  27847. ActionListenerList* broadcastListeners;
  27848. friend class JUCEApplication;
  27849. bool quitMessagePosted, quitMessageReceived;
  27850. int64 messageThreadId;
  27851. VoidArray modalComponents;
  27852. static void* exitModalLoopCallback (void*);
  27853. void postMessageToQueue (Message* const message);
  27854. static void doPlatformSpecificInitialisation();
  27855. static void doPlatformSpecificShutdown();
  27856. friend class MessageManagerLock;
  27857. CriticalSection messageDispatchLock;
  27858. int64 currentLockingThreadId;
  27859. MessageManager (const MessageManager&);
  27860. const MessageManager& operator= (const MessageManager&);
  27861. };
  27862. /** Used to make sure that the calling thread has exclusive access to the message loop.
  27863. Because it's not thread-safe to call any of the Component or other UI classes
  27864. from threads other than the message thread, one of these objects can be used to
  27865. lock the message loop and allow this to be done. The message thread will be
  27866. suspended for the lifetime of the MessageManagerLock object, so create one on
  27867. the stack like this: @code
  27868. void MyThread::run()
  27869. {
  27870. someData = 1234;
  27871. const MessageManagerLock mmLock;
  27872. // the event loop will now be locked so it's safe to make a few calls..
  27873. myComponent->setBounds (newBounds);
  27874. myComponent->repaint();
  27875. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  27876. }
  27877. @endcode
  27878. Obviously be careful not to create one of these and leave it lying around, or
  27879. your app will grind to a halt!
  27880. Another caveat is that using this in conjunction with other CriticalSections
  27881. can create lots of interesting ways of producing a deadlock! In particular, if
  27882. your message thread calls stopThread() for a thread that uses these locks,
  27883. you'll get an (occasional) deadlock..
  27884. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  27885. */
  27886. class JUCE_API MessageManagerLock
  27887. {
  27888. public:
  27889. /** Tries to acquire a lock on the message manager.
  27890. If this constructor
  27891. When this constructor returns, the message manager will have finished processing the
  27892. last message and will not send another message until this MessageManagerLock is
  27893. deleted.
  27894. If the current thread already has the lock, nothing will be done, so it's perfectly
  27895. safe to create these locks recursively.
  27896. */
  27897. MessageManagerLock() throw();
  27898. /** Releases the current thread's lock on the message manager.
  27899. Make sure this object is created and deleted by the same thread,
  27900. otherwise there are no guarantees what will happen!
  27901. */
  27902. ~MessageManagerLock() throw();
  27903. /** Tries to acquire a lock on the message manager.
  27904. This does the same thing as the normal constructor, but while it's waiting to get
  27905. the lock, it checks the specified thread to see if it has been given the
  27906. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  27907. without gaining the lock.
  27908. To find out whether the lock was successful, call lockWasGained(). If this is
  27909. false, your thread is being told to die, so you'd better get out of there.
  27910. If the current thread already has the lock, nothing will be done, so it's perfectly
  27911. safe to create these locks recursively.
  27912. E.g.
  27913. @code
  27914. void run()
  27915. {
  27916. ...
  27917. while (! threadShouldExit())
  27918. {
  27919. MessageManagerLock mml (Thread::getCurrentThread());
  27920. if (! mml.lockWasGained)
  27921. return; // another thread is trying to kill us!
  27922. ..do some locked stuff here..
  27923. }
  27924. ..and now the MM is now unlocked..
  27925. }
  27926. @endcode
  27927. */
  27928. MessageManagerLock (Thread* const threadToCheckForExitSignal) throw();
  27929. /** Returns true if the lock was successfully acquired.
  27930. (See the constructor that takes a Thread for more info).
  27931. */
  27932. bool lockWasGained() const throw() { return locked; }
  27933. private:
  27934. int64 lastLockingThreadId;
  27935. bool locked;
  27936. };
  27937. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27938. /********* End of inlined file: juce_MessageManager.h *********/
  27939. #endif
  27940. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  27941. /********* Start of inlined file: juce_MultiTimer.h *********/
  27942. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  27943. #define __JUCE_MULTITIMER_JUCEHEADER__
  27944. /**
  27945. A type of timer class that can run multiple timers with different frequencies,
  27946. all of which share a single callback.
  27947. This class is very similar to the Timer class, but allows you run multiple
  27948. separate timers, where each one has a unique ID number. The methods in this
  27949. class are exactly equivalent to those in Timer, but with the addition of
  27950. this ID number.
  27951. To use it, you need to create a subclass of MultiTimer, implementing the
  27952. timerCallback() method. Then you can start timers with startTimer(), and
  27953. each time the callback is triggered, it passes in the ID of the timer that
  27954. caused it.
  27955. @see Timer
  27956. */
  27957. class JUCE_API MultiTimer
  27958. {
  27959. protected:
  27960. /** Creates a MultiTimer.
  27961. When created, no timers are running, so use startTimer() to start things off.
  27962. */
  27963. MultiTimer() throw();
  27964. /** Creates a copy of another timer.
  27965. Note that this timer will not contain any running timers, even if the one you're
  27966. copying from was running.
  27967. */
  27968. MultiTimer (const MultiTimer& other) throw();
  27969. public:
  27970. /** Destructor. */
  27971. virtual ~MultiTimer();
  27972. /** The user-defined callback routine that actually gets called by each of the
  27973. timers that are running.
  27974. It's perfectly ok to call startTimer() or stopTimer() from within this
  27975. callback to change the subsequent intervals.
  27976. */
  27977. virtual void timerCallback (const int timerId) = 0;
  27978. /** Starts a timer and sets the length of interval required.
  27979. If the timer is already started, this will reset it, so the
  27980. time between calling this method and the next timer callback
  27981. will not be less than the interval length passed in.
  27982. @param timerId a unique Id number that identifies the timer to
  27983. start. This is the id that will be passed back
  27984. to the timerCallback() method when this timer is
  27985. triggered
  27986. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  27987. rounded up to 1)
  27988. */
  27989. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  27990. /** Stops a timer.
  27991. If a timer has been started with the given ID number, it will be cancelled.
  27992. No more callbacks will be made for the specified timer after this method returns.
  27993. If this is called from a different thread, any callbacks that may
  27994. be currently executing may be allowed to finish before the method
  27995. returns.
  27996. */
  27997. void stopTimer (const int timerId) throw();
  27998. /** Checks whether a timer has been started for a specified ID.
  27999. @returns true if a timer with the given ID is running.
  28000. */
  28001. bool isTimerRunning (const int timerId) const throw();
  28002. /** Returns the interval for a specified timer ID.
  28003. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28004. is running for the ID number specified.
  28005. */
  28006. int getTimerInterval (const int timerId) const throw();
  28007. private:
  28008. CriticalSection timerListLock;
  28009. VoidArray timers;
  28010. const MultiTimer& operator= (const MultiTimer&);
  28011. };
  28012. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28013. /********* End of inlined file: juce_MultiTimer.h *********/
  28014. #endif
  28015. #ifndef __JUCE_TIMER_JUCEHEADER__
  28016. #endif
  28017. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28018. #endif
  28019. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28020. /********* Start of inlined file: juce_GradientBrush.h *********/
  28021. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28022. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28023. /********* Start of inlined file: juce_ColourGradient.h *********/
  28024. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28025. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28026. /**
  28027. Structure used to define a colour gradient for painting areas.
  28028. @see GradientBrush
  28029. */
  28030. class JUCE_API ColourGradient
  28031. {
  28032. public:
  28033. /** Creates a gradient object.
  28034. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28035. colour2 should be. In between them there's a gradient.
  28036. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28037. its centre.
  28038. The alpha transparencies of the colours are used, so note that
  28039. if you blend from transparent to a solid colour, the RGB of the transparent
  28040. colour will become visible in parts of the gradient. e.g. blending
  28041. from Colour::transparentBlack to Colours::white will produce a
  28042. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28043. will be white all the way across.
  28044. @see ColourGradient
  28045. */
  28046. ColourGradient (const Colour& colour1,
  28047. const float x1,
  28048. const float y1,
  28049. const Colour& colour2,
  28050. const float x2,
  28051. const float y2,
  28052. const bool isRadial) throw();
  28053. /** Creates an uninitialised gradient.
  28054. If you use this constructor instead of the other one, be sure to set all the
  28055. object's public member variables before using it!
  28056. */
  28057. ColourGradient() throw();
  28058. /** Destructor */
  28059. ~ColourGradient() throw();
  28060. /** Removes any colours that have been added.
  28061. This will also remove any start and end colours, so the gradient won't work. You'll
  28062. need to add more colours with addColour().
  28063. */
  28064. void clearColours() throw();
  28065. /** Adds a colour at a point along the length of the gradient.
  28066. This allows the gradient to go through a spectrum of colours, instead of just a
  28067. start and end colour.
  28068. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28069. of the distance along the line between the two points
  28070. at which the colour should occur.
  28071. @param colour the colour that should be used at this point
  28072. */
  28073. void addColour (const double proportionAlongGradient,
  28074. const Colour& colour) throw();
  28075. /** Multiplies the alpha value of all the colours by the given scale factor */
  28076. void multiplyOpacity (const float multiplier) throw();
  28077. /** Returns the number of colour-stops that have been added. */
  28078. int getNumColours() const throw();
  28079. /** Returns the position along the length of the gradient of the colour with this index.
  28080. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28081. */
  28082. double getColourPosition (const int index) const throw();
  28083. /** Returns the colour that was added with a given index.
  28084. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28085. */
  28086. const Colour getColour (const int index) const throw();
  28087. /** Creates a set of interpolated premultiplied ARGB values.
  28088. The caller must delete the array that is returned using juce_free().
  28089. */
  28090. PixelARGB* createLookupTable (int& numEntries) const throw();
  28091. /** Returns true if all colours are opaque. */
  28092. bool isOpaque() const throw();
  28093. /** Returns true if all colours are completely transparent. */
  28094. bool isInvisible() const throw();
  28095. float x1;
  28096. float y1;
  28097. float x2;
  28098. float y2;
  28099. /** If true, the gradient should be filled circularly, centred around
  28100. (x1, y1), with (x2, y2) defining a point on the circumference.
  28101. If false, the gradient is linear between the two points.
  28102. */
  28103. bool isRadial;
  28104. /** A transform to apply to the resultant gradient shape */
  28105. AffineTransform transform;
  28106. juce_UseDebuggingNewOperator
  28107. private:
  28108. Array <uint32> colours;
  28109. };
  28110. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28111. /********* End of inlined file: juce_ColourGradient.h *********/
  28112. /**
  28113. A Brush that fills areas with a colour gradient.
  28114. The gradient can either be linear or circular.
  28115. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28116. */
  28117. class JUCE_API GradientBrush : public Brush
  28118. {
  28119. public:
  28120. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28121. (x1, y1) is the location relative to the origin of the Graphics context,
  28122. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28123. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28124. its centre.
  28125. The alpha transparencies of the colours are used, so the brush
  28126. need not be completely opaque. Note that this means that if you
  28127. blend from transparent to a solid colour, the RGB of the transparent
  28128. colour will become visible in parts of the gradient. e.g. blending
  28129. from Colour::transparentBlack to Colours::white will produce a
  28130. grey colour, but Colour::transparentWhite to Colours::white will be
  28131. white all the way across.
  28132. @see ColourGradient
  28133. */
  28134. GradientBrush (const Colour& colour1,
  28135. const float x1,
  28136. const float y1,
  28137. const Colour& colour2,
  28138. const float x2,
  28139. const float y2,
  28140. const bool isRadial) throw();
  28141. /** Creates a gradient brush from a ColourGradient object.
  28142. */
  28143. GradientBrush (const ColourGradient& gradient) throw();
  28144. /** Destructor. */
  28145. ~GradientBrush() throw();
  28146. Brush* createCopy() const throw();
  28147. void applyTransform (const AffineTransform& transform) throw();
  28148. void multiplyOpacity (const float multiple) throw();
  28149. bool isInvisible() const throw();
  28150. void paintPath (LowLevelGraphicsContext& context,
  28151. const Path& path, const AffineTransform& transform) throw();
  28152. void paintRectangle (LowLevelGraphicsContext& context,
  28153. int x, int y, int w, int h) throw();
  28154. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28155. const Image& alphaChannelImage, int imageX, int imageY,
  28156. int x, int y, int w, int h) throw();
  28157. juce_UseDebuggingNewOperator
  28158. protected:
  28159. ColourGradient gradient;
  28160. private:
  28161. GradientBrush (const GradientBrush&);
  28162. const GradientBrush& operator= (const GradientBrush&);
  28163. };
  28164. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28165. /********* End of inlined file: juce_GradientBrush.h *********/
  28166. #endif
  28167. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28168. /********* Start of inlined file: juce_ImageBrush.h *********/
  28169. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28170. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28171. /********* Start of inlined file: juce_Image.h *********/
  28172. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28173. #define __JUCE_IMAGE_JUCEHEADER__
  28174. /**
  28175. Holds a fixed-size bitmap.
  28176. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28177. To draw into an image, create a Graphics object for it.
  28178. e.g. @code
  28179. // create a transparent 500x500 image..
  28180. Image myImage (Image::RGB, 500, 500, true);
  28181. Graphics g (myImage);
  28182. g.setColour (Colours::red);
  28183. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28184. @endcode
  28185. Other useful ways to create an image are with the ImageCache class, or the
  28186. ImageFileFormat, which provides a way to load common image files.
  28187. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28188. */
  28189. class JUCE_API Image
  28190. {
  28191. public:
  28192. enum PixelFormat
  28193. {
  28194. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28195. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28196. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28197. };
  28198. /** Creates an in-memory image with a specified size and format.
  28199. @param format the number of colour channels in the image
  28200. @param imageWidth the desired width of the image, in pixels - this value must be
  28201. greater than zero (otherwise a width of 1 will be used)
  28202. @param imageHeight the desired width of the image, in pixels - this value must be
  28203. greater than zero (otherwise a height of 1 will be used)
  28204. @param clearImage if true, the image will initially be cleared to black or transparent
  28205. black. If false, the image may contain random data, and the
  28206. user will have to deal with this
  28207. */
  28208. Image (const PixelFormat format,
  28209. const int imageWidth,
  28210. const int imageHeight,
  28211. const bool clearImage);
  28212. /** Creates a copy of another image.
  28213. @see createCopy
  28214. */
  28215. Image (const Image& other);
  28216. /** Destructor. */
  28217. virtual ~Image();
  28218. /** Returns the image's width (in pixels). */
  28219. int getWidth() const throw() { return imageWidth; }
  28220. /** Returns the image's height (in pixels). */
  28221. int getHeight() const throw() { return imageHeight; }
  28222. /** Returns the image's pixel format. */
  28223. PixelFormat getFormat() const throw() { return format; }
  28224. /** True if the image's format is ARGB. */
  28225. bool isARGB() const throw() { return format == ARGB; }
  28226. /** True if the image's format is RGB. */
  28227. bool isRGB() const throw() { return format == RGB; }
  28228. /** True if the image contains an alpha-channel. */
  28229. bool hasAlphaChannel() const throw() { return format != RGB; }
  28230. /** Clears a section of the image with a given colour.
  28231. This won't do any alpha-blending - it just sets all pixels in the image to
  28232. the given colour (which may be non-opaque if the image has an alpha channel).
  28233. */
  28234. virtual void clear (int x, int y, int w, int h,
  28235. const Colour& colourToClearTo = Colour (0x00000000));
  28236. /** Returns a new image that's a copy of this one.
  28237. A new size for the copied image can be specified, or values less than
  28238. zero can be passed-in to use the image's existing dimensions.
  28239. It's up to the caller to delete the image when no longer needed.
  28240. */
  28241. virtual Image* createCopy (int newWidth = -1,
  28242. int newHeight = -1,
  28243. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28244. /** Returns the colour of one of the pixels in the image.
  28245. If the co-ordinates given are beyond the image's boundaries, this will
  28246. return Colours::transparentBlack.
  28247. (0, 0) is the image's top-left corner.
  28248. @see getAlphaAt, setPixelAt, blendPixelAt
  28249. */
  28250. virtual const Colour getPixelAt (const int x, const int y) const;
  28251. /** Sets the colour of one of the image's pixels.
  28252. If the co-ordinates are beyond the image's boundaries, then nothing will
  28253. happen.
  28254. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28255. just replace the existing pixel with the given one. The colour's opacity
  28256. will be ignored if this image doesn't have an alpha-channel.
  28257. (0, 0) is the image's top-left corner.
  28258. @see blendPixelAt
  28259. */
  28260. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28261. /** Changes the opacity of a pixel.
  28262. This only has an effect if the image has an alpha channel and if the
  28263. given co-ordinates are inside the image's boundary.
  28264. The multiplier must be in the range 0 to 1.0, and the current alpha
  28265. at the given co-ordinates will be multiplied by this value.
  28266. @see getAlphaAt, setPixelAt
  28267. */
  28268. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28269. /** Changes the overall opacity of the image.
  28270. This will multiply the alpha value of each pixel in the image by the given
  28271. amount (limiting the resulting alpha values between 0 and 255). This allows
  28272. you to make an image more or less transparent.
  28273. If the image doesn't have an alpha channel, this won't have any effect.
  28274. */
  28275. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28276. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28277. */
  28278. virtual void desaturate();
  28279. /** Locks some of the pixels in the image so they can be read and written to.
  28280. This returns a pointer to some memory containing the pixels in the given
  28281. rectangle. It also returns values for the line and pixel stride used within
  28282. the data. The format of the pixel data is the same as that of this image.
  28283. When you've finished reading and changing the data, you must call
  28284. releasePixelDataReadWrite() to give the pixels back to the image.
  28285. For images that are stored in memory, this method may just return a direct
  28286. pointer to the image's data, but other types of image may be stored elsewhere,
  28287. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28288. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28289. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28290. instead.
  28291. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28292. */
  28293. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28294. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28295. */
  28296. virtual void releasePixelDataReadWrite (void* sourceData);
  28297. /** Locks some of the pixels in the image so they can be read.
  28298. This returns a pointer to some memory containing the pixels in the given
  28299. rectangle. It also returns values for the line and pixel stride used within
  28300. the data. The format of the pixel data is the same as that of this image.
  28301. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28302. to let the image free the memory if necessary.
  28303. For images that are stored in memory, this method may just return a direct
  28304. pointer to the image's data, but other types of image may be stored elsewhere,
  28305. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28306. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28307. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28308. instead.
  28309. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28310. */
  28311. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28312. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28313. */
  28314. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28315. /** Copies some pixel values to a rectangle of the image.
  28316. The format of the pixel data must match that of the image itself, and the
  28317. rectangle supplied must be within the image's bounds.
  28318. */
  28319. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28320. const uint8* sourcePixelData, int sourceLineStride);
  28321. /** Copies a section of the image to somewhere else within itself.
  28322. */
  28323. virtual void moveImageSection (int destX, int destY,
  28324. int sourceX, int sourceY,
  28325. int width, int height);
  28326. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28327. of the image.
  28328. @param result the list that will have the area added to it
  28329. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28330. above this level will be considered opaque
  28331. */
  28332. void createSolidAreaMask (RectangleList& result,
  28333. const float alphaThreshold = 0.5f) const;
  28334. juce_UseDebuggingNewOperator
  28335. /** Creates a context suitable for drawing onto this image.
  28336. Don't call this method directly! It's used internally by the Graphics class.
  28337. */
  28338. virtual LowLevelGraphicsContext* createLowLevelContext();
  28339. protected:
  28340. const PixelFormat format;
  28341. const int imageWidth, imageHeight;
  28342. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28343. Image (const PixelFormat format,
  28344. const int imageWidth,
  28345. const int imageHeight);
  28346. int pixelStride, lineStride;
  28347. uint8* imageData;
  28348. private:
  28349. const Image& operator= (const Image&);
  28350. };
  28351. #endif // __JUCE_IMAGE_JUCEHEADER__
  28352. /********* End of inlined file: juce_Image.h *********/
  28353. /**
  28354. A Brush that fills areas with tiled repetitions of an image.
  28355. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28356. */
  28357. class JUCE_API ImageBrush : public Brush
  28358. {
  28359. public:
  28360. /* Creates an image brush, ready for use in Graphics::setBrush().
  28361. (x, y) is an anchor point for the top-left of the image
  28362. A reference to the image passed in will be kept, so don't delete
  28363. it within the lifetime of this object
  28364. */
  28365. ImageBrush (Image* const image,
  28366. const int anchorX,
  28367. const int anchorY,
  28368. const float opacity) throw();
  28369. /** Destructor. */
  28370. ~ImageBrush() throw();
  28371. Brush* createCopy() const throw();
  28372. void applyTransform (const AffineTransform& transform) throw();
  28373. void multiplyOpacity (const float multiple) throw();
  28374. bool isInvisible() const throw();
  28375. void paintPath (LowLevelGraphicsContext& context,
  28376. const Path& path, const AffineTransform& transform) throw();
  28377. void paintRectangle (LowLevelGraphicsContext& context,
  28378. int x, int y, int w, int h) throw();
  28379. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28380. const Image& alphaChannelImage, int imageX, int imageY,
  28381. int x, int y, int w, int h) throw();
  28382. juce_UseDebuggingNewOperator
  28383. protected:
  28384. Image* image;
  28385. int anchorX, anchorY;
  28386. float opacity;
  28387. private:
  28388. ImageBrush (const ImageBrush&);
  28389. const ImageBrush& operator= (const ImageBrush&);
  28390. void getStartXY (int& x, int& y) const throw();
  28391. };
  28392. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28393. /********* End of inlined file: juce_ImageBrush.h *********/
  28394. #endif
  28395. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28396. #endif
  28397. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28398. #endif
  28399. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28400. #endif
  28401. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28402. #endif
  28403. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28404. #endif
  28405. #ifndef __JUCE_FONT_JUCEHEADER__
  28406. #endif
  28407. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28408. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28409. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28410. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28411. /**
  28412. An glyph from a particular font, with a particular size, style,
  28413. typeface and position.
  28414. @see GlyphArrangement, Font
  28415. */
  28416. class JUCE_API PositionedGlyph
  28417. {
  28418. public:
  28419. /** Returns the character the glyph represents. */
  28420. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28421. /** Checks whether the glyph is actually empty. */
  28422. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28423. /** Returns the position of the glyph's left-hand edge. */
  28424. float getLeft() const throw() { return x; }
  28425. /** Returns the position of the glyph's right-hand edge. */
  28426. float getRight() const throw() { return x + w; }
  28427. /** Returns the y position of the glyph's baseline. */
  28428. float getBaselineY() const throw() { return y; }
  28429. /** Returns the y position of the top of the glyph. */
  28430. float getTop() const throw() { return y - fontAscent; }
  28431. /** Returns the y position of the bottom of the glyph. */
  28432. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28433. /** Shifts the glyph's position by a relative amount. */
  28434. void moveBy (const float deltaX,
  28435. const float deltaY) throw();
  28436. /** Draws the glyph into a graphics context. */
  28437. void draw (const Graphics& g) const throw();
  28438. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28439. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28440. /** Returns the path for this glyph.
  28441. @param path the glyph's outline will be appended to this path
  28442. */
  28443. void createPath (Path& path) const throw();
  28444. /** Checks to see if a point lies within this glyph. */
  28445. bool hitTest (float x, float y) const throw();
  28446. juce_UseDebuggingNewOperator
  28447. private:
  28448. friend class GlyphArrangement;
  28449. float x, y, w;
  28450. float fontHeight, fontAscent, fontHorizontalScale;
  28451. bool isUnderlined;
  28452. const TypefaceGlyphInfo* glyphInfo;
  28453. PositionedGlyph() throw();
  28454. };
  28455. /**
  28456. A set of glyphs, each with a position.
  28457. You can create a GlyphArrangement, text to it and then draw it onto a
  28458. graphics context. It's used internally by the text methods in the
  28459. Graphics class, but can be used directly if more control is needed.
  28460. @see Font, PositionedGlyph
  28461. */
  28462. class JUCE_API GlyphArrangement
  28463. {
  28464. public:
  28465. /** Creates an empty arrangement. */
  28466. GlyphArrangement() throw();
  28467. /** Takes a copy of another arrangement. */
  28468. GlyphArrangement (const GlyphArrangement& other) throw();
  28469. /** Copies another arrangement onto this one.
  28470. To add another arrangement without clearing this one, use addGlyphArrangement().
  28471. */
  28472. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28473. /** Destructor. */
  28474. ~GlyphArrangement() throw();
  28475. /** Returns the total number of glyphs in the arrangement. */
  28476. int getNumGlyphs() const throw() { return numGlyphs; }
  28477. /** Returns one of the glyphs from the arrangement.
  28478. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28479. careful not to pass an out-of-range index here, as it
  28480. doesn't do any bounds-checking.
  28481. */
  28482. PositionedGlyph& getGlyph (const int index) const throw();
  28483. /** Clears all text from the arrangement and resets it.
  28484. */
  28485. void clear() throw();
  28486. /** Appends a line of text to the arrangement.
  28487. This will add the text as a single line, where x is the left-hand edge of the
  28488. first character, and y is the position for the text's baseline.
  28489. If the text contains new-lines or carriage-returns, this will ignore them - use
  28490. addJustifiedText() to add multi-line arrangements.
  28491. */
  28492. void addLineOfText (const Font& font,
  28493. const String& text,
  28494. const float x,
  28495. const float y) throw();
  28496. /** Adds a line of text, truncating it if it's wider than a specified size.
  28497. This is the same as addLineOfText(), but if the line's width exceeds the value
  28498. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  28499. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  28500. */
  28501. void addCurtailedLineOfText (const Font& font,
  28502. const String& text,
  28503. float x,
  28504. const float y,
  28505. const float maxWidthPixels,
  28506. const bool useEllipsis) throw();
  28507. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  28508. This will add text to the arrangement, breaking it into new lines either where there
  28509. is a new-line or carriage-return character in the text, or where a line's width
  28510. exceeds the value set in maxLineWidth.
  28511. Each line that is added will be laid out using the flags set in horizontalLayout, so
  28512. the lines can be left- or right-justified, or centred horizontally in the space
  28513. between x and (x + maxLineWidth).
  28514. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  28515. lines will be placed below it, separated by a distance of font.getHeight().
  28516. */
  28517. void addJustifiedText (const Font& font,
  28518. const String& text,
  28519. float x, float y,
  28520. const float maxLineWidth,
  28521. const Justification& horizontalLayout) throw();
  28522. /** Tries to fit some text withing a given space.
  28523. This does its best to make the given text readable within the specified rectangle,
  28524. so it useful for labelling things.
  28525. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  28526. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  28527. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  28528. it's been truncated.
  28529. A Justification parameter lets you specify how the text is laid out within the rectangle,
  28530. both horizontally and vertically.
  28531. @see Graphics::drawFittedText
  28532. */
  28533. void addFittedText (const Font& font,
  28534. const String& text,
  28535. float x, float y,
  28536. float width, float height,
  28537. const Justification& layout,
  28538. int maximumLinesToUse,
  28539. const float minimumHorizontalScale = 0.7f) throw();
  28540. /** Appends another glyph arrangement to this one. */
  28541. void addGlyphArrangement (const GlyphArrangement& other) throw();
  28542. /** Draws this glyph arrangement to a graphics context.
  28543. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  28544. method, which renders the glyphs as filled vectors.
  28545. */
  28546. void draw (const Graphics& g) const throw();
  28547. /** Draws this glyph arrangement to a graphics context.
  28548. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  28549. method for non-transformed arrangements.
  28550. */
  28551. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28552. /** Converts the set of glyphs into a path.
  28553. @param path the glyphs' outlines will be appended to this path
  28554. */
  28555. void createPath (Path& path) const throw();
  28556. /** Looks for a glyph that contains the given co-ordinate.
  28557. @returns the index of the glyph, or -1 if none were found.
  28558. */
  28559. int findGlyphIndexAt (float x, float y) const throw();
  28560. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  28561. @param startIndex the first glyph to test
  28562. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  28563. startIndex will be included
  28564. @param left on return, the leftmost co-ordinate of the rectangle
  28565. @param top on return, the top co-ordinate of the rectangle
  28566. @param right on return, the rightmost co-ordinate of the rectangle
  28567. @param bottom on return, the bottom co-ordinate of the rectangle
  28568. @param includeWhitespace if true, the extent of any whitespace characters will also
  28569. be taken into account
  28570. */
  28571. void getBoundingBox (int startIndex,
  28572. int numGlyphs,
  28573. float& left,
  28574. float& top,
  28575. float& right,
  28576. float& bottom,
  28577. const bool includeWhitespace) const throw();
  28578. /** Shifts a set of glyphs by a given amount.
  28579. @param startIndex the first glyph to transform
  28580. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  28581. startIndex will be used
  28582. @param deltaX the amount to add to their x-positions
  28583. @param deltaY the amount to add to their y-positions
  28584. */
  28585. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  28586. const float deltaX,
  28587. const float deltaY) throw();
  28588. /** Removes a set of glyphs from the arrangement.
  28589. @param startIndex the first glyph to remove
  28590. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  28591. startIndex will be deleted
  28592. */
  28593. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  28594. /** Expands or compresses a set of glyphs horizontally.
  28595. @param startIndex the first glyph to transform
  28596. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  28597. startIndex will be used
  28598. @param horizontalScaleFactor how much to scale their horizontal width by
  28599. */
  28600. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  28601. const float horizontalScaleFactor) throw();
  28602. /** Justifies a set of glyphs within a given space.
  28603. This moves the glyphs as a block so that the whole thing is located within the
  28604. given rectangle with the specified layout.
  28605. If the Justification::horizontallyJustified flag is specified, each line will
  28606. be stretched out to fill the specified width.
  28607. */
  28608. void justifyGlyphs (const int startIndex, const int numGlyphs,
  28609. const float x,
  28610. const float y,
  28611. const float width,
  28612. const float height,
  28613. const Justification& justification) throw();
  28614. juce_UseDebuggingNewOperator
  28615. private:
  28616. int numGlyphs, numAllocated;
  28617. PositionedGlyph* glyphs;
  28618. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  28619. void removeLast() throw();
  28620. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  28621. void incGlyphRefCount (const int index) const throw();
  28622. void decGlyphRefCount (const int index) const throw();
  28623. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  28624. };
  28625. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28626. /********* End of inlined file: juce_GlyphArrangement.h *********/
  28627. #endif
  28628. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28629. /********* Start of inlined file: juce_TextLayout.h *********/
  28630. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28631. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  28632. class Graphics;
  28633. /**
  28634. A laid-out arrangement of text.
  28635. You can add text in different fonts to a TextLayout object, then call its
  28636. layout() method to word-wrap it into lines. The layout can then be drawn
  28637. using a graphics context.
  28638. It's handy if you've got a message to display, because you can format it,
  28639. measure the extent of the layout, and then create a suitably-sized window
  28640. to show it in.
  28641. @see Font, Graphics::drawFittedText, GlyphArrangement
  28642. */
  28643. class JUCE_API TextLayout
  28644. {
  28645. public:
  28646. /** Creates an empty text layout.
  28647. Text can then be appended using the appendText() method.
  28648. */
  28649. TextLayout() throw();
  28650. /** Creates a copy of another layout object. */
  28651. TextLayout (const TextLayout& other) throw();
  28652. /** Creates a text layout from an initial string and font. */
  28653. TextLayout (const String& text, const Font& font) throw();
  28654. /** Destructor. */
  28655. ~TextLayout() throw();
  28656. /** Copies another layout onto this one. */
  28657. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  28658. /** Clears the layout, removing all its text. */
  28659. void clear() throw();
  28660. /** Adds a string to the end of the arrangement.
  28661. The string will be broken onto new lines wherever it contains
  28662. carriage-returns or linefeeds. After adding it, you can call layout()
  28663. to wrap long lines into a paragraph and justify it.
  28664. */
  28665. void appendText (const String& textToAppend,
  28666. const Font& fontToUse) throw();
  28667. /** Replaces all the text with a new string.
  28668. This is equivalent to calling clear() followed by appendText().
  28669. */
  28670. void setText (const String& newText,
  28671. const Font& fontToUse) throw();
  28672. /** Breaks the text up to form a paragraph with the given width.
  28673. @param maximumWidth any text wider than this will be split
  28674. across multiple lines
  28675. @param justification how the lines are to be laid-out horizontally
  28676. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  28677. width that keeps all the lines of text at a
  28678. similar length - this is good when you're displaying
  28679. a short message and don't want it to get split
  28680. onto two lines with only a couple of words on
  28681. the second line, which looks untidy.
  28682. */
  28683. void layout (int maximumWidth,
  28684. const Justification& justification,
  28685. const bool attemptToBalanceLineLengths) throw();
  28686. /** Returns the overall width of the entire text layout. */
  28687. int getWidth() const throw();
  28688. /** Returns the overall height of the entire text layout. */
  28689. int getHeight() const throw();
  28690. /** Returns the total number of lines of text. */
  28691. int getNumLines() const throw() { return totalLines; }
  28692. /** Returns the width of a particular line of text.
  28693. @param lineNumber the line, from 0 to (getNumLines() - 1)
  28694. */
  28695. int getLineWidth (const int lineNumber) const throw();
  28696. /** Renders the text at a specified position using a graphics context.
  28697. */
  28698. void draw (Graphics& g,
  28699. const int topLeftX,
  28700. const int topLeftY) const throw();
  28701. /** Renders the text within a specified rectangle using a graphics context.
  28702. The justification flags dictate how the block of text should be positioned
  28703. within the rectangle.
  28704. */
  28705. void drawWithin (Graphics& g,
  28706. int x, int y, int w, int h,
  28707. const Justification& layoutFlags) const throw();
  28708. juce_UseDebuggingNewOperator
  28709. private:
  28710. VoidArray tokens;
  28711. int totalLines;
  28712. };
  28713. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  28714. /********* End of inlined file: juce_TextLayout.h *********/
  28715. #endif
  28716. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  28717. #endif
  28718. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28719. /********* Start of inlined file: juce_EdgeTable.h *********/
  28720. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28721. #define __JUCE_EDGETABLE_JUCEHEADER__
  28722. class Path;
  28723. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  28724. /**
  28725. A table of horizontal scan-line segments - used for rasterising Paths.
  28726. @see Path, Graphics
  28727. */
  28728. class JUCE_API EdgeTable
  28729. {
  28730. public:
  28731. /** Indicates the quality at which the edge table should be generated.
  28732. Higher values will have better quality anti-aliasing, but will take
  28733. longer to generate the edge table and to render it.
  28734. */
  28735. enum OversamplingLevel
  28736. {
  28737. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  28738. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  28739. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  28740. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  28741. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  28742. normal user-interface use. */
  28743. };
  28744. /** Creates an empty edge table ready to have paths added.
  28745. A table is created with a fixed vertical size, and only sections of paths
  28746. which lie within their range will be added to the table.
  28747. @param topY the lowest y co-ordinate that the table can contain
  28748. @param height the number of horizontal lines it can contain
  28749. @param verticalOversampling the amount of oversampling used for anti-aliasing
  28750. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  28751. worth changing this except for very special purposes
  28752. */
  28753. EdgeTable (const int topY,
  28754. const int height,
  28755. const OversamplingLevel verticalOversampling = Oversampling_4times,
  28756. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  28757. /** Creates a copy of another edge table. */
  28758. EdgeTable (const EdgeTable& other) throw();
  28759. /** Copies from another edge table. */
  28760. const EdgeTable& operator= (const EdgeTable& other) throw();
  28761. /** Destructor. */
  28762. ~EdgeTable() throw();
  28763. /** Adds edges to the table for a path.
  28764. This will add horizontal lines to the edge table for any parts of the path
  28765. which lie within the vertical bounds for which this table was created.
  28766. @param path the path to add
  28767. @param transform an optional transform to apply to the path while it's
  28768. being added
  28769. */
  28770. void addPath (const Path& path,
  28771. const AffineTransform& transform) throw();
  28772. /** Reduces the amount of space the table has allocated.
  28773. This will shrink the table down to use as little memory as possible - useful for
  28774. read-only tables that get stored and re-used for rendering.
  28775. */
  28776. void optimiseTable() throw();
  28777. /** Iterates the lines in the table, for rendering.
  28778. This function will iterate each line in the table, and call a user-defined class
  28779. to render each pixel or continuous line of pixels that the table contains.
  28780. @param iterationCallback this templated class must contain the following methods:
  28781. @code
  28782. inline void setEdgeTableYPos (int y);
  28783. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  28784. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  28785. @endcode
  28786. (these don't necessarily have to be 'const', but it might help it go faster)
  28787. @param clipLeft the left-hand edge of the rectangle which should be iterated
  28788. @param clipTop the top edge of the rectangle which should be iterated
  28789. @param clipRight the right-hand edge of the rectangle which should be iterated
  28790. @param clipBottom the bottom edge of the rectangle which should be iterated
  28791. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  28792. */
  28793. template <class EdgeTableIterationCallback>
  28794. void iterate (EdgeTableIterationCallback& iterationCallback,
  28795. const int clipLeft,
  28796. int clipTop,
  28797. const int clipRight,
  28798. int clipBottom,
  28799. const int subPixelXOffset) const
  28800. {
  28801. if (clipTop < top)
  28802. clipTop = top;
  28803. if (clipBottom > top + height)
  28804. clipBottom = top + height;
  28805. const int* singleLine = table + lineStrideElements
  28806. * ((clipTop - top) << (int) oversampling);
  28807. int mergedLineAllocation = 128;
  28808. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  28809. int* mergedLine = (int*) temp.getData();
  28810. const int timesOverSampling = 1 << (int) oversampling;
  28811. for (int y = clipTop; y < clipBottom; ++y)
  28812. {
  28813. int numMergedPoints = 0;
  28814. // sort all the oversampled lines into a single merged line ready to draw..
  28815. for (int over = timesOverSampling; --over >= 0;)
  28816. {
  28817. const int* l = singleLine;
  28818. singleLine += lineStrideElements;
  28819. int num = *l;
  28820. jassert (num >= 0);
  28821. if (num > 0)
  28822. {
  28823. if (numMergedPoints + num >= mergedLineAllocation)
  28824. {
  28825. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  28826. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  28827. mergedLine = (int*) temp.getData();
  28828. }
  28829. while (--num >= 0)
  28830. {
  28831. const int x = *++l;
  28832. const int winding = *++l;
  28833. int n = numMergedPoints << 1;
  28834. while (n > 0)
  28835. {
  28836. const int cx = mergedLine [n - 2];
  28837. if (cx <= x)
  28838. break;
  28839. mergedLine [n] = cx;
  28840. --n;
  28841. mergedLine [n + 2] = mergedLine [n];
  28842. --n;
  28843. }
  28844. mergedLine [n] = x;
  28845. mergedLine [n + 1] = winding;
  28846. ++numMergedPoints;
  28847. }
  28848. }
  28849. }
  28850. if (--numMergedPoints > 0)
  28851. {
  28852. const int* line = mergedLine;
  28853. int x = subPixelXOffset + *line;
  28854. int level = *++line;
  28855. int levelAccumulator = 0;
  28856. iterationCallback.setEdgeTableYPos (y);
  28857. while (--numMergedPoints >= 0)
  28858. {
  28859. const int endX = subPixelXOffset + *++line;
  28860. jassert (endX >= x);
  28861. const int absLevel = abs (level);
  28862. int endOfRun = (endX >> 8);
  28863. if (endOfRun == (x >> 8))
  28864. {
  28865. // small segment within the same pixel, so just save it for the next
  28866. // time round..
  28867. levelAccumulator += (endX - x) * absLevel;
  28868. }
  28869. else
  28870. {
  28871. // plot the fist pixel of this segment, including any accumulated
  28872. // levels from smaller segments that haven't been drawn yet
  28873. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  28874. levelAccumulator >>= 8;
  28875. if (levelAccumulator > 0xff)
  28876. levelAccumulator = 0xff;
  28877. x >>= 8;
  28878. if (x >= clipRight)
  28879. {
  28880. levelAccumulator = 0;
  28881. break;
  28882. }
  28883. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  28884. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  28885. if (++x >= clipRight)
  28886. {
  28887. levelAccumulator = 0;
  28888. break;
  28889. }
  28890. // if there's a segment of solid pixels, do it all in one go..
  28891. if (absLevel > 0 && endOfRun > x)
  28892. {
  28893. if (x < clipLeft)
  28894. x = clipLeft;
  28895. if (endOfRun > clipRight)
  28896. endOfRun = clipRight;
  28897. const int numPix = endOfRun - x;
  28898. if (numPix > 0)
  28899. iterationCallback.handleEdgeTableLine (x, numPix,
  28900. jmin (absLevel, 0xff));
  28901. }
  28902. // save the bit at the end to be drawn next time round the loop.
  28903. levelAccumulator = (endX & 0xff) * absLevel;
  28904. }
  28905. level += *++line;
  28906. x = endX;
  28907. }
  28908. if (levelAccumulator > 0)
  28909. {
  28910. levelAccumulator >>= 8;
  28911. if (levelAccumulator > 0xff)
  28912. levelAccumulator = 0xff;
  28913. x >>= 8;
  28914. if (x >= clipLeft && x < clipRight)
  28915. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  28916. }
  28917. }
  28918. }
  28919. }
  28920. juce_UseDebuggingNewOperator
  28921. private:
  28922. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  28923. int* table;
  28924. int top, height, maxEdgesPerLine, lineStrideElements;
  28925. OversamplingLevel oversampling;
  28926. // this will assume that the y co-ord is within bounds, and will avoid checking
  28927. // this for speed.
  28928. void addEdgePoint (const int x, const int y, const int winding) throw();
  28929. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  28930. };
  28931. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  28932. /********* End of inlined file: juce_EdgeTable.h *********/
  28933. #endif
  28934. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  28935. #endif
  28936. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  28937. #endif
  28938. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  28939. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  28940. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  28941. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  28942. /**
  28943. Interface class for graphics context objects, used internally by the Graphics class.
  28944. Users are not supposed to create instances of this class directly - do your drawing
  28945. via the Graphics object instead.
  28946. It's a base class for different types of graphics context, that may perform software-based
  28947. or OS-accelerated rendering.
  28948. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  28949. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  28950. context.
  28951. */
  28952. class JUCE_API LowLevelGraphicsContext
  28953. {
  28954. protected:
  28955. LowLevelGraphicsContext();
  28956. public:
  28957. virtual ~LowLevelGraphicsContext();
  28958. /** Returns true if this device is vector-based, e.g. a printer. */
  28959. virtual bool isVectorDevice() const = 0;
  28960. /** Moves the origin to a new position.
  28961. The co-ords are relative to the current origin, and indicate the new position
  28962. of (0, 0).
  28963. */
  28964. virtual void setOrigin (int x, int y) = 0;
  28965. /** Cliping co-ords are relative to the origin. */
  28966. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  28967. /** Cliping co-ords are relative to the origin. */
  28968. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  28969. /** Cliping co-ords are relative to the origin. */
  28970. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  28971. virtual void saveState() = 0;
  28972. virtual void restoreState() = 0;
  28973. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  28974. virtual const Rectangle getClipBounds() const = 0;
  28975. virtual bool isClipEmpty() const = 0;
  28976. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  28977. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  28978. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  28979. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  28980. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  28981. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  28982. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  28983. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  28984. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  28985. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  28986. virtual void blendImage (const Image& sourceImage,
  28987. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  28988. float alpha) = 0;
  28989. virtual void blendImageRescaling (const Image& sourceImage,
  28990. int destX, int destY, int destW, int destH,
  28991. int sourceX, int sourceY, int sourceW, int sourceH,
  28992. float alpha, const Graphics::ResamplingQuality quality) = 0;
  28993. virtual void blendImageWarping (const Image& sourceImage,
  28994. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  28995. const AffineTransform& transform,
  28996. float alpha, const Graphics::ResamplingQuality quality) = 0;
  28997. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  28998. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  28999. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29000. };
  29001. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29002. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29003. #endif
  29004. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29005. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29006. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29007. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29008. /**
  29009. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29010. into a PostScript document.
  29011. */
  29012. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29013. {
  29014. public:
  29015. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29016. const String& documentTitle,
  29017. const int totalWidth,
  29018. const int totalHeight);
  29019. ~LowLevelGraphicsPostScriptRenderer();
  29020. bool isVectorDevice() const;
  29021. void setOrigin (int x, int y);
  29022. bool reduceClipRegion (int x, int y, int w, int h);
  29023. bool reduceClipRegion (const RectangleList& clipRegion);
  29024. void excludeClipRegion (int x, int y, int w, int h);
  29025. void saveState();
  29026. void restoreState();
  29027. bool clipRegionIntersects (int x, int y, int w, int h);
  29028. const Rectangle getClipBounds() const;
  29029. bool isClipEmpty() const;
  29030. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29031. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29032. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29033. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29034. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29035. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29036. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29037. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29038. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29039. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29040. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29041. int sourceX, int sourceY, float alpha);
  29042. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29043. int sourceX, int sourceY, int sourceW, int sourceH,
  29044. float alpha, const Graphics::ResamplingQuality quality);
  29045. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29046. const AffineTransform& transform,
  29047. float alpha, const Graphics::ResamplingQuality quality);
  29048. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29049. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29050. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29051. juce_UseDebuggingNewOperator
  29052. protected:
  29053. OutputStream& out;
  29054. RectangleList* clip;
  29055. int totalWidth, totalHeight, xOffset, yOffset;
  29056. bool needToClip;
  29057. Colour lastColour;
  29058. struct SavedState
  29059. {
  29060. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29061. ~SavedState();
  29062. RectangleList* clip;
  29063. const int xOffset, yOffset;
  29064. private:
  29065. SavedState (const SavedState&);
  29066. const SavedState& operator= (const SavedState&);
  29067. };
  29068. OwnedArray <SavedState> stateStack;
  29069. void writeClip();
  29070. void writeColour (const Colour& colour);
  29071. void writePath (const Path& path) const;
  29072. void writeXY (const float x, const float y) const;
  29073. void writeTransform (const AffineTransform& trans) const;
  29074. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29075. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29076. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29077. };
  29078. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29079. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29080. #endif
  29081. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29082. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29083. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29084. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29085. /**
  29086. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29087. its rendering in memory.
  29088. User code is not supposed to create instances of this class directly - do all your
  29089. rendering via the Graphics class instead.
  29090. */
  29091. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29092. {
  29093. public:
  29094. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29095. ~LowLevelGraphicsSoftwareRenderer();
  29096. bool isVectorDevice() const;
  29097. void setOrigin (int x, int y);
  29098. bool reduceClipRegion (int x, int y, int w, int h);
  29099. bool reduceClipRegion (const RectangleList& clipRegion);
  29100. void excludeClipRegion (int x, int y, int w, int h);
  29101. void saveState();
  29102. void restoreState();
  29103. bool clipRegionIntersects (int x, int y, int w, int h);
  29104. const Rectangle getClipBounds() const;
  29105. bool isClipEmpty() const;
  29106. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29107. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29108. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29109. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29110. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29111. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29112. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29113. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29114. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29115. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29116. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29117. int sourceX, int sourceY, float alpha);
  29118. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29119. int sourceX, int sourceY, int sourceW, int sourceH,
  29120. float alpha, const Graphics::ResamplingQuality quality);
  29121. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29122. const AffineTransform& transform,
  29123. float alpha, const Graphics::ResamplingQuality quality);
  29124. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29125. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29126. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29127. RectangleList* getRawClipRegion() throw() { return clip; }
  29128. juce_UseDebuggingNewOperator
  29129. protected:
  29130. Image& image;
  29131. RectangleList* clip;
  29132. int xOffset, yOffset;
  29133. struct SavedState
  29134. {
  29135. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29136. ~SavedState();
  29137. RectangleList* clip;
  29138. const int xOffset, yOffset;
  29139. private:
  29140. SavedState (const SavedState&);
  29141. const SavedState& operator= (const SavedState&);
  29142. };
  29143. OwnedArray <SavedState> stateStack;
  29144. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29145. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29146. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29147. const Path& path, const AffineTransform& transform,
  29148. int& x, int& y, int& w, int& h) const;
  29149. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29150. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29151. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29152. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29153. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29154. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29155. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29156. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29157. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29158. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29159. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29160. float alpha);
  29161. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29162. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29163. const AffineTransform& transform,
  29164. float alpha, const Graphics::ResamplingQuality quality);
  29165. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29166. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29167. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29168. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29169. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29170. };
  29171. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29172. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29173. #endif
  29174. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29175. #endif
  29176. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29177. #endif
  29178. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29179. #endif
  29180. #ifndef __JUCE_LINE_JUCEHEADER__
  29181. #endif
  29182. #ifndef __JUCE_PATH_JUCEHEADER__
  29183. #endif
  29184. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29185. /********* Start of inlined file: juce_PathIterator.h *********/
  29186. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29187. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29188. /**
  29189. Flattens a Path object into a series of straight-line sections.
  29190. Use one of these to iterate through a Path object, and it will convert
  29191. all the curves into line sections so it's easy to render or perform
  29192. geometric operations on.
  29193. @see Path
  29194. */
  29195. class JUCE_API PathFlatteningIterator
  29196. {
  29197. public:
  29198. /** Creates a PathFlatteningIterator.
  29199. After creation, use the next() method to initialise the fields in the
  29200. object with the first line's position.
  29201. @param path the path to iterate along
  29202. @param transform a transform to apply to each point in the path being iterated
  29203. @param tolerence the amount by which the curves are allowed to deviate from the
  29204. lines into which they are being broken down - a higher tolerence
  29205. is a bit faster, but less smooth.
  29206. */
  29207. PathFlatteningIterator (const Path& path,
  29208. const AffineTransform& transform = AffineTransform::identity,
  29209. float tolerence = 9.0f) throw();
  29210. /** Destructor. */
  29211. ~PathFlatteningIterator() throw();
  29212. /** Fetches the next line segment from the path.
  29213. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29214. so that they describe the new line segment.
  29215. @returns false when there are no more lines to fetch.
  29216. */
  29217. bool next() throw();
  29218. /** The x position of the start of the current line segment. */
  29219. float x1;
  29220. /** The y position of the start of the current line segment. */
  29221. float y1;
  29222. /** The x position of the end of the current line segment. */
  29223. float x2;
  29224. /** The y position of the end of the current line segment. */
  29225. float y2;
  29226. /** Indicates whether the current line segment is closing a sub-path.
  29227. If the current line is the one that connects the end of a sub-path
  29228. back to the start again, this will be true.
  29229. */
  29230. bool closesSubPath;
  29231. /** The index of the current line within the current sub-path.
  29232. E.g. you can use this to see whether the line is the first one in the
  29233. subpath by seeing if it's 0.
  29234. */
  29235. int subPathIndex;
  29236. /** Returns true if the current segment is the last in the current sub-path. */
  29237. bool isLastInSubpath() const throw() { return stackPos == stackBase; }
  29238. juce_UseDebuggingNewOperator
  29239. private:
  29240. const Path& path;
  29241. const AffineTransform transform;
  29242. float* points;
  29243. float tolerence, subPathCloseX, subPathCloseY;
  29244. bool isIdentityTransform;
  29245. float* stackBase;
  29246. float* stackPos;
  29247. int index, stackSize;
  29248. PathFlatteningIterator (const PathFlatteningIterator&);
  29249. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29250. };
  29251. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29252. /********* End of inlined file: juce_PathIterator.h *********/
  29253. #endif
  29254. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29255. #endif
  29256. #ifndef __JUCE_POINT_JUCEHEADER__
  29257. #endif
  29258. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29259. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29260. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29261. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29262. /**
  29263. A rectangle whose co-ordinates can be defined in terms of absolute or
  29264. proportional distances.
  29265. Designed mainly for storing component positions, this gives you a lot of
  29266. control over how each co-ordinate is stored, either as an absolute position,
  29267. or as a proportion of the size of a parent rectangle.
  29268. It also allows you to define the anchor points by which the rectangle is
  29269. positioned, so for example you could specify that the top right of the
  29270. rectangle should be an absolute distance from its parent's bottom-right corner.
  29271. This object can be stored as a string, which takes the form "x y w h", including
  29272. symbols like '%' and letters to indicate the anchor point. See its toString()
  29273. method for more info.
  29274. Example usage:
  29275. @code
  29276. class MyComponent
  29277. {
  29278. void resized()
  29279. {
  29280. // this will set the child component's x to be 20% of our width, its y
  29281. // to be 30, its width to be 150, and its height to be 50% of our
  29282. // height..
  29283. const PositionedRectangle pos1 ("20% 30 150 50%");
  29284. pos1.applyToComponent (*myChildComponent1);
  29285. // this will inset the child component with a gap of 10 pixels
  29286. // around each of its edges..
  29287. const PositionedRectangle pos2 ("10 10 20M 20M");
  29288. pos2.applyToComponent (*myChildComponent2);
  29289. }
  29290. };
  29291. @endcode
  29292. */
  29293. class JUCE_API PositionedRectangle
  29294. {
  29295. public:
  29296. /** Creates an empty rectangle with all co-ordinates set to zero.
  29297. The default anchor point is top-left; the default
  29298. */
  29299. PositionedRectangle() throw();
  29300. /** Initialises a PositionedRectangle from a saved string version.
  29301. The string must be in the format generated by toString().
  29302. */
  29303. PositionedRectangle (const String& stringVersion) throw();
  29304. /** Creates a copy of another PositionedRectangle. */
  29305. PositionedRectangle (const PositionedRectangle& other) throw();
  29306. /** Copies another PositionedRectangle. */
  29307. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29308. /** Destructor. */
  29309. ~PositionedRectangle() throw();
  29310. /** Returns a string version of this position, from which it can later be
  29311. re-generated.
  29312. The format is four co-ordinates, "x y w h".
  29313. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29314. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29315. as a percentage, e.g. "80%".
  29316. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29317. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29318. the parent's right-hand edge.
  29319. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29320. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29321. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29322. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29323. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29324. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29325. has "c" appended to it. So "-50Rc" would mean that this component's
  29326. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29327. this component's centre should be placed 40% across the parent's width.
  29328. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29329. the number has "M" appended to it.
  29330. To reload a stored string, use the constructor that takes a string parameter.
  29331. */
  29332. const String toString() const throw();
  29333. /** Calculates the absolute position, given the size of the space that
  29334. it should go in.
  29335. This will work out any proportional distances and sizes relative to the
  29336. target rectangle, and will return the absolute position.
  29337. @see applyToComponent
  29338. */
  29339. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29340. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29341. */
  29342. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29343. double& x,
  29344. double& y,
  29345. double& width,
  29346. double& height) const throw();
  29347. /** This sets the bounds of the given component to this position.
  29348. This is equivalent to writing:
  29349. @code
  29350. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29351. @endcode
  29352. @see getRectangle, updateFromComponent
  29353. */
  29354. void applyToComponent (Component& comp) const throw();
  29355. /** Updates this object's co-ordinates to match the given rectangle.
  29356. This will set all co-ordinates based on the given rectangle, re-calculating
  29357. any proportional distances, and using the current anchor points.
  29358. So for example if the x co-ordinate mode is currently proportional, this will
  29359. re-calculate x based on the rectangle's relative position within the target
  29360. rectangle's width.
  29361. If the target rectangle's width or height are zero then it may not be possible
  29362. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29363. will not be changed.
  29364. */
  29365. void updateFrom (const Rectangle& newPosition,
  29366. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29367. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29368. */
  29369. void updateFromDouble (const double x, const double y,
  29370. const double width, const double height,
  29371. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29372. /** Updates this object's co-ordinates to match the bounds of this component.
  29373. This is equivalent to calling updateFrom() with the component's bounds and
  29374. it parent size.
  29375. If the component doesn't currently have a parent, then proportional co-ordinates
  29376. might not be updated because it would need to know the parent's size to do the
  29377. maths for this.
  29378. */
  29379. void updateFromComponent (const Component& comp) throw();
  29380. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29381. enum AnchorPoint
  29382. {
  29383. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29384. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29385. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29386. };
  29387. /** Specifies how an x or y co-ordinate should be interpreted. */
  29388. enum PositionMode
  29389. {
  29390. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29391. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29392. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29393. 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. */
  29394. };
  29395. /** Specifies how the width or height should be interpreted. */
  29396. enum SizeMode
  29397. {
  29398. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29399. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29400. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29401. };
  29402. /** Sets all options for all co-ordinates.
  29403. This requires a reference rectangle to be specified, because if you're changing any
  29404. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29405. the co-ordinates, and will need to know the parent size so it can calculate this.
  29406. */
  29407. void setModes (const AnchorPoint xAnchorMode,
  29408. const PositionMode xPositionMode,
  29409. const AnchorPoint yAnchorMode,
  29410. const PositionMode yPositionMode,
  29411. const SizeMode widthMode,
  29412. const SizeMode heightMode,
  29413. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29414. /** Returns the anchoring mode for the x co-ordinate.
  29415. To change any of the modes, use setModes().
  29416. */
  29417. AnchorPoint getAnchorPointX() const throw();
  29418. /** Returns the positioning mode for the x co-ordinate.
  29419. To change any of the modes, use setModes().
  29420. */
  29421. PositionMode getPositionModeX() const throw();
  29422. /** Returns the raw x co-ordinate.
  29423. If the x position mode is absolute, then this will be the absolute value. If it's
  29424. proportional, then this will be a fractional proportion, where 1.0 means the full
  29425. width of the parent space.
  29426. */
  29427. double getX() const throw() { return x; }
  29428. /** Sets the raw value of the x co-ordinate.
  29429. See getX() for the meaning of this value.
  29430. */
  29431. void setX (const double newX) throw() { x = newX; }
  29432. /** Returns the anchoring mode for the y co-ordinate.
  29433. To change any of the modes, use setModes().
  29434. */
  29435. AnchorPoint getAnchorPointY() const throw();
  29436. /** Returns the positioning mode for the y co-ordinate.
  29437. To change any of the modes, use setModes().
  29438. */
  29439. PositionMode getPositionModeY() const throw();
  29440. /** Returns the raw y co-ordinate.
  29441. If the y position mode is absolute, then this will be the absolute value. If it's
  29442. proportional, then this will be a fractional proportion, where 1.0 means the full
  29443. height of the parent space.
  29444. */
  29445. double getY() const throw() { return y; }
  29446. /** Sets the raw value of the y co-ordinate.
  29447. See getY() for the meaning of this value.
  29448. */
  29449. void setY (const double newY) throw() { y = newY; }
  29450. /** Returns the mode used to calculate the width.
  29451. To change any of the modes, use setModes().
  29452. */
  29453. SizeMode getWidthMode() const throw();
  29454. /** Returns the raw width value.
  29455. If the width mode is absolute, then this will be the absolute value. If the mode is
  29456. proportional, then this will be a fractional proportion, where 1.0 means the full
  29457. width of the parent space.
  29458. */
  29459. double getWidth() const throw() { return w; }
  29460. /** Sets the raw width value.
  29461. See getWidth() for the details about what this value means.
  29462. */
  29463. void setWidth (const double newWidth) throw() { w = newWidth; }
  29464. /** Returns the mode used to calculate the height.
  29465. To change any of the modes, use setModes().
  29466. */
  29467. SizeMode getHeightMode() const throw();
  29468. /** Returns the raw height value.
  29469. If the height mode is absolute, then this will be the absolute value. If the mode is
  29470. proportional, then this will be a fractional proportion, where 1.0 means the full
  29471. height of the parent space.
  29472. */
  29473. double getHeight() const throw() { return h; }
  29474. /** Sets the raw height value.
  29475. See getHeight() for the details about what this value means.
  29476. */
  29477. void setHeight (const double newHeight) throw() { h = newHeight; }
  29478. /** If the size and position are constance, and wouldn't be affected by changes
  29479. in the parent's size, then this will return true.
  29480. */
  29481. bool isPositionAbsolute() const throw();
  29482. /** Compares two objects. */
  29483. const bool operator== (const PositionedRectangle& other) const throw();
  29484. /** Compares two objects. */
  29485. const bool operator!= (const PositionedRectangle& other) const throw();
  29486. juce_UseDebuggingNewOperator
  29487. private:
  29488. double x, y, w, h;
  29489. uint8 xMode, yMode, wMode, hMode;
  29490. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  29491. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  29492. void decodePosString (const String& s, uint8& mode, double& value) throw();
  29493. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  29494. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  29495. const uint8 xMode, const uint8 wMode,
  29496. const int parentPos, const int parentSize) const throw();
  29497. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  29498. const uint8 xMode, const uint8 wMode,
  29499. const int parentPos, const int parentSize) const throw();
  29500. };
  29501. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29502. /********* End of inlined file: juce_PositionedRectangle.h *********/
  29503. #endif
  29504. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29505. #endif
  29506. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  29507. #endif
  29508. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29509. #endif
  29510. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29511. /********* Start of inlined file: juce_ImageCache.h *********/
  29512. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29513. #define __JUCE_IMAGECACHE_JUCEHEADER__
  29514. /**
  29515. A global cache of images that have been loaded from files or memory.
  29516. If you're loading an image and may need to use the image in more than one
  29517. place, this is used to allow the same image to be shared rather than loading
  29518. multiple copies into memory.
  29519. Another advantage is that after images are released, they will be kept in
  29520. memory for a few seconds before it is actually deleted, so if you're repeatedly
  29521. loading/deleting the same image, it'll reduce the chances of having to reload it
  29522. each time.
  29523. @see Image, ImageFileFormat
  29524. */
  29525. class JUCE_API ImageCache : private DeletedAtShutdown,
  29526. private Timer
  29527. {
  29528. public:
  29529. /** Loads an image from a file, (or just returns the image if it's already cached).
  29530. If the cache already contains an image that was loaded from this file,
  29531. that image will be returned. Otherwise, this method will try to load the
  29532. file, add it to the cache, and return it.
  29533. It's very important not to delete the image that is returned - instead use
  29534. the ImageCache::release() method.
  29535. Also, remember that the image returned is shared, so drawing into it might
  29536. affect other things that are using it!
  29537. @param file the file to try to load
  29538. @returns the image, or null if it there was an error loading it
  29539. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29540. */
  29541. static Image* getFromFile (const File& file);
  29542. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  29543. If the cache already contains an image that was loaded from this block of memory,
  29544. that image will be returned. Otherwise, this method will try to load the
  29545. file, add it to the cache, and return it.
  29546. It's very important not to delete the image that is returned - instead use
  29547. the ImageCache::release() method.
  29548. Also, remember that the image returned is shared, so drawing into it might
  29549. affect other things that are using it!
  29550. @param imageData the block of memory containing the image data
  29551. @param dataSize the data size in bytes
  29552. @returns the image, or null if it there was an error loading it
  29553. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29554. */
  29555. static Image* getFromMemory (const void* imageData,
  29556. const int dataSize);
  29557. /** Releases an image that was previously created by the ImageCache.
  29558. If an image has been returned by the getFromFile() or getFromMemory() methods,
  29559. it mustn't be deleted directly, but should be released with this method
  29560. instead.
  29561. @see getFromFile, getFromMemory
  29562. */
  29563. static void release (Image* const imageToRelease);
  29564. /** Checks whether an image is in the cache or not.
  29565. @returns true if the image is currently in the cache
  29566. */
  29567. static bool isImageInCache (Image* const imageToLookFor);
  29568. /** Increments the reference-count for a cached image.
  29569. If the image isn't in the cache, this method won't do anything.
  29570. */
  29571. static void incReferenceCount (Image* const image);
  29572. /** Checks the cache for an image with a particular hashcode.
  29573. If there's an image in the cache with this hashcode, it will be returned,
  29574. otherwise it will return zero.
  29575. If an image is returned, it must be released with the release() method
  29576. when no longer needed, to maintain the correct reference counts.
  29577. @param hashCode the hash code that would have been associated with the
  29578. image by addImageToCache()
  29579. @see addImageToCache
  29580. */
  29581. static Image* getFromHashCode (const int64 hashCode);
  29582. /** Adds an image to the cache with a user-defined hash-code.
  29583. After calling this, responsibilty for deleting the image will be taken
  29584. by the ImageCache.
  29585. The image will be initially be given a reference count of 1, so call
  29586. the release() method to delete it.
  29587. @param image the image to add
  29588. @param hashCode the hash-code to associate with it
  29589. @see getFromHashCode
  29590. */
  29591. static void addImageToCache (Image* const image,
  29592. const int64 hashCode);
  29593. /** Changes the amount of time before an unused image will be removed from the cache.
  29594. By default this is about 5 seconds.
  29595. */
  29596. static void setCacheTimeout (const int millisecs);
  29597. juce_UseDebuggingNewOperator
  29598. private:
  29599. CriticalSection lock;
  29600. VoidArray images;
  29601. ImageCache() throw();
  29602. ImageCache (const ImageCache&);
  29603. const ImageCache& operator= (const ImageCache&);
  29604. ~ImageCache();
  29605. void timerCallback();
  29606. };
  29607. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  29608. /********* End of inlined file: juce_ImageCache.h *********/
  29609. #endif
  29610. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29611. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  29612. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29613. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29614. /**
  29615. Represents a filter kernel to use in convoluting an image.
  29616. @see Image::applyConvolution
  29617. */
  29618. class JUCE_API ImageConvolutionKernel
  29619. {
  29620. public:
  29621. /** Creates an empty convulution kernel.
  29622. @param size the length of each dimension of the kernel, so e.g. if the size
  29623. is 5, it will create a 5x5 kernel
  29624. */
  29625. ImageConvolutionKernel (const int size) throw();
  29626. /** Destructor. */
  29627. ~ImageConvolutionKernel() throw();
  29628. /** Resets all values in the kernel to zero.
  29629. */
  29630. void clear() throw();
  29631. /** Sets the value of a specific cell in the kernel.
  29632. The x and y parameters must be in the range 0 < x < getKernelSize().
  29633. @see setOverallSum
  29634. */
  29635. void setKernelValue (const int x,
  29636. const int y,
  29637. const float value) throw();
  29638. /** Rescales all values in the kernel to make the total add up to a fixed value.
  29639. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  29640. */
  29641. void setOverallSum (const float desiredTotalSum) throw();
  29642. /** Multiplies all values in the kernel by a value. */
  29643. void rescaleAllValues (const float multiplier) throw();
  29644. /** Intialises the kernel for a gaussian blur.
  29645. @param blurRadius this may be larger or smaller than the kernel's actual
  29646. size but this will obviously be wasteful or clip at the
  29647. edges. Ideally the kernel should be just larger than
  29648. (blurRadius * 2).
  29649. */
  29650. void createGaussianBlur (const float blurRadius) throw();
  29651. /** Returns the size of the kernel.
  29652. E.g. if it's a 3x3 kernel, this returns 3.
  29653. */
  29654. int getKernelSize() const throw() { return size; }
  29655. /** Returns a 2-dimensional array of the kernel's values.
  29656. The size of each dimension of the array will be getKernelSize().
  29657. */
  29658. float** getValues() const throw() { return values; }
  29659. /** Applies the kernel to an image.
  29660. @param destImage the image that will receive the resultant convoluted pixels.
  29661. @param sourceImage an optional source image to read from - if this is 0, then the
  29662. destination image will be used as the source. If an image is
  29663. specified, it must be exactly the same size and type as the destination
  29664. image.
  29665. @param x the region of the image to apply the filter to
  29666. @param y the region of the image to apply the filter to
  29667. @param width the region of the image to apply the filter to
  29668. @param height the region of the image to apply the filter to
  29669. */
  29670. void applyToImage (Image& destImage,
  29671. const Image* sourceImage,
  29672. int x,
  29673. int y,
  29674. int width,
  29675. int height) const;
  29676. juce_UseDebuggingNewOperator
  29677. private:
  29678. float** values;
  29679. int size;
  29680. // no reason not to implement these one day..
  29681. ImageConvolutionKernel (const ImageConvolutionKernel&);
  29682. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  29683. };
  29684. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29685. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  29686. #endif
  29687. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29688. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  29689. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29690. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29691. /**
  29692. Base-class for codecs that can read and write image file formats such
  29693. as PNG, JPEG, etc.
  29694. This class also contains static methods to make it easy to load images
  29695. from files, streams or from memory.
  29696. @see Image, ImageCache
  29697. */
  29698. class JUCE_API ImageFileFormat
  29699. {
  29700. protected:
  29701. /** Creates an ImageFormat. */
  29702. ImageFileFormat() throw() {}
  29703. public:
  29704. /** Destructor. */
  29705. virtual ~ImageFileFormat() throw() {}
  29706. /** Returns a description of this file format.
  29707. E.g. "JPEG", "PNG"
  29708. */
  29709. virtual const String getFormatName() = 0;
  29710. /** Returns true if the given stream seems to contain data that this format
  29711. understands.
  29712. The format class should only read the first few bytes of the stream and sniff
  29713. for header bytes that it understands.
  29714. @see decodeImage
  29715. */
  29716. virtual bool canUnderstand (InputStream& input) = 0;
  29717. /** Tries to decode and return an image from the given stream.
  29718. This will be called for an image format after calling its canUnderStand() method
  29719. to see if it can handle the stream.
  29720. @param input the stream to read the data from. The stream will be positioned
  29721. at the start of the image data (but this may not necessarily
  29722. be position 0)
  29723. @returns the image that was decoded, or 0 if it fails. It's the
  29724. caller's responsibility to delete this image when no longer needed.
  29725. @see loadFrom
  29726. */
  29727. virtual Image* decodeImage (InputStream& input) = 0;
  29728. /** Attempts to write an image to a stream.
  29729. To specify extra information like encoding quality, there will be appropriate parameters
  29730. in the subclasses of the specific file types.
  29731. @returns true if it nothing went wrong.
  29732. */
  29733. virtual bool writeImageToStream (const Image& sourceImage,
  29734. OutputStream& destStream) = 0;
  29735. /** Tries the built-in decoders to see if it can find one to read this stream.
  29736. There are currently built-in decoders for PNG, JPEG and GIF formats.
  29737. The object that is returned should not be deleted by the caller.
  29738. @see canUnderstand, decodeImage, loadFrom
  29739. */
  29740. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  29741. /** Tries to load an image from a stream.
  29742. This will use the findImageFormatForStream() method to locate a suitable
  29743. codec, and use that to load the image.
  29744. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29745. caller's responsibility to delete this image when no longer needed.
  29746. */
  29747. static Image* loadFrom (InputStream& input);
  29748. /** Tries to load an image from a file.
  29749. This will use the findImageFormatForStream() method to locate a suitable
  29750. codec, and use that to load the image.
  29751. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29752. caller's responsibility to delete this image when no longer needed.
  29753. */
  29754. static Image* loadFrom (const File& file);
  29755. /** Tries to load an image from a block of raw image data.
  29756. This will use the findImageFormatForStream() method to locate a suitable
  29757. codec, and use that to load the image.
  29758. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29759. caller's responsibility to delete this image when no longer needed.
  29760. */
  29761. static Image* loadFrom (const void* rawData,
  29762. const int numBytesOfData);
  29763. };
  29764. /**
  29765. A type of ImageFileFormat for reading and writing PNG files.
  29766. @see ImageFileFormat, JPEGImageFormat
  29767. */
  29768. class PNGImageFormat : public ImageFileFormat
  29769. {
  29770. public:
  29771. PNGImageFormat() throw();
  29772. ~PNGImageFormat() throw();
  29773. const String getFormatName();
  29774. bool canUnderstand (InputStream& input);
  29775. Image* decodeImage (InputStream& input);
  29776. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29777. };
  29778. /**
  29779. A type of ImageFileFormat for reading and writing JPEG files.
  29780. @see ImageFileFormat, PNGImageFormat
  29781. */
  29782. class JPEGImageFormat : public ImageFileFormat
  29783. {
  29784. public:
  29785. JPEGImageFormat() throw();
  29786. ~JPEGImageFormat() throw();
  29787. /** Specifies the quality to be used when writing a JPEG file.
  29788. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  29789. any negative value is "default" quality
  29790. */
  29791. void setQuality (const float newQuality);
  29792. const String getFormatName();
  29793. bool canUnderstand (InputStream& input);
  29794. Image* decodeImage (InputStream& input);
  29795. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29796. private:
  29797. float quality;
  29798. };
  29799. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29800. /********* End of inlined file: juce_ImageFileFormat.h *********/
  29801. #endif
  29802. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29803. /********* Start of inlined file: juce_Drawable.h *********/
  29804. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29805. #define __JUCE_DRAWABLE_JUCEHEADER__
  29806. /**
  29807. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  29808. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29809. */
  29810. class JUCE_API Drawable
  29811. {
  29812. protected:
  29813. /** The base class can't be instantiated directly.
  29814. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29815. */
  29816. Drawable();
  29817. public:
  29818. /** Destructor. */
  29819. virtual ~Drawable();
  29820. /** Creates a deep copy of this Drawable object.
  29821. Use this to create a new copy of this and any sub-objects in the tree.
  29822. */
  29823. virtual Drawable* createCopy() const = 0;
  29824. /** Renders this Drawable object.
  29825. This is the main rendering method you should call to render a Drawable.
  29826. @see drawWithin
  29827. */
  29828. virtual void draw (Graphics& g,
  29829. const AffineTransform& transform = AffineTransform::identity) const = 0;
  29830. /** Renders the Drawable at a given offset within the Graphics context.
  29831. The co-ordinates passed-in are used to translate the object relative to its own
  29832. origin before drawing it - this is basically a quick way of saying:
  29833. @code
  29834. draw (g, AffineTransform::translation (x, y)).
  29835. @endcode
  29836. */
  29837. void drawAt (Graphics& g,
  29838. const float x,
  29839. const float y) const;
  29840. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  29841. changing its aspect-ratio.
  29842. The object can placed arbitrarily within the rectangle based on a Justification type,
  29843. and can either be made as big as possible, or just reduced to fit.
  29844. @param g the graphics context to render onto
  29845. @param destX top-left of the target rectangle to fit it into
  29846. @param destY top-left of the target rectangle to fit it into
  29847. @param destWidth size of the target rectangle to fit the image into
  29848. @param destHeight size of the target rectangle to fit the image into
  29849. @param placement defines the alignment and rescaling to use to fit
  29850. this object within the target rectangle.
  29851. */
  29852. void drawWithin (Graphics& g,
  29853. const int destX,
  29854. const int destY,
  29855. const int destWidth,
  29856. const int destHeight,
  29857. const RectanglePlacement& placement) const;
  29858. /** Returns the smallest rectangle that can contain this Drawable object.
  29859. Co-ordinates are relative to the object's own origin.
  29860. */
  29861. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  29862. /** Returns true if the given point is somewhere inside this Drawable.
  29863. Co-ordinates are relative to the object's own origin.
  29864. */
  29865. virtual bool hitTest (float x, float y) const = 0;
  29866. /** Returns the name given to this drawable.
  29867. @see setName
  29868. */
  29869. const String& getName() const throw() { return name; }
  29870. /** Assigns a name to this drawable. */
  29871. void setName (const String& newName) throw() { name = newName; }
  29872. /** Tries to turn some kind of image file into a drawable.
  29873. The data could be an image that the ImageFileFormat class understands, or it
  29874. could be SVG.
  29875. */
  29876. static Drawable* createFromImageData (const void* data, const int numBytes);
  29877. /** Tries to turn a stream containing some kind of image data into a drawable.
  29878. The data could be an image that the ImageFileFormat class understands, or it
  29879. could be SVG.
  29880. */
  29881. static Drawable* createFromImageDataStream (InputStream& dataSource);
  29882. /** Tries to turn a file containing some kind of image data into a drawable.
  29883. The data could be an image that the ImageFileFormat class understands, or it
  29884. could be SVG.
  29885. */
  29886. static Drawable* createFromImageFile (const File& file);
  29887. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  29888. into a Drawable tree.
  29889. The object returned must be deleted by the caller. If something goes wrong
  29890. while parsing, it may return 0.
  29891. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  29892. implementation, but it can return the basic vector objects.
  29893. */
  29894. static Drawable* createFromSVG (const XmlElement& svgDocument);
  29895. juce_UseDebuggingNewOperator
  29896. private:
  29897. Drawable (const Drawable&);
  29898. const Drawable& operator= (const Drawable&);
  29899. String name;
  29900. };
  29901. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  29902. /********* End of inlined file: juce_Drawable.h *********/
  29903. #endif
  29904. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29905. /********* Start of inlined file: juce_DrawableComposite.h *********/
  29906. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29907. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29908. /**
  29909. A drawable object which acts as a container for a set of other Drawables.
  29910. @see Drawable
  29911. */
  29912. class JUCE_API DrawableComposite : public Drawable
  29913. {
  29914. public:
  29915. /** Creates a composite Drawable.
  29916. */
  29917. DrawableComposite();
  29918. /** Destructor. */
  29919. virtual ~DrawableComposite();
  29920. /** Adds a new sub-drawable to this one.
  29921. This passes in a Drawable pointer for this object to look after. To add a copy
  29922. of a drawable, use the form of this method that takes a Drawable reference instead.
  29923. @param drawable the object to add - this will be deleted automatically
  29924. when no longer needed, so the caller mustn't keep any
  29925. pointers to it.
  29926. @param transform the transform to apply to this drawable when it's being
  29927. drawn
  29928. @param index where to insert it in the list of drawables. 0 is the back,
  29929. -1 is the front, or any value from 0 and getNumDrawables()
  29930. can be used
  29931. @see removeDrawable
  29932. */
  29933. void insertDrawable (Drawable* drawable,
  29934. const AffineTransform& transform = AffineTransform::identity,
  29935. const int index = -1);
  29936. /** Adds a new sub-drawable to this one.
  29937. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  29938. for this object to look after, use the form of this method that takes a Drawable
  29939. pointer instead.
  29940. @param drawable the object to add - an internal copy will be made of this object
  29941. @param transform the transform to apply to this drawable when it's being
  29942. drawn
  29943. @param index where to insert it in the list of drawables. 0 is the back,
  29944. -1 is the front, or any value from 0 and getNumDrawables()
  29945. can be used
  29946. @see removeDrawable
  29947. */
  29948. void insertDrawable (const Drawable& drawable,
  29949. const AffineTransform& transform = AffineTransform::identity,
  29950. const int index = -1);
  29951. /** Deletes one of the Drawable objects.
  29952. @param index the index of the drawable to delete, between 0
  29953. and (getNumDrawables() - 1).
  29954. @see insertDrawable, getNumDrawables
  29955. */
  29956. void removeDrawable (const int index);
  29957. /** Returns the number of drawables contained inside this one.
  29958. @see getDrawable
  29959. */
  29960. int getNumDrawables() const throw() { return drawables.size(); }
  29961. /** Returns one of the drawables that are contained in this one.
  29962. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  29963. to find it.
  29964. The pointer returned is managed by this object and will be deleted when no longer
  29965. needed, so be careful what you do with it.
  29966. @see getNumDrawables
  29967. */
  29968. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  29969. /** Returns the transform that applies to one of the drawables that are contained in this one.
  29970. The pointer returned is managed by this object and will be deleted when no longer
  29971. needed, so be careful what you do with it.
  29972. @see getNumDrawables
  29973. */
  29974. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  29975. /** Brings one of the Drawables to the front.
  29976. @param index the index of the drawable to move, between 0
  29977. and (getNumDrawables() - 1).
  29978. @see insertDrawable, getNumDrawables
  29979. */
  29980. void bringToFront (const int index);
  29981. /** @internal */
  29982. void draw (Graphics& g, const AffineTransform& transform) const;
  29983. /** @internal */
  29984. void getBounds (float& x, float& y, float& width, float& height) const;
  29985. /** @internal */
  29986. bool hitTest (float x, float y) const;
  29987. /** @internal */
  29988. Drawable* createCopy() const;
  29989. juce_UseDebuggingNewOperator
  29990. private:
  29991. OwnedArray <Drawable> drawables;
  29992. OwnedArray <AffineTransform> transforms;
  29993. DrawableComposite (const DrawableComposite&);
  29994. const DrawableComposite& operator= (const DrawableComposite&);
  29995. };
  29996. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29997. /********* End of inlined file: juce_DrawableComposite.h *********/
  29998. #endif
  29999. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30000. /********* Start of inlined file: juce_DrawableImage.h *********/
  30001. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30002. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30003. /**
  30004. A drawable object which is a bitmap image.
  30005. @see Drawable
  30006. */
  30007. class JUCE_API DrawableImage : public Drawable
  30008. {
  30009. public:
  30010. DrawableImage();
  30011. /** Destructor. */
  30012. virtual ~DrawableImage();
  30013. /** Sets the image that this drawable will render.
  30014. An internal copy is made of the image passed-in. If you want to provide an
  30015. image that this object can take charge of without needing to create a copy,
  30016. use the other setImage() method.
  30017. */
  30018. void setImage (const Image& imageToCopy);
  30019. /** Sets the image that this drawable will render.
  30020. An internal copy of this will not be made, so the caller mustn't delete
  30021. the image while it's still being used by this object.
  30022. A good way to use this is with the ImageCache - if you create an image
  30023. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30024. it'll be released neatly with its reference count being decreased.
  30025. @param imageToUse the image to render
  30026. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30027. then the image will be deleted when this object no longer
  30028. needs it - unless the image was created by the ImageCache,
  30029. in which case it will be released with ImageCache::release().
  30030. */
  30031. void setImage (Image* imageToUse,
  30032. const bool releaseWhenNotNeeded);
  30033. /** Returns the current image. */
  30034. Image* getImage() const throw() { return image; }
  30035. /** Clears (and possibly deletes) the currently set image. */
  30036. void clearImage();
  30037. /** Sets the opacity to use when drawing the image. */
  30038. void setOpacity (const float newOpacity);
  30039. /** Returns the image's opacity. */
  30040. float getOpacity() const throw() { return opacity; }
  30041. /** Sets a colour to draw over the image's alpha channel.
  30042. By default this is transparent so isn't drawn, but if you set a non-transparent
  30043. colour here, then it will be overlaid on the image, using the image's alpha
  30044. channel as a mask.
  30045. This is handy for doing things like darkening or lightening an image by overlaying
  30046. it with semi-transparent black or white.
  30047. */
  30048. void setOverlayColour (const Colour& newOverlayColour);
  30049. /** Returns the overlay colour. */
  30050. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30051. /** @internal */
  30052. void draw (Graphics& g, const AffineTransform& transform) const;
  30053. /** @internal */
  30054. void getBounds (float& x, float& y, float& width, float& height) const;
  30055. /** @internal */
  30056. bool hitTest (float x, float y) const;
  30057. /** @internal */
  30058. Drawable* createCopy() const;
  30059. juce_UseDebuggingNewOperator
  30060. private:
  30061. Image* image;
  30062. bool canDeleteImage;
  30063. float opacity;
  30064. Colour overlayColour;
  30065. DrawableImage (const DrawableImage&);
  30066. const DrawableImage& operator= (const DrawableImage&);
  30067. };
  30068. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30069. /********* End of inlined file: juce_DrawableImage.h *********/
  30070. #endif
  30071. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30072. /********* Start of inlined file: juce_DrawablePath.h *********/
  30073. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30074. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30075. /**
  30076. A drawable object which renders a filled or outlined shape.
  30077. @see Drawable
  30078. */
  30079. class JUCE_API DrawablePath : public Drawable
  30080. {
  30081. public:
  30082. /** Creates a DrawablePath.
  30083. */
  30084. DrawablePath();
  30085. /** Destructor. */
  30086. virtual ~DrawablePath();
  30087. /** Changes the path that will be drawn.
  30088. @see setSolidFill, setOutline
  30089. */
  30090. void setPath (const Path& newPath);
  30091. /** Returns the current path. */
  30092. const Path& getPath() const throw() { return path; }
  30093. /** Sets a colour to fill the path with.
  30094. This colour is used to fill the path - if you don't want the path to be
  30095. filled (e.g. if you're just drawing an outline), set this colour to be
  30096. transparent.
  30097. @see setPath, setOutline
  30098. */
  30099. void setSolidFill (const Colour& newColour);
  30100. /** Sets a custom brush to use to fill the path.
  30101. @see setSolidFill
  30102. */
  30103. void setFillBrush (const Brush& newBrush);
  30104. /** Returns the brush currently being used to fill the shape. */
  30105. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30106. /** Changes the properties of the outline that will be drawn around the path.
  30107. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30108. colour passed-in here will be used for it.
  30109. @see setPath, setSolidFill
  30110. */
  30111. void setOutline (const float thickness,
  30112. const Colour& outlineColour);
  30113. /** Changes the properties of the outline that will be drawn around the path.
  30114. If the stroke type has 0 thickness, no outline will be drawn.
  30115. @see setPath, setSolidFill
  30116. */
  30117. void setOutline (const PathStrokeType& strokeType,
  30118. const Brush& strokeBrush);
  30119. /** Returns the current outline style. */
  30120. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30121. /** Returns the brush currently being used to draw the outline. */
  30122. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30123. /** @internal */
  30124. void draw (Graphics& g, const AffineTransform& transform) const;
  30125. /** @internal */
  30126. void getBounds (float& x, float& y, float& width, float& height) const;
  30127. /** @internal */
  30128. bool hitTest (float x, float y) const;
  30129. /** @internal */
  30130. Drawable* createCopy() const;
  30131. juce_UseDebuggingNewOperator
  30132. private:
  30133. Path path, outline;
  30134. Brush* fillBrush;
  30135. Brush* strokeBrush;
  30136. PathStrokeType strokeType;
  30137. void updateOutline();
  30138. DrawablePath (const DrawablePath&);
  30139. const DrawablePath& operator= (const DrawablePath&);
  30140. };
  30141. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30142. /********* End of inlined file: juce_DrawablePath.h *********/
  30143. #endif
  30144. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30145. /********* Start of inlined file: juce_DrawableText.h *********/
  30146. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30147. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30148. /**
  30149. A drawable object which renders a line of text.
  30150. @see Drawable
  30151. */
  30152. class JUCE_API DrawableText : public Drawable
  30153. {
  30154. public:
  30155. /** Creates a DrawableText object. */
  30156. DrawableText();
  30157. /** Destructor. */
  30158. virtual ~DrawableText();
  30159. /** Sets the block of text to render */
  30160. void setText (const GlyphArrangement& newText);
  30161. /** Sets a single line of text to render.
  30162. This is a convenient method of adding a single line - for
  30163. more complex text, use the setText() that takes a
  30164. GlyphArrangement instead.
  30165. */
  30166. void setText (const String& newText, const Font& fontToUse);
  30167. /** Returns the text arrangement that was set with setText(). */
  30168. const GlyphArrangement& getText() const throw() { return text; }
  30169. /** Sets the colour of the text. */
  30170. void setColour (const Colour& newColour);
  30171. /** Returns the current text colour. */
  30172. const Colour& getColour() const throw() { return colour; }
  30173. /** @internal */
  30174. void draw (Graphics& g, const AffineTransform& transform) const;
  30175. /** @internal */
  30176. void getBounds (float& x, float& y, float& width, float& height) const;
  30177. /** @internal */
  30178. bool hitTest (float x, float y) const;
  30179. /** @internal */
  30180. Drawable* createCopy() const;
  30181. juce_UseDebuggingNewOperator
  30182. private:
  30183. GlyphArrangement text;
  30184. Colour colour;
  30185. DrawableText (const DrawableText&);
  30186. const DrawableText& operator= (const DrawableText&);
  30187. };
  30188. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30189. /********* End of inlined file: juce_DrawableText.h *********/
  30190. #endif
  30191. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30192. #endif
  30193. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30194. #endif
  30195. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30196. #endif
  30197. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30198. #endif
  30199. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30200. /********* Start of inlined file: juce_ArrowButton.h *********/
  30201. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30202. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30203. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30204. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30205. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30206. /**
  30207. An effect filter that adds a drop-shadow behind the image's content.
  30208. (This will only work on images/components that aren't opaque, of course).
  30209. When added to a component, this effect will draw a soft-edged
  30210. shadow based on what gets drawn inside it. The shadow will also
  30211. be applied to the component's children.
  30212. For speed, this doesn't use a proper gaussian blur, but cheats by
  30213. using a simple bilinear filter. If you need a really high-quality
  30214. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30215. @see Component::setComponentEffect
  30216. */
  30217. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30218. {
  30219. public:
  30220. /** Creates a default drop-shadow effect.
  30221. To customise the shadow's appearance, use the setShadowProperties()
  30222. method.
  30223. */
  30224. DropShadowEffect();
  30225. /** Destructor. */
  30226. ~DropShadowEffect();
  30227. /** Sets up parameters affecting the shadow's appearance.
  30228. @param newRadius the (approximate) radius of the blur used
  30229. @param newOpacity the opacity with which the shadow is rendered
  30230. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30231. component's contents
  30232. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30233. component's contents
  30234. */
  30235. void setShadowProperties (const float newRadius,
  30236. const float newOpacity,
  30237. const int newShadowOffsetX,
  30238. const int newShadowOffsetY);
  30239. /** @internal */
  30240. void applyEffect (Image& sourceImage, Graphics& destContext);
  30241. juce_UseDebuggingNewOperator
  30242. private:
  30243. int offsetX, offsetY;
  30244. float radius, opacity;
  30245. };
  30246. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30247. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30248. /**
  30249. A button with an arrow in it.
  30250. @see Button
  30251. */
  30252. class JUCE_API ArrowButton : public Button
  30253. {
  30254. public:
  30255. /** Creates an ArrowButton.
  30256. @param buttonName the name to give the button
  30257. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30258. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30259. @param arrowColour the colour to use for the arrow
  30260. */
  30261. ArrowButton (const String& buttonName,
  30262. float arrowDirection,
  30263. const Colour& arrowColour);
  30264. /** Destructor. */
  30265. ~ArrowButton();
  30266. juce_UseDebuggingNewOperator
  30267. protected:
  30268. /** @internal */
  30269. void paintButton (Graphics& g,
  30270. bool isMouseOverButton,
  30271. bool isButtonDown);
  30272. /** @internal */
  30273. void buttonStateChanged();
  30274. private:
  30275. Colour colour;
  30276. DropShadowEffect shadow;
  30277. Path path;
  30278. int offset;
  30279. ArrowButton (const ArrowButton&);
  30280. const ArrowButton& operator= (const ArrowButton&);
  30281. };
  30282. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30283. /********* End of inlined file: juce_ArrowButton.h *********/
  30284. #endif
  30285. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30286. #endif
  30287. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30288. /********* Start of inlined file: juce_DrawableButton.h *********/
  30289. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30290. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30291. /**
  30292. A button that displays a Drawable.
  30293. Up to three Drawable objects can be given to this button, to represent the
  30294. 'normal', 'over' and 'down' states.
  30295. @see Button
  30296. */
  30297. class JUCE_API DrawableButton : public Button
  30298. {
  30299. public:
  30300. enum ButtonStyle
  30301. {
  30302. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30303. ImageRaw, /**< The button will just display the images in their normal size and position.
  30304. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30305. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30306. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30307. };
  30308. /** Creates a DrawableButton.
  30309. After creating one of these, use setImages() to specify the drawables to use.
  30310. @param buttonName the name to give the component
  30311. @param buttonStyle the layout to use
  30312. @see ButtonStyle, setButtonStyle, setImages
  30313. */
  30314. DrawableButton (const String& buttonName,
  30315. const ButtonStyle buttonStyle);
  30316. /** Destructor. */
  30317. ~DrawableButton();
  30318. /** Sets up the images to draw for the various button states.
  30319. The button will keep its own internal copies of these drawables.
  30320. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30321. will be made of the object passed-in if it is non-zero.
  30322. @param overImage the thing to draw for the button's 'over' state - if this is
  30323. zero, the button's normal image will be used when the mouse is
  30324. over it. An internal copy will be made of the object passed-in
  30325. if it is non-zero.
  30326. @param downImage the thing to draw for the button's 'down' state - if this is
  30327. zero, the 'over' image will be used instead (or the normal image
  30328. as a last resort). An internal copy will be made of the object
  30329. passed-in if it is non-zero.
  30330. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30331. the normal image will be drawn with a reduced opacity instead.
  30332. An internal copy will be made of the object passed-in if it is
  30333. non-zero.
  30334. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30335. state is 'on'. If this is 0, the normal image is used instead
  30336. @param overImageOn same as the overImage, but this is used when the button's toggle
  30337. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30338. @param downImageOn same as the downImage, but this is used when the button's toggle
  30339. state is 'on'. If this is 0, the overImageOn is drawn instead
  30340. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30341. state is 'on'. If this is 0, the normal image will be drawn instead
  30342. with a reduced opacity
  30343. */
  30344. void setImages (const Drawable* normalImage,
  30345. const Drawable* overImage = 0,
  30346. const Drawable* downImage = 0,
  30347. const Drawable* disabledImage = 0,
  30348. const Drawable* normalImageOn = 0,
  30349. const Drawable* overImageOn = 0,
  30350. const Drawable* downImageOn = 0,
  30351. const Drawable* disabledImageOn = 0);
  30352. /** Changes the button's style.
  30353. @see ButtonStyle
  30354. */
  30355. void setButtonStyle (const ButtonStyle newStyle);
  30356. /** Changes the button's background colours.
  30357. The toggledOffColour is the colour to use when the button's toggle state
  30358. is off, and toggledOnColour when it's on.
  30359. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30360. used to fill the background of the component.
  30361. For an ImageOnButtonBackground style, the colour is used to draw the
  30362. button's lozenge shape and exactly how the colour's used will depend
  30363. on the LookAndFeel.
  30364. */
  30365. void setBackgroundColours (const Colour& toggledOffColour,
  30366. const Colour& toggledOnColour);
  30367. /** Returns the current background colour being used.
  30368. @see setBackgroundColour
  30369. */
  30370. const Colour& getBackgroundColour() const throw();
  30371. /** Gives the button an optional amount of space around the edge of the drawable.
  30372. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30373. ones on a button background. If the button is too small for the given gap, a
  30374. smaller gap will be used.
  30375. By default there's a gap of about 3 pixels.
  30376. */
  30377. void setEdgeIndent (const int numPixelsIndent);
  30378. /** Returns the image that the button is currently displaying. */
  30379. const Drawable* getCurrentImage() const throw();
  30380. const Drawable* getNormalImage() const throw();
  30381. const Drawable* getOverImage() const throw();
  30382. const Drawable* getDownImage() const throw();
  30383. juce_UseDebuggingNewOperator
  30384. protected:
  30385. /** @internal */
  30386. void paintButton (Graphics& g,
  30387. bool isMouseOverButton,
  30388. bool isButtonDown);
  30389. private:
  30390. ButtonStyle style;
  30391. Drawable* normalImage;
  30392. Drawable* overImage;
  30393. Drawable* downImage;
  30394. Drawable* disabledImage;
  30395. Drawable* normalImageOn;
  30396. Drawable* overImageOn;
  30397. Drawable* downImageOn;
  30398. Drawable* disabledImageOn;
  30399. Colour backgroundOff, backgroundOn;
  30400. int edgeIndent;
  30401. void deleteImages();
  30402. DrawableButton (const DrawableButton&);
  30403. const DrawableButton& operator= (const DrawableButton&);
  30404. };
  30405. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30406. /********* End of inlined file: juce_DrawableButton.h *********/
  30407. #endif
  30408. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30409. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30410. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30411. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30412. /**
  30413. A button showing an underlined weblink, that will launch the link
  30414. when it's clicked.
  30415. @see Button
  30416. */
  30417. class JUCE_API HyperlinkButton : public Button
  30418. {
  30419. public:
  30420. /** Creates a HyperlinkButton.
  30421. @param linkText the text that will be displayed in the button - this is
  30422. also set as the Component's name, but the text can be
  30423. changed later with the Button::getButtonText() method
  30424. @param linkURL the URL to launch when the user clicks the button
  30425. */
  30426. HyperlinkButton (const String& linkText,
  30427. const URL& linkURL);
  30428. /** Destructor. */
  30429. ~HyperlinkButton();
  30430. /** Changes the font to use for the text.
  30431. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30432. to match the size of the component.
  30433. */
  30434. void setFont (const Font& newFont,
  30435. const bool resizeToMatchComponentHeight,
  30436. const Justification& justificationType = Justification::horizontallyCentred);
  30437. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30438. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30439. methods.
  30440. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30441. */
  30442. enum ColourIds
  30443. {
  30444. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30445. };
  30446. /** Changes the URL that the button will trigger. */
  30447. void setURL (const URL& newURL) throw();
  30448. /** Returns the URL that the button will trigger. */
  30449. const URL& getURL() const throw() { return url; }
  30450. /** Resizes the button horizontally to fit snugly around the text.
  30451. This won't affect the button's height.
  30452. */
  30453. void changeWidthToFitText();
  30454. juce_UseDebuggingNewOperator
  30455. protected:
  30456. /** @internal */
  30457. void clicked();
  30458. /** @internal */
  30459. void colourChanged();
  30460. /** @internal */
  30461. void paintButton (Graphics& g,
  30462. bool isMouseOverButton,
  30463. bool isButtonDown);
  30464. private:
  30465. URL url;
  30466. Font font;
  30467. bool resizeFont;
  30468. Justification justification;
  30469. const Font getFontToUse() const;
  30470. HyperlinkButton (const HyperlinkButton&);
  30471. const HyperlinkButton& operator= (const HyperlinkButton&);
  30472. };
  30473. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30474. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30475. #endif
  30476. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30477. /********* Start of inlined file: juce_ImageButton.h *********/
  30478. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30479. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30480. /**
  30481. As the title suggests, this is a button containing an image.
  30482. The colour and transparency of the image can be set to vary when the
  30483. button state changes.
  30484. @see Button, ShapeButton, TextButton
  30485. */
  30486. class JUCE_API ImageButton : public Button
  30487. {
  30488. public:
  30489. /** Creates an ImageButton.
  30490. Use setImage() to specify the image to use. The colours and opacities that
  30491. are specified here can be changed later using setDrawingOptions().
  30492. @param name the name to give the component
  30493. */
  30494. ImageButton (const String& name);
  30495. /** Destructor. */
  30496. ~ImageButton();
  30497. /** Sets up the images to draw in various states.
  30498. Important! Bear in mind that if you pass the same image in for more than one of
  30499. these parameters, this button will delete it (or release from the ImageCache)
  30500. multiple times!
  30501. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30502. resized to the same dimensions as the normal image
  30503. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30504. button when the button's size changes
  30505. @param preserveImageProportions if true then any rescaling of the image to fit
  30506. the button will keep the image's x and y proportions
  30507. correct - i.e. it won't distort its shape, although
  30508. this might create gaps around the edges
  30509. @param normalImage the image to use when the button is in its normal state. The
  30510. image passed in will be deleted (or released if it
  30511. was created by the ImageCache class) when the
  30512. button no longer needs it.
  30513. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30514. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30515. normal image - if this colour is transparent, no overlay
  30516. will be drawn. The overlay will be drawn over the top of the
  30517. image, so you can basically add a solid or semi-transparent
  30518. colour to the image to brighten or darken it
  30519. @param overImage the image to use when the mouse is over the button. If
  30520. you want to use the same image as was set in the normalImage
  30521. parameter, this value can be 0. As for normalImage, it
  30522. will be deleted or released by the button when no longer
  30523. needed
  30524. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30525. is over the button
  30526. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30527. image when the mouse is over - if this colour is transparent,
  30528. no overlay will be drawn
  30529. @param downImage an image to use when the button is pressed down. If set
  30530. to zero, the 'over' image will be drawn instead (or the
  30531. normal image if there isn't an 'over' image either). This
  30532. image will be deleted or released by the button when no
  30533. longer needed
  30534. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30535. is pressed
  30536. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30537. image when the button is pressed down - if this colour is
  30538. transparent, no overlay will be drawn
  30539. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30540. whenever it's inside the button's bounding rectangle. If
  30541. set to values higher than 0, the mouse will only be
  30542. considered to be over the image when the value of the
  30543. image's alpha channel at that position is greater than
  30544. this level.
  30545. */
  30546. void setImages (const bool resizeButtonNowToFitThisImage,
  30547. const bool rescaleImagesWhenButtonSizeChanges,
  30548. const bool preserveImageProportions,
  30549. Image* const normalImage,
  30550. const float imageOpacityWhenNormal,
  30551. const Colour& overlayColourWhenNormal,
  30552. Image* const overImage,
  30553. const float imageOpacityWhenOver,
  30554. const Colour& overlayColourWhenOver,
  30555. Image* const downImage,
  30556. const float imageOpacityWhenDown,
  30557. const Colour& overlayColourWhenDown,
  30558. const float hitTestAlphaThreshold = 0.0f);
  30559. /** Returns the currently set 'normal' image. */
  30560. Image* getNormalImage() const throw();
  30561. /** Returns the image that's drawn when the mouse is over the button.
  30562. If an 'over' image has been set, this will return it; otherwise it'll
  30563. just return the normal image.
  30564. */
  30565. Image* getOverImage() const throw();
  30566. /** Returns the image that's drawn when the button is held down.
  30567. If a 'down' image has been set, this will return it; otherwise it'll
  30568. return the 'over' image or normal image, depending on what's available.
  30569. */
  30570. Image* getDownImage() const throw();
  30571. juce_UseDebuggingNewOperator
  30572. protected:
  30573. /** @internal */
  30574. bool hitTest (int x, int y);
  30575. /** @internal */
  30576. void paintButton (Graphics& g,
  30577. bool isMouseOverButton,
  30578. bool isButtonDown);
  30579. private:
  30580. bool scaleImageToFit, preserveProportions;
  30581. unsigned char alphaThreshold;
  30582. int imageX, imageY, imageW, imageH;
  30583. Image* normalImage;
  30584. Image* overImage;
  30585. Image* downImage;
  30586. float normalOpacity, overOpacity, downOpacity;
  30587. Colour normalOverlay, overOverlay, downOverlay;
  30588. Image* getCurrentImage() const;
  30589. void deleteImages();
  30590. ImageButton (const ImageButton&);
  30591. const ImageButton& operator= (const ImageButton&);
  30592. };
  30593. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30594. /********* End of inlined file: juce_ImageButton.h *********/
  30595. #endif
  30596. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30597. /********* Start of inlined file: juce_ShapeButton.h *********/
  30598. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30599. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30600. /**
  30601. A button that contains a filled shape.
  30602. @see Button, ImageButton, TextButton, ArrowButton
  30603. */
  30604. class JUCE_API ShapeButton : public Button
  30605. {
  30606. public:
  30607. /** Creates a ShapeButton.
  30608. @param name a name to give the component - see Component::setName()
  30609. @param normalColour the colour to fill the shape with when the mouse isn't over
  30610. @param overColour the colour to use when the mouse is over the shape
  30611. @param downColour the colour to use when the button is in the pressed-down state
  30612. */
  30613. ShapeButton (const String& name,
  30614. const Colour& normalColour,
  30615. const Colour& overColour,
  30616. const Colour& downColour);
  30617. /** Destructor. */
  30618. ~ShapeButton();
  30619. /** Sets the shape to use.
  30620. @param newShape the shape to use
  30621. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30622. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30623. the button is resized
  30624. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30625. */
  30626. void setShape (const Path& newShape,
  30627. const bool resizeNowToFitThisShape,
  30628. const bool maintainShapeProportions,
  30629. const bool hasDropShadow);
  30630. /** Set the colours to use for drawing the shape.
  30631. @param normalColour the colour to fill the shape with when the mouse isn't over
  30632. @param overColour the colour to use when the mouse is over the shape
  30633. @param downColour the colour to use when the button is in the pressed-down state
  30634. */
  30635. void setColours (const Colour& normalColour,
  30636. const Colour& overColour,
  30637. const Colour& downColour);
  30638. /** Sets up an outline to draw around the shape.
  30639. @param outlineColour the colour to use
  30640. @param outlineStrokeWidth the thickness of line to draw
  30641. */
  30642. void setOutline (const Colour& outlineColour,
  30643. const float outlineStrokeWidth);
  30644. juce_UseDebuggingNewOperator
  30645. protected:
  30646. /** @internal */
  30647. void paintButton (Graphics& g,
  30648. bool isMouseOverButton,
  30649. bool isButtonDown);
  30650. private:
  30651. Colour normalColour, overColour, downColour, outlineColour;
  30652. DropShadowEffect shadow;
  30653. Path shape;
  30654. bool maintainShapeProportions;
  30655. float outlineWidth;
  30656. ShapeButton (const ShapeButton&);
  30657. const ShapeButton& operator= (const ShapeButton&);
  30658. };
  30659. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  30660. /********* End of inlined file: juce_ShapeButton.h *********/
  30661. #endif
  30662. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30663. #endif
  30664. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30665. /********* Start of inlined file: juce_ToggleButton.h *********/
  30666. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30667. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30668. /**
  30669. A button that can be toggled on/off.
  30670. All buttons can be toggle buttons, but this lets you create one of the
  30671. standard ones which has a tick-box and a text label next to it.
  30672. @see Button, DrawableButton, TextButton
  30673. */
  30674. class JUCE_API ToggleButton : public Button
  30675. {
  30676. public:
  30677. /** Creates a ToggleButton.
  30678. @param buttonText the text to put in the button (the component's name is also
  30679. initially set to this string, but these can be changed later
  30680. using the setName() and setButtonText() methods)
  30681. */
  30682. ToggleButton (const String& buttonText);
  30683. /** Destructor. */
  30684. ~ToggleButton();
  30685. /** Resizes the button to fit neatly around its current text.
  30686. The button's height won't be affected, only its width.
  30687. */
  30688. void changeWidthToFitText();
  30689. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30690. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30691. methods.
  30692. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30693. */
  30694. enum ColourIds
  30695. {
  30696. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  30697. };
  30698. juce_UseDebuggingNewOperator
  30699. protected:
  30700. /** @internal */
  30701. void paintButton (Graphics& g,
  30702. bool isMouseOverButton,
  30703. bool isButtonDown);
  30704. /** @internal */
  30705. void colourChanged();
  30706. private:
  30707. ToggleButton (const ToggleButton&);
  30708. const ToggleButton& operator= (const ToggleButton&);
  30709. };
  30710. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30711. /********* End of inlined file: juce_ToggleButton.h *********/
  30712. #endif
  30713. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30714. /********* Start of inlined file: juce_ToolbarButton.h *********/
  30715. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30716. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30717. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  30718. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30719. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30720. /********* Start of inlined file: juce_Toolbar.h *********/
  30721. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  30722. #define __JUCE_TOOLBAR_JUCEHEADER__
  30723. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  30724. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30725. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30726. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  30727. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30728. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30729. /**
  30730. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  30731. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  30732. derive your component from this class, and make sure that it is somewhere inside a
  30733. DragAndDropContainer component.
  30734. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30735. the operating system onto your component, you don't need any of these classes: instead
  30736. see the FileDragAndDropTarget class.
  30737. @see DragAndDropContainer, FileDragAndDropTarget
  30738. */
  30739. class JUCE_API DragAndDropTarget
  30740. {
  30741. public:
  30742. /** Destructor. */
  30743. virtual ~DragAndDropTarget() {}
  30744. /** Callback to check whether this target is interested in the type of object being
  30745. dragged.
  30746. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30747. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30748. @returns true if this component wants to receive the other callbacks regarging this
  30749. type of object; if it returns false, no other callbacks will be made.
  30750. */
  30751. virtual bool isInterestedInDragSource (const String& sourceDescription,
  30752. Component* sourceComponent) = 0;
  30753. /** Callback to indicate that something is being dragged over this component.
  30754. This gets called when the user moves the mouse into this component while dragging
  30755. something.
  30756. Use this callback as a trigger to make your component repaint itself to give the
  30757. user feedback about whether the item can be dropped here or not.
  30758. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30759. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30760. @param x the mouse x position, relative to this component
  30761. @param y the mouse y position, relative to this component
  30762. @see itemDragExit
  30763. */
  30764. virtual void itemDragEnter (const String& sourceDescription,
  30765. Component* sourceComponent,
  30766. int x,
  30767. int y);
  30768. /** Callback to indicate that the user is dragging something over this component.
  30769. This gets called when the user moves the mouse over this component while dragging
  30770. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  30771. this lets you know what happens in-between.
  30772. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30773. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30774. @param x the mouse x position, relative to this component
  30775. @param y the mouse y position, relative to this component
  30776. */
  30777. virtual void itemDragMove (const String& sourceDescription,
  30778. Component* sourceComponent,
  30779. int x,
  30780. int y);
  30781. /** Callback to indicate that something has been dragged off the edge of this component.
  30782. This gets called when the user moves the mouse out of this component while dragging
  30783. something.
  30784. If you've used itemDragEnter() to repaint your component and give feedback, use this
  30785. as a signal to repaint it in its normal state.
  30786. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30787. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30788. @see itemDragEnter
  30789. */
  30790. virtual void itemDragExit (const String& sourceDescription,
  30791. Component* sourceComponent);
  30792. /** Callback to indicate that the user has dropped something onto this component.
  30793. When the user drops an item this get called, and you can use the description to
  30794. work out whether your object wants to deal with it or not.
  30795. Note that after this is called, the itemDragExit method may not be called, so you should
  30796. clean up in here if there's anything you need to do when the drag finishes.
  30797. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30798. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30799. @param x the mouse x position, relative to this component
  30800. @param y the mouse y position, relative to this component
  30801. */
  30802. virtual void itemDropped (const String& sourceDescription,
  30803. Component* sourceComponent,
  30804. int x,
  30805. int y) = 0;
  30806. /** Overriding this allows the target to tell the drag container whether to
  30807. draw the drag image while the cursor is over it.
  30808. By default it returns true, but if you return false, then the normal drag
  30809. image will not be shown when the cursor is over this target.
  30810. */
  30811. virtual bool shouldDrawDragImageWhenOver();
  30812. };
  30813. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30814. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  30815. /**
  30816. Enables drag-and-drop behaviour for a component and all its sub-components.
  30817. For a component to be able to make or receive drag-and-drop events, one of its parent
  30818. components must derive from this class. It's probably best for the top-level
  30819. component to implement it.
  30820. Then to start a drag operation, any sub-component can just call the startDragging()
  30821. method, and this object will take over, tracking the mouse and sending appropriate
  30822. callbacks to any child components derived from DragAndDropTarget which the mouse
  30823. moves over.
  30824. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30825. the operating system onto your component, you don't need any of these classes: you can do this
  30826. simply by overriding Component::filesDropped().
  30827. @see DragAndDropTarget
  30828. */
  30829. class JUCE_API DragAndDropContainer
  30830. {
  30831. public:
  30832. /** Creates a DragAndDropContainer.
  30833. The object that derives from this class must also be a Component.
  30834. */
  30835. DragAndDropContainer();
  30836. /** Destructor. */
  30837. virtual ~DragAndDropContainer();
  30838. /** Begins a drag-and-drop operation.
  30839. This starts a drag-and-drop operation - call it when the user drags the
  30840. mouse in your drag-source component, and this object will track mouse
  30841. movements until the user lets go of the mouse button, and will send
  30842. appropriate messages to DragAndDropTarget objects that the mouse moves
  30843. over.
  30844. findParentDragContainerFor() is a handy method to call to find the
  30845. drag container to use for a component.
  30846. @param sourceDescription a string to use as the description of the thing being
  30847. dragged - this will be passed to the objects that might be
  30848. dropped-onto so they can decide if they want to handle it or
  30849. not
  30850. @param sourceComponent the component that is being dragged
  30851. @param dragImage the image to drag around underneath the mouse. If this is
  30852. zero, a snapshot of the sourceComponent will be used instead. An
  30853. image passed-in will be deleted by this object when no longer
  30854. needed.
  30855. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  30856. window, and can be dragged to DragAndDropTargets that are the
  30857. children of components other than this one.
  30858. */
  30859. void startDragging (const String& sourceDescription,
  30860. Component* sourceComponent,
  30861. Image* dragImage = 0,
  30862. const bool allowDraggingToOtherJuceWindows = false);
  30863. /** Returns true if something is currently being dragged. */
  30864. bool isDragAndDropActive() const;
  30865. /** Returns the description of the thing that's currently being dragged.
  30866. If nothing's being dragged, this will return an empty string, otherwise it's the
  30867. string that was passed into startDragging().
  30868. @see startDragging
  30869. */
  30870. const String getCurrentDragDescription() const;
  30871. /** Utility to find the DragAndDropContainer for a given Component.
  30872. This will search up this component's parent hierarchy looking for the first
  30873. parent component which is a DragAndDropContainer.
  30874. It's useful when a component wants to call startDragging but doesn't know
  30875. the DragAndDropContainer it should to use.
  30876. Obviously this may return 0 if it doesn't find a suitable component.
  30877. */
  30878. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  30879. /** This performs a synchronous drag-and-drop of a set of files to some external
  30880. application.
  30881. You can call this function in response to a mouseDrag callback, and it will
  30882. block, running its own internal message loop and tracking the mouse, while it
  30883. uses a native operating system drag-and-drop operation to move or copy some
  30884. files to another application.
  30885. @param files a list of filenames to drag
  30886. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  30887. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  30888. @returns true if the files were successfully dropped somewhere, or false if it
  30889. was interrupted
  30890. @see performExternalDragDropOfText
  30891. */
  30892. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  30893. /** This performs a synchronous drag-and-drop of a block of text to some external
  30894. application.
  30895. You can call this function in response to a mouseDrag callback, and it will
  30896. block, running its own internal message loop and tracking the mouse, while it
  30897. uses a native operating system drag-and-drop operation to move or copy some
  30898. text to another application.
  30899. @param text the text to copy
  30900. @returns true if the text was successfully dropped somewhere, or false if it
  30901. was interrupted
  30902. @see performExternalDragDropOfFiles
  30903. */
  30904. static bool performExternalDragDropOfText (const String& text);
  30905. juce_UseDebuggingNewOperator
  30906. protected:
  30907. /** Override this if you want to be able to perform an external drag a set of files
  30908. when the user drags outside of this container component.
  30909. This method will be called when a drag operation moves outside the Juce-based window,
  30910. and if you want it to then perform a file drag-and-drop, add the filenames you want
  30911. to the array passed in, and return true.
  30912. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  30913. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  30914. @param files on return, the filenames you want to drag
  30915. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  30916. it must make a copy of them (see the performExternalDragDropOfFiles()
  30917. method)
  30918. @see performExternalDragDropOfFiles
  30919. */
  30920. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  30921. Component* dragSourceComponent,
  30922. StringArray& files,
  30923. bool& canMoveFiles);
  30924. private:
  30925. friend class DragImageComponent;
  30926. Component* dragImageComponent;
  30927. String currentDragDesc;
  30928. };
  30929. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30930. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  30931. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  30932. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30933. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30934. /**
  30935. Animates a set of components, moving it to a new position.
  30936. To use this, create a ComponentAnimator, and use its animateComponent() method
  30937. to tell it to move components to destination positions. Any number of
  30938. components can be animated by one ComponentAnimator object (if you've got a
  30939. lot of components to move, it's much more efficient to share a single animator
  30940. than to have many animators running at once).
  30941. You'll need to make sure the animator object isn't deleted before it finishes
  30942. moving the components.
  30943. */
  30944. class JUCE_API ComponentAnimator : private Timer
  30945. {
  30946. public:
  30947. /** Creates a ComponentAnimator. */
  30948. ComponentAnimator();
  30949. /** Destructor. */
  30950. ~ComponentAnimator();
  30951. /** Starts a component moving from its current position to a specified position.
  30952. If the component is already in the middle of an animation, that will be abandoned,
  30953. and a new animation will begin, moving the component from its current location.
  30954. The start and end speed parameters let you apply some acceleration to the component's
  30955. movement.
  30956. @param component the component to move
  30957. @param finalPosition the destination position and size to move it to
  30958. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  30959. to arrive at its destination
  30960. @param startSpeed a value to indicate the relative start speed of the
  30961. animation. If this is 0, the component will start
  30962. by accelerating from rest; higher values mean that it
  30963. will have an initial speed greater than zero. If the
  30964. value if greater than 1, it will decelerate towards the
  30965. middle of its journey. To move the component at a constant
  30966. rate for its entire animation, set both the start and
  30967. end speeds to 1.0
  30968. @param endSpeed a relative speed at which the component should be moving
  30969. when the animation finishes. If this is 0, the component
  30970. will decelerate to a standstill at its final position; higher
  30971. values mean the component will still be moving when it stops.
  30972. To move the component at a constant rate for its entire
  30973. animation, set both the start and end speeds to 1.0
  30974. */
  30975. void animateComponent (Component* const component,
  30976. const Rectangle& finalPosition,
  30977. const int millisecondsToSpendMoving,
  30978. const double startSpeed = 1.0,
  30979. const double endSpeed = 1.0);
  30980. /** Stops a component if it's currently being animated.
  30981. If moveComponentToItsFinalPosition is true, then the component will
  30982. be immediately moved to its destination position and size. If false, it will be
  30983. left in whatever location it currently occupies.
  30984. */
  30985. void cancelAnimation (Component* const component,
  30986. const bool moveComponentToItsFinalPosition);
  30987. /** Clears all of the active animations.
  30988. If moveComponentsToTheirFinalPositions is true, all the components will
  30989. be immediately set to their final positions. If false, they will be
  30990. left in whatever locations they currently occupy.
  30991. */
  30992. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  30993. /** Returns the destination position for a component.
  30994. If the component is being animated, this will return the target position that
  30995. was specified when animateComponent() was called.
  30996. If the specified component isn't currently being animated, this method will just
  30997. return its current position.
  30998. */
  30999. const Rectangle getComponentDestination (Component* const component);
  31000. juce_UseDebuggingNewOperator
  31001. private:
  31002. VoidArray tasks;
  31003. uint32 lastTime;
  31004. void* findTaskFor (Component* const component) const;
  31005. void timerCallback();
  31006. };
  31007. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31008. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31009. class ToolbarItemComponent;
  31010. class ToolbarItemFactory;
  31011. class MissingItemsComponent;
  31012. /**
  31013. A toolbar component.
  31014. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31015. and looks after their order and layout.
  31016. Items (icon buttons or other custom components) are added to a toolbar using a
  31017. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31018. toolbar might contain more than one instance of a particular item type.
  31019. Toolbars can be interactively customised, allowing the user to drag the items
  31020. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31021. component as a source of new items.
  31022. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31023. */
  31024. class JUCE_API Toolbar : public Component,
  31025. public DragAndDropContainer,
  31026. public DragAndDropTarget,
  31027. private ButtonListener
  31028. {
  31029. public:
  31030. /** Creates an empty toolbar component.
  31031. To add some icons or other components to your toolbar, you'll need to
  31032. create a ToolbarItemFactory class that can create a suitable set of
  31033. ToolbarItemComponents.
  31034. @see ToolbarItemFactory, ToolbarItemComponents
  31035. */
  31036. Toolbar();
  31037. /** Destructor.
  31038. Any items on the bar will be deleted when the toolbar is deleted.
  31039. */
  31040. ~Toolbar();
  31041. /** Changes the bar's orientation.
  31042. @see isVertical
  31043. */
  31044. void setVertical (const bool shouldBeVertical);
  31045. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31046. You can change the bar's orientation with setVertical().
  31047. */
  31048. bool isVertical() const throw() { return vertical; }
  31049. /** Returns the depth of the bar.
  31050. If the bar is horizontal, this will return its height; if it's vertical, it
  31051. will return its width.
  31052. @see getLength
  31053. */
  31054. int getThickness() const throw();
  31055. /** Returns the length of the bar.
  31056. If the bar is horizontal, this will return its width; if it's vertical, it
  31057. will return its height.
  31058. @see getThickness
  31059. */
  31060. int getLength() const throw();
  31061. /** Deletes all items from the bar.
  31062. */
  31063. void clear();
  31064. /** Adds an item to the toolbar.
  31065. The factory's ToolbarItemFactory::createItem() will be called by this method
  31066. to create the component that will actually be added to the bar.
  31067. The new item will be inserted at the specified index (if the index is -1, it
  31068. will be added to the right-hand or bottom end of the bar).
  31069. Once added, the component will be automatically deleted by this object when it
  31070. is no longer needed.
  31071. @see ToolbarItemFactory
  31072. */
  31073. void addItem (ToolbarItemFactory& factory,
  31074. const int itemId,
  31075. const int insertIndex = -1);
  31076. /** Deletes one of the items from the bar.
  31077. */
  31078. void removeToolbarItem (const int itemIndex);
  31079. /** Returns the number of items currently on the toolbar.
  31080. @see getItemId, getItemComponent
  31081. */
  31082. int getNumItems() const throw();
  31083. /** Returns the ID of the item with the given index.
  31084. If the index is less than zero or greater than the number of items,
  31085. this will return 0.
  31086. @see getNumItems
  31087. */
  31088. int getItemId (const int itemIndex) const throw();
  31089. /** Returns the component being used for the item with the given index.
  31090. If the index is less than zero or greater than the number of items,
  31091. this will return 0.
  31092. @see getNumItems
  31093. */
  31094. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31095. /** Clears this toolbar and adds to it the default set of items that the specified
  31096. factory creates.
  31097. @see ToolbarItemFactory::getDefaultItemSet
  31098. */
  31099. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31100. /** Options for the way items should be displayed.
  31101. @see setStyle, getStyle
  31102. */
  31103. enum ToolbarItemStyle
  31104. {
  31105. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31106. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31107. textOnly /**< Means that the toolbar only display text labels for each item. */
  31108. };
  31109. /** Returns the toolbar's current style.
  31110. @see ToolbarItemStyle, setStyle
  31111. */
  31112. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31113. /** Changes the toolbar's current style.
  31114. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31115. */
  31116. void setStyle (const ToolbarItemStyle& newStyle);
  31117. /** Flags used by the showCustomisationDialog() method. */
  31118. enum CustomisationFlags
  31119. {
  31120. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31121. show the "icons only" option on its choice of toolbar styles. */
  31122. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31123. show the "icons with text" option on its choice of toolbar styles. */
  31124. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31125. show the "text only" option on its choice of toolbar styles. */
  31126. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31127. show a button to reset the toolbar to its default set of items. */
  31128. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31129. };
  31130. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31131. The dialog contains a ToolbarItemPalette and various controls for editing other
  31132. aspects of the toolbar. This method will block and run the dialog box modally,
  31133. returning when the user closes it.
  31134. The factory is used to determine the set of items that will be shown on the
  31135. palette.
  31136. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31137. enum.
  31138. @see ToolbarItemPalette
  31139. */
  31140. void showCustomisationDialog (ToolbarItemFactory& factory,
  31141. const int optionFlags = allCustomisationOptionsEnabled);
  31142. /** Turns on or off the toolbar's editing mode, in which its items can be
  31143. rearranged by the user.
  31144. (In most cases it's easier just to use showCustomisationDialog() instead of
  31145. trying to enable editing directly).
  31146. @see ToolbarItemPalette
  31147. */
  31148. void setEditingActive (const bool editingEnabled);
  31149. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31150. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31151. methods.
  31152. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31153. */
  31154. enum ColourIds
  31155. {
  31156. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31157. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31158. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31159. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31160. over them. */
  31161. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31162. held down on them. */
  31163. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31164. when the style is set to iconsWithText or textOnly. */
  31165. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31166. the customisation dialog is active and the mouse moves over them. */
  31167. };
  31168. /** Returns a string that represents the toolbar's current set of items.
  31169. This lets you later restore the same item layout using restoreFromString().
  31170. @see restoreFromString
  31171. */
  31172. const String toString() const;
  31173. /** Restores a set of items that was previously stored in a string by the toString()
  31174. method.
  31175. The factory object is used to create any item components that are needed.
  31176. @see toString
  31177. */
  31178. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31179. const String& savedVersion);
  31180. /** @internal */
  31181. void paint (Graphics& g);
  31182. /** @internal */
  31183. void resized();
  31184. /** @internal */
  31185. void buttonClicked (Button*);
  31186. /** @internal */
  31187. void mouseDown (const MouseEvent&);
  31188. /** @internal */
  31189. bool isInterestedInDragSource (const String&, Component*);
  31190. /** @internal */
  31191. void itemDragMove (const String&, Component*, int, int);
  31192. /** @internal */
  31193. void itemDragExit (const String&, Component*);
  31194. /** @internal */
  31195. void itemDropped (const String&, Component*, int, int);
  31196. /** @internal */
  31197. void updateAllItemPositions (const bool animate);
  31198. /** @internal */
  31199. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31200. juce_UseDebuggingNewOperator
  31201. private:
  31202. Button* missingItemsButton;
  31203. bool vertical, isEditingActive;
  31204. ToolbarItemStyle toolbarStyle;
  31205. ComponentAnimator animator;
  31206. friend class MissingItemsComponent;
  31207. Array <ToolbarItemComponent*> items;
  31208. friend class ItemDragAndDropOverlayComponent;
  31209. static const tchar* const toolbarDragDescriptor;
  31210. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31211. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31212. Toolbar (const Toolbar&);
  31213. const Toolbar& operator= (const Toolbar&);
  31214. };
  31215. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31216. /********* End of inlined file: juce_Toolbar.h *********/
  31217. class ItemDragAndDropOverlayComponent;
  31218. /**
  31219. A component that can be used as one of the items in a Toolbar.
  31220. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31221. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31222. class for further info about creating them.
  31223. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31224. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31225. calling the constructor, and override contentAreaChanged(), in which you can position
  31226. any sub-components you need to add.
  31227. To add basic buttons without writing a special subclass, have a look at the
  31228. ToolbarButton class.
  31229. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31230. */
  31231. class JUCE_API ToolbarItemComponent : public Button
  31232. {
  31233. public:
  31234. /** Constructor.
  31235. @param itemId the ID of the type of toolbar item which this represents
  31236. @param labelText the text to display if the toolbar's style is set to
  31237. Toolbar::iconsWithText or Toolbar::textOnly
  31238. @param isBeingUsedAsAButton set this to false if you don't want the button
  31239. to draw itself with button over/down states when the mouse
  31240. moves over it or clicks
  31241. */
  31242. ToolbarItemComponent (const int itemId,
  31243. const String& labelText,
  31244. const bool isBeingUsedAsAButton);
  31245. /** Destructor. */
  31246. ~ToolbarItemComponent();
  31247. /** Returns the item type ID that this component represents.
  31248. This value is in the constructor.
  31249. */
  31250. int getItemId() const throw() { return itemId; }
  31251. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31252. inside one.
  31253. */
  31254. Toolbar* getToolbar() const;
  31255. /** Returns true if this component is currently inside a toolbar which is vertical.
  31256. @see Toolbar::isVertical
  31257. */
  31258. bool isToolbarVertical() const;
  31259. /** Returns the current style setting of this item.
  31260. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31261. @see setStyle, Toolbar::getStyle
  31262. */
  31263. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31264. /** Changes the current style setting of this item.
  31265. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31266. by the toolbar that holds this item.
  31267. @see setStyle, Toolbar::setStyle
  31268. */
  31269. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31270. /** Returns the area of the component that should be used to display the button image or
  31271. other contents of the item.
  31272. This content area may change when the item's style changes, and may leave a space around the
  31273. edge of the component where the text label can be shown.
  31274. @see contentAreaChanged
  31275. */
  31276. const Rectangle getContentArea() const throw() { return contentArea; }
  31277. /** This method must return the size criteria for this item, based on a given toolbar
  31278. size and orientation.
  31279. The preferredSize, minSize and maxSize values must all be set by your implementation
  31280. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31281. toolbar, they refer to the item's height.
  31282. The preferredSize is the size that the component would like to be, and this must be
  31283. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31284. the same value.
  31285. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31286. Toolbar::getThickness().
  31287. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31288. vertically.
  31289. */
  31290. virtual bool getToolbarItemSizes (int toolbarThickness,
  31291. bool isToolbarVertical,
  31292. int& preferredSize,
  31293. int& minSize,
  31294. int& maxSize) = 0;
  31295. /** Your subclass should use this method to draw its content area.
  31296. The graphics object that is passed-in will have been clipped and had its origin
  31297. moved to fit the content area as specified get getContentArea(). The width and height
  31298. parameters are the width and height of the content area.
  31299. If the component you're writing isn't a button, you can just do nothing in this method.
  31300. */
  31301. virtual void paintButtonArea (Graphics& g,
  31302. int width, int height,
  31303. bool isMouseOver, bool isMouseDown) = 0;
  31304. /** Callback to indicate that the content area of this item has changed.
  31305. This might be because the component was resized, or because the style changed and
  31306. the space needed for the text label is different.
  31307. See getContentArea() for a description of what the area is.
  31308. */
  31309. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31310. /** Editing modes.
  31311. These are used by setEditingMode(), but will be rarely needed in user code.
  31312. */
  31313. enum ToolbarEditingMode
  31314. {
  31315. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31316. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31317. customisation mode, and the items can be dragged around. */
  31318. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31319. dragged onto a toolbar to add it to that bar.*/
  31320. };
  31321. /** Changes the editing mode of this component.
  31322. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31323. and is unlikely to be of much use in end-user-code.
  31324. */
  31325. void setEditingMode (const ToolbarEditingMode newMode);
  31326. /** Returns the current editing mode of this component.
  31327. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31328. and is unlikely to be of much use in end-user-code.
  31329. */
  31330. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31331. /** @internal */
  31332. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31333. /** @internal */
  31334. void resized();
  31335. juce_UseDebuggingNewOperator
  31336. private:
  31337. friend class Toolbar;
  31338. friend class ItemDragAndDropOverlayComponent;
  31339. const int itemId;
  31340. ToolbarEditingMode mode;
  31341. Toolbar::ToolbarItemStyle toolbarStyle;
  31342. Component* overlayComp;
  31343. int dragOffsetX, dragOffsetY;
  31344. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31345. Rectangle contentArea;
  31346. ToolbarItemComponent (const ToolbarItemComponent&);
  31347. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31348. };
  31349. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31350. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31351. /**
  31352. A type of button designed to go on a toolbar.
  31353. This simple button can have two Drawable objects specified - one for normal
  31354. use and another one (optionally) for the button's "on" state if it's a
  31355. toggle button.
  31356. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31357. */
  31358. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31359. {
  31360. public:
  31361. /** Creates a ToolbarButton.
  31362. @param itemId the ID for this toolbar item type. This is passed through to the
  31363. ToolbarItemComponent constructor
  31364. @param labelText the text to display on the button (if the toolbar is using a style
  31365. that shows text labels). This is passed through to the
  31366. ToolbarItemComponent constructor
  31367. @param normalImage a drawable object that the button should use as its icon. The object
  31368. that is passed-in here will be kept by this object and will be
  31369. deleted when no longer needed or when this button is deleted.
  31370. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31371. is in a toggled-on state (see the Button::getToggleState() method). If
  31372. 0 is passed-in here, then the normal image will be used instead, regardless
  31373. of the toggle state. The object that is passed-in here will be kept by
  31374. this object and will be deleted when no longer needed or when this button
  31375. is deleted.
  31376. */
  31377. ToolbarButton (const int itemId,
  31378. const String& labelText,
  31379. Drawable* const normalImage,
  31380. Drawable* const toggledOnImage);
  31381. /** Destructor. */
  31382. ~ToolbarButton();
  31383. /** @internal */
  31384. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31385. int& minSize, int& maxSize);
  31386. /** @internal */
  31387. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31388. /** @internal */
  31389. void contentAreaChanged (const Rectangle& newBounds);
  31390. juce_UseDebuggingNewOperator
  31391. private:
  31392. Drawable* const normalImage;
  31393. Drawable* const toggledOnImage;
  31394. ToolbarButton (const ToolbarButton&);
  31395. const ToolbarButton& operator= (const ToolbarButton&);
  31396. };
  31397. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31398. /********* End of inlined file: juce_ToolbarButton.h *********/
  31399. #endif
  31400. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31401. #endif
  31402. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31403. /********* Start of inlined file: juce_GlowEffect.h *********/
  31404. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31405. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31406. /**
  31407. A component effect that adds a coloured blur around the component's contents.
  31408. (This will only work on non-opaque components).
  31409. @see Component::setComponentEffect, DropShadowEffect
  31410. */
  31411. class JUCE_API GlowEffect : public ImageEffectFilter
  31412. {
  31413. public:
  31414. /** Creates a default 'glow' effect.
  31415. To customise its appearance, use the setGlowProperties() method.
  31416. */
  31417. GlowEffect();
  31418. /** Destructor. */
  31419. ~GlowEffect();
  31420. /** Sets the glow's radius and colour.
  31421. The radius is how large the blur should be, and the colour is
  31422. used to render it (for a less intense glow, lower the colour's
  31423. opacity).
  31424. */
  31425. void setGlowProperties (const float newRadius,
  31426. const Colour& newColour);
  31427. /** @internal */
  31428. void applyEffect (Image& sourceImage, Graphics& destContext);
  31429. juce_UseDebuggingNewOperator
  31430. private:
  31431. float radius;
  31432. Colour colour;
  31433. };
  31434. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31435. /********* End of inlined file: juce_GlowEffect.h *********/
  31436. #endif
  31437. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31438. #endif
  31439. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31440. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31441. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31442. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31443. /**
  31444. An effect filter that reduces the image's opacity.
  31445. This can be used to make a component (and its child components) more
  31446. transparent.
  31447. @see Component::setComponentEffect
  31448. */
  31449. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31450. {
  31451. public:
  31452. /** Creates the effect object.
  31453. The opacity of the component to which the effect is applied will be
  31454. scaled by the given factor (in the range 0 to 1.0f).
  31455. */
  31456. ReduceOpacityEffect (const float opacity = 1.0f);
  31457. /** Destructor. */
  31458. ~ReduceOpacityEffect();
  31459. /** Sets how much to scale the component's opacity.
  31460. @param newOpacity should be between 0 and 1.0f
  31461. */
  31462. void setOpacity (const float newOpacity);
  31463. /** @internal */
  31464. void applyEffect (Image& sourceImage, Graphics& destContext);
  31465. juce_UseDebuggingNewOperator
  31466. private:
  31467. float opacity;
  31468. };
  31469. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31470. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31471. #endif
  31472. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31473. #endif
  31474. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31475. #endif
  31476. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31477. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31478. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31479. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31480. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31481. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31482. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31483. /**
  31484. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31485. command in a ApplicationCommandManager.
  31486. Normally, you won't actually create a KeyPressMappingSet directly, because
  31487. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  31488. you'd create yourself an ApplicationCommandManager, and call its
  31489. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  31490. KeyPressMappingSet.
  31491. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  31492. to the top-level component for which you want to handle keystrokes. So for example:
  31493. @code
  31494. class MyMainWindow : public Component
  31495. {
  31496. ApplicationCommandManager* myCommandManager;
  31497. public:
  31498. MyMainWindow()
  31499. {
  31500. myCommandManager = new ApplicationCommandManager();
  31501. // first, make sure the command manager has registered all the commands that its
  31502. // targets can perform..
  31503. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  31504. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  31505. // this will use the command manager to initialise the KeyPressMappingSet with
  31506. // the default keypresses that were specified when the targets added their commands
  31507. // to the manager.
  31508. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  31509. // having set up the default key-mappings, you might now want to load the last set
  31510. // of mappings that the user configured.
  31511. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  31512. // Now tell our top-level window to send any keypresses that arrive to the
  31513. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  31514. addKeyListener (myCommandManager->getKeyMappings());
  31515. }
  31516. ...
  31517. }
  31518. @endcode
  31519. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  31520. register to be told when a command or mapping is added, removed, etc.
  31521. There's also a UI component called KeyMappingEditorComponent that can be used
  31522. to easily edit the key mappings.
  31523. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  31524. */
  31525. class JUCE_API KeyPressMappingSet : public KeyListener,
  31526. public ChangeBroadcaster,
  31527. public FocusChangeListener
  31528. {
  31529. public:
  31530. /** Creates a KeyPressMappingSet for a given command manager.
  31531. Normally, you won't actually create a KeyPressMappingSet directly, because
  31532. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  31533. best thing to do is to create your ApplicationCommandManager, and use the
  31534. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  31535. When a suitable keypress happens, the manager's invoke() method will be
  31536. used to invoke the appropriate command.
  31537. @see ApplicationCommandManager
  31538. */
  31539. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  31540. /** Creates an copy of a KeyPressMappingSet. */
  31541. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  31542. /** Destructor. */
  31543. ~KeyPressMappingSet();
  31544. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  31545. /** Returns a list of keypresses that are assigned to a particular command.
  31546. @param commandID the command's ID
  31547. */
  31548. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  31549. /** Assigns a keypress to a command.
  31550. If the keypress is already assigned to a different command, it will first be
  31551. removed from that command, to avoid it triggering multiple functions.
  31552. @param commandID the ID of the command that you want to add a keypress to. If
  31553. this is 0, the keypress will be removed from anything that it
  31554. was previously assigned to, but not re-assigned
  31555. @param newKeyPress the new key-press
  31556. @param insertIndex if this is less than zero, the key will be appended to the
  31557. end of the list of keypresses; otherwise the new keypress will
  31558. be inserted into the existing list at this index
  31559. */
  31560. void addKeyPress (const CommandID commandID,
  31561. const KeyPress& newKeyPress,
  31562. int insertIndex = -1) throw();
  31563. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  31564. @see resetToDefaultMapping
  31565. */
  31566. void resetToDefaultMappings() throw();
  31567. /** Resets all key-mappings to the defaults for a particular command.
  31568. @see resetToDefaultMappings
  31569. */
  31570. void resetToDefaultMapping (const CommandID commandID) throw();
  31571. /** Removes all keypresses that are assigned to any commands. */
  31572. void clearAllKeyPresses() throw();
  31573. /** Removes all keypresses that are assigned to a particular command. */
  31574. void clearAllKeyPresses (const CommandID commandID) throw();
  31575. /** Removes one of the keypresses that are assigned to a command.
  31576. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  31577. which the keyPressIndex refers.
  31578. */
  31579. void removeKeyPress (const CommandID commandID,
  31580. const int keyPressIndex) throw();
  31581. /** Removes a keypress from any command that it may be assigned to.
  31582. */
  31583. void removeKeyPress (const KeyPress& keypress) throw();
  31584. /** Returns true if the given command is linked to this key. */
  31585. bool containsMapping (const CommandID commandID,
  31586. const KeyPress& keyPress) const throw();
  31587. /** Looks for a command that corresponds to a keypress.
  31588. @returns the UID of the command or 0 if none was found
  31589. */
  31590. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  31591. /** Tries to recreate the mappings from a previously stored state.
  31592. The XML passed in must have been created by the createXml() method.
  31593. If the stored state makes any reference to commands that aren't
  31594. currently available, these will be ignored.
  31595. If the set of mappings being loaded was a set of differences (using createXml (true)),
  31596. then this will call resetToDefaultMappings() and then merge the saved mappings
  31597. on top. If the saved set was created with createXml (false), then this method
  31598. will first clear all existing mappings and load the saved ones as a complete set.
  31599. @returns true if it manages to load the XML correctly
  31600. @see createXml
  31601. */
  31602. bool restoreFromXml (const XmlElement& xmlVersion);
  31603. /** Creates an XML representation of the current mappings.
  31604. This will produce a lump of XML that can be later reloaded using
  31605. restoreFromXml() to recreate the current mapping state.
  31606. The object that is returned must be deleted by the caller.
  31607. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  31608. will be saved into the XML. If it's true, then the XML will
  31609. only store the differences between the current mappings and
  31610. the default mappings you'd get from calling resetToDefaultMappings().
  31611. The advantage of saving a set of differences from the default is that
  31612. if you change the default mappings (in a new version of your app, for
  31613. example), then these will be merged into a user's saved preferences.
  31614. @see restoreFromXml
  31615. */
  31616. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  31617. /** @internal */
  31618. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31619. /** @internal */
  31620. bool keyStateChanged (Component* originatingComponent);
  31621. /** @internal */
  31622. void globalFocusChanged (Component* focusedComponent);
  31623. juce_UseDebuggingNewOperator
  31624. private:
  31625. ApplicationCommandManager* commandManager;
  31626. struct CommandMapping
  31627. {
  31628. CommandID commandID;
  31629. Array <KeyPress> keypresses;
  31630. bool wantsKeyUpDownCallbacks;
  31631. };
  31632. OwnedArray <CommandMapping> mappings;
  31633. struct KeyPressTime
  31634. {
  31635. KeyPress key;
  31636. uint32 timeWhenPressed;
  31637. };
  31638. OwnedArray <KeyPressTime> keysDown;
  31639. void handleMessage (const Message& message);
  31640. void invokeCommand (const CommandID commandID,
  31641. const KeyPress& keyPress,
  31642. const bool isKeyDown,
  31643. const int millisecsSinceKeyPressed,
  31644. Component* const originatingComponent) const;
  31645. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  31646. };
  31647. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31648. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  31649. /********* Start of inlined file: juce_TreeView.h *********/
  31650. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  31651. #define __JUCE_TREEVIEW_JUCEHEADER__
  31652. class TreeView;
  31653. /**
  31654. An item in a treeview.
  31655. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  31656. own sub-items.
  31657. To implement an item that contains sub-items, override the itemOpennessChanged()
  31658. method so that when it is opened, it adds the new sub-items to itself using the
  31659. addSubItem method. Depending on the nature of the item it might choose to only
  31660. do this the first time it's opened, or it might want to refresh itself each time.
  31661. It also has the option of deleting its sub-items when it is closed, or leaving them
  31662. in place.
  31663. */
  31664. class JUCE_API TreeViewItem
  31665. {
  31666. public:
  31667. /** Constructor. */
  31668. TreeViewItem();
  31669. /** Destructor. */
  31670. virtual ~TreeViewItem();
  31671. /** Returns the number of sub-items that have been added to this item.
  31672. Note that this doesn't mean much if the node isn't open.
  31673. @see getSubItem, mightContainSubItems, addSubItem
  31674. */
  31675. int getNumSubItems() const throw();
  31676. /** Returns one of the item's sub-items.
  31677. Remember that the object returned might get deleted at any time when its parent
  31678. item is closed or refreshed, depending on the nature of the items you're using.
  31679. @see getNumSubItems
  31680. */
  31681. TreeViewItem* getSubItem (const int index) const throw();
  31682. /** Removes any sub-items. */
  31683. void clearSubItems();
  31684. /** Adds a sub-item.
  31685. @param newItem the object to add to the item's sub-item list. Once added, these can be
  31686. found using getSubItem(). When the items are later removed with
  31687. removeSubItem() (or when this item is deleted), they will be deleted.
  31688. @param insertPosition the index which the new item should have when it's added. If this
  31689. value is less than 0, the item will be added to the end of the list.
  31690. */
  31691. void addSubItem (TreeViewItem* const newItem,
  31692. const int insertPosition = -1);
  31693. /** Removes one of the sub-items.
  31694. @param index the item to remove
  31695. @param deleteItem if true, the item that is removed will also be deleted.
  31696. */
  31697. void removeSubItem (const int index,
  31698. const bool deleteItem = true);
  31699. /** Returns the TreeView to which this item belongs. */
  31700. TreeView* getOwnerView() const throw() { return ownerView; }
  31701. /** Returns the item within which this item is contained. */
  31702. TreeViewItem* getParentItem() const throw() { return parentItem; }
  31703. /** True if this item is currently open in the treeview. */
  31704. bool isOpen() const throw();
  31705. /** Opens or closes the item.
  31706. When opened or closed, the item's itemOpennessChanged() method will be called,
  31707. and a subclass should use this callback to create and add any sub-items that
  31708. it needs to.
  31709. @see itemOpennessChanged, mightContainSubItems
  31710. */
  31711. void setOpen (const bool shouldBeOpen);
  31712. /** True if this item is currently selected.
  31713. Use this when painting the node, to decide whether to draw it as selected or not.
  31714. */
  31715. bool isSelected() const throw();
  31716. /** Selects or deselects the item.
  31717. This will cause a callback to itemSelectionChanged()
  31718. */
  31719. void setSelected (const bool shouldBeSelected,
  31720. const bool deselectOtherItemsFirst);
  31721. /** Returns the rectangle that this item occupies.
  31722. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  31723. top-left of the TreeView comp, so this will depend on the scroll-position of
  31724. the tree. If false, it is relative to the top-left of the topmost item in the
  31725. tree (so this would be unaffected by scrolling the view).
  31726. */
  31727. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  31728. /** Sends a signal to the treeview to make it refresh itself.
  31729. Call this if your items have changed and you want the tree to update to reflect
  31730. this.
  31731. */
  31732. void treeHasChanged() const throw();
  31733. /** Returns the row number of this item in the tree.
  31734. The row number of an item will change according to which items are open.
  31735. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  31736. */
  31737. int getRowNumberInTree() const throw();
  31738. /** Changes whether lines are drawn to connect any sub-items to this item.
  31739. By default, line-drawing is turned on.
  31740. */
  31741. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  31742. /** Tells the tree whether this item can potentially be opened.
  31743. If your item could contain sub-items, this should return true; if it returns
  31744. false then the tree will not try to open the item. This determines whether or
  31745. not the item will be drawn with a 'plus' button next to it.
  31746. */
  31747. virtual bool mightContainSubItems() = 0;
  31748. /** Returns a string to uniquely identify this item.
  31749. If you're planning on using the TreeView::getOpennessState() method, then
  31750. these strings will be used to identify which nodes are open. The string
  31751. should be unique amongst the item's sibling items, but it's ok for there
  31752. to be duplicates at other levels of the tree.
  31753. If you're not going to store the state, then it's ok not to bother implementing
  31754. this method.
  31755. */
  31756. virtual const String getUniqueName() const;
  31757. /** Called when an item is opened or closed.
  31758. When setOpen() is called and the item has specified that it might
  31759. have sub-items with the mightContainSubItems() method, this method
  31760. is called to let the item create or manage its sub-items.
  31761. So when this is called with isNowOpen set to true (i.e. when the item is being
  31762. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  31763. refresh its sub-item list.
  31764. When this is called with isNowOpen set to false, the subclass might want
  31765. to use clearSubItems() to save on space, or it might choose to leave them,
  31766. depending on the nature of the tree.
  31767. You could also use this callback as a trigger to start a background process
  31768. which asynchronously creates sub-items and adds them, if that's more
  31769. appropriate for the task in hand.
  31770. @see mightContainSubItems
  31771. */
  31772. virtual void itemOpennessChanged (bool isNowOpen);
  31773. /** Must return the width required by this item.
  31774. If your item needs to have a particular width in pixels, return that value; if
  31775. you'd rather have it just fill whatever space is available in the treeview,
  31776. return -1.
  31777. If all your items return -1, no horizontal scrollbar will be shown, but if any
  31778. items have fixed widths and extend beyond the width of the treeview, a
  31779. scrollbar will appear.
  31780. Each item can be a different width, but if they change width, you should call
  31781. treeHasChanged() to update the tree.
  31782. */
  31783. virtual int getItemWidth() const { return -1; }
  31784. /** Must return the height required by this item.
  31785. This is the height in pixels that the item will take up. Items in the tree
  31786. can be different heights, but if they change height, you should call
  31787. treeHasChanged() to update the tree.
  31788. */
  31789. virtual int getItemHeight() const { return 20; }
  31790. /** Creates a component that will be used to represent this item.
  31791. You don't have to implement this method - if it returns 0 then no component
  31792. will be used for the item, and you can just draw it using the paintItem()
  31793. callback. But if you do return a component, it will be positioned in the
  31794. treeview so that it can be used to represent this item.
  31795. The component returned will be managed by the treeview, so always return
  31796. a new component, and don't keep a reference to it, as the treeview will
  31797. delete it later when it goes off the screen or is no longer needed. Also
  31798. bear in mind that if the component keeps a reference to the item that
  31799. created it, that item could be deleted before the component. Its position
  31800. and size will be completely managed by the tree, so don't attempt to move it
  31801. around.
  31802. Something you may want to do with your component is to give it a pointer to
  31803. the TreeView that created it. This is perfectly safe, and there's no danger
  31804. of it becoming a dangling pointer because the TreeView will always delete
  31805. the component before it is itself deleted.
  31806. As long as you stick to these rules you can return whatever kind of
  31807. component you like. It's most useful if you're doing things like drag-and-drop
  31808. of items, or want to use a Label component to edit item names, etc.
  31809. */
  31810. virtual Component* createItemComponent() { return 0; }
  31811. /** Draws the item's contents.
  31812. You can choose to either implement this method and draw each item, or you
  31813. can use createItemComponent() to create a component that will represent the
  31814. item.
  31815. If all you need in your tree is to be able to draw the items and detect when
  31816. the user selects or double-clicks one of them, it's probably enough to
  31817. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  31818. complicated interactions, you may need to use createItemComponent() instead.
  31819. @param g the graphics context to draw into
  31820. @param width the width of the area available for drawing
  31821. @param height the height of the area available for drawing
  31822. */
  31823. virtual void paintItem (Graphics& g, int width, int height);
  31824. /** Called when the user clicks on this item.
  31825. If you're using createItemComponent() to create a custom component for the
  31826. item, the mouse-clicks might not make it through to the treeview, but this
  31827. is how you find out about clicks when just drawing each item individually.
  31828. The associated mouse-event details are passed in, so you can find out about
  31829. which button, where it was, etc.
  31830. @see itemDoubleClicked
  31831. */
  31832. virtual void itemClicked (const MouseEvent& e);
  31833. /** Called when the user double-clicks on this item.
  31834. If you're using createItemComponent() to create a custom component for the
  31835. item, the mouse-clicks might not make it through to the treeview, but this
  31836. is how you find out about clicks when just drawing each item individually.
  31837. The associated mouse-event details are passed in, so you can find out about
  31838. which button, where it was, etc.
  31839. If not overridden, the base class method here will open or close the item as
  31840. if the 'plus' button had been clicked.
  31841. @see itemClicked
  31842. */
  31843. virtual void itemDoubleClicked (const MouseEvent& e);
  31844. /** Called when the item is selected or deselected.
  31845. Use this if you want to do something special when the item's selectedness
  31846. changes. By default it'll get repainted when this happens.
  31847. */
  31848. virtual void itemSelectionChanged (bool isNowSelected);
  31849. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  31850. If this returns a non-empty name then when the user drags an item, the treeview will
  31851. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  31852. a drag-and-drop operation, using this string as the source description, with the treeview
  31853. itself as the source component.
  31854. If you need more complex drag-and-drop behaviour, you can use custom components for
  31855. the items, and use those to trigger the drag.
  31856. @see DragAndDropContainer::startDragging
  31857. */
  31858. virtual const String getDragSourceDescription();
  31859. juce_UseDebuggingNewOperator
  31860. private:
  31861. TreeView* ownerView;
  31862. TreeViewItem* parentItem;
  31863. OwnedArray <TreeViewItem> subItems;
  31864. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  31865. int uid;
  31866. bool selected : 1;
  31867. bool redrawNeeded : 1;
  31868. bool drawLinesInside : 1;
  31869. unsigned int openness : 2;
  31870. friend class TreeView;
  31871. friend class TreeViewContentComponent;
  31872. void updatePositions (int newY);
  31873. int getIndentX() const throw();
  31874. void setOwnerView (TreeView* const newOwner) throw();
  31875. void paintRecursively (Graphics& g, int width);
  31876. TreeViewItem* findItemRecursively (int y) throw();
  31877. TreeViewItem* getDeepestOpenParentItem() throw();
  31878. void restoreFromXml (const XmlElement& e);
  31879. XmlElement* createXmlOpenness() const;
  31880. bool isLastOfSiblings() const throw();
  31881. TreeViewItem* getTopLevelItem() throw();
  31882. int getNumRows() const throw();
  31883. TreeViewItem* getItemOnRow (int index) throw();
  31884. void deselectAllRecursively();
  31885. int countSelectedItemsRecursively() const throw();
  31886. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  31887. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  31888. TreeViewItem (const TreeViewItem&);
  31889. const TreeViewItem& operator= (const TreeViewItem&);
  31890. };
  31891. /**
  31892. A tree-view component.
  31893. Use one of these to hold and display a structure of TreeViewItem objects.
  31894. */
  31895. class JUCE_API TreeView : public Component,
  31896. public SettableTooltipClient,
  31897. private AsyncUpdater
  31898. {
  31899. public:
  31900. /** Creates an empty treeview.
  31901. Once you've got a treeview component, you'll need to give it something to
  31902. display, using the setRootItem() method.
  31903. */
  31904. TreeView (const String& componentName = String::empty);
  31905. /** Destructor. */
  31906. ~TreeView();
  31907. /** Sets the item that is displayed in the treeview.
  31908. A tree has a single root item which contains as many sub-items as it needs. If
  31909. you want the tree to contain a number of root items, you should still use a single
  31910. root item above these, but hide it using setRootItemVisible().
  31911. You can pass in 0 to this method to clear the tree and remove its current root item.
  31912. The object passed in will not be deleted by the treeview, it's up to the caller
  31913. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  31914. this item until you've removed it from the tree, either by calling setRootItem (0),
  31915. or by deleting the tree first.
  31916. */
  31917. void setRootItem (TreeViewItem* const newRootItem);
  31918. /** Returns the tree's root item.
  31919. This will be the last object passed to setRootItem(), or 0 if none has been set.
  31920. */
  31921. TreeViewItem* getRootItem() const throw() { return rootItem; }
  31922. /** Changes whether the tree's root item is shown or not.
  31923. If the root item is hidden, only its sub-items will be shown in the treeview - this
  31924. lets you make the tree look as if it's got many root items. If it's hidden, this call
  31925. will also make sure the root item is open (otherwise the treeview would look empty).
  31926. */
  31927. void setRootItemVisible (const bool shouldBeVisible);
  31928. /** Returns true if the root item is visible.
  31929. @see setRootItemVisible
  31930. */
  31931. bool isRootItemVisible() const throw() { return rootItemVisible; }
  31932. /** Sets whether items are open or closed by default.
  31933. Normally, items are closed until the user opens them, but you can use this
  31934. to make them default to being open until explicitly closed.
  31935. @see areItemsOpenByDefault
  31936. */
  31937. void setDefaultOpenness (const bool isOpenByDefault);
  31938. /** Returns true if the tree's items default to being open.
  31939. @see setDefaultOpenness
  31940. */
  31941. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  31942. /** This sets a flag to indicate that the tree can be used for multi-selection.
  31943. You can always select multiple items internally by calling the
  31944. TreeViewItem::setSelected() method, but this flag indicates whether the user
  31945. is allowed to multi-select by clicking on the tree.
  31946. By default it is disabled.
  31947. @see isMultiSelectEnabled
  31948. */
  31949. void setMultiSelectEnabled (const bool canMultiSelect);
  31950. /** Returns whether multi-select has been enabled for the tree.
  31951. @see setMultiSelectEnabled
  31952. */
  31953. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  31954. /** Deselects any items that are currently selected. */
  31955. void clearSelectedItems();
  31956. /** Returns the number of items that are currently selected.
  31957. @see getSelectedItem, clearSelectedItems
  31958. */
  31959. int getNumSelectedItems() const throw();
  31960. /** Returns one of the selected items in the tree.
  31961. @param index the index, 0 to (getNumSelectedItems() - 1)
  31962. */
  31963. TreeViewItem* getSelectedItem (const int index) const throw();
  31964. /** Returns the number of rows the tree is using.
  31965. This will depend on which items are open.
  31966. @see TreeViewItem::getRowNumberInTree()
  31967. */
  31968. int getNumRowsInTree() const;
  31969. /** Returns the item on a particular row of the tree.
  31970. If the index is out of range, this will return 0.
  31971. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  31972. */
  31973. TreeViewItem* getItemOnRow (int index) const;
  31974. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  31975. void scrollToKeepItemVisible (TreeViewItem* item);
  31976. /** Returns the treeview's Viewport object. */
  31977. Viewport* getViewport() const throw() { return viewport; }
  31978. /** Returns the number of pixels by which each nested level of the tree is indented.
  31979. @see setIndentSize
  31980. */
  31981. int getIndentSize() const throw() { return indentSize; }
  31982. /** Changes the distance by which each nested level of the tree is indented.
  31983. @see getIndentSize
  31984. */
  31985. void setIndentSize (const int newIndentSize);
  31986. /** Saves the current state of open/closed nodes so it can be restored later.
  31987. This takes a snapshot of which nodes have been explicitly opened or closed,
  31988. and records it as XML. To identify node objects it uses the
  31989. TreeViewItem::getUniqueName() method to create named paths. This
  31990. means that the same state of open/closed nodes can be restored to a
  31991. completely different instance of the tree, as long as it contains nodes
  31992. whose unique names are the same.
  31993. The caller is responsible for deleting the object that is returned.
  31994. @param alsoIncludeScrollPosition if this is true, the state will also
  31995. include information about where the
  31996. tree has been scrolled to vertically,
  31997. so this can also be restored
  31998. @see restoreOpennessState
  31999. */
  32000. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32001. /** Restores a previously saved arrangement of open/closed nodes.
  32002. This will try to restore a snapshot of the tree's state that was created by
  32003. the getOpennessState() method. If any of the nodes named in the original
  32004. XML aren't present in this tree, they will be ignored.
  32005. @see getOpennessState
  32006. */
  32007. void restoreOpennessState (const XmlElement& newState);
  32008. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32009. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32010. methods.
  32011. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32012. */
  32013. enum ColourIds
  32014. {
  32015. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32016. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32017. };
  32018. /** @internal */
  32019. void paint (Graphics& g);
  32020. /** @internal */
  32021. void resized();
  32022. /** @internal */
  32023. bool keyPressed (const KeyPress& key);
  32024. /** @internal */
  32025. void colourChanged();
  32026. juce_UseDebuggingNewOperator
  32027. private:
  32028. friend class TreeViewItem;
  32029. friend class TreeViewContentComponent;
  32030. Viewport* viewport;
  32031. CriticalSection nodeAlterationLock;
  32032. TreeViewItem* rootItem;
  32033. int indentSize;
  32034. bool defaultOpenness : 1;
  32035. bool needsRecalculating : 1;
  32036. bool rootItemVisible : 1;
  32037. bool multiSelectEnabled : 1;
  32038. void itemsChanged() throw();
  32039. void handleAsyncUpdate();
  32040. void moveSelectedRow (int delta);
  32041. TreeView (const TreeView&);
  32042. const TreeView& operator= (const TreeView&);
  32043. };
  32044. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32045. /********* End of inlined file: juce_TreeView.h *********/
  32046. /**
  32047. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32048. object.
  32049. @see KeyPressMappingSet
  32050. */
  32051. class JUCE_API KeyMappingEditorComponent : public Component,
  32052. public TreeViewItem,
  32053. public ChangeListener,
  32054. private ButtonListener
  32055. {
  32056. public:
  32057. /** Creates a KeyMappingEditorComponent.
  32058. @param mappingSet this is the set of mappings to display and
  32059. edit. Make sure the mappings object is not
  32060. deleted before this component!
  32061. @param showResetToDefaultButton if true, then at the bottom of the
  32062. list, the component will include a 'reset to
  32063. defaults' button.
  32064. */
  32065. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32066. const bool showResetToDefaultButton);
  32067. /** Destructor. */
  32068. virtual ~KeyMappingEditorComponent();
  32069. /** Sets up the colours to use for parts of the component.
  32070. @param mainBackground colour to use for most of the background
  32071. @param textColour colour to use for the text
  32072. */
  32073. void setColours (const Colour& mainBackground,
  32074. const Colour& textColour);
  32075. /** Returns the KeyPressMappingSet that this component is acting upon.
  32076. */
  32077. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32078. /** Can be overridden if some commands need to be excluded from the list.
  32079. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32080. method to decide what to return, but you can override it to handle special cases.
  32081. */
  32082. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32083. /** Can be overridden to indicate that some commands are shown as read-only.
  32084. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32085. method to decide what to return, but you can override it to handle special cases.
  32086. */
  32087. virtual bool isCommandReadOnly (const CommandID commandID);
  32088. /** This can be overridden to let you change the format of the string used
  32089. to describe a keypress.
  32090. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32091. keys that are triggered by something else externally. If you override the
  32092. method, be sure to let the base class's method handle keys you're not
  32093. interested in.
  32094. */
  32095. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32096. /** @internal */
  32097. void parentHierarchyChanged();
  32098. /** @internal */
  32099. void resized();
  32100. /** @internal */
  32101. void changeListenerCallback (void*);
  32102. /** @internal */
  32103. bool mightContainSubItems();
  32104. /** @internal */
  32105. const String getUniqueName() const;
  32106. /** @internal */
  32107. void buttonClicked (Button* button);
  32108. juce_UseDebuggingNewOperator
  32109. private:
  32110. KeyPressMappingSet* mappings;
  32111. TreeView* tree;
  32112. friend class KeyMappingTreeViewItem;
  32113. friend class KeyCategoryTreeViewItem;
  32114. friend class KeyMappingItemComponent;
  32115. friend class KeyMappingChangeButton;
  32116. Colour backgroundColour, textColour;
  32117. TextButton* resetButton;
  32118. void assignNewKey (const CommandID commandID, int index);
  32119. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32120. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32121. };
  32122. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32123. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32124. #endif
  32125. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32126. #endif
  32127. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32128. #endif
  32129. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32130. #endif
  32131. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32132. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32133. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32134. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32135. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32136. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32137. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32138. class MenuBarModel;
  32139. /**
  32140. A class to receive callbacks when a MenuBarModel changes.
  32141. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32142. */
  32143. class JUCE_API MenuBarModelListener
  32144. {
  32145. public:
  32146. /** Destructor. */
  32147. virtual ~MenuBarModelListener() {}
  32148. /** This callback is made when items are changed in the menu bar model.
  32149. */
  32150. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32151. /** This callback is made when an application command is invoked that
  32152. is represented by one of the items in the menu bar model.
  32153. */
  32154. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32155. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32156. };
  32157. /**
  32158. A class for controlling MenuBar components.
  32159. This class is used to tell a MenuBar what menus to show, and to respond
  32160. to a menu being selected.
  32161. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32162. */
  32163. class JUCE_API MenuBarModel : private AsyncUpdater,
  32164. private ApplicationCommandManagerListener
  32165. {
  32166. public:
  32167. MenuBarModel() throw();
  32168. /** Destructor. */
  32169. virtual ~MenuBarModel();
  32170. /** Call this when some of your menu items have changed.
  32171. This method will cause a callback to any MenuBarListener objects that
  32172. are registered with this model.
  32173. If this model is displaying items from an ApplicationCommandManager, you
  32174. can use the setApplicationCommandManagerToWatch() method to cause
  32175. change messages to be sent automatically when the ApplicationCommandManager
  32176. is changed.
  32177. @see addListener, removeListener, MenuBarListener
  32178. */
  32179. void menuItemsChanged();
  32180. /** Tells the menu bar to listen to the specified command manager, and to update
  32181. itself when the commands change.
  32182. This will also allow it to flash a menu name when a command from that menu
  32183. is invoked using a keystroke.
  32184. */
  32185. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32186. /** Registers a listener for callbacks when the menu items in this model change.
  32187. The listener object will get callbacks when this object's menuItemsChanged()
  32188. method is called.
  32189. @see removeListener
  32190. */
  32191. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32192. /** Removes a listener.
  32193. @see addListener
  32194. */
  32195. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32196. /** This method must return a list of the names of the menus. */
  32197. virtual const StringArray getMenuBarNames() = 0;
  32198. /** This should return the popup menu to display for a given top-level menu.
  32199. @param topLevelMenuIndex the index of the top-level menu to show
  32200. @param menuName the name of the top-level menu item to show
  32201. */
  32202. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32203. const String& menuName) = 0;
  32204. /** This is called when a menu item has been clicked on.
  32205. @param menuItemID the item ID of the PopupMenu item that was selected
  32206. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32207. chosen (just in case you've used duplicate ID numbers
  32208. on more than one of the popup menus)
  32209. */
  32210. virtual void menuItemSelected (int menuItemID,
  32211. int topLevelMenuIndex) = 0;
  32212. #if JUCE_MAC || DOXYGEN
  32213. /** MAC ONLY - Sets the model that is currently being shown as the main
  32214. menu bar at the top of the screen on the Mac.
  32215. You can pass 0 to stop the current model being displayed. Be careful
  32216. not to delete a model while it is being used.
  32217. */
  32218. static void setMacMainMenu (MenuBarModel* newMenuBarModel) throw();
  32219. /** MAC ONLY - Returns the menu model that is currently being shown as
  32220. the main menu bar.
  32221. */
  32222. static MenuBarModel* getMacMainMenu() throw();
  32223. #endif
  32224. /** @internal */
  32225. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32226. /** @internal */
  32227. void applicationCommandListChanged();
  32228. /** @internal */
  32229. void handleAsyncUpdate();
  32230. juce_UseDebuggingNewOperator
  32231. private:
  32232. ApplicationCommandManager* manager;
  32233. SortedSet <void*> listeners;
  32234. MenuBarModel (const MenuBarModel&);
  32235. const MenuBarModel& operator= (const MenuBarModel&);
  32236. };
  32237. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32238. /********* End of inlined file: juce_MenuBarModel.h *********/
  32239. /**
  32240. A menu bar component.
  32241. @see MenuBarModel
  32242. */
  32243. class JUCE_API MenuBarComponent : public Component,
  32244. private MenuBarModelListener,
  32245. private Timer
  32246. {
  32247. public:
  32248. /** Creates a menu bar.
  32249. @param model the model object to use to control this bar. You can
  32250. pass 0 into this if you like, and set the model later
  32251. using the setModel() method
  32252. */
  32253. MenuBarComponent (MenuBarModel* const model);
  32254. /** Destructor. */
  32255. ~MenuBarComponent();
  32256. /** Changes the model object to use to control the bar.
  32257. This can be 0, in which case the bar will be empty. Don't delete the object
  32258. that is passed-in while it's still being used by this MenuBar.
  32259. */
  32260. void setModel (MenuBarModel* const newModel);
  32261. /** Pops up one of the menu items.
  32262. This lets you manually open one of the menus - it could be triggered by a
  32263. key shortcut, for example.
  32264. */
  32265. void showMenu (const int menuIndex);
  32266. /** @internal */
  32267. void paint (Graphics& g);
  32268. /** @internal */
  32269. void resized();
  32270. /** @internal */
  32271. void mouseEnter (const MouseEvent& e);
  32272. /** @internal */
  32273. void mouseExit (const MouseEvent& e);
  32274. /** @internal */
  32275. void mouseDown (const MouseEvent& e);
  32276. /** @internal */
  32277. void mouseDrag (const MouseEvent& e);
  32278. /** @internal */
  32279. void mouseUp (const MouseEvent& e);
  32280. /** @internal */
  32281. void mouseMove (const MouseEvent& e);
  32282. /** @internal */
  32283. void inputAttemptWhenModal();
  32284. /** @internal */
  32285. void handleCommandMessage (int commandId);
  32286. /** @internal */
  32287. bool keyPressed (const KeyPress& key);
  32288. /** @internal */
  32289. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32290. /** @internal */
  32291. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32292. const ApplicationCommandTarget::InvocationInfo& info);
  32293. juce_UseDebuggingNewOperator
  32294. private:
  32295. MenuBarModel* model;
  32296. StringArray menuNames;
  32297. Array <int> xPositions;
  32298. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32299. int lastMouseX, lastMouseY;
  32300. bool inModalState;
  32301. Component* currentPopup;
  32302. int getItemAt (int x, int y);
  32303. void updateItemUnderMouse (const int x, const int y);
  32304. void hideCurrentMenu();
  32305. void timerCallback();
  32306. void repaintMenuItem (int index);
  32307. MenuBarComponent (const MenuBarComponent&);
  32308. const MenuBarComponent& operator= (const MenuBarComponent&);
  32309. };
  32310. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32311. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32312. #endif
  32313. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32314. #endif
  32315. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32316. #endif
  32317. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32318. #endif
  32319. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32320. /********* Start of inlined file: juce_ComponentDragger.h *********/
  32321. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32322. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32323. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32324. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32325. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32326. /**
  32327. A class that imposes restrictions on a Component's size or position.
  32328. This is used by classes such as ResizableCornerComponent,
  32329. ResizableBorderComponent and ResizableWindow.
  32330. The base class can impose some basic size and position limits, but you can
  32331. also subclass this for custom uses.
  32332. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  32333. */
  32334. class JUCE_API ComponentBoundsConstrainer
  32335. {
  32336. public:
  32337. /** When first created, the object will not impose any restrictions on the components. */
  32338. ComponentBoundsConstrainer() throw();
  32339. /** Destructor. */
  32340. virtual ~ComponentBoundsConstrainer();
  32341. /** Imposes a minimum width limit. */
  32342. void setMinimumWidth (const int minimumWidth) throw();
  32343. /** Returns the current minimum width. */
  32344. int getMinimumWidth() const throw() { return minW; }
  32345. /** Imposes a maximum width limit. */
  32346. void setMaximumWidth (const int maximumWidth) throw();
  32347. /** Returns the current maximum width. */
  32348. int getMaximumWidth() const throw() { return maxW; }
  32349. /** Imposes a minimum height limit. */
  32350. void setMinimumHeight (const int minimumHeight) throw();
  32351. /** Returns the current minimum height. */
  32352. int getMinimumHeight() const throw() { return minH; }
  32353. /** Imposes a maximum height limit. */
  32354. void setMaximumHeight (const int maximumHeight) throw();
  32355. /** Returns the current maximum height. */
  32356. int getMaximumHeight() const throw() { return maxH; }
  32357. /** Imposes a minimum width and height limit. */
  32358. void setMinimumSize (const int minimumWidth,
  32359. const int minimumHeight) throw();
  32360. /** Imposes a maximum width and height limit. */
  32361. void setMaximumSize (const int maximumWidth,
  32362. const int maximumHeight) throw();
  32363. /** Set all the maximum and minimum dimensions. */
  32364. void setSizeLimits (const int minimumWidth,
  32365. const int minimumHeight,
  32366. const int maximumWidth,
  32367. const int maximumHeight) throw();
  32368. /** Sets the amount by which the component is allowed to go off-screen.
  32369. The values indicate how many pixels must remain on-screen when dragged off
  32370. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  32371. when the component goes off the top of the screen, its y-position will be
  32372. clipped so that there are always at least 10 pixels on-screen. In other words,
  32373. the lowest y-position it can take would be (10 - the component's height).
  32374. If you pass 0 or less for one of these amounts, the component is allowed
  32375. to move beyond that edge completely, with no restrictions at all.
  32376. If you pass a very large number (i.e. larger that the dimensions of the
  32377. component itself), then the component won't be allowed to overlap that
  32378. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  32379. the component will bump into the left side of the screen and go no further.
  32380. */
  32381. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  32382. const int minimumWhenOffTheLeft,
  32383. const int minimumWhenOffTheBottom,
  32384. const int minimumWhenOffTheRight) throw();
  32385. /** Specifies a width-to-height ratio that the resizer should always maintain.
  32386. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  32387. will always be maintained as this multiple of the height.
  32388. @see setResizeLimits
  32389. */
  32390. void setFixedAspectRatio (const double widthOverHeight) throw();
  32391. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  32392. If no aspect ratio is being enforced, this will return 0.
  32393. */
  32394. double getFixedAspectRatio() const throw();
  32395. /** This callback changes the given co-ordinates to impose whatever the current
  32396. constraints are set to be.
  32397. @param x the x position that should be examined and adjusted
  32398. @param y the y position that should be examined and adjusted
  32399. @param w the width that should be examined and adjusted
  32400. @param h the height that should be examined and adjusted
  32401. @param previousBounds the component's current size
  32402. @param limits the region in which the component can be positioned
  32403. @param isStretchingTop whether the top edge of the component is being resized
  32404. @param isStretchingLeft whether the left edge of the component is being resized
  32405. @param isStretchingBottom whether the bottom edge of the component is being resized
  32406. @param isStretchingRight whether the right edge of the component is being resized
  32407. */
  32408. virtual void checkBounds (int& x, int& y, int& w, int& h,
  32409. const Rectangle& previousBounds,
  32410. const Rectangle& limits,
  32411. const bool isStretchingTop,
  32412. const bool isStretchingLeft,
  32413. const bool isStretchingBottom,
  32414. const bool isStretchingRight);
  32415. /** This callback happens when the resizer is about to start dragging. */
  32416. virtual void resizeStart();
  32417. /** This callback happens when the resizer has finished dragging. */
  32418. virtual void resizeEnd();
  32419. /** Checks the given bounds, and then sets the component to the corrected size. */
  32420. void setBoundsForComponent (Component* const component,
  32421. int x, int y, int w, int h,
  32422. const bool isStretchingTop,
  32423. const bool isStretchingLeft,
  32424. const bool isStretchingBottom,
  32425. const bool isStretchingRight);
  32426. /** Called by setBoundsForComponent() to apply a new constrained size to a
  32427. component.
  32428. By default this just calls setBounds(), but it virtual in case it's needed for
  32429. extremely cunning purposes.
  32430. */
  32431. virtual void applyBoundsToComponent (Component* component,
  32432. int x, int y, int w, int h);
  32433. juce_UseDebuggingNewOperator
  32434. private:
  32435. int minW, maxW, minH, maxH;
  32436. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  32437. double aspectRatio;
  32438. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  32439. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  32440. };
  32441. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32442. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32443. /**
  32444. An object to take care of the logic for dragging components around with the mouse.
  32445. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  32446. then in your mouseDrag() callback, call dragComponent().
  32447. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  32448. to limit the component's position and keep it on-screen.
  32449. e.g. @code
  32450. class MyDraggableComp
  32451. {
  32452. ComponentDragger myDragger;
  32453. void mouseDown (const MouseEvent& e)
  32454. {
  32455. myDragger.startDraggingComponent (this, 0);
  32456. }
  32457. void mouseDrag (const MouseEvent& e)
  32458. {
  32459. myDragger.dragComponent (this, e);
  32460. }
  32461. };
  32462. @endcode
  32463. */
  32464. class JUCE_API ComponentDragger
  32465. {
  32466. public:
  32467. /** Creates a ComponentDragger. */
  32468. ComponentDragger();
  32469. /** Destructor. */
  32470. virtual ~ComponentDragger();
  32471. /** Call this from your component's mouseDown() method, to prepare for dragging.
  32472. @param componentToDrag the component that you want to drag
  32473. @param constrainer a constrainer object to use to keep the component
  32474. from going offscreen
  32475. @see dragComponent
  32476. */
  32477. void startDraggingComponent (Component* const componentToDrag,
  32478. ComponentBoundsConstrainer* constrainer);
  32479. /** Call this from your mouseDrag() callback to move the component.
  32480. This will move the component, but will first check the validity of the
  32481. component's new position using the checkPosition() method, which you
  32482. can override if you need to enforce special positioning limits on the
  32483. component.
  32484. @param componentToDrag the component that you want to drag
  32485. @param e the current mouse-drag event
  32486. @see dragComponent
  32487. */
  32488. void dragComponent (Component* const componentToDrag,
  32489. const MouseEvent& e);
  32490. juce_UseDebuggingNewOperator
  32491. private:
  32492. ComponentBoundsConstrainer* constrainer;
  32493. int originalX, originalY;
  32494. };
  32495. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32496. /********* End of inlined file: juce_ComponentDragger.h *********/
  32497. #endif
  32498. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32499. #endif
  32500. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32501. #endif
  32502. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32503. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32504. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32505. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32506. /**
  32507. Components derived from this class can have files dropped onto them by an external application.
  32508. @see DragAndDropContainer
  32509. */
  32510. class JUCE_API FileDragAndDropTarget
  32511. {
  32512. public:
  32513. /** Destructor. */
  32514. virtual ~FileDragAndDropTarget() {}
  32515. /** Callback to check whether this target is interested in the set of files being offered.
  32516. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32517. component, so don't do anything time-consuming in here, like opening the files to have a look
  32518. inside them!
  32519. @param files the set of (absolute) pathnames of the files that the user is dragging
  32520. @returns true if this component wants to receive the other callbacks regarging this
  32521. type of object; if it returns false, no other callbacks will be made.
  32522. */
  32523. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32524. /** Callback to indicate that some files are being dragged over this component.
  32525. This gets called when the user moves the mouse into this component while dragging.
  32526. Use this callback as a trigger to make your component repaint itself to give the
  32527. user feedback about whether the files can be dropped here or not.
  32528. @param files the set of (absolute) pathnames of the files that the user is dragging
  32529. @param x the mouse x position, relative to this component
  32530. @param y the mouse y position, relative to this component
  32531. */
  32532. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32533. /** Callback to indicate that the user is dragging some files over this component.
  32534. This gets called when the user moves the mouse over this component while dragging.
  32535. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32536. this lets you know what happens in-between.
  32537. @param files the set of (absolute) pathnames of the files that the user is dragging
  32538. @param x the mouse x position, relative to this component
  32539. @param y the mouse y position, relative to this component
  32540. */
  32541. virtual void fileDragMove (const StringArray& files, int x, int y);
  32542. /** Callback to indicate that the mouse has moved away from this component.
  32543. This gets called when the user moves the mouse out of this component while dragging
  32544. the files.
  32545. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32546. as a signal to repaint it in its normal state.
  32547. @param files the set of (absolute) pathnames of the files that the user is dragging
  32548. */
  32549. virtual void fileDragExit (const StringArray& files);
  32550. /** Callback to indicate that the user has dropped the files onto this component.
  32551. When the user drops the files, this get called, and you can use the files in whatever
  32552. way is appropriate.
  32553. Note that after this is called, the fileDragExit method may not be called, so you should
  32554. clean up in here if there's anything you need to do when the drag finishes.
  32555. @param files the set of (absolute) pathnames of the files that the user is dragging
  32556. @param x the mouse x position, relative to this component
  32557. @param y the mouse y position, relative to this component
  32558. */
  32559. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32560. };
  32561. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32562. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32563. #endif
  32564. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32565. /********* Start of inlined file: juce_LassoComponent.h *********/
  32566. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32567. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32568. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  32569. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32570. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32571. /** Manages a list of selectable items.
  32572. Use one of these to keep a track of things that the user has highlighted, like
  32573. icons or things in a list.
  32574. The class is templated so that you can use it to hold either a set of pointers
  32575. to objects, or a set of ID numbers or handles, for cases where each item may
  32576. not always have a corresponding object.
  32577. To be informed when items are selected/deselected, register a ChangeListener with
  32578. this object.
  32579. @see SelectableObject
  32580. */
  32581. template <class SelectableItemType>
  32582. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  32583. {
  32584. public:
  32585. /** Creates an empty set. */
  32586. SelectedItemSet()
  32587. {
  32588. }
  32589. /** Creates a set based on an array of items. */
  32590. SelectedItemSet (const Array <SelectableItemType>& items)
  32591. : selectedItems (items)
  32592. {
  32593. }
  32594. /** Creates a copy of another set. */
  32595. SelectedItemSet (const SelectedItemSet& other)
  32596. : selectedItems (other.selectedItems)
  32597. {
  32598. }
  32599. /** Creates a copy of another set. */
  32600. const SelectedItemSet& operator= (const SelectedItemSet& other)
  32601. {
  32602. if (selectedItems != other.selectedItems)
  32603. {
  32604. selectedItems = other.selectedItems;
  32605. changed();
  32606. }
  32607. return *this;
  32608. }
  32609. /** Destructor. */
  32610. ~SelectedItemSet()
  32611. {
  32612. }
  32613. /** Clears any other currently selected items, and selects this item.
  32614. If this item is already the only thing selected, no change notification
  32615. will be sent out.
  32616. @see addToSelection, addToSelectionBasedOnModifiers
  32617. */
  32618. void selectOnly (SelectableItemType item)
  32619. {
  32620. if (isSelected (item))
  32621. {
  32622. for (int i = selectedItems.size(); --i >= 0;)
  32623. {
  32624. if (selectedItems.getUnchecked(i) != item)
  32625. {
  32626. deselect (selectedItems.getUnchecked(i));
  32627. i = jmin (i, selectedItems.size());
  32628. }
  32629. }
  32630. }
  32631. else
  32632. {
  32633. deselectAll();
  32634. changed();
  32635. selectedItems.add (item);
  32636. itemSelected (item);
  32637. }
  32638. }
  32639. /** Selects an item.
  32640. If the item is already selected, no change notification will be sent out.
  32641. @see selectOnly, addToSelectionBasedOnModifiers
  32642. */
  32643. void addToSelection (SelectableItemType item)
  32644. {
  32645. if (! isSelected (item))
  32646. {
  32647. changed();
  32648. selectedItems.add (item);
  32649. itemSelected (item);
  32650. }
  32651. }
  32652. /** Selects or deselects an item.
  32653. This will use the modifier keys to decide whether to deselect other items
  32654. first.
  32655. So if the shift key is held down, the item will be added without deselecting
  32656. anything (same as calling addToSelection() )
  32657. If no modifiers are down, the current selection will be cleared first (same
  32658. as calling selectOnly() )
  32659. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  32660. so it'll be added to the set unless it's already there, in which case it'll be
  32661. deselected.
  32662. If the items that you're selecting can also be dragged, you may need to use the
  32663. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  32664. subtleties of this kind of usage.
  32665. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  32666. */
  32667. void addToSelectionBasedOnModifiers (SelectableItemType item,
  32668. const ModifierKeys& modifiers)
  32669. {
  32670. if (modifiers.isShiftDown())
  32671. {
  32672. addToSelection (item);
  32673. }
  32674. else if (modifiers.isCommandDown())
  32675. {
  32676. if (isSelected (item))
  32677. deselect (item);
  32678. else
  32679. addToSelection (item);
  32680. }
  32681. else
  32682. {
  32683. selectOnly (item);
  32684. }
  32685. }
  32686. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  32687. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  32688. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  32689. makes it easy to handle multiple-selection of sets of objects that can also
  32690. be dragged.
  32691. For example, if you have several items already selected, and you click on
  32692. one of them (without dragging), then you'd expect this to deselect the other, and
  32693. just select the item you clicked on. But if you had clicked on this item and
  32694. dragged it, you'd have expected them all to stay selected.
  32695. When you call this method, you'll need to store the boolean result, because the
  32696. addToSelectionOnMouseUp() method will need to be know this value.
  32697. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  32698. */
  32699. bool addToSelectionOnMouseDown (SelectableItemType item,
  32700. const ModifierKeys& modifiers)
  32701. {
  32702. if (isSelected (item))
  32703. {
  32704. return ! modifiers.isPopupMenu();
  32705. }
  32706. else
  32707. {
  32708. addToSelectionBasedOnModifiers (item, modifiers);
  32709. return false;
  32710. }
  32711. }
  32712. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  32713. Call this during a mouseUp callback, when you have previously called the
  32714. addToSelectionOnMouseDown() method during your mouseDown event.
  32715. See addToSelectionOnMouseDown() for more info
  32716. @param item the item to select (or deselect)
  32717. @param modifiers the modifiers from the mouse-up event
  32718. @param wasItemDragged true if your item was dragged during the mouse click
  32719. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  32720. back from the addToSelectionOnMouseDown() call that you
  32721. should have made during the matching mouseDown event
  32722. */
  32723. void addToSelectionOnMouseUp (SelectableItemType item,
  32724. const ModifierKeys& modifiers,
  32725. const bool wasItemDragged,
  32726. const bool resultOfMouseDownSelectMethod)
  32727. {
  32728. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  32729. addToSelectionBasedOnModifiers (item, modifiers);
  32730. }
  32731. /** Deselects an item. */
  32732. void deselect (SelectableItemType item)
  32733. {
  32734. const int i = selectedItems.indexOf (item);
  32735. if (i >= 0)
  32736. {
  32737. changed();
  32738. itemDeselected (selectedItems.remove (i));
  32739. }
  32740. }
  32741. /** Deselects all items. */
  32742. void deselectAll()
  32743. {
  32744. if (selectedItems.size() > 0)
  32745. {
  32746. changed();
  32747. for (int i = selectedItems.size(); --i >= 0;)
  32748. {
  32749. itemDeselected (selectedItems.remove (i));
  32750. i = jmin (i, selectedItems.size());
  32751. }
  32752. }
  32753. }
  32754. /** Returns the number of currently selected items.
  32755. @see getSelectedItem
  32756. */
  32757. int getNumSelected() const throw()
  32758. {
  32759. return selectedItems.size();
  32760. }
  32761. /** Returns one of the currently selected items.
  32762. Returns 0 if the index is out-of-range.
  32763. @see getNumSelected
  32764. */
  32765. SelectableItemType getSelectedItem (const int index) const throw()
  32766. {
  32767. return selectedItems [index];
  32768. }
  32769. /** True if this item is currently selected. */
  32770. bool isSelected (const SelectableItemType item) const throw()
  32771. {
  32772. return selectedItems.contains (item);
  32773. }
  32774. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  32775. /** Can be overridden to do special handling when an item is selected.
  32776. For example, if the item is an object, you might want to call it and tell
  32777. it that it's being selected.
  32778. */
  32779. virtual void itemSelected (SelectableItemType item) {}
  32780. /** Can be overridden to do special handling when an item is deselected.
  32781. For example, if the item is an object, you might want to call it and tell
  32782. it that it's being deselected.
  32783. */
  32784. virtual void itemDeselected (SelectableItemType item) {}
  32785. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  32786. */
  32787. void changed (const bool synchronous = false)
  32788. {
  32789. if (synchronous)
  32790. sendSynchronousChangeMessage (this);
  32791. else
  32792. sendChangeMessage (this);
  32793. }
  32794. juce_UseDebuggingNewOperator
  32795. private:
  32796. Array <SelectableItemType> selectedItems;
  32797. };
  32798. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32799. /********* End of inlined file: juce_SelectedItemSet.h *********/
  32800. /**
  32801. A class used by the LassoComponent to manage the things that it selects.
  32802. This allows the LassoComponent to find out which items are within the lasso,
  32803. and to change the list of selected items.
  32804. @see LassoComponent, SelectedItemSet
  32805. */
  32806. template <class SelectableItemType>
  32807. class LassoSource
  32808. {
  32809. public:
  32810. /** Destructor. */
  32811. virtual ~LassoSource() {}
  32812. /** Returns the set of items that lie within a given lassoable region.
  32813. Your implementation of this method must find all the relevent items that lie
  32814. within the given rectangle. and add them to the itemsFound array.
  32815. The co-ordinates are relative to the top-left of the lasso component's parent
  32816. component. (i.e. they are the same as the size and position of the lasso
  32817. component itself).
  32818. */
  32819. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  32820. int x, int y, int width, int height) = 0;
  32821. /** Returns the SelectedItemSet that the lasso should update.
  32822. This set will be continuously updated by the LassoComponent as it gets
  32823. dragged around, so make sure that you've got a ChangeListener attached to
  32824. the set so that your UI objects will know when the selection changes and
  32825. be able to update themselves appropriately.
  32826. */
  32827. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  32828. };
  32829. /**
  32830. A component that acts as a rectangular selection region, which you drag with
  32831. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  32832. To use one of these:
  32833. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  32834. component, and call its beginLasso() method, giving it a
  32835. suitable LassoSource object that it can use to find out which items are in
  32836. the active area.
  32837. - Each time your parent component gets a mouseDrag event, call dragLasso()
  32838. to update the lasso's position - it will use its LassoSource to calculate and
  32839. update the current selection.
  32840. - After the drag has finished and you get a mouseUp callback, you should call
  32841. endLasso() to clean up. This will make the lasso component invisible, and you
  32842. can remove it from the parent component, or delete it.
  32843. The class takes into account the modifier keys that are being held down while
  32844. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  32845. be added to the original selection; if ctrl or command is pressed, they will be
  32846. xor'ed with any previously selected items.
  32847. @see LassoSource, SelectedItemSet
  32848. */
  32849. template <class SelectableItemType>
  32850. class LassoComponent : public Component
  32851. {
  32852. public:
  32853. /** Creates a Lasso component.
  32854. The fill colour is used to fill the lasso'ed rectangle, and the outline
  32855. colour is used to draw a line around its edge.
  32856. */
  32857. LassoComponent (const int outlineThickness_ = 1)
  32858. : source (0),
  32859. outlineThickness (outlineThickness_)
  32860. {
  32861. }
  32862. /** Destructor. */
  32863. ~LassoComponent()
  32864. {
  32865. }
  32866. /** Call this in your mouseDown event, to initialise a drag.
  32867. Pass in a suitable LassoSource object which the lasso will use to find
  32868. the items and change the selection.
  32869. After using this method to initialise the lasso, repeatedly call dragLasso()
  32870. in your component's mouseDrag callback.
  32871. @see dragLasso, endLasso, LassoSource
  32872. */
  32873. void beginLasso (const MouseEvent& e,
  32874. LassoSource <SelectableItemType>* const lassoSource)
  32875. {
  32876. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  32877. jassert (lassoSource != 0); // the source can't be null!
  32878. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  32879. source = lassoSource;
  32880. if (lassoSource != 0)
  32881. originalSelection = lassoSource->getLassoSelection().getItemArray();
  32882. setSize (0, 0);
  32883. }
  32884. /** Call this in your mouseDrag event, to update the lasso's position.
  32885. This must be repeatedly calling when the mouse is dragged, after you've
  32886. first initialised the lasso with beginLasso().
  32887. This method takes into account the modifier keys that are being held down, so
  32888. if shift is pressed, then the lassoed items will be added to any that were
  32889. previously selected; if ctrl or command is pressed, then they will be xor'ed
  32890. with previously selected items.
  32891. @see beginLasso, endLasso
  32892. */
  32893. void dragLasso (const MouseEvent& e)
  32894. {
  32895. if (source != 0)
  32896. {
  32897. const int x1 = e.getMouseDownX();
  32898. const int y1 = e.getMouseDownY();
  32899. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  32900. setVisible (true);
  32901. Array <SelectableItemType> itemsInLasso;
  32902. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  32903. if (e.mods.isShiftDown())
  32904. {
  32905. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  32906. itemsInLasso.addArray (originalSelection);
  32907. }
  32908. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  32909. {
  32910. Array <SelectableItemType> originalMinusNew (originalSelection);
  32911. originalMinusNew.removeValuesIn (itemsInLasso);
  32912. itemsInLasso.removeValuesIn (originalSelection);
  32913. itemsInLasso.addArray (originalMinusNew);
  32914. }
  32915. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  32916. }
  32917. }
  32918. /** Call this in your mouseUp event, after the lasso has been dragged.
  32919. @see beginLasso, dragLasso
  32920. */
  32921. void endLasso()
  32922. {
  32923. source = 0;
  32924. originalSelection.clear();
  32925. setVisible (false);
  32926. }
  32927. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32928. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32929. methods.
  32930. Note that you can also use the constants from TextEditor::ColourIds to change the
  32931. colour of the text editor that is opened when a label is editable.
  32932. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32933. */
  32934. enum ColourIds
  32935. {
  32936. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  32937. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  32938. };
  32939. /** @internal */
  32940. void paint (Graphics& g)
  32941. {
  32942. g.fillAll (findColour (lassoFillColourId));
  32943. g.setColour (findColour (lassoOutlineColourId));
  32944. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  32945. // this suggests that you've left a lasso comp lying around after the
  32946. // mouse drag has finished.. Be careful to call endLasso() when you get a
  32947. // mouse-up event.
  32948. jassert (isMouseButtonDownAnywhere());
  32949. }
  32950. /** @internal */
  32951. bool hitTest (int x, int y) { return false; }
  32952. juce_UseDebuggingNewOperator
  32953. private:
  32954. Array <SelectableItemType> originalSelection;
  32955. LassoSource <SelectableItemType>* source;
  32956. int outlineThickness;
  32957. };
  32958. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32959. /********* End of inlined file: juce_LassoComponent.h *********/
  32960. #endif
  32961. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  32962. #endif
  32963. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  32964. #endif
  32965. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  32966. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  32967. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  32968. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  32969. /**
  32970. Monitors a component for mouse activity, and triggers a callback
  32971. when the mouse hovers in one place for a specified length of time.
  32972. To use a hover-detector, just create one and call its setHoverComponent()
  32973. method to start it watching a component. You can call setHoverComponent (0)
  32974. to make it inactive.
  32975. (Be careful not to delete a component that's being monitored without first
  32976. stopping or deleting the hover detector).
  32977. */
  32978. class JUCE_API MouseHoverDetector
  32979. {
  32980. public:
  32981. /** Creates a hover detector.
  32982. Initially the object is inactive, and you need to tell it which component
  32983. to monitor, using the setHoverComponent() method.
  32984. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  32985. needs to stay still before the mouseHovered() method
  32986. is invoked. You can change this setting later with
  32987. the setHoverTimeMillisecs() method
  32988. */
  32989. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  32990. /** Destructor. */
  32991. virtual ~MouseHoverDetector();
  32992. /** Changes the time for which the mouse has to stay still before it's considered
  32993. to be hovering.
  32994. */
  32995. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  32996. /** Changes the component that's being monitored for hovering.
  32997. Be careful not to delete a component that's being monitored without first
  32998. stopping or deleting the hover detector.
  32999. */
  33000. void setHoverComponent (Component* const newSourceComponent);
  33001. protected:
  33002. /** Called back when the mouse hovers.
  33003. After the mouse has stayed still over the component for the length of time
  33004. specified by setHoverTimeMillisecs(), this method will be invoked.
  33005. When the mouse is first moved after this callback has occurred, the
  33006. mouseMovedAfterHover() method will be called.
  33007. @param mouseX the mouse's X position relative to the component being monitored
  33008. @param mouseY the mouse's Y position relative to the component being monitored
  33009. */
  33010. virtual void mouseHovered (int mouseX,
  33011. int mouseY) = 0;
  33012. /** Called when the mouse is moved away after just having hovered. */
  33013. virtual void mouseMovedAfterHover() = 0;
  33014. private:
  33015. class JUCE_API HoverDetectorInternal : public MouseListener,
  33016. public Timer
  33017. {
  33018. public:
  33019. MouseHoverDetector* owner;
  33020. int lastX, lastY;
  33021. void timerCallback();
  33022. void mouseEnter (const MouseEvent&);
  33023. void mouseExit (const MouseEvent&);
  33024. void mouseDown (const MouseEvent&);
  33025. void mouseUp (const MouseEvent&);
  33026. void mouseMove (const MouseEvent&);
  33027. void mouseWheelMove (const MouseEvent&, float, float);
  33028. } internalTimer;
  33029. friend class HoverDetectorInternal;
  33030. Component* source;
  33031. int hoverTimeMillisecs;
  33032. bool hasJustHovered;
  33033. void hoverTimerCallback();
  33034. void checkJustHoveredCallback();
  33035. };
  33036. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33037. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33038. #endif
  33039. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33040. #endif
  33041. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33042. #endif
  33043. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33044. #endif
  33045. #ifndef __JUCE_LABEL_JUCEHEADER__
  33046. #endif
  33047. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33048. #endif
  33049. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33050. /********* Start of inlined file: juce_ProgressBar.h *********/
  33051. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33052. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33053. /**
  33054. A progress bar component.
  33055. To use this, just create one and make it visible. It'll run its own timer
  33056. to keep an eye on a variable that you give it, and will automatically
  33057. redraw itself when the variable changes.
  33058. For an easy way of running a background task with a dialog box showing its
  33059. progress, see the ThreadWithProgressWindow class.
  33060. @see ThreadWithProgressWindow
  33061. */
  33062. class JUCE_API ProgressBar : public Component,
  33063. public SettableTooltipClient,
  33064. private Timer
  33065. {
  33066. public:
  33067. /** Creates a ProgressBar.
  33068. @param progress pass in a reference to a double that you're going to
  33069. update with your task's progress. The ProgressBar will
  33070. monitor the value of this variable and will redraw itself
  33071. when the value changes. The range is from 0 to 1.0. Obviously
  33072. you'd better be careful not to delete this variable while the
  33073. ProgressBar still exists!
  33074. */
  33075. ProgressBar (double& progress);
  33076. /** Destructor. */
  33077. ~ProgressBar();
  33078. /** Turns the percentage display on or off.
  33079. By default this is on, and the progress bar will display a text string showing
  33080. its current percentage.
  33081. */
  33082. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33083. /** Gives the progress bar a string to display inside it.
  33084. If you call this, it will turn off the percentage display.
  33085. @see setPercentageDisplay
  33086. */
  33087. void setTextToDisplay (const String& text);
  33088. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33089. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33090. methods.
  33091. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33092. */
  33093. enum ColourIds
  33094. {
  33095. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33096. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33097. classes will probably use variations on this colour. */
  33098. };
  33099. juce_UseDebuggingNewOperator
  33100. protected:
  33101. /** @internal */
  33102. void paint (Graphics& g);
  33103. /** @internal */
  33104. void lookAndFeelChanged();
  33105. /** @internal */
  33106. void visibilityChanged();
  33107. /** @internal */
  33108. void colourChanged();
  33109. private:
  33110. double& progress;
  33111. double currentValue;
  33112. bool displayPercentage;
  33113. String displayedMessage, currentMessage;
  33114. void timerCallback();
  33115. ProgressBar (const ProgressBar&);
  33116. const ProgressBar& operator= (const ProgressBar&);
  33117. };
  33118. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33119. /********* End of inlined file: juce_ProgressBar.h *********/
  33120. #endif
  33121. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33122. /********* Start of inlined file: juce_Slider.h *********/
  33123. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33124. #define __JUCE_SLIDER_JUCEHEADER__
  33125. /********* Start of inlined file: juce_SliderListener.h *********/
  33126. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33127. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33128. class Slider;
  33129. /**
  33130. A class for receiving callbacks from a Slider.
  33131. To be told when a slider's value changes, you can register a SliderListener
  33132. object using Slider::addListener().
  33133. @see Slider::addListener, Slider::removeListener
  33134. */
  33135. class JUCE_API SliderListener
  33136. {
  33137. public:
  33138. /** Destructor. */
  33139. virtual ~SliderListener() {}
  33140. /** Called when the slider's value is changed.
  33141. This may be caused by dragging it, or by typing in its text entry box,
  33142. or by a call to Slider::setValue().
  33143. You can find out the new value using Slider::getValue().
  33144. @see Slider::valueChanged
  33145. */
  33146. virtual void sliderValueChanged (Slider* slider) = 0;
  33147. /** Called when the slider is about to be dragged.
  33148. This is called when a drag begins, then it's followed by multiple calls
  33149. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33150. user lets go.
  33151. @see sliderDragEnded, Slider::startedDragging
  33152. */
  33153. virtual void sliderDragStarted (Slider* slider);
  33154. /** Called after a drag operation has finished.
  33155. @see sliderDragStarted, Slider::stoppedDragging
  33156. */
  33157. virtual void sliderDragEnded (Slider* slider);
  33158. };
  33159. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33160. /********* End of inlined file: juce_SliderListener.h *********/
  33161. /**
  33162. A slider control for changing a value.
  33163. The slider can be horizontal, vertical, or rotary, and can optionally have
  33164. a text-box inside it to show an editable display of the current value.
  33165. To use it, create a Slider object and use the setSliderStyle() method
  33166. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33167. To define the values that it can be set to, see the setRange() and setValue() methods.
  33168. There are also lots of custom tweaks you can do by subclassing and overriding
  33169. some of the virtual methods, such as changing the scaling, changing the format of
  33170. the text display, custom ways of limiting the values, etc.
  33171. You can register SliderListeners with a slider, which will be informed when the value
  33172. changes, or a subclass can override valueChanged() to be informed synchronously.
  33173. @see SliderListener
  33174. */
  33175. class JUCE_API Slider : public Component,
  33176. public SettableTooltipClient,
  33177. private AsyncUpdater,
  33178. private ButtonListener,
  33179. private LabelListener
  33180. {
  33181. public:
  33182. /** Creates a slider.
  33183. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33184. setRange(), etc.
  33185. */
  33186. Slider (const String& componentName);
  33187. /** Destructor. */
  33188. ~Slider();
  33189. /** The types of slider available.
  33190. @see setSliderStyle, setRotaryParameters
  33191. */
  33192. enum SliderStyle
  33193. {
  33194. LinearHorizontal, /**< A traditional horizontal slider. */
  33195. LinearVertical, /**< A traditional vertical slider. */
  33196. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33197. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33198. @see setRotaryParameters */
  33199. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33200. @see setRotaryParameters */
  33201. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33202. @see setRotaryParameters */
  33203. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33204. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33205. @see setMinValue, setMaxValue */
  33206. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33207. @see setMinValue, setMaxValue */
  33208. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33209. value, with the current value being somewhere between them.
  33210. @see setMinValue, setMaxValue */
  33211. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33212. value, with the current value being somewhere between them.
  33213. @see setMinValue, setMaxValue */
  33214. };
  33215. /** Changes the type of slider interface being used.
  33216. @param newStyle the type of interface
  33217. @see setRotaryParameters, setVelocityBasedMode,
  33218. */
  33219. void setSliderStyle (const SliderStyle newStyle);
  33220. /** Returns the slider's current style.
  33221. @see setSliderStyle
  33222. */
  33223. SliderStyle getSliderStyle() const throw() { return style; }
  33224. /** Changes the properties of a rotary slider.
  33225. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33226. the slider's minimum value is represented
  33227. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33228. the slider's maximum value is represented. This must be
  33229. greater than startAngleRadians
  33230. @param stopAtEnd if true, then when the slider is dragged around past the
  33231. minimum or maximum, it'll stop there; if false, it'll wrap
  33232. back to the opposite value
  33233. */
  33234. void setRotaryParameters (const float startAngleRadians,
  33235. const float endAngleRadians,
  33236. const bool stopAtEnd);
  33237. /** Sets the distance the mouse has to move to drag the slider across
  33238. the full extent of its range.
  33239. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33240. relative mouse movements to adjust the slider.
  33241. */
  33242. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33243. /** Changes the way the the mouse is used when dragging the slider.
  33244. If true, this will turn on velocity-sensitive dragging, so that
  33245. the faster the mouse moves, the bigger the movement to the slider. This
  33246. helps when making accurate adjustments if the slider's range is quite large.
  33247. If false, the slider will just try to snap to wherever the mouse is.
  33248. */
  33249. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33250. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33251. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33252. or if you're holding down ctrl.
  33253. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33254. @param threshold the minimum number of pixels that the mouse needs to move for it
  33255. to be treated as a movement
  33256. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33257. the threshold is reached
  33258. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33259. key to toggle velocity-sensitive mode
  33260. */
  33261. void setVelocityModeParameters (const double sensitivity = 1.0,
  33262. const int threshold = 1,
  33263. const double offset = 0.0,
  33264. const bool userCanPressKeyToSwapMode = true) throw();
  33265. /** Sets up a skew factor to alter the way values are distributed.
  33266. You may want to use a range of values on the slider where more accuracy
  33267. is required towards one end of the range, so this will logarithmically
  33268. spread the values across the length of the slider.
  33269. If the factor is < 1.0, the lower end of the range will fill more of the
  33270. slider's length; if the factor is > 1.0, the upper end of the range
  33271. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33272. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33273. method instead.
  33274. @see getSkewFactor, setSkewFactorFromMidPoint
  33275. */
  33276. void setSkewFactor (const double factor) throw();
  33277. /** Sets up a skew factor to alter the way values are distributed.
  33278. This allows you to specify the slider value that should appear in the
  33279. centre of the slider's visible range.
  33280. @see setSkewFactor, getSkewFactor
  33281. */
  33282. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33283. /** Returns the current skew factor.
  33284. See setSkewFactor for more info.
  33285. @see setSkewFactor, setSkewFactorFromMidPoint
  33286. */
  33287. double getSkewFactor() const throw() { return skewFactor; }
  33288. /** Used by setIncDecButtonsMode().
  33289. */
  33290. enum IncDecButtonMode
  33291. {
  33292. incDecButtonsNotDraggable,
  33293. incDecButtonsDraggable_AutoDirection,
  33294. incDecButtonsDraggable_Horizontal,
  33295. incDecButtonsDraggable_Vertical
  33296. };
  33297. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33298. can be dragged on the buttons to drag the values.
  33299. By default this is turned off. When enabled, clicking on the buttons still works
  33300. them as normal, but by holding down the mouse on a button and dragging it a little
  33301. distance, it flips into a mode where the value can be dragged. The drag direction can
  33302. either be set explicitly to be vertical or horizontal, or can be set to
  33303. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33304. are side-by-side or above each other.
  33305. */
  33306. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33307. /** The position of the slider's text-entry box.
  33308. @see setTextBoxStyle
  33309. */
  33310. enum TextEntryBoxPosition
  33311. {
  33312. NoTextBox, /**< Doesn't display a text box. */
  33313. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33314. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33315. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33316. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33317. };
  33318. /** Changes the location and properties of the text-entry box.
  33319. @param newPosition where it should go (or NoTextBox to not have one at all)
  33320. @param isReadOnly if true, it's a read-only display
  33321. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33322. room for the slider as well!
  33323. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33324. room for the slider as well!
  33325. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33326. */
  33327. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33328. const bool isReadOnly,
  33329. const int textEntryBoxWidth,
  33330. const int textEntryBoxHeight);
  33331. /** Returns the status of the text-box.
  33332. @see setTextBoxStyle
  33333. */
  33334. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33335. /** Returns the width used for the text-box.
  33336. @see setTextBoxStyle
  33337. */
  33338. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33339. /** Returns the height used for the text-box.
  33340. @see setTextBoxStyle
  33341. */
  33342. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33343. /** Makes the text-box editable.
  33344. By default this is true, and the user can enter values into the textbox,
  33345. but it can be turned off if that's not suitable.
  33346. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33347. */
  33348. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33349. /** Returns true if the text-box is read-only.
  33350. @see setTextBoxStyle
  33351. */
  33352. bool isTextBoxEditable() const throw() { return editableText; }
  33353. /** If the text-box is editable, this will give it the focus so that the user can
  33354. type directly into it.
  33355. This is basically the effect as the user clicking on it.
  33356. */
  33357. void showTextBox();
  33358. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33359. focus away from it.
  33360. @param discardCurrentEditorContents if true, the slider's value will be left
  33361. unchanged; if false, the current contents of the
  33362. text editor will be used to set the slider position
  33363. before it is hidden.
  33364. */
  33365. void hideTextBox (const bool discardCurrentEditorContents);
  33366. /** Changes the slider's current value.
  33367. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33368. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33369. want to handle it.
  33370. @param newValue the new value to set - this will be restricted by the
  33371. minimum and maximum range, and will be snapped to the
  33372. nearest interval if one has been set
  33373. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33374. any SliderListeners or the valueChanged() method
  33375. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33376. synchronously; if false, it will be asynchronous
  33377. */
  33378. void setValue (double newValue,
  33379. const bool sendUpdateMessage = true,
  33380. const bool sendMessageSynchronously = false);
  33381. /** Returns the slider's current value. */
  33382. double getValue() const throw();
  33383. /** Sets the limits that the slider's value can take.
  33384. @param newMinimum the lowest value allowed
  33385. @param newMaximum the highest value allowed
  33386. @param newInterval the steps in which the value is allowed to increase - if this
  33387. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33388. */
  33389. void setRange (const double newMinimum,
  33390. const double newMaximum,
  33391. const double newInterval = 0);
  33392. /** Returns the current maximum value.
  33393. @see setRange
  33394. */
  33395. double getMaximum() const throw() { return maximum; }
  33396. /** Returns the current minimum value.
  33397. @see setRange
  33398. */
  33399. double getMinimum() const throw() { return minimum; }
  33400. /** Returns the current step-size for values.
  33401. @see setRange
  33402. */
  33403. double getInterval() const throw() { return interval; }
  33404. /** For a slider with two or three thumbs, this returns the lower of its values.
  33405. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33406. A slider with three values also uses the normal getValue() and setValue() methods to
  33407. control the middle value.
  33408. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33409. */
  33410. double getMinValue() const throw();
  33411. /** For a slider with two or three thumbs, this sets the lower of its values.
  33412. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33413. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33414. want to handle it.
  33415. @param newValue the new value to set - this will be restricted by the
  33416. minimum and maximum range, and the max value (in a two-value
  33417. slider) or the mid value (in a three-value slider), and
  33418. will be snapped to the nearest interval if one has been set.
  33419. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33420. any SliderListeners or the valueChanged() method
  33421. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33422. synchronously; if false, it will be asynchronous
  33423. @see getMinValue, setMaxValue, setValue
  33424. */
  33425. void setMinValue (double newValue,
  33426. const bool sendUpdateMessage = true,
  33427. const bool sendMessageSynchronously = false);
  33428. /** For a slider with two or three thumbs, this returns the higher of its values.
  33429. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33430. A slider with three values also uses the normal getValue() and setValue() methods to
  33431. control the middle value.
  33432. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33433. */
  33434. double getMaxValue() const throw();
  33435. /** For a slider with two or three thumbs, this sets the lower of its values.
  33436. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33437. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33438. want to handle it.
  33439. @param newValue the new value to set - this will be restricted by the
  33440. minimum and maximum range, and the max value (in a two-value
  33441. slider) or the mid value (in a three-value slider), and
  33442. will be snapped to the nearest interval if one has been set.
  33443. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33444. any SliderListeners or the valueChanged() method
  33445. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33446. synchronously; if false, it will be asynchronous
  33447. @see getMaxValue, setMinValue, setValue
  33448. */
  33449. void setMaxValue (double newValue,
  33450. const bool sendUpdateMessage = true,
  33451. const bool sendMessageSynchronously = false);
  33452. /** Adds a listener to be called when this slider's value changes. */
  33453. void addListener (SliderListener* const listener) throw();
  33454. /** Removes a previously-registered listener. */
  33455. void removeListener (SliderListener* const listener) throw();
  33456. /** This lets you choose whether double-clicking moves the slider to a given position.
  33457. By default this is turned off, but it's handy if you want a double-click to act
  33458. as a quick way of resetting a slider. Just pass in the value you want it to
  33459. go to when double-clicked.
  33460. @see getDoubleClickReturnValue
  33461. */
  33462. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  33463. const double valueToSetOnDoubleClick) throw();
  33464. /** Returns the values last set by setDoubleClickReturnValue() method.
  33465. Sets isEnabled to true if double-click is enabled, and returns the value
  33466. that was set.
  33467. @see setDoubleClickReturnValue
  33468. */
  33469. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  33470. /** Tells the slider whether to keep sending change messages while the user
  33471. is dragging the slider.
  33472. If set to true, a change message will only be sent when the user has
  33473. dragged the slider and let go. If set to false (the default), then messages
  33474. will be continuously sent as they drag it while the mouse button is still
  33475. held down.
  33476. */
  33477. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  33478. /** This lets you change whether the slider thumb jumps to the mouse position
  33479. when you click.
  33480. By default, this is true. If it's false, then the slider moves with relative
  33481. motion when you drag it.
  33482. This only applies to linear bars, and won't affect two- or three- value
  33483. sliders.
  33484. */
  33485. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  33486. /** If enabled, this gives the slider a pop-up bubble which appears while the
  33487. slider is being dragged.
  33488. This can be handy if your slider doesn't have a text-box, so that users can
  33489. see the value just when they're changing it.
  33490. If you pass a component as the parentComponentToUse parameter, the pop-up
  33491. bubble will be added as a child of that component when it's needed. If you
  33492. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  33493. transparent window, so if you're using an OS that can't do transparent windows
  33494. you'll have to add it to a parent component instead).
  33495. */
  33496. void setPopupDisplayEnabled (const bool isEnabled,
  33497. Component* const parentComponentToUse) throw();
  33498. /** If this is set to true, then right-clicking on the slider will pop-up
  33499. a menu to let the user change the way it works.
  33500. By default this is turned off, but when turned on, the menu will include
  33501. things like velocity sensitivity, and for rotary sliders, whether they
  33502. use a linear or rotary mouse-drag to move them.
  33503. */
  33504. void setPopupMenuEnabled (const bool menuEnabled) throw();
  33505. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  33506. By default it's enabled.
  33507. */
  33508. void setScrollWheelEnabled (const bool enabled) throw();
  33509. /** Returns a number to indicate which thumb is currently being dragged by the
  33510. mouse.
  33511. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  33512. the maximum-value thumb, or -1 if none is currently down.
  33513. */
  33514. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  33515. /** Callback to indicate that the user is about to start dragging the slider.
  33516. @see SliderListener::sliderDragStarted
  33517. */
  33518. virtual void startedDragging();
  33519. /** Callback to indicate that the user has just stopped dragging the slider.
  33520. @see SliderListener::sliderDragEnded
  33521. */
  33522. virtual void stoppedDragging();
  33523. /** Callback to indicate that the user has just moved the slider.
  33524. @see SliderListener::sliderValueChanged
  33525. */
  33526. virtual void valueChanged();
  33527. /** Callback to indicate that the user has just moved the slider.
  33528. Note - the valueChanged() method has changed its format and now no longer has
  33529. any parameters. Update your code to use the new version.
  33530. This version has been left here with an int as its return value to cause
  33531. a syntax error if you've got existing code that uses the old version.
  33532. */
  33533. virtual int valueChanged (double) { jassertfalse; return 0; }
  33534. /** Subclasses can override this to convert a text string to a value.
  33535. When the user enters something into the text-entry box, this method is
  33536. called to convert it to a value.
  33537. The default routine just tries to convert it to a double.
  33538. @see getTextFromValue
  33539. */
  33540. virtual double getValueFromText (const String& text);
  33541. /** Turns the slider's current value into a text string.
  33542. Subclasses can override this to customise the formatting of the text-entry box.
  33543. The default implementation just turns the value into a string, using
  33544. a number of decimal places based on the range interval. If a suffix string
  33545. has been set using setTextValueSuffix(), this will be appended to the text.
  33546. @see getValueFromText
  33547. */
  33548. virtual const String getTextFromValue (double value);
  33549. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  33550. a string.
  33551. This is used by the default implementation of getTextFromValue(), and is just
  33552. appended to the numeric value. For more advanced formatting, you can override
  33553. getTextFromValue() and do something else.
  33554. */
  33555. void setTextValueSuffix (const String& suffix);
  33556. /** Allows a user-defined mapping of distance along the slider to its value.
  33557. The default implementation for this performs the skewing operation that
  33558. can be set up in the setSkewFactor() method. Override it if you need
  33559. some kind of custom mapping instead, but make sure you also implement the
  33560. inverse function in valueToProportionOfLength().
  33561. @param proportion a value 0 to 1.0, indicating a distance along the slider
  33562. @returns the slider value that is represented by this position
  33563. @see valueToProportionOfLength
  33564. */
  33565. virtual double proportionOfLengthToValue (double proportion);
  33566. /** Allows a user-defined mapping of value to the position of the slider along its length.
  33567. The default implementation for this performs the skewing operation that
  33568. can be set up in the setSkewFactor() method. Override it if you need
  33569. some kind of custom mapping instead, but make sure you also implement the
  33570. inverse function in proportionOfLengthToValue().
  33571. @param value a valid slider value, between the range of values specified in
  33572. setRange()
  33573. @returns a value 0 to 1.0 indicating the distance along the slider that
  33574. represents this value
  33575. @see proportionOfLengthToValue
  33576. */
  33577. virtual double valueToProportionOfLength (double value);
  33578. /** Returns the X or Y coordinate of a value along the slider's length.
  33579. If the slider is horizontal, this will be the X coordinate of the given
  33580. value, relative to the left of the slider. If it's vertical, then this will
  33581. be the Y coordinate, relative to the top of the slider.
  33582. If the slider is rotary, this will throw an assertion and return 0. If the
  33583. value is out-of-range, it will be constrained to the length of the slider.
  33584. */
  33585. float getPositionOfValue (const double value);
  33586. /** This can be overridden to allow the slider to snap to user-definable values.
  33587. If overridden, it will be called when the user tries to move the slider to
  33588. a given position, and allows a subclass to sanity-check this value, possibly
  33589. returning a different value to use instead.
  33590. @param attemptedValue the value the user is trying to enter
  33591. @param userIsDragging true if the user is dragging with the mouse; false if
  33592. they are entering the value using the text box
  33593. @returns the value to use instead
  33594. */
  33595. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  33596. /** This can be called to force the text box to update its contents.
  33597. (Not normally needed, as this is done automatically).
  33598. */
  33599. void updateText();
  33600. /** True if the slider moves horizontally. */
  33601. bool isHorizontal() const throw();
  33602. /** True if the slider moves vertically. */
  33603. bool isVertical() const throw();
  33604. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  33605. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33606. methods.
  33607. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33608. */
  33609. enum ColourIds
  33610. {
  33611. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  33612. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  33613. and feel class how this is used. */
  33614. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  33615. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  33616. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  33617. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  33618. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  33619. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  33620. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  33621. };
  33622. juce_UseDebuggingNewOperator
  33623. protected:
  33624. /** @internal */
  33625. void labelTextChanged (Label*);
  33626. /** @internal */
  33627. void paint (Graphics& g);
  33628. /** @internal */
  33629. void resized();
  33630. /** @internal */
  33631. void mouseDown (const MouseEvent& e);
  33632. /** @internal */
  33633. void mouseUp (const MouseEvent& e);
  33634. /** @internal */
  33635. void mouseDrag (const MouseEvent& e);
  33636. /** @internal */
  33637. void mouseDoubleClick (const MouseEvent& e);
  33638. /** @internal */
  33639. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33640. /** @internal */
  33641. void modifierKeysChanged (const ModifierKeys& modifiers);
  33642. /** @internal */
  33643. void buttonClicked (Button* button);
  33644. /** @internal */
  33645. void lookAndFeelChanged();
  33646. /** @internal */
  33647. void enablementChanged();
  33648. /** @internal */
  33649. void focusOfChildComponentChanged (FocusChangeType cause);
  33650. /** @internal */
  33651. void handleAsyncUpdate();
  33652. /** @internal */
  33653. void colourChanged();
  33654. private:
  33655. SortedSet <void*> listeners;
  33656. double currentValue, valueMin, valueMax;
  33657. double minimum, maximum, interval, doubleClickReturnValue;
  33658. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  33659. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  33660. int velocityModeThreshold;
  33661. float rotaryStart, rotaryEnd;
  33662. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  33663. int sliderRegionStart, sliderRegionSize;
  33664. int sliderBeingDragged;
  33665. int pixelsForFullDragExtent;
  33666. Rectangle sliderRect;
  33667. String textSuffix;
  33668. SliderStyle style;
  33669. TextEntryBoxPosition textBoxPos;
  33670. int textBoxWidth, textBoxHeight;
  33671. IncDecButtonMode incDecButtonMode;
  33672. bool editableText : 1, doubleClickToValue : 1;
  33673. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  33674. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  33675. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  33676. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  33677. Font font;
  33678. Label* valueBox;
  33679. Button* incButton;
  33680. Button* decButton;
  33681. Component* popupDisplay;
  33682. Component* parentForPopupDisplay;
  33683. float getLinearSliderPos (const double value);
  33684. void restoreMouseIfHidden();
  33685. void sendDragStart();
  33686. void sendDragEnd();
  33687. double constrainedValue (double value) const throw();
  33688. void triggerChangeMessage (const bool synchronous);
  33689. bool incDecDragDirectionIsHorizontal() const throw();
  33690. Slider (const Slider&);
  33691. const Slider& operator= (const Slider&);
  33692. };
  33693. #endif // __JUCE_SLIDER_JUCEHEADER__
  33694. /********* End of inlined file: juce_Slider.h *********/
  33695. #endif
  33696. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33697. #endif
  33698. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33699. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  33700. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33701. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33702. class TableHeaderComponent;
  33703. /**
  33704. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  33705. You can register one of these objects for table events using TableHeaderComponent::addListener()
  33706. and TableHeaderComponent::removeListener().
  33707. @see TableHeaderComponent
  33708. */
  33709. class JUCE_API TableHeaderListener
  33710. {
  33711. public:
  33712. TableHeaderListener() {}
  33713. /** Destructor. */
  33714. virtual ~TableHeaderListener() {}
  33715. /** This is called when some of the table's columns are added, removed, hidden,
  33716. or rearranged.
  33717. */
  33718. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  33719. /** This is called when one or more of the table's columns are resized.
  33720. */
  33721. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  33722. /** This is called when the column by which the table should be sorted is changed.
  33723. */
  33724. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  33725. /** This is called when the user begins or ends dragging one of the columns around.
  33726. When the user starts dragging a column, this is called with the ID of that
  33727. column. When they finish dragging, it is called again with 0 as the ID.
  33728. */
  33729. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  33730. int columnIdNowBeingDragged);
  33731. };
  33732. /**
  33733. A component that displays a strip of column headings for a table, and allows these
  33734. to be resized, dragged around, etc.
  33735. This is just the component that goes at the top of a table. You can use it
  33736. directly for custom components, or to create a simple table, use the
  33737. TableListBox class.
  33738. To use one of these, create it and use addColumn() to add all the columns that you need.
  33739. Each column must be given a unique ID number that's used to refer to it.
  33740. @see TableListBox, TableHeaderListener
  33741. */
  33742. class JUCE_API TableHeaderComponent : public Component,
  33743. private AsyncUpdater
  33744. {
  33745. public:
  33746. /** Creates an empty table header.
  33747. */
  33748. TableHeaderComponent();
  33749. /** Destructor. */
  33750. ~TableHeaderComponent();
  33751. /** A combination of these flags are passed into the addColumn() method to specify
  33752. the properties of a column.
  33753. */
  33754. enum ColumnPropertyFlags
  33755. {
  33756. 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. */
  33757. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  33758. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  33759. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  33760. 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. */
  33761. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  33762. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  33763. /** This set of default flags is used as the default parameter value in addColumn(). */
  33764. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  33765. /** A quick way of combining flags for a column that's not resizable. */
  33766. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  33767. /** A quick way of combining flags for a column that's not resizable or sortable. */
  33768. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  33769. /** A quick way of combining flags for a column that's not sortable. */
  33770. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  33771. };
  33772. /** Adds a column to the table.
  33773. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  33774. registered listeners.
  33775. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  33776. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  33777. a unique ID. This is used to identify the column later on, after the user may have
  33778. changed the order that they appear in
  33779. @param width the initial width of the column, in pixels
  33780. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  33781. if the 'resizable' flag is specified for this column
  33782. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  33783. if the 'resizable' flag is specified for this column
  33784. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  33785. properties of this column
  33786. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  33787. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  33788. all columns, not just the index amongst those that are currently visible
  33789. */
  33790. void addColumn (const String& columnName,
  33791. const int columnId,
  33792. const int width,
  33793. const int minimumWidth = 30,
  33794. const int maximumWidth = -1,
  33795. const int propertyFlags = defaultFlags,
  33796. const int insertIndex = -1);
  33797. /** Removes a column with the given ID.
  33798. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  33799. registered listeners.
  33800. */
  33801. void removeColumn (const int columnIdToRemove);
  33802. /** Deletes all columns from the table.
  33803. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  33804. registered listeners.
  33805. */
  33806. void removeAllColumns();
  33807. /** Returns the number of columns in the table.
  33808. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  33809. return the total number of columns, including hidden ones.
  33810. @see isColumnVisible
  33811. */
  33812. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  33813. /** Returns the name for a column.
  33814. @see setColumnName
  33815. */
  33816. const String getColumnName (const int columnId) const throw();
  33817. /** Changes the name of a column. */
  33818. void setColumnName (const int columnId, const String& newName);
  33819. /** Moves a column to a different index in the table.
  33820. @param columnId the column to move
  33821. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  33822. */
  33823. void moveColumn (const int columnId, int newVisibleIndex);
  33824. /** Changes the width of a column.
  33825. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  33826. */
  33827. void setColumnWidth (const int columnId, const int newWidth);
  33828. /** Shows or hides a column.
  33829. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  33830. @see isColumnVisible
  33831. */
  33832. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  33833. /** Returns true if this column is currently visible.
  33834. @see setColumnVisible
  33835. */
  33836. bool isColumnVisible (const int columnId) const;
  33837. /** Changes the column which is the sort column.
  33838. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  33839. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  33840. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  33841. @see getSortColumnId, isSortedForwards, reSortTable
  33842. */
  33843. void setSortColumnId (const int columnId, const bool sortForwards);
  33844. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  33845. @see setSortColumnId, isSortedForwards
  33846. */
  33847. int getSortColumnId() const throw();
  33848. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  33849. @see setSortColumnId
  33850. */
  33851. bool isSortedForwards() const throw();
  33852. /** Triggers a re-sort of the table according to the current sort-column.
  33853. If you modifiy the table's contents, you can call this to signal that the table needs
  33854. to be re-sorted.
  33855. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  33856. tableSortOrderChanged() method of any listeners).
  33857. */
  33858. void reSortTable();
  33859. /** Returns the total width of all the visible columns in the table.
  33860. */
  33861. int getTotalWidth() const throw();
  33862. /** Returns the index of a given column.
  33863. If there's no such column ID, this will return -1.
  33864. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  33865. otherwise it'll return the index amongst all the columns, including any hidden ones.
  33866. */
  33867. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  33868. /** Returns the ID of the column at a given index.
  33869. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  33870. otherwise it'll count it amongst all the columns, including any hidden ones.
  33871. If the index is out-of-range, it'll return 0.
  33872. */
  33873. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  33874. /** Returns the rectangle containing of one of the columns.
  33875. The index is an index from 0 to the number of columns that are currently visible (hidden
  33876. ones are not counted). It returns a rectangle showing the position of the column relative
  33877. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  33878. */
  33879. const Rectangle getColumnPosition (const int index) const throw();
  33880. /** Finds the column ID at a given x-position in the component.
  33881. If there is a column at this point this returns its ID, or if not, it will return 0.
  33882. */
  33883. int getColumnIdAtX (const int xToFind) const throw();
  33884. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  33885. entire width of the component.
  33886. By default this is disabled. Turning it on also means that when resizing a column, those
  33887. on the right will be squashed to fit.
  33888. */
  33889. void setStretchToFitActive (const bool shouldStretchToFit);
  33890. /** Returns true if stretch-to-fit has been enabled.
  33891. @see setStretchToFitActive
  33892. */
  33893. bool isStretchToFitActive() const throw();
  33894. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  33895. specified width, keeping their relative proportions the same.
  33896. If the minimum widths of the columns are too wide to fit into this space, it may
  33897. actually end up wider.
  33898. */
  33899. void resizeAllColumnsToFit (int targetTotalWidth);
  33900. /** Enables or disables the pop-up menu.
  33901. The default menu allows the user to show or hide columns. You can add custom
  33902. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  33903. By default the menu is enabled.
  33904. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  33905. */
  33906. void setPopupMenuActive (const bool hasMenu);
  33907. /** Returns true if the pop-up menu is enabled.
  33908. @see setPopupMenuActive
  33909. */
  33910. bool isPopupMenuActive() const throw();
  33911. /** Returns a string that encapsulates the table's current layout.
  33912. This can be restored later using restoreFromString(). It saves the order of
  33913. the columns, the currently-sorted column, and the widths.
  33914. @see restoreFromString
  33915. */
  33916. const String toString() const;
  33917. /** Restores the state of the table, based on a string previously created with
  33918. toString().
  33919. @see toString
  33920. */
  33921. void restoreFromString (const String& storedVersion);
  33922. /** Adds a listener to be informed about things that happen to the header. */
  33923. void addListener (TableHeaderListener* const newListener) throw();
  33924. /** Removes a previously-registered listener. */
  33925. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  33926. /** This can be overridden to handle a mouse-click on one of the column headers.
  33927. The default implementation will use this click to call getSortColumnId() and
  33928. change the sort order.
  33929. */
  33930. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  33931. /** This can be overridden to add custom items to the pop-up menu.
  33932. If you override this, you should call the superclass's method to add its
  33933. column show/hide items, if you want them on the menu as well.
  33934. Then to handle the result, override reactToMenuItem().
  33935. @see reactToMenuItem
  33936. */
  33937. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  33938. /** Override this to handle any custom items that you have added to the
  33939. pop-up menu with an addMenuItems() override.
  33940. If the menuReturnId isn't one of your own custom menu items, you'll need to
  33941. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  33942. handle the items that it had added.
  33943. @see addMenuItems
  33944. */
  33945. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  33946. /** @internal */
  33947. void paint (Graphics& g);
  33948. /** @internal */
  33949. void resized();
  33950. /** @internal */
  33951. void mouseMove (const MouseEvent&);
  33952. /** @internal */
  33953. void mouseEnter (const MouseEvent&);
  33954. /** @internal */
  33955. void mouseExit (const MouseEvent&);
  33956. /** @internal */
  33957. void mouseDown (const MouseEvent&);
  33958. /** @internal */
  33959. void mouseDrag (const MouseEvent&);
  33960. /** @internal */
  33961. void mouseUp (const MouseEvent&);
  33962. /** @internal */
  33963. const MouseCursor getMouseCursor();
  33964. juce_UseDebuggingNewOperator
  33965. private:
  33966. struct ColumnInfo
  33967. {
  33968. String name;
  33969. int id, propertyFlags, width, minimumWidth, maximumWidth;
  33970. double lastDeliberateWidth;
  33971. bool isVisible() const throw();
  33972. };
  33973. OwnedArray <ColumnInfo> columns;
  33974. Array <TableHeaderListener*> listeners;
  33975. Component* dragOverlayComp;
  33976. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  33977. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  33978. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  33979. ColumnInfo* getInfoForId (const int columnId) const throw();
  33980. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  33981. void sendColumnsChanged();
  33982. void handleAsyncUpdate();
  33983. void beginDrag (const MouseEvent&);
  33984. void endDrag (const int finalIndex);
  33985. int getResizeDraggerAt (const int mouseX) const throw();
  33986. void updateColumnUnderMouse (int x, int y);
  33987. void showColumnChooserMenu (const int);
  33988. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  33989. TableHeaderComponent (const TableHeaderComponent&);
  33990. const TableHeaderComponent operator= (const TableHeaderComponent&);
  33991. };
  33992. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33993. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  33994. #endif
  33995. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  33996. /********* Start of inlined file: juce_TableListBox.h *********/
  33997. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  33998. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  33999. /**
  34000. One of these is used by a TableListBox as the data model for the table's contents.
  34001. The virtual methods that you override in this class take care of drawing the
  34002. table cells, and reacting to events.
  34003. @see TableListBox
  34004. */
  34005. class JUCE_API TableListBoxModel
  34006. {
  34007. public:
  34008. TableListBoxModel() {}
  34009. /** Destructor. */
  34010. virtual ~TableListBoxModel() {}
  34011. /** This must return the number of rows currently in the table.
  34012. If the number of rows changes, you must call TableListBox::updateContent() to
  34013. cause it to refresh the list.
  34014. */
  34015. virtual int getNumRows() = 0;
  34016. /** This must draw the background behind one of the rows in the table.
  34017. The graphics context has its origin at the row's top-left, and your method
  34018. should fill the area specified by the width and height parameters.
  34019. */
  34020. virtual void paintRowBackground (Graphics& g,
  34021. int rowNumber,
  34022. int width, int height,
  34023. bool rowIsSelected) = 0;
  34024. /** This must draw one of the cells.
  34025. The graphics context's origin will already be set to the top-left of the cell,
  34026. whose size is specified by (width, height).
  34027. */
  34028. virtual void paintCell (Graphics& g,
  34029. int rowNumber,
  34030. int columnId,
  34031. int width, int height,
  34032. bool rowIsSelected) = 0;
  34033. /** This is used to create or update a custom component to go in a cell.
  34034. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34035. and handle mouse clicks with cellClicked().
  34036. This method will be called whenever a custom component might need to be updated - e.g.
  34037. when the table is changed, or TableListBox::updateContent() is called.
  34038. If you don't need a custom component for the specified cell, then return 0.
  34039. If you do want a custom component, and the existingComponentToUpdate is null, then
  34040. this method must create a new component suitable for the cell, and return it.
  34041. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34042. by this method. In this case, the method must either update it to make sure it's correctly representing
  34043. the given cell (which may be different from the one that the component was created for), or it can
  34044. delete this component and return a new one.
  34045. */
  34046. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34047. Component* existingComponentToUpdate);
  34048. /** This callback is made when the user clicks on one of the cells in the table.
  34049. The mouse event's coordinates will be relative to the entire table row.
  34050. @see cellDoubleClicked, backgroundClicked
  34051. */
  34052. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34053. /** This callback is made when the user clicks on one of the cells in the table.
  34054. The mouse event's coordinates will be relative to the entire table row.
  34055. @see cellClicked, backgroundClicked
  34056. */
  34057. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34058. /** This can be overridden to react to the user double-clicking on a part of the list where
  34059. there are no rows.
  34060. @see cellClicked
  34061. */
  34062. virtual void backgroundClicked();
  34063. /** This callback is made when the table's sort order is changed.
  34064. This could be because the user has clicked a column header, or because the
  34065. TableHeaderComponent::setSortColumnId() method was called.
  34066. If you implement this, your method should re-sort the table using the given
  34067. column as the key.
  34068. */
  34069. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34070. /** Returns the best width for one of the columns.
  34071. If you implement this method, you should measure the width of all the items
  34072. in this column, and return the best size.
  34073. Returning 0 means that the column shouldn't be changed.
  34074. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34075. */
  34076. virtual int getColumnAutoSizeWidth (int columnId);
  34077. /** Override this to be informed when rows are selected or deselected.
  34078. @see ListBox::selectedRowsChanged()
  34079. */
  34080. virtual void selectedRowsChanged (int lastRowSelected);
  34081. /** Override this to be informed when the delete key is pressed.
  34082. @see ListBox::deleteKeyPressed()
  34083. */
  34084. virtual void deleteKeyPressed (int lastRowSelected);
  34085. /** Override this to be informed when the return key is pressed.
  34086. @see ListBox::returnKeyPressed()
  34087. */
  34088. virtual void returnKeyPressed (int lastRowSelected);
  34089. /** Override this to be informed when the list is scrolled.
  34090. This might be caused by the user moving the scrollbar, or by programmatic changes
  34091. to the list position.
  34092. */
  34093. virtual void listWasScrolled();
  34094. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34095. If this returns a non-empty name then when the user drags a row, the table will try to
  34096. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34097. drag-and-drop operation, using this string as the source description, and the listbox
  34098. itself as the source component.
  34099. @see DragAndDropContainer::startDragging
  34100. */
  34101. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34102. };
  34103. /**
  34104. A table of cells, using a TableHeaderComponent as its header.
  34105. This component makes it easy to create a table by providing a TableListBoxModel as
  34106. the data source.
  34107. @see TableListBoxModel, TableHeaderComponent
  34108. */
  34109. class JUCE_API TableListBox : public ListBox,
  34110. private ListBoxModel,
  34111. private TableHeaderListener
  34112. {
  34113. public:
  34114. /** Creates a TableListBox.
  34115. The model pointer passed-in can be null, in which case you can set it later
  34116. with setModel().
  34117. */
  34118. TableListBox (const String& componentName,
  34119. TableListBoxModel* const model);
  34120. /** Destructor. */
  34121. ~TableListBox();
  34122. /** Changes the TableListBoxModel that is being used for this table.
  34123. */
  34124. void setModel (TableListBoxModel* const newModel);
  34125. /** Returns the model currently in use. */
  34126. TableListBoxModel* getModel() const throw() { return model; }
  34127. /** Returns the header component being used in this table. */
  34128. TableHeaderComponent* getHeader() const throw() { return header; }
  34129. /** Changes the height of the table header component.
  34130. @see getHeaderHeight
  34131. */
  34132. void setHeaderHeight (const int newHeight);
  34133. /** Returns the height of the table header.
  34134. @see setHeaderHeight
  34135. */
  34136. int getHeaderHeight() const throw();
  34137. /** Resizes a column to fit its contents.
  34138. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34139. and applies that to the column.
  34140. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34141. */
  34142. void autoSizeColumn (const int columnId);
  34143. /** Calls autoSizeColumn() for all columns in the table. */
  34144. void autoSizeAllColumns();
  34145. /** Enables or disables the auto size options on the popup menu.
  34146. By default, these are enabled.
  34147. */
  34148. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34149. /** True if the auto-size options should be shown on the menu.
  34150. @see setAutoSizeMenuOptionsShown
  34151. */
  34152. bool isAutoSizeMenuOptionShown() const throw();
  34153. /** Returns the position of one of the cells in the table.
  34154. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34155. the table component's top-left. The row number isn't checked to see if it's
  34156. in-range, but the column ID must exist or this will return an empty rectangle.
  34157. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34158. top-left of the table's top-left cell.
  34159. */
  34160. const Rectangle getCellPosition (const int columnId,
  34161. const int rowNumber,
  34162. const bool relativeToComponentTopLeft) const;
  34163. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34164. @see ListBox::scrollToEnsureRowIsOnscreen
  34165. */
  34166. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34167. /** @internal */
  34168. int getNumRows();
  34169. /** @internal */
  34170. void paintListBoxItem (int, Graphics&, int, int, bool);
  34171. /** @internal */
  34172. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34173. /** @internal */
  34174. void selectedRowsChanged (int lastRowSelected);
  34175. /** @internal */
  34176. void deleteKeyPressed (int currentSelectedRow);
  34177. /** @internal */
  34178. void returnKeyPressed (int currentSelectedRow);
  34179. /** @internal */
  34180. void backgroundClicked();
  34181. /** @internal */
  34182. void listWasScrolled();
  34183. /** @internal */
  34184. void tableColumnsChanged (TableHeaderComponent*);
  34185. /** @internal */
  34186. void tableColumnsResized (TableHeaderComponent*);
  34187. /** @internal */
  34188. void tableSortOrderChanged (TableHeaderComponent*);
  34189. /** @internal */
  34190. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34191. /** @internal */
  34192. void resized();
  34193. juce_UseDebuggingNewOperator
  34194. private:
  34195. TableHeaderComponent* header;
  34196. TableListBoxModel* model;
  34197. int columnIdNowBeingDragged;
  34198. bool autoSizeOptionsShown;
  34199. void updateColumnComponents() const;
  34200. TableListBox (const TableListBox&);
  34201. const TableListBox& operator= (const TableListBox&);
  34202. };
  34203. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34204. /********* End of inlined file: juce_TableListBox.h *********/
  34205. #endif
  34206. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34207. #endif
  34208. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34209. #endif
  34210. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34211. #endif
  34212. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34213. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  34214. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34215. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34216. /**
  34217. A factory object which can create ToolbarItemComponent objects.
  34218. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34219. that it can create.
  34220. Each type of item is identified by a unique ID, and multiple instances of an
  34221. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34222. bars).
  34223. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34224. */
  34225. class JUCE_API ToolbarItemFactory
  34226. {
  34227. public:
  34228. ToolbarItemFactory();
  34229. /** Destructor. */
  34230. virtual ~ToolbarItemFactory();
  34231. /** A set of reserved item ID values, used for the built-in item types.
  34232. */
  34233. enum SpecialItemIds
  34234. {
  34235. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34236. can be placed between sets of items to break them into groups. */
  34237. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34238. items.*/
  34239. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34240. either side of it, filling any available space. */
  34241. };
  34242. /** Must return a list of the IDs for all the item types that this factory can create.
  34243. The ids should be added to the array that is passed-in.
  34244. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34245. and the predefined IDs in the SpecialItemIds enum.
  34246. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34247. to this list if you want your toolbar to be able to contain those items.
  34248. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34249. of available items, and their order on the palette will reflect the order in which
  34250. they appear on this list.
  34251. @see ToolbarItemPalette
  34252. */
  34253. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34254. /** Must return the set of items that should be added to a toolbar as its default set.
  34255. This method is used by Toolbar::addDefaultItems() to determine which items to
  34256. create.
  34257. The items that your method adds to the array that is passed-in will be added to the
  34258. toolbar in the same order. Items can appear in the list more than once.
  34259. */
  34260. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34261. /** Must create an instance of one of the items that the factory lists in its
  34262. getAllToolbarItemIds() method.
  34263. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34264. method, except for the built-in item types from the SpecialItemIds enum, which
  34265. are created internally by the toolbar code.
  34266. Try not to keep a pointer to the object that is returned, as it will be deleted
  34267. automatically by the toolbar, and remember that multiple instances of the same
  34268. item type are likely to exist at the same time.
  34269. */
  34270. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  34271. };
  34272. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34273. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  34274. #endif
  34275. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34276. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  34277. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34278. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34279. /**
  34280. A component containing a list of toolbar items, which the user can drag onto
  34281. a toolbar to add them.
  34282. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34283. which automatically shows one of these in a dialog box with lots of extra controls.
  34284. @see Toolbar
  34285. */
  34286. class JUCE_API ToolbarItemPalette : public Component,
  34287. public DragAndDropContainer
  34288. {
  34289. public:
  34290. /** Creates a palette of items for a given factory, with the aim of adding them
  34291. to the specified toolbar.
  34292. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34293. set of items that are shown in this palette.
  34294. The toolbar and factory must not be deleted while this object exists.
  34295. */
  34296. ToolbarItemPalette (ToolbarItemFactory& factory,
  34297. Toolbar* const toolbar);
  34298. /** Destructor. */
  34299. ~ToolbarItemPalette();
  34300. /** @internal */
  34301. void resized();
  34302. juce_UseDebuggingNewOperator
  34303. private:
  34304. ToolbarItemFactory& factory;
  34305. Toolbar* toolbar;
  34306. Viewport* viewport;
  34307. friend class Toolbar;
  34308. void replaceComponent (ToolbarItemComponent* const comp);
  34309. ToolbarItemPalette (const ToolbarItemPalette&);
  34310. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34311. };
  34312. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34313. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  34314. #endif
  34315. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34316. #endif
  34317. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34318. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34319. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34320. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34321. /**
  34322. A PropertyComponent that contains an on/off toggle button.
  34323. This type of property component can be used if you have a boolean value to
  34324. toggle on/off.
  34325. @see PropertyComponent
  34326. */
  34327. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  34328. private ButtonListener
  34329. {
  34330. public:
  34331. /** Creates a button component.
  34332. @param propertyName the property name to be passed to the PropertyComponent
  34333. @param buttonTextWhenTrue the text shown in the button when the value is true
  34334. @param buttonTextWhenFalse the text shown in the button when the value is false
  34335. */
  34336. BooleanPropertyComponent (const String& propertyName,
  34337. const String& buttonTextWhenTrue,
  34338. const String& buttonTextWhenFalse);
  34339. /** Destructor. */
  34340. ~BooleanPropertyComponent();
  34341. /** Called to change the state of the boolean value. */
  34342. virtual void setState (const bool newState) = 0;
  34343. /** Must return the current value of the property. */
  34344. virtual bool getState() const = 0;
  34345. /** @internal */
  34346. void paint (Graphics& g);
  34347. /** @internal */
  34348. void refresh();
  34349. /** @internal */
  34350. void buttonClicked (Button*);
  34351. juce_UseDebuggingNewOperator
  34352. private:
  34353. ToggleButton* button;
  34354. String onText, offText;
  34355. };
  34356. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34357. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  34358. #endif
  34359. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34360. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  34361. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34362. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34363. /**
  34364. A PropertyComponent that contains a button.
  34365. This type of property component can be used if you need a button to trigger some
  34366. kind of action.
  34367. @see PropertyComponent
  34368. */
  34369. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  34370. private ButtonListener
  34371. {
  34372. public:
  34373. /** Creates a button component.
  34374. @param propertyName the property name to be passed to the PropertyComponent
  34375. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  34376. */
  34377. ButtonPropertyComponent (const String& propertyName,
  34378. const bool triggerOnMouseDown);
  34379. /** Destructor. */
  34380. ~ButtonPropertyComponent();
  34381. /** Called when the user clicks the button.
  34382. */
  34383. virtual void buttonClicked() = 0;
  34384. /** Returns the string that should be displayed in the button.
  34385. If you need to change this string, call refresh() to update the component.
  34386. */
  34387. virtual const String getButtonText() const = 0;
  34388. /** @internal */
  34389. void refresh();
  34390. /** @internal */
  34391. void buttonClicked (Button*);
  34392. juce_UseDebuggingNewOperator
  34393. private:
  34394. TextButton* button;
  34395. };
  34396. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34397. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  34398. #endif
  34399. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34400. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  34401. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34402. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34403. /**
  34404. A PropertyComponent that shows its value as a combo box.
  34405. This type of property component contains a list of options and has a
  34406. combo box to choose one.
  34407. Your subclass's constructor must add some strings to the choices StringArray
  34408. and these are shown in the list.
  34409. The getIndex() method will be called to find out which option is the currently
  34410. selected one. If you call refresh() it will call getIndex() to check whether
  34411. the value has changed, and will update the combo box if needed.
  34412. If the user selects a different item from the list, setIndex() will be
  34413. called to let your class process this.
  34414. @see PropertyComponent, PropertyPanel
  34415. */
  34416. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  34417. private ComboBoxListener
  34418. {
  34419. public:
  34420. /** Creates the component.
  34421. Your subclass's constructor must add a list of options to the choices
  34422. member variable.
  34423. */
  34424. ChoicePropertyComponent (const String& propertyName);
  34425. /** Destructor. */
  34426. ~ChoicePropertyComponent();
  34427. /** Called when the user selects an item from the combo box.
  34428. Your subclass must use this callback to update the value that this component
  34429. represents. The index is the index of the chosen item in the choices
  34430. StringArray.
  34431. */
  34432. virtual void setIndex (const int newIndex) = 0;
  34433. /** Returns the index of the item that should currently be shown.
  34434. This is the index of the item in the choices StringArray that will be
  34435. shown.
  34436. */
  34437. virtual int getIndex() const = 0;
  34438. /** Returns the list of options. */
  34439. const StringArray& getChoices() const throw();
  34440. /** @internal */
  34441. void refresh();
  34442. /** @internal */
  34443. void comboBoxChanged (ComboBox*);
  34444. juce_UseDebuggingNewOperator
  34445. protected:
  34446. /** The list of options that will be shown in the combo box.
  34447. Your subclass must populate this array in its constructor. If any empty
  34448. strings are added, these will be replaced with horizontal separators (see
  34449. ComboBox::addSeparator() for more info).
  34450. */
  34451. StringArray choices;
  34452. private:
  34453. ComboBox* comboBox;
  34454. };
  34455. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34456. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  34457. #endif
  34458. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  34459. #endif
  34460. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  34461. #endif
  34462. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34463. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34464. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34465. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34466. /**
  34467. A PropertyComponent that shows its value as a slider.
  34468. @see PropertyComponent, Slider
  34469. */
  34470. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  34471. private SliderListener
  34472. {
  34473. public:
  34474. /** Creates the property component.
  34475. The ranges, interval and skew factor are passed to the Slider component.
  34476. If you need to customise the slider in other ways, your constructor can
  34477. access the slider member variable and change it directly.
  34478. */
  34479. SliderPropertyComponent (const String& propertyName,
  34480. const double rangeMin,
  34481. const double rangeMax,
  34482. const double interval,
  34483. const double skewFactor = 1.0);
  34484. /** Destructor. */
  34485. ~SliderPropertyComponent();
  34486. /** Called when the user moves the slider to change its value.
  34487. Your subclass must use this method to update whatever item this property
  34488. represents.
  34489. */
  34490. virtual void setValue (const double newValue) = 0;
  34491. /** Returns the value that the slider should show. */
  34492. virtual const double getValue() const = 0;
  34493. /** @internal */
  34494. void refresh();
  34495. /** @internal */
  34496. void changeListenerCallback (void*);
  34497. /** @internal */
  34498. void sliderValueChanged (Slider*);
  34499. juce_UseDebuggingNewOperator
  34500. protected:
  34501. /** The slider component being used in this component.
  34502. Your subclass has access to this in case it needs to customise it in some way.
  34503. */
  34504. Slider* slider;
  34505. };
  34506. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34507. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  34508. #endif
  34509. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34510. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  34511. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34512. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34513. /**
  34514. A PropertyComponent that shows its value as editable text.
  34515. @see PropertyComponent
  34516. */
  34517. class JUCE_API TextPropertyComponent : public PropertyComponent
  34518. {
  34519. public:
  34520. /** Creates a text property component.
  34521. The maxNumChars is used to set the length of string allowable, and isMultiLine
  34522. sets whether the text editor allows carriage returns.
  34523. @see TextEditor
  34524. */
  34525. TextPropertyComponent (const String& propertyName,
  34526. const int maxNumChars,
  34527. const bool isMultiLine);
  34528. /** Destructor. */
  34529. ~TextPropertyComponent();
  34530. /** Called when the user edits the text.
  34531. Your subclass must use this callback to change the value of whatever item
  34532. this property component represents.
  34533. */
  34534. virtual void setText (const String& newText) = 0;
  34535. /** Returns the text that should be shown in the text editor.
  34536. */
  34537. virtual const String getText() const = 0;
  34538. /** @internal */
  34539. void refresh();
  34540. /** @internal */
  34541. void textWasEdited();
  34542. juce_UseDebuggingNewOperator
  34543. private:
  34544. Label* textEditor;
  34545. };
  34546. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34547. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  34548. #endif
  34549. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  34550. #endif
  34551. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34552. #endif
  34553. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34554. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  34555. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34556. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34557. /** An object that watches for any movement of a component or any of its parent components.
  34558. This makes it easy to check when a component is moved relative to its top-level
  34559. peer window. The normal Component::moved() method is only called when a component
  34560. moves relative to its immediate parent, and sometimes you want to know if any of
  34561. components higher up the tree have moved (which of course will affect the overall
  34562. position of all their sub-components).
  34563. It also includes a callback that lets you know when the top-level peer is changed.
  34564. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  34565. because they need to keep their custom windows in the right place and respond to
  34566. changes in the peer.
  34567. */
  34568. class JUCE_API ComponentMovementWatcher : public ComponentListener
  34569. {
  34570. public:
  34571. /** Creates a ComponentMovementWatcher to watch a given target component. */
  34572. ComponentMovementWatcher (Component* const component);
  34573. /** Destructor. */
  34574. ~ComponentMovementWatcher();
  34575. /** This callback happens when the component that is being watched is moved
  34576. relative to its top-level peer window, or when it is resized.
  34577. */
  34578. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  34579. /** This callback happens when the component's top-level peer is changed.
  34580. */
  34581. virtual void componentPeerChanged() = 0;
  34582. juce_UseDebuggingNewOperator
  34583. /** @internal */
  34584. void componentParentHierarchyChanged (Component& component);
  34585. /** @internal */
  34586. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34587. private:
  34588. Component* const component;
  34589. ComponentPeer* lastPeer;
  34590. VoidArray registeredParentComps;
  34591. bool reentrant;
  34592. int lastX, lastY, lastWidth, lastHeight;
  34593. #ifdef JUCE_DEBUG
  34594. ComponentDeletionWatcher* deletionWatcher;
  34595. #endif
  34596. void unregister() throw();
  34597. void registerWithParentComps() throw();
  34598. ComponentMovementWatcher (const ComponentMovementWatcher&);
  34599. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  34600. };
  34601. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34602. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  34603. #endif
  34604. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34605. /********* Start of inlined file: juce_GroupComponent.h *********/
  34606. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34607. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34608. /**
  34609. A component that draws an outline around itself and has an optional title at
  34610. the top, for drawing an outline around a group of controls.
  34611. */
  34612. class JUCE_API GroupComponent : public Component
  34613. {
  34614. public:
  34615. /** Creates a GroupComponent.
  34616. @param componentName the name to give the component
  34617. @param labelText the text to show at the top of the outline
  34618. */
  34619. GroupComponent (const String& componentName,
  34620. const String& labelText);
  34621. /** Destructor. */
  34622. ~GroupComponent();
  34623. /** Changes the text that's shown at the top of the component. */
  34624. void setText (const String& newText) throw();
  34625. /** Returns the currently displayed text label. */
  34626. const String getText() const throw();
  34627. /** Sets the positioning of the text label.
  34628. (The default is Justification::left)
  34629. @see getTextLabelPosition
  34630. */
  34631. void setTextLabelPosition (const Justification& justification);
  34632. /** Returns the current text label position.
  34633. @see setTextLabelPosition
  34634. */
  34635. const Justification getTextLabelPosition() const throw() { return justification; }
  34636. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34637. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34638. methods.
  34639. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34640. */
  34641. enum ColourIds
  34642. {
  34643. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  34644. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  34645. };
  34646. /** @internal */
  34647. void paint (Graphics& g);
  34648. /** @internal */
  34649. void enablementChanged();
  34650. /** @internal */
  34651. void colourChanged();
  34652. private:
  34653. String text;
  34654. Justification justification;
  34655. GroupComponent (const GroupComponent&);
  34656. const GroupComponent& operator= (const GroupComponent&);
  34657. };
  34658. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34659. /********* End of inlined file: juce_GroupComponent.h *********/
  34660. #endif
  34661. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34662. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  34663. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34664. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34665. /********* Start of inlined file: juce_TabbedComponent.h *********/
  34666. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34667. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34668. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  34669. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34670. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34671. class TabbedButtonBar;
  34672. /** In a TabbedButtonBar, this component is used for each of the buttons.
  34673. If you want to create a TabbedButtonBar with custom tab components, derive
  34674. your component from this class, and override the TabbedButtonBar::createTabButton()
  34675. method to create it instead of the default one.
  34676. @see TabbedButtonBar
  34677. */
  34678. class JUCE_API TabBarButton : public Button
  34679. {
  34680. public:
  34681. /** Creates the tab button. */
  34682. TabBarButton (const String& name,
  34683. TabbedButtonBar* const ownerBar,
  34684. const int tabIndex);
  34685. /** Destructor. */
  34686. ~TabBarButton();
  34687. /** Chooses the best length for the tab, given the specified depth.
  34688. If the tab is horizontal, this should return its width, and the depth
  34689. specifies its height. If it's vertical, it should return the height, and
  34690. the depth is actually its width.
  34691. */
  34692. virtual int getBestTabLength (const int depth);
  34693. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  34694. void clicked (const ModifierKeys& mods);
  34695. bool hitTest (int x, int y);
  34696. juce_UseDebuggingNewOperator
  34697. protected:
  34698. friend class TabbedButtonBar;
  34699. TabbedButtonBar* const owner;
  34700. int tabIndex, overlapPixels;
  34701. DropShadowEffect shadow;
  34702. /** Returns an area of the component that's safe to draw in.
  34703. This deals with the orientation of the tabs, which affects which side is
  34704. touching the tabbed box's content component.
  34705. */
  34706. void getActiveArea (int& x, int& y, int& w, int& h);
  34707. private:
  34708. TabBarButton (const TabBarButton&);
  34709. const TabBarButton& operator= (const TabBarButton&);
  34710. };
  34711. /**
  34712. A vertical or horizontal bar containing tabs that you can select.
  34713. You can use one of these to generate things like a dialog box that has
  34714. tabbed pages you can flip between. Attach a ChangeListener to the
  34715. button bar to be told when the user changes the page.
  34716. An easier method than doing this is to use a TabbedComponent, which
  34717. contains its own TabbedButtonBar and which takes care of the layout
  34718. and other housekeeping.
  34719. @see TabbedComponent
  34720. */
  34721. class JUCE_API TabbedButtonBar : public Component,
  34722. public ChangeBroadcaster,
  34723. public ButtonListener
  34724. {
  34725. public:
  34726. /** The placement of the tab-bar
  34727. @see setOrientation, getOrientation
  34728. */
  34729. enum Orientation
  34730. {
  34731. TabsAtTop,
  34732. TabsAtBottom,
  34733. TabsAtLeft,
  34734. TabsAtRight
  34735. };
  34736. /** Creates a TabbedButtonBar with a given placement.
  34737. You can change the orientation later if you need to.
  34738. */
  34739. TabbedButtonBar (const Orientation orientation);
  34740. /** Destructor. */
  34741. ~TabbedButtonBar();
  34742. /** Changes the bar's orientation.
  34743. This won't change the bar's actual size - you'll need to do that yourself,
  34744. but this determines which direction the tabs go in, and which side they're
  34745. stuck to.
  34746. */
  34747. void setOrientation (const Orientation orientation);
  34748. /** Returns the current orientation.
  34749. @see setOrientation
  34750. */
  34751. Orientation getOrientation() const throw() { return orientation; }
  34752. /** Deletes all the tabs from the bar.
  34753. @see addTab
  34754. */
  34755. void clearTabs();
  34756. /** Adds a tab to the bar.
  34757. Tabs are added in left-to-right reading order.
  34758. If this is the first tab added, it'll also be automatically selected.
  34759. */
  34760. void addTab (const String& tabName,
  34761. const Colour& tabBackgroundColour,
  34762. int insertIndex = -1);
  34763. /** Changes the name of one of the tabs. */
  34764. void setTabName (const int tabIndex,
  34765. const String& newName);
  34766. /** Gets rid of one of the tabs. */
  34767. void removeTab (const int tabIndex);
  34768. /** Moves a tab to a new index in the list.
  34769. Pass -1 as the index to move it to the end of the list.
  34770. */
  34771. void moveTab (const int currentIndex,
  34772. const int newIndex);
  34773. /** Returns the number of tabs in the bar. */
  34774. int getNumTabs() const;
  34775. /** Returns a list of all the tab names in the bar. */
  34776. const StringArray getTabNames() const;
  34777. /** Changes the currently selected tab.
  34778. This will send a change message and cause a synchronous callback to
  34779. the currentTabChanged() method. (But if the given tab is already selected,
  34780. nothing will be done).
  34781. To deselect all the tabs, use an index of -1.
  34782. */
  34783. void setCurrentTabIndex (int newTabIndex);
  34784. /** Returns the name of the currently selected tab.
  34785. This could be an empty string if none are selected.
  34786. */
  34787. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  34788. /** Returns the index of the currently selected tab.
  34789. This could return -1 if none are selected.
  34790. */
  34791. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  34792. /** Callback method to indicate the selected tab has been changed.
  34793. @see setCurrentTabIndex
  34794. */
  34795. virtual void currentTabChanged (const int newCurrentTabIndex,
  34796. const String& newCurrentTabName);
  34797. /** Callback method to indicate that the user has right-clicked on a tab.
  34798. (Or ctrl-clicked on the Mac)
  34799. */
  34800. virtual void popupMenuClickOnTab (const int tabIndex,
  34801. const String& tabName);
  34802. /** Returns the colour of a tab.
  34803. This is the colour that was specified in addTab().
  34804. */
  34805. const Colour getTabBackgroundColour (const int tabIndex);
  34806. /** Changes the background colour of a tab.
  34807. @see addTab, getTabBackgroundColour
  34808. */
  34809. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  34810. /** @internal */
  34811. void resized();
  34812. /** @internal */
  34813. void buttonClicked (Button* button);
  34814. /** @internal */
  34815. void lookAndFeelChanged();
  34816. juce_UseDebuggingNewOperator
  34817. protected:
  34818. /** This creates one of the tabs.
  34819. If you need to use custom tab components, you can override this method and
  34820. return your own class instead of the default.
  34821. */
  34822. virtual TabBarButton* createTabButton (const String& tabName,
  34823. const int tabIndex);
  34824. private:
  34825. Orientation orientation;
  34826. StringArray tabs;
  34827. Array <Colour> tabColours;
  34828. int currentTabIndex;
  34829. Component* behindFrontTab;
  34830. Button* extraTabsButton;
  34831. TabBarButton* getTabButton (const int index) const;
  34832. TabbedButtonBar (const TabbedButtonBar&);
  34833. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  34834. };
  34835. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34836. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  34837. /**
  34838. A component with a TabbedButtonBar along one of its sides.
  34839. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  34840. with addTab(), and this will take care of showing the pages for you when the
  34841. user clicks on a different tab.
  34842. @see TabbedButtonBar
  34843. */
  34844. class JUCE_API TabbedComponent : public Component
  34845. {
  34846. public:
  34847. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  34848. Once created, add some tabs with the addTab() method.
  34849. */
  34850. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  34851. /** Destructor. */
  34852. ~TabbedComponent();
  34853. /** Changes the placement of the tabs.
  34854. This will rearrange the layout to place the tabs along the appropriate
  34855. side of this component, and will shift the content component accordingly.
  34856. @see TabbedButtonBar::setOrientation
  34857. */
  34858. void setOrientation (const TabbedButtonBar::Orientation orientation);
  34859. /** Returns the current tab placement.
  34860. @see setOrientation, TabbedButtonBar::getOrientation
  34861. */
  34862. TabbedButtonBar::Orientation getOrientation() const throw();
  34863. /** Specifies how many pixels wide or high the tab-bar should be.
  34864. If the tabs are placed along the top or bottom, this specified the height
  34865. of the bar; if they're along the left or right edges, it'll be the width
  34866. of the bar.
  34867. */
  34868. void setTabBarDepth (const int newDepth);
  34869. /** Returns the current thickness of the tab bar.
  34870. @see setTabBarDepth
  34871. */
  34872. int getTabBarDepth() const throw() { return tabDepth; }
  34873. /** Specifies an outline that should be drawn around the entire content component.
  34874. If this thickness is > 0, a line of the specified colour will be drawn around
  34875. the three sides of the content component which don't touch the tab-bar, and
  34876. the content component will be inset by this amount.
  34877. */
  34878. void setOutline (const Colour& newOutlineColour,
  34879. const int newThickness);
  34880. /** Specifies a gap to leave around the edge of the content component.
  34881. Each edge of the content component will be indented by the given number of pixels.
  34882. */
  34883. void setIndent (const int indentThickness);
  34884. /** Removes all the tabs from the bar.
  34885. @see TabbedButtonBar::clearTabs
  34886. */
  34887. void clearTabs();
  34888. /** Adds a tab to the tab-bar.
  34889. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  34890. is true, it will be deleted when the tab is removed or when this object is
  34891. deleted.
  34892. @see TabbedButtonBar::addTab
  34893. */
  34894. void addTab (const String& tabName,
  34895. const Colour& tabBackgroundColour,
  34896. Component* const contentComponent,
  34897. const bool deleteComponentWhenNotNeeded,
  34898. const int insertIndex = -1);
  34899. /** Changes the name of one of the tabs. */
  34900. void setTabName (const int tabIndex,
  34901. const String& newName);
  34902. /** Gets rid of one of the tabs. */
  34903. void removeTab (const int tabIndex);
  34904. /** Returns the number of tabs in the bar. */
  34905. int getNumTabs() const;
  34906. /** Returns a list of all the tab names in the bar. */
  34907. const StringArray getTabNames() const;
  34908. /** Returns the content component that was added for the given index.
  34909. Be sure not to use or delete the components that are returned, as this may interfere
  34910. with the TabbedComponent's use of them.
  34911. */
  34912. Component* getTabContentComponent (const int tabIndex) const throw();
  34913. /** Returns the colour of one of the tabs. */
  34914. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  34915. /** Changes the background colour of one of the tabs. */
  34916. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  34917. /** Changes the currently-selected tab.
  34918. To deselect all the tabs, pass -1 as the index.
  34919. @see TabbedButtonBar::setCurrentTabIndex
  34920. */
  34921. void setCurrentTabIndex (const int newTabIndex);
  34922. /** Returns the index of the currently selected tab.
  34923. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  34924. */
  34925. int getCurrentTabIndex() const;
  34926. /** Returns the name of the currently selected tab.
  34927. @see addTab, TabbedButtonBar::getCurrentTabName()
  34928. */
  34929. const String& getCurrentTabName() const;
  34930. /** Returns the current component that's filling the panel.
  34931. This will return 0 if there isn't one.
  34932. */
  34933. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  34934. /** Callback method to indicate the selected tab has been changed.
  34935. @see setCurrentTabIndex
  34936. */
  34937. virtual void currentTabChanged (const int newCurrentTabIndex,
  34938. const String& newCurrentTabName);
  34939. /** Callback method to indicate that the user has right-clicked on a tab.
  34940. (Or ctrl-clicked on the Mac)
  34941. */
  34942. virtual void popupMenuClickOnTab (const int tabIndex,
  34943. const String& tabName);
  34944. /** Returns the tab button bar component that is being used.
  34945. */
  34946. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  34947. /** @internal */
  34948. void paint (Graphics& g);
  34949. /** @internal */
  34950. void resized();
  34951. /** @internal */
  34952. void lookAndFeelChanged();
  34953. juce_UseDebuggingNewOperator
  34954. protected:
  34955. TabbedButtonBar* tabs;
  34956. /** This creates one of the tab buttons.
  34957. If you need to use custom tab components, you can override this method and
  34958. return your own class instead of the default.
  34959. */
  34960. virtual TabBarButton* createTabButton (const String& tabName,
  34961. const int tabIndex);
  34962. private:
  34963. Array <Component*> contentComponents;
  34964. Component* panelComponent;
  34965. int tabDepth;
  34966. Colour outlineColour;
  34967. int outlineThickness, edgeIndent;
  34968. friend class TabCompButtonBar;
  34969. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  34970. TabbedComponent (const TabbedComponent&);
  34971. const TabbedComponent& operator= (const TabbedComponent&);
  34972. };
  34973. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34974. /********* End of inlined file: juce_TabbedComponent.h *********/
  34975. /********* Start of inlined file: juce_DocumentWindow.h *********/
  34976. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  34977. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  34978. /********* Start of inlined file: juce_ResizableWindow.h *********/
  34979. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  34980. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  34981. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  34982. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34983. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34984. /********* Start of inlined file: juce_DropShadower.h *********/
  34985. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  34986. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  34987. /**
  34988. Adds a drop-shadow to a component.
  34989. This object creates and manages a set of components which sit around a
  34990. component, creating a gaussian shadow around it. The components will track
  34991. the position of the component and if it's brought to the front they'll also
  34992. follow this.
  34993. For desktop windows you don't need to use this class directly - just
  34994. set the Component::windowHasDropShadow flag when calling
  34995. Component::addToDesktop(), and the system will create one of these if it's
  34996. needed (which it obviously isn't on the Mac, for example).
  34997. */
  34998. class JUCE_API DropShadower : public ComponentListener
  34999. {
  35000. public:
  35001. /** Creates a DropShadower.
  35002. @param alpha the opacity of the shadows, from 0 to 1.0
  35003. @param xOffset the horizontal displacement of the shadow, in pixels
  35004. @param yOffset the vertical displacement of the shadow, in pixels
  35005. @param blurRadius the radius of the blur to use for creating the shadow
  35006. */
  35007. DropShadower (const float alpha = 0.5f,
  35008. const int xOffset = 1,
  35009. const int yOffset = 5,
  35010. const float blurRadius = 10.0f);
  35011. /** Destructor. */
  35012. virtual ~DropShadower();
  35013. /** Attaches the DropShadower to the component you want to shadow. */
  35014. void setOwner (Component* componentToFollow);
  35015. /** @internal */
  35016. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35017. /** @internal */
  35018. void componentBroughtToFront (Component& component);
  35019. /** @internal */
  35020. void componentChildrenChanged (Component& component);
  35021. /** @internal */
  35022. void componentParentHierarchyChanged (Component& component);
  35023. /** @internal */
  35024. void componentVisibilityChanged (Component& component);
  35025. juce_UseDebuggingNewOperator
  35026. private:
  35027. Component* owner;
  35028. int numShadows;
  35029. Component* shadowWindows[4];
  35030. Image* shadowImageSections[12];
  35031. const int shadowEdge, xOffset, yOffset;
  35032. const float alpha, blurRadius;
  35033. bool inDestructor, reentrant;
  35034. void updateShadows();
  35035. void setShadowImage (Image* const src,
  35036. const int num,
  35037. const int w, const int h,
  35038. const int sx, const int sy) throw();
  35039. void bringShadowWindowsToFront();
  35040. void deleteShadowWindows();
  35041. DropShadower (const DropShadower&);
  35042. const DropShadower& operator= (const DropShadower&);
  35043. };
  35044. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35045. /********* End of inlined file: juce_DropShadower.h *********/
  35046. /**
  35047. A base class for top-level windows.
  35048. This class is used for components that are considered a major part of your
  35049. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35050. etc. Things like menus that pop up briefly aren't derived from it.
  35051. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35052. could itself be the child of another component.
  35053. The class manages a list of all instances of top-level windows that are in use,
  35054. and each one is also given the concept of being "active". The active window is
  35055. one that is actively being used by the user. This isn't quite the same as the
  35056. component with the keyboard focus, because there may be a popup menu or other
  35057. temporary window which gets keyboard focus while the active top level window is
  35058. unchanged.
  35059. A top-level window also has an optional drop-shadow.
  35060. @see ResizableWindow, DocumentWindow, DialogWindow
  35061. */
  35062. class JUCE_API TopLevelWindow : public Component
  35063. {
  35064. public:
  35065. /** Creates a TopLevelWindow.
  35066. @param name the name to give the component
  35067. @param addToDesktop if true, the window will be automatically added to the
  35068. desktop; if false, you can use it as a child component
  35069. */
  35070. TopLevelWindow (const String& name,
  35071. const bool addToDesktop);
  35072. /** Destructor. */
  35073. ~TopLevelWindow();
  35074. /** True if this is currently the TopLevelWindow that is actively being used.
  35075. This isn't quite the same as having keyboard focus, because the focus may be
  35076. on a child component or a temporary pop-up menu, etc, while this window is
  35077. still considered to be active.
  35078. @see activeWindowStatusChanged
  35079. */
  35080. bool isActiveWindow() const throw() { return windowIsActive_; }
  35081. /** This will set the bounds of the window so that it's centred in front of another
  35082. window.
  35083. If your app has a few windows open and want to pop up a dialog box for one of
  35084. them, you can use this to show it in front of the relevent parent window, which
  35085. is a bit neater than just having it appear in the middle of the screen.
  35086. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35087. be used instead. If no window is focused, it'll just default to the middle of the
  35088. screen.
  35089. */
  35090. void centreAroundComponent (Component* componentToCentreAround,
  35091. const int width, const int height);
  35092. /** Turns the drop-shadow on and off. */
  35093. void setDropShadowEnabled (const bool useShadow);
  35094. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35095. @see isUsingNativeTitleBar
  35096. */
  35097. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35098. /** Returns true if the window is currently using an OS-native title bar.
  35099. @see setUsingNativeTitleBar
  35100. */
  35101. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35102. /** Returns the number of TopLevelWindow objects currently in use.
  35103. @see getTopLevelWindow
  35104. */
  35105. static int getNumTopLevelWindows() throw();
  35106. /** Returns one of the TopLevelWindow objects currently in use.
  35107. The index is 0 to (getNumTopLevelWindows() - 1).
  35108. */
  35109. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35110. /** Returns the currently-active top level window.
  35111. There might not be one, of course, so this can return 0.
  35112. */
  35113. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35114. juce_UseDebuggingNewOperator
  35115. /** @internal */
  35116. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35117. protected:
  35118. /** This callback happens when this window becomes active or inactive.
  35119. @see isActiveWindow
  35120. */
  35121. virtual void activeWindowStatusChanged();
  35122. /** @internal */
  35123. void focusOfChildComponentChanged (FocusChangeType cause);
  35124. /** @internal */
  35125. void parentHierarchyChanged();
  35126. /** @internal */
  35127. void visibilityChanged();
  35128. /** @internal */
  35129. virtual int getDesktopWindowStyleFlags() const;
  35130. /** @internal */
  35131. void recreateDesktopWindow();
  35132. private:
  35133. friend class TopLevelWindowManager;
  35134. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35135. DropShadower* shadower;
  35136. void setWindowActive (const bool isNowActive) throw();
  35137. TopLevelWindow (const TopLevelWindow&);
  35138. const TopLevelWindow& operator= (const TopLevelWindow&);
  35139. };
  35140. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35141. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35142. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35143. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35144. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35145. /**
  35146. A component that resizes its parent window when dragged.
  35147. This component forms a frame around the edge of a component, allowing it to
  35148. be dragged by the edges or corners to resize it - like the way windows are
  35149. resized in MSWindows or Linux.
  35150. To use it, just add it to your component, making it fill the entire parent component
  35151. (there's a mouse hit-test that only traps mouse-events which land around the
  35152. edge of the component, so it's even ok to put it on top of any other components
  35153. you're using). Make sure you rescale the resizer component to fill the parent
  35154. each time the parent's size changes.
  35155. @see ResizableCornerComponent
  35156. */
  35157. class JUCE_API ResizableBorderComponent : public Component
  35158. {
  35159. public:
  35160. /** Creates a resizer.
  35161. Pass in the target component which you want to be resized when this one is
  35162. dragged.
  35163. The target component will usually be a parent of the resizer component, but this
  35164. isn't mandatory.
  35165. Remember that when the target component is resized, it'll need to move and
  35166. resize this component to keep it in place, as this won't happen automatically.
  35167. If the constrainer parameter is non-zero, then this object will be used to enforce
  35168. limits on the size and position that the component can be stretched to. Make sure
  35169. that the constrainer isn't deleted while still in use by this object.
  35170. @see ComponentBoundsConstrainer
  35171. */
  35172. ResizableBorderComponent (Component* const componentToResize,
  35173. ComponentBoundsConstrainer* const constrainer);
  35174. /** Destructor. */
  35175. ~ResizableBorderComponent();
  35176. /** Specifies how many pixels wide the draggable edges of this component are.
  35177. @see getBorderThickness
  35178. */
  35179. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35180. /** Returns the number of pixels wide that the draggable edges of this component are.
  35181. @see setBorderThickness
  35182. */
  35183. const BorderSize getBorderThickness() const throw();
  35184. juce_UseDebuggingNewOperator
  35185. protected:
  35186. /** @internal */
  35187. void paint (Graphics& g);
  35188. /** @internal */
  35189. void mouseEnter (const MouseEvent& e);
  35190. /** @internal */
  35191. void mouseMove (const MouseEvent& e);
  35192. /** @internal */
  35193. void mouseDown (const MouseEvent& e);
  35194. /** @internal */
  35195. void mouseDrag (const MouseEvent& e);
  35196. /** @internal */
  35197. void mouseUp (const MouseEvent& e);
  35198. /** @internal */
  35199. bool hitTest (int x, int y);
  35200. private:
  35201. Component* const component;
  35202. ComponentBoundsConstrainer* constrainer;
  35203. BorderSize borderSize;
  35204. int originalX, originalY, originalW, originalH;
  35205. int mouseZone;
  35206. void updateMouseZone (const MouseEvent& e) throw();
  35207. ResizableBorderComponent (const ResizableBorderComponent&);
  35208. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35209. };
  35210. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35211. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35212. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35213. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35214. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35215. /** A component that resizes a parent window when dragged.
  35216. This is the small triangular stripey resizer component you get in the bottom-right
  35217. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35218. a larger component and it will automatically resize its parent when it gets dragged
  35219. around.
  35220. @see ResizableFrameComponent
  35221. */
  35222. class JUCE_API ResizableCornerComponent : public Component
  35223. {
  35224. public:
  35225. /** Creates a resizer.
  35226. Pass in the target component which you want to be resized when this one is
  35227. dragged.
  35228. The target component will usually be a parent of the resizer component, but this
  35229. isn't mandatory.
  35230. Remember that when the target component is resized, it'll need to move and
  35231. resize this component to keep it in place, as this won't happen automatically.
  35232. If the constrainer parameter is non-zero, then this object will be used to enforce
  35233. limits on the size and position that the component can be stretched to. Make sure
  35234. that the constrainer isn't deleted while still in use by this object. If you
  35235. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35236. @see ComponentBoundsConstrainer
  35237. */
  35238. ResizableCornerComponent (Component* const componentToResize,
  35239. ComponentBoundsConstrainer* const constrainer);
  35240. /** Destructor. */
  35241. ~ResizableCornerComponent();
  35242. juce_UseDebuggingNewOperator
  35243. protected:
  35244. /** @internal */
  35245. void paint (Graphics& g);
  35246. /** @internal */
  35247. void mouseDown (const MouseEvent& e);
  35248. /** @internal */
  35249. void mouseDrag (const MouseEvent& e);
  35250. /** @internal */
  35251. void mouseUp (const MouseEvent& e);
  35252. /** @internal */
  35253. bool hitTest (int x, int y);
  35254. private:
  35255. Component* const component;
  35256. ComponentBoundsConstrainer* constrainer;
  35257. int originalX, originalY, originalW, originalH;
  35258. ResizableCornerComponent (const ResizableCornerComponent&);
  35259. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35260. };
  35261. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35262. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35263. /**
  35264. A base class for top-level windows that can be dragged around and resized.
  35265. To add content to the window, use its setContentComponent() method to
  35266. give it a component that will remain positioned inside it (leaving a gap around
  35267. the edges for a border).
  35268. It's not advisable to add child components directly to a ResizableWindow: put them
  35269. inside your content component instead. And overriding methods like resized(), moved(), etc
  35270. is also not recommended - instead override these methods for your content component.
  35271. (If for some obscure reason you do need to override these methods, always remember to
  35272. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35273. decorations correctly).
  35274. By default resizing isn't enabled - use the setResizable() method to enable it and
  35275. to choose the style of resizing to use.
  35276. @see TopLevelWindow
  35277. */
  35278. class JUCE_API ResizableWindow : public TopLevelWindow
  35279. {
  35280. public:
  35281. /** Creates a ResizableWindow.
  35282. @param name the name to give the component
  35283. @param backgroundColour the colour to use for filling the window's background.
  35284. @param addToDesktop if true, the window will be automatically added to the
  35285. desktop; if false, you can use it as a child component
  35286. */
  35287. ResizableWindow (const String& name,
  35288. const Colour& backgroundColour,
  35289. const bool addToDesktop);
  35290. /** Destructor.
  35291. If a content component has been set with setContentComponent(), it
  35292. will be deleted.
  35293. */
  35294. ~ResizableWindow();
  35295. /** Returns the colour currently being used for the window's background.
  35296. As a convenience the window will fill itself with this colour, but you
  35297. can override the paint() method if you need more customised behaviour.
  35298. @see setBackgroundColour
  35299. */
  35300. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35301. /** Changes the colour currently being used for the window's background.
  35302. As a convenience the window will fill itself with this colour, but you
  35303. can override the paint() method if you need more customised behaviour.
  35304. Note that the opaque state of this window is altered by this call to reflect
  35305. the opacity of the colour passed-in. On window systems which can't support
  35306. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35307. be using this class as a base for a semi-transparent component anyway).
  35308. @see getBackgroundColour
  35309. */
  35310. void setBackgroundColour (const Colour& newColour);
  35311. /** Make the window resizable or fixed.
  35312. @param shouldBeResizable whether it's resizable at all
  35313. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35314. bottom-right; if false, it'll use a ResizableBorderComponent
  35315. around the edge
  35316. @see setResizeLimits, isResizable
  35317. */
  35318. void setResizable (const bool shouldBeResizable,
  35319. const bool useBottomRightCornerResizer);
  35320. /** True if resizing is enabled.
  35321. @see setResizable
  35322. */
  35323. bool isResizable() const throw();
  35324. /** This sets the maximum and minimum sizes for the window.
  35325. If the window's current size is outside these limits, it will be resized to
  35326. make sure it's within them.
  35327. Calling setBounds() on the component will bypass any size checking - it's only when
  35328. the window is being resized by the user that these values are enforced.
  35329. @see setResizable, setFixedAspectRatio
  35330. */
  35331. void setResizeLimits (const int newMinimumWidth,
  35332. const int newMinimumHeight,
  35333. const int newMaximumWidth,
  35334. const int newMaximumHeight) throw();
  35335. /** Returns the bounds constrainer object that this window is using.
  35336. You can access this to change its properties.
  35337. */
  35338. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35339. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35340. A pointer to the object you pass in will be kept, but it won't be deleted
  35341. by this object, so it's the caller's responsiblity to manage it.
  35342. If you pass 0, then no contraints will be placed on the positioning of the window.
  35343. */
  35344. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35345. /** Calls the window's setBounds method, after first checking these bounds
  35346. with the current constrainer.
  35347. @see setConstrainer
  35348. */
  35349. void setBoundsConstrained (int x, int y, int width, int height);
  35350. /** Returns true if the window is currently in full-screen mode.
  35351. @see setFullScreen
  35352. */
  35353. bool isFullScreen() const;
  35354. /** Puts the window into full-screen mode, or restores it to its normal size.
  35355. If true, the window will become full-screen; if false, it will return to the
  35356. last size it was before being made full-screen.
  35357. @see isFullScreen
  35358. */
  35359. void setFullScreen (const bool shouldBeFullScreen);
  35360. /** Returns true if the window is currently minimised.
  35361. @see setMinimised
  35362. */
  35363. bool isMinimised() const;
  35364. /** Minimises the window, or restores it to its previous position and size.
  35365. When being un-minimised, it'll return to the last position and size it
  35366. was in before being minimised.
  35367. @see isMinimised
  35368. */
  35369. void setMinimised (const bool shouldMinimise);
  35370. /** Returns a string which encodes the window's current size and position.
  35371. This string will encapsulate the window's size, position, and whether it's
  35372. in full-screen mode. It's intended for letting your application save and
  35373. restore a window's position.
  35374. Use the restoreWindowStateFromString() to restore from a saved state.
  35375. @see restoreWindowStateFromString
  35376. */
  35377. const String getWindowStateAsString();
  35378. /** Restores the window to a previously-saved size and position.
  35379. This restores the window's size, positon and full-screen status from an
  35380. string that was previously created with the getWindowStateAsString()
  35381. method.
  35382. @returns false if the string wasn't a valid window state
  35383. @see getWindowStateAsString
  35384. */
  35385. bool restoreWindowStateFromString (const String& previousState);
  35386. /** Returns the current content component.
  35387. This will be the component set by setContentComponent(), or 0 if none
  35388. has yet been specified.
  35389. @see setContentComponent
  35390. */
  35391. Component* getContentComponent() const throw() { return contentComponent; }
  35392. /** Changes the current content component.
  35393. This sets a component that will be placed in the centre of the ResizableWindow,
  35394. (leaving a space around the edge for the border).
  35395. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35396. with addChildComponent(). Instead, add them to the content component.
  35397. @param newContentComponent the new component to use (or null to not use one) - this
  35398. component will be deleted either when replaced by another call
  35399. to this method, or when the ResizableWindow is deleted.
  35400. To remove a content component without deleting it, use
  35401. setContentComponent (0, false).
  35402. @param deleteOldOne if true, the previous content component will be deleted; if
  35403. false, the previous component will just be removed without
  35404. deleting it.
  35405. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35406. it always fits around the size of the content component. If false, the
  35407. new content will be resized to fit the current space available.
  35408. */
  35409. void setContentComponent (Component* const newContentComponent,
  35410. const bool deleteOldOne = true,
  35411. const bool resizeToFit = false);
  35412. /** Changes the window so that the content component ends up with the specified size.
  35413. This is basically a setSize call on the window, but which adds on the borders,
  35414. so you can specify the content component's target size.
  35415. */
  35416. void setContentComponentSize (int width, int height);
  35417. juce_UseDebuggingNewOperator
  35418. protected:
  35419. /** @internal */
  35420. void paint (Graphics& g);
  35421. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35422. void moved();
  35423. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35424. void resized();
  35425. /** @internal */
  35426. void mouseDown (const MouseEvent& e);
  35427. /** @internal */
  35428. void mouseDrag (const MouseEvent& e);
  35429. /** @internal */
  35430. void lookAndFeelChanged();
  35431. /** @internal */
  35432. void childBoundsChanged (Component* child);
  35433. /** @internal */
  35434. void parentSizeChanged();
  35435. /** @internal */
  35436. void visibilityChanged();
  35437. /** @internal */
  35438. void activeWindowStatusChanged();
  35439. /** @internal */
  35440. int getDesktopWindowStyleFlags() const;
  35441. /** Returns the width of the border to use around the window.
  35442. @see getContentComponentBorder
  35443. */
  35444. virtual const BorderSize getBorderThickness();
  35445. /** Returns the insets to use when positioning the content component.
  35446. @see getBorderThickness
  35447. */
  35448. virtual const BorderSize getContentComponentBorder();
  35449. #ifdef JUCE_DEBUG
  35450. /** Overridden to warn people about adding components directly to this component
  35451. instead of using setContentComponent().
  35452. If you know what you're doing and are sure you really want to add a component, specify
  35453. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35454. */
  35455. void addChildComponent (Component* const child, int zOrder = -1);
  35456. /** Overridden to warn people about adding components directly to this component
  35457. instead of using setContentComponent().
  35458. If you know what you're doing and are sure you really want to add a component, specify
  35459. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35460. */
  35461. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35462. #endif
  35463. ResizableCornerComponent* resizableCorner;
  35464. ResizableBorderComponent* resizableBorder;
  35465. private:
  35466. Component* contentComponent;
  35467. bool resizeToFitContent, fullscreen;
  35468. Colour backgroundColour;
  35469. ComponentDragger dragger;
  35470. Rectangle lastNonFullScreenPos;
  35471. ComponentBoundsConstrainer defaultConstrainer;
  35472. ComponentBoundsConstrainer* constrainer;
  35473. #ifdef JUCE_DEBUG
  35474. bool hasBeenResized;
  35475. #endif
  35476. void updateLastPos();
  35477. ResizableWindow (const ResizableWindow&);
  35478. const ResizableWindow& operator= (const ResizableWindow&);
  35479. // (xxx remove these eventually)
  35480. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35481. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35482. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35483. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35484. };
  35485. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35486. /********* End of inlined file: juce_ResizableWindow.h *********/
  35487. /**
  35488. A resizable window with a title bar and maximise, minimise and close buttons.
  35489. This subclass of ResizableWindow creates a fairly standard type of window with
  35490. a title bar and various buttons. The name of the component is shown in the
  35491. title bar, and an icon can optionally be specified with setIcon().
  35492. All the methods available to a ResizableWindow are also available to this,
  35493. so it can easily be made resizable, minimised, maximised, etc.
  35494. It's not advisable to add child components directly to a DocumentWindow: put them
  35495. inside your content component instead. And overriding methods like resized(), moved(), etc
  35496. is also not recommended - instead override these methods for your content component.
  35497. (If for some obscure reason you do need to override these methods, always remember to
  35498. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35499. decorations correctly).
  35500. You can also automatically add a menu bar to the window, using the setMenuBar()
  35501. method.
  35502. @see ResizableWindow, DialogWindow
  35503. */
  35504. class JUCE_API DocumentWindow : public ResizableWindow
  35505. {
  35506. public:
  35507. /** The set of available button-types that can be put on the title bar.
  35508. @see setTitleBarButtonsRequired
  35509. */
  35510. enum TitleBarButtons
  35511. {
  35512. minimiseButton = 1,
  35513. maximiseButton = 2,
  35514. closeButton = 4,
  35515. /** A combination of all the buttons above. */
  35516. allButtons = 7
  35517. };
  35518. /** Creates a DocumentWindow.
  35519. @param name the name to give the component - this is also
  35520. the title shown at the top of the window. To change
  35521. this later, use setName()
  35522. @param backgroundColour the colour to use for filling the window's background.
  35523. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35524. should be shown on the title bar. This value is a bitwise
  35525. combination of values from the TitleBarButtons enum. Note
  35526. that it can be "allButtons" to get them all. You
  35527. can change this later with the setTitleBarButtonsRequired()
  35528. method, which can also specify where they are positioned.
  35529. @param addToDesktop if true, the window will be automatically added to the
  35530. desktop; if false, you can use it as a child component
  35531. @see TitleBarButtons
  35532. */
  35533. DocumentWindow (const String& name,
  35534. const Colour& backgroundColour,
  35535. const int requiredButtons,
  35536. const bool addToDesktop = true);
  35537. /** Destructor.
  35538. If a content component has been set with setContentComponent(), it
  35539. will be deleted.
  35540. */
  35541. ~DocumentWindow();
  35542. /** Changes the component's name.
  35543. (This is overridden from Component::setName() to cause a repaint, as
  35544. the name is what gets drawn across the window's title bar).
  35545. */
  35546. void setName (const String& newName);
  35547. /** Sets an icon to show in the title bar, next to the title.
  35548. A copy is made internally of the image, so the caller can delete the
  35549. image after calling this. If 0 is passed-in, any existing icon will be
  35550. removed.
  35551. */
  35552. void setIcon (const Image* imageToUse);
  35553. /** Changes the height of the title-bar. */
  35554. void setTitleBarHeight (const int newHeight);
  35555. /** Returns the current title bar height. */
  35556. int getTitleBarHeight() const;
  35557. /** Changes the set of title-bar buttons being shown.
  35558. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35559. should be shown on the title bar. This value is a bitwise
  35560. combination of values from the TitleBarButtons enum. Note
  35561. that it can be "allButtons" to get them all.
  35562. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  35563. left side of the bar; if false, they'll be placed at the right
  35564. */
  35565. void setTitleBarButtonsRequired (const int requiredButtons,
  35566. const bool positionTitleBarButtonsOnLeft);
  35567. /** Sets whether the title should be centred within the window.
  35568. If true, the title text is shown in the middle of the title-bar; if false,
  35569. it'll be shown at the left of the bar.
  35570. */
  35571. void setTitleBarTextCentred (const bool textShouldBeCentred);
  35572. /** Creates a menu inside this window.
  35573. @param menuBarModel this specifies a MenuBarModel that should be used to
  35574. generate the contents of a menu bar that will be placed
  35575. just below the title bar, and just above any content
  35576. component. If this value is zero, any existing menu bar
  35577. will be removed from the component; if non-zero, one will
  35578. be added if it's required.
  35579. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  35580. or less to use the look-and-feel's default size.
  35581. */
  35582. void setMenuBar (MenuBarModel* menuBarModel,
  35583. const int menuBarHeight = 0);
  35584. /** This method is called when the user tries to close the window.
  35585. This is triggered by the user clicking the close button, or using some other
  35586. OS-specific key shortcut or OS menu for getting rid of a window.
  35587. If the window is just a pop-up, you should override this closeButtonPressed()
  35588. method and make it delete the window in whatever way is appropriate for your
  35589. app. E.g. you might just want to call "delete this".
  35590. If your app is centred around this window such that the whole app should quit when
  35591. the window is closed, then you will probably want to use this method as an opportunity
  35592. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  35593. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  35594. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  35595. or closing it via the taskbar icon on Windows).
  35596. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  35597. redirects it to call this method, so any methods of closing the window that are
  35598. caught by userTriedToCloseWindow() will also end up here).
  35599. */
  35600. virtual void closeButtonPressed();
  35601. /** Callback that is triggered when the minimise button is pressed.
  35602. The default implementation of this calls ResizableWindow::setMinimised(), but
  35603. you can override it to do more customised behaviour.
  35604. */
  35605. virtual void minimiseButtonPressed();
  35606. /** Callback that is triggered when the maximise button is pressed, or when the
  35607. title-bar is double-clicked.
  35608. The default implementation of this calls ResizableWindow::setFullScreen(), but
  35609. you can override it to do more customised behaviour.
  35610. */
  35611. virtual void maximiseButtonPressed();
  35612. /** Returns the close button, (or 0 if there isn't one). */
  35613. Button* getCloseButton() const throw();
  35614. /** Returns the minimise button, (or 0 if there isn't one). */
  35615. Button* getMinimiseButton() const throw();
  35616. /** Returns the maximise button, (or 0 if there isn't one). */
  35617. Button* getMaximiseButton() const throw();
  35618. /** @internal */
  35619. void paint (Graphics& g);
  35620. /** @internal */
  35621. void resized();
  35622. /** @internal */
  35623. void lookAndFeelChanged();
  35624. /** @internal */
  35625. const BorderSize getBorderThickness();
  35626. /** @internal */
  35627. const BorderSize getContentComponentBorder();
  35628. /** @internal */
  35629. void mouseDoubleClick (const MouseEvent& e);
  35630. /** @internal */
  35631. void userTriedToCloseWindow();
  35632. /** @internal */
  35633. void activeWindowStatusChanged();
  35634. /** @internal */
  35635. int getDesktopWindowStyleFlags() const;
  35636. /** @internal */
  35637. void parentHierarchyChanged();
  35638. juce_UseDebuggingNewOperator
  35639. private:
  35640. int titleBarHeight, menuBarHeight, requiredButtons;
  35641. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  35642. Button* titleBarButtons [3];
  35643. Image* titleBarIcon;
  35644. MenuBarComponent* menuBar;
  35645. MenuBarModel* menuBarModel;
  35646. class ButtonListenerProxy : public ButtonListener
  35647. {
  35648. public:
  35649. ButtonListenerProxy();
  35650. void buttonClicked (Button* button);
  35651. DocumentWindow* owner;
  35652. } buttonListener;
  35653. int getBorderSize() const;
  35654. void repaintTitleBar();
  35655. DocumentWindow (const DocumentWindow&);
  35656. const DocumentWindow& operator= (const DocumentWindow&);
  35657. };
  35658. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35659. /********* End of inlined file: juce_DocumentWindow.h *********/
  35660. class MultiDocumentPanel;
  35661. class MDITabbedComponentInternal;
  35662. /**
  35663. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  35664. component.
  35665. It's like a normal DocumentWindow but has some extra functionality to make sure
  35666. everything works nicely inside a MultiDocumentPanel.
  35667. @see MultiDocumentPanel
  35668. */
  35669. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  35670. {
  35671. public:
  35672. /**
  35673. */
  35674. MultiDocumentPanelWindow (const Colour& backgroundColour);
  35675. /** Destructor. */
  35676. ~MultiDocumentPanelWindow();
  35677. /** @internal */
  35678. void maximiseButtonPressed();
  35679. /** @internal */
  35680. void closeButtonPressed();
  35681. /** @internal */
  35682. void activeWindowStatusChanged();
  35683. /** @internal */
  35684. void broughtToFront();
  35685. juce_UseDebuggingNewOperator
  35686. private:
  35687. void updateOrder();
  35688. MultiDocumentPanel* getOwner() const throw();
  35689. };
  35690. /**
  35691. A component that contains a set of other components either in floating windows
  35692. or tabs.
  35693. This acts as a panel that can be used to hold a set of open document windows, with
  35694. different layout modes.
  35695. Use addDocument() and closeDocument() to add or remove components from the
  35696. panel - never use any of the Component methods to access the panel's child
  35697. components directly, as these are managed internally.
  35698. */
  35699. class JUCE_API MultiDocumentPanel : public Component,
  35700. private ComponentListener
  35701. {
  35702. public:
  35703. /** Creates an empty panel.
  35704. Use addDocument() and closeDocument() to add or remove components from the
  35705. panel - never use any of the Component methods to access the panel's child
  35706. components directly, as these are managed internally.
  35707. */
  35708. MultiDocumentPanel();
  35709. /** Destructor.
  35710. When deleted, this will call closeAllDocuments (false) to make sure all its
  35711. components are deleted. If you need to make sure all documents are saved
  35712. before closing, then you should call closeAllDocuments (true) and check that
  35713. it returns true before deleting the panel.
  35714. */
  35715. ~MultiDocumentPanel();
  35716. /** Tries to close all the documents.
  35717. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35718. be called for each open document, and any of these calls fails, this method
  35719. will stop and return false, leaving some documents still open.
  35720. If checkItsOkToCloseFirst is false, then all documents will be closed
  35721. unconditionally.
  35722. @see closeDocument
  35723. */
  35724. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  35725. /** Adds a document component to the panel.
  35726. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  35727. this will fail and return false. (If it does fail, the component passed-in will not be
  35728. deleted, even if deleteWhenRemoved was set to true).
  35729. The MultiDocumentPanel will deal with creating a window border to go around your component,
  35730. so just pass in the bare content component here, no need to give it a ResizableWindow
  35731. or DocumentWindow.
  35732. @param component the component to add
  35733. @param backgroundColour the background colour to use to fill the component's
  35734. window or tab
  35735. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  35736. or closeAllDocuments(), then it will be deleted. If false, then
  35737. the caller must handle the component's deletion
  35738. */
  35739. bool addDocument (Component* const component,
  35740. const Colour& backgroundColour,
  35741. const bool deleteWhenRemoved);
  35742. /** Closes one of the documents.
  35743. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35744. be called, and if it fails, this method will return false without closing the
  35745. document.
  35746. If checkItsOkToCloseFirst is false, then the documents will be closed
  35747. unconditionally.
  35748. The component will be deleted if the deleteWhenRemoved parameter was set to
  35749. true when it was added with addDocument.
  35750. @see addDocument, closeAllDocuments
  35751. */
  35752. bool closeDocument (Component* component,
  35753. const bool checkItsOkToCloseFirst);
  35754. /** Returns the number of open document windows.
  35755. @see getDocument
  35756. */
  35757. int getNumDocuments() const throw();
  35758. /** Returns one of the open documents.
  35759. The order of the documents in this array may change when they are added, removed
  35760. or moved around.
  35761. @see getNumDocuments
  35762. */
  35763. Component* getDocument (const int index) const throw();
  35764. /** Returns the document component that is currently focused or on top.
  35765. If currently using floating windows, then this will be the component in the currently
  35766. active window, or the top component if none are active.
  35767. If it's currently in tabbed mode, then it'll return the component in the active tab.
  35768. @see setActiveDocument
  35769. */
  35770. Component* getActiveDocument() const throw();
  35771. /** Makes one of the components active and brings it to the top.
  35772. @see getActiveDocument
  35773. */
  35774. void setActiveDocument (Component* component);
  35775. /** Callback which gets invoked when the currently-active document changes. */
  35776. virtual void activeDocumentChanged();
  35777. /** Sets a limit on how many windows can be open at once.
  35778. If this is zero or less there's no limit (the default). addDocument() will fail
  35779. if this number is exceeded.
  35780. */
  35781. void setMaximumNumDocuments (const int maximumNumDocuments);
  35782. /** Sets an option to make the document fullscreen if there's only one document open.
  35783. If set to true, then if there's only one document, it'll fill the whole of this
  35784. component without tabs or a window border. If false, then tabs or a window
  35785. will always be shown, even if there's only one document. If there's more than
  35786. one document open, then this option makes no difference.
  35787. */
  35788. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  35789. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  35790. */
  35791. bool isFullscreenWhenOneDocument() const throw();
  35792. /** The different layout modes available. */
  35793. enum LayoutMode
  35794. {
  35795. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  35796. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  35797. };
  35798. /** Changes the panel's mode.
  35799. @see LayoutMode, getLayoutMode
  35800. */
  35801. void setLayoutMode (const LayoutMode newLayoutMode);
  35802. /** Returns the current layout mode. */
  35803. LayoutMode getLayoutMode() const throw() { return mode; }
  35804. /** Sets the background colour for the whole panel.
  35805. Each document has its own background colour, but this is the one used to fill the areas
  35806. behind them.
  35807. */
  35808. void setBackgroundColour (const Colour& newBackgroundColour);
  35809. /** Returns the current background colour.
  35810. @see setBackgroundColour
  35811. */
  35812. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35813. /** A subclass must override this to say whether its currently ok for a document
  35814. to be closed.
  35815. This method is called by closeDocument() and closeAllDocuments() to indicate that
  35816. a document should be saved if possible, ready for it to be closed.
  35817. If this method returns true, then it means the document is ok and can be closed.
  35818. If it returns false, then it means that the closeDocument() method should stop
  35819. and not close.
  35820. Normally, you'd use this method to ask the user if they want to save any changes,
  35821. then return true if the save operation went ok. If the user cancelled the save
  35822. operation you could return false here to abort the close operation.
  35823. If your component is based on the FileBasedDocument class, then you'd probably want
  35824. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  35825. FileBasedDocument::savedOk
  35826. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  35827. */
  35828. virtual bool tryToCloseDocument (Component* component) = 0;
  35829. /** Creates a new window to be used for a document.
  35830. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  35831. but you might want to override it to return a custom component.
  35832. */
  35833. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  35834. /** @internal */
  35835. void paint (Graphics& g);
  35836. /** @internal */
  35837. void resized();
  35838. /** @internal */
  35839. void componentNameChanged (Component&);
  35840. juce_UseDebuggingNewOperator
  35841. private:
  35842. LayoutMode mode;
  35843. Array <Component*> components;
  35844. TabbedComponent* tabComponent;
  35845. Colour backgroundColour;
  35846. int maximumNumDocuments, numDocsBeforeTabsUsed;
  35847. friend class MultiDocumentPanelWindow;
  35848. friend class MDITabbedComponentInternal;
  35849. Component* getContainerComp (Component* c) const;
  35850. void updateOrder();
  35851. void addWindow (Component* component);
  35852. };
  35853. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35854. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  35855. #endif
  35856. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35857. #endif
  35858. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35859. #endif
  35860. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  35861. #endif
  35862. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35863. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  35864. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35865. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35866. /**
  35867. For laying out a set of components, where the components have preferred sizes
  35868. and size limits, but where they are allowed to stretch to fill the available
  35869. space.
  35870. For example, if you have a component containing several other components, and
  35871. each one should be given a share of the total size, you could use one of these
  35872. to resize the child components when the parent component is resized. Then
  35873. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  35874. A StretchableLayoutManager operates only in one dimension, so if you have a set
  35875. of components stacked vertically on top of each other, you'd use one to manage their
  35876. heights. To build up complex arrangements of components, e.g. for applications
  35877. with multiple nested panels, you would use more than one StretchableLayoutManager.
  35878. E.g. by using two (one vertical, one horizontal), you could create a resizable
  35879. spreadsheet-style table.
  35880. E.g.
  35881. @code
  35882. class MyComp : public Component
  35883. {
  35884. StretchableLayoutManager myLayout;
  35885. MyComp()
  35886. {
  35887. myLayout.setItemLayout (0, // for item 0
  35888. 50, 100, // must be between 50 and 100 pixels in size
  35889. -0.6); // and its preferred size is 60% of the total available space
  35890. myLayout.setItemLayout (1, // for item 1
  35891. -0.2, -0.6, // size must be between 20% and 60% of the available space
  35892. 50); // and its preferred size is 50 pixels
  35893. }
  35894. void resized()
  35895. {
  35896. // make a list of two of our child components that we want to reposition
  35897. Component* comps[] = { myComp1, myComp2 };
  35898. // this will position the 2 components, one above the other, to fit
  35899. // vertically into the rectangle provided.
  35900. myLayout.layOutComponents (comps, 2,
  35901. 0, 0, getWidth(), getHeight(),
  35902. true);
  35903. }
  35904. };
  35905. @endcode
  35906. @see StretchableLayoutResizerBar
  35907. */
  35908. class JUCE_API StretchableLayoutManager
  35909. {
  35910. public:
  35911. /** Creates an empty layout.
  35912. You'll need to add some item properties to the layout before it can be used
  35913. to resize things - see setItemLayout().
  35914. */
  35915. StretchableLayoutManager();
  35916. /** Destructor. */
  35917. ~StretchableLayoutManager();
  35918. /** For a numbered item, this sets its size limits and preferred size.
  35919. @param itemIndex the index of the item to change.
  35920. @param minimumSize the minimum size that this item is allowed to be - a positive number
  35921. indicates an absolute size in pixels. A negative number indicates a
  35922. proportion of the available space (e.g -0.5 is 50%)
  35923. @param maximumSize the maximum size that this item is allowed to be - a positive number
  35924. indicates an absolute size in pixels. A negative number indicates a
  35925. proportion of the available space
  35926. @param preferredSize the size that this item would like to be, if there's enough room. A
  35927. positive number indicates an absolute size in pixels. A negative number
  35928. indicates a proportion of the available space
  35929. @see getItemLayout
  35930. */
  35931. void setItemLayout (const int itemIndex,
  35932. const double minimumSize,
  35933. const double maximumSize,
  35934. const double preferredSize);
  35935. /** For a numbered item, this returns its size limits and preferred size.
  35936. @param itemIndex the index of the item.
  35937. @param minimumSize the minimum size that this item is allowed to be - a positive number
  35938. indicates an absolute size in pixels. A negative number indicates a
  35939. proportion of the available space (e.g -0.5 is 50%)
  35940. @param maximumSize the maximum size that this item is allowed to be - a positive number
  35941. indicates an absolute size in pixels. A negative number indicates a
  35942. proportion of the available space
  35943. @param preferredSize the size that this item would like to be, if there's enough room. A
  35944. positive number indicates an absolute size in pixels. A negative number
  35945. indicates a proportion of the available space
  35946. @returns false if the item's properties hadn't been set
  35947. @see setItemLayout
  35948. */
  35949. bool getItemLayout (const int itemIndex,
  35950. double& minimumSize,
  35951. double& maximumSize,
  35952. double& preferredSize) const;
  35953. /** Clears all the properties that have been set with setItemLayout() and resets
  35954. this object to its initial state.
  35955. */
  35956. void clearAllItems();
  35957. /** Takes a set of components that correspond to the layout's items, and positions
  35958. them to fill a space.
  35959. This will try to give each item its preferred size, whether that's a relative size
  35960. or an absolute one.
  35961. @param components an array of components that correspond to each of the
  35962. numbered items that the StretchableLayoutManager object
  35963. has been told about with setItemLayout()
  35964. @param numComponents the number of components in the array that is passed-in. This
  35965. should be the same as the number of items this object has been
  35966. told about.
  35967. @param x the left of the rectangle in which the components should
  35968. be laid out
  35969. @param y the top of the rectangle in which the components should
  35970. be laid out
  35971. @param width the width of the rectangle in which the components should
  35972. be laid out
  35973. @param height the height of the rectangle in which the components should
  35974. be laid out
  35975. @param vertically if true, the components will be positioned in a vertical stack,
  35976. so that they fill the height of the rectangle. If false, they
  35977. will be placed side-by-side in a horizontal line, filling the
  35978. available width
  35979. @param resizeOtherDimension if true, this means that the components will have their
  35980. other dimension resized to fit the space - i.e. if the 'vertically'
  35981. parameter is true, their x-positions and widths are adjusted to fit
  35982. the x and width parameters; if 'vertically' is false, their y-positions
  35983. and heights are adjusted to fit the y and height parameters.
  35984. */
  35985. void layOutComponents (Component** const components,
  35986. int numComponents,
  35987. int x, int y, int width, int height,
  35988. const bool vertically,
  35989. const bool resizeOtherDimension);
  35990. /** Returns the current position of one of the items.
  35991. This is only a valid call after layOutComponents() has been called, as it
  35992. returns the last position that this item was placed at. If the layout was
  35993. vertical, the value returned will be the y position of the top of the item,
  35994. relative to the top of the rectangle in which the items were placed (so for
  35995. example, item 0 will always have position of 0, even in the rectangle passed
  35996. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  35997. the position returned is the item's left-hand position, again relative to the
  35998. x position of the rectangle used.
  35999. @see getItemCurrentSize, setItemPosition
  36000. */
  36001. int getItemCurrentPosition (const int itemIndex) const;
  36002. /** Returns the current size of one of the items.
  36003. This is only meaningful after layOutComponents() has been called, as it
  36004. returns the last size that this item was given. If the layout was done
  36005. vertically, it'll return the item's height in pixels; if it was horizontal,
  36006. it'll return its width.
  36007. @see getItemCurrentRelativeSize
  36008. */
  36009. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36010. /** Returns the current size of one of the items.
  36011. This is only meaningful after layOutComponents() has been called, as it
  36012. returns the last size that this item was given. If the layout was done
  36013. vertically, it'll return a negative value representing the item's height relative
  36014. to the last size used for laying the components out; if the layout was done
  36015. horizontally it'll be the proportion of its width.
  36016. @see getItemCurrentAbsoluteSize
  36017. */
  36018. double getItemCurrentRelativeSize (const int itemIndex) const;
  36019. /** Moves one of the items, shifting along any other items as necessary in
  36020. order to get it to the desired position.
  36021. Calling this method will also update the preferred sizes of the items it
  36022. shuffles along, so that they reflect their new positions.
  36023. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36024. about when it's dragged).
  36025. @param itemIndex the item to move
  36026. @param newPosition the absolute position that you'd like this item to move
  36027. to. The item might not be able to always reach exactly this position,
  36028. because other items may have minimum sizes that constrain how
  36029. far it can go
  36030. */
  36031. void setItemPosition (const int itemIndex,
  36032. int newPosition);
  36033. juce_UseDebuggingNewOperator
  36034. private:
  36035. struct ItemLayoutProperties
  36036. {
  36037. int itemIndex;
  36038. int currentSize;
  36039. double minSize, maxSize, preferredSize;
  36040. };
  36041. OwnedArray <ItemLayoutProperties> items;
  36042. int totalSize;
  36043. static int sizeToRealSize (double size, int totalSpace);
  36044. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36045. void setTotalSize (const int newTotalSize);
  36046. int fitComponentsIntoSpace (const int startIndex,
  36047. const int endIndex,
  36048. const int availableSpace,
  36049. int startPos);
  36050. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36051. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36052. void updatePrefSizesToMatchCurrentPositions();
  36053. StretchableLayoutManager (const StretchableLayoutManager&);
  36054. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36055. };
  36056. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36057. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36058. #endif
  36059. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36060. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36061. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36062. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36063. /**
  36064. A component that acts as one of the vertical or horizontal bars you see being
  36065. used to resize panels in a window.
  36066. One of these acts with a StretchableLayoutManager to resize the other components.
  36067. @see StretchableLayoutManager
  36068. */
  36069. class JUCE_API StretchableLayoutResizerBar : public Component
  36070. {
  36071. public:
  36072. /** Creates a resizer bar for use on a specified layout.
  36073. @param layoutToUse the layout that will be affected when this bar
  36074. is dragged
  36075. @param itemIndexInLayout the item index in the layout that corresponds to
  36076. this bar component. You'll need to set up the item
  36077. properties in a suitable way for a divider bar, e.g.
  36078. for an 8-pixel wide bar which, you could call
  36079. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36080. @param isBarVertical true if it's an upright bar that you drag left and
  36081. right; false for a horizontal one that you drag up and
  36082. down
  36083. */
  36084. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36085. const int itemIndexInLayout,
  36086. const bool isBarVertical);
  36087. /** Destructor. */
  36088. ~StretchableLayoutResizerBar();
  36089. /** This is called when the bar is dragged.
  36090. This method must update the positions of any components whose position is
  36091. determined by the StretchableLayoutManager, because they might have just
  36092. moved.
  36093. The default implementation calls the resized() method of this component's
  36094. parent component, because that's often where you're likely to apply the
  36095. layout, but it can be overridden for more specific needs.
  36096. */
  36097. virtual void hasBeenMoved();
  36098. /** @internal */
  36099. void paint (Graphics& g);
  36100. /** @internal */
  36101. void mouseDown (const MouseEvent& e);
  36102. /** @internal */
  36103. void mouseDrag (const MouseEvent& e);
  36104. juce_UseDebuggingNewOperator
  36105. private:
  36106. StretchableLayoutManager* layout;
  36107. int itemIndex, mouseDownPos;
  36108. bool isVertical;
  36109. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36110. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36111. };
  36112. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36113. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36114. #endif
  36115. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36116. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36117. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36118. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36119. /**
  36120. A utility class for fitting a set of objects whose sizes can vary between
  36121. a minimum and maximum size, into a space.
  36122. This is a trickier algorithm than it would first seem, so I've put it in this
  36123. class to allow it to be shared by various bits of code.
  36124. To use it, create one of these objects, call addItem() to add the list of items
  36125. you need, then call resizeToFit(), which will change all their sizes. You can
  36126. then retrieve the new sizes with getItemSize() and getNumItems().
  36127. It's currently used by the TableHeaderComponent for stretching out the table
  36128. headings to fill the table's width.
  36129. */
  36130. class StretchableObjectResizer
  36131. {
  36132. public:
  36133. /** Creates an empty object resizer. */
  36134. StretchableObjectResizer();
  36135. /** Destructor. */
  36136. ~StretchableObjectResizer();
  36137. /** Adds an item to the list.
  36138. The order parameter lets you specify groups of items that are resized first when some
  36139. space needs to be found. Those items with an order of 0 will be the first ones to be
  36140. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36141. will then try resizing the items with an order of 1, then 2, and so on.
  36142. */
  36143. void addItem (const double currentSize,
  36144. const double minSize,
  36145. const double maxSize,
  36146. const int order = 0);
  36147. /** Resizes all the items to fit this amount of space.
  36148. This will attempt to fit them in without exceeding each item's miniumum and
  36149. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36150. further, the final size may be greater or less than the size passed in.
  36151. After calling this method, you can retrieve the new sizes with the getItemSize()
  36152. method.
  36153. */
  36154. void resizeToFit (const double targetSize);
  36155. /** Returns the number of items that have been added. */
  36156. int getNumItems() const throw() { return items.size(); }
  36157. /** Returns the size of one of the items. */
  36158. double getItemSize (const int index) const throw();
  36159. juce_UseDebuggingNewOperator
  36160. private:
  36161. struct Item
  36162. {
  36163. double size;
  36164. double minSize;
  36165. double maxSize;
  36166. int order;
  36167. };
  36168. OwnedArray <Item> items;
  36169. StretchableObjectResizer (const StretchableObjectResizer&);
  36170. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36171. };
  36172. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36173. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36174. #endif
  36175. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36176. #endif
  36177. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36178. #endif
  36179. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36180. #endif
  36181. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36182. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36183. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36184. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36185. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  36186. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36187. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36188. /********* Start of inlined file: juce_FileFilter.h *********/
  36189. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36190. #define __JUCE_FILEFILTER_JUCEHEADER__
  36191. /**
  36192. Interface for deciding which files are suitable for something.
  36193. For example, this is used by DirectoryContentsList to select which files
  36194. go into the list.
  36195. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36196. */
  36197. class JUCE_API FileFilter
  36198. {
  36199. public:
  36200. /** Creates a filter with the given description.
  36201. The description can be returned later with the getDescription() method.
  36202. */
  36203. FileFilter (const String& filterDescription);
  36204. /** Destructor. */
  36205. virtual ~FileFilter();
  36206. /** Returns the description that the filter was created with. */
  36207. const String& getDescription() const throw();
  36208. /** Should return true if this file is suitable for inclusion in whatever context
  36209. the object is being used.
  36210. */
  36211. virtual bool isFileSuitable (const File& file) const = 0;
  36212. /** Should return true if this directory is suitable for inclusion in whatever context
  36213. the object is being used.
  36214. */
  36215. virtual bool isDirectorySuitable (const File& file) const = 0;
  36216. protected:
  36217. String description;
  36218. };
  36219. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36220. /********* End of inlined file: juce_FileFilter.h *********/
  36221. /**
  36222. A class to asynchronously scan for details about the files in a directory.
  36223. This keeps a list of files and some information about them, using a background
  36224. thread to scan for more files. As files are found, it broadcasts change messages
  36225. to tell any listeners.
  36226. @see FileListComponent, FileBrowserComponent
  36227. */
  36228. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36229. public TimeSliceClient
  36230. {
  36231. public:
  36232. /** Creates a directory list.
  36233. To set the directory it should point to, use setDirectory(), which will
  36234. also start it scanning for files on the background thread.
  36235. When the background thread finds and adds new files to this list, the
  36236. ChangeBroadcaster class will send a change message, so you can register
  36237. listeners and update them when the list changes.
  36238. @param fileFilter an optional filter to select which files are
  36239. included in the list. If this is 0, then all files
  36240. and directories are included. Make sure that the
  36241. filter doesn't get deleted during the lifetime of this
  36242. object
  36243. @param threadToUse a thread object that this list can use
  36244. to scan for files as a background task. Make sure
  36245. that the thread you give it has been started, or you
  36246. won't get any files!
  36247. */
  36248. DirectoryContentsList (const FileFilter* const fileFilter,
  36249. TimeSliceThread& threadToUse);
  36250. /** Destructor. */
  36251. ~DirectoryContentsList();
  36252. /** Sets the directory to look in for files.
  36253. If the directory that's passed in is different to the current one, this will
  36254. also start the background thread scanning it for files.
  36255. */
  36256. void setDirectory (const File& directory,
  36257. const bool includeDirectories,
  36258. const bool includeFiles);
  36259. /** Returns the directory that's currently being used. */
  36260. const File& getDirectory() const throw();
  36261. /** Clears the list, and stops the thread scanning for files. */
  36262. void clear();
  36263. /** Clears the list and restarts scanning the directory for files. */
  36264. void refresh();
  36265. /** True if the background thread hasn't yet finished scanning for files. */
  36266. bool isStillLoading() const;
  36267. /** Tells the list whether or not to ignore hidden files.
  36268. By default these are ignored.
  36269. */
  36270. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  36271. /** Contains cached information about one of the files in a DirectoryContentsList.
  36272. */
  36273. struct FileInfo
  36274. {
  36275. /** The filename.
  36276. This isn't a full pathname, it's just the last part of the path, same as you'd
  36277. get from File::getFileName().
  36278. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36279. */
  36280. String filename;
  36281. /** File size in bytes. */
  36282. int64 fileSize;
  36283. /** File modification time.
  36284. As supplied by File::getLastModificationTime().
  36285. */
  36286. Time modificationTime;
  36287. /** File creation time.
  36288. As supplied by File::getCreationTime().
  36289. */
  36290. Time creationTime;
  36291. /** True if the file is a directory. */
  36292. bool isDirectory;
  36293. /** True if the file is read-only. */
  36294. bool isReadOnly;
  36295. };
  36296. /** Returns the number of files currently available in the list.
  36297. The info about one of these files can be retrieved with getFileInfo() or
  36298. getFile().
  36299. Obviously as the background thread runs and scans the directory for files, this
  36300. number will change.
  36301. @see getFileInfo, getFile
  36302. */
  36303. int getNumFiles() const;
  36304. /** Returns the cached information about one of the files in the list.
  36305. If the index is in-range, this will return true and will copy the file's details
  36306. to the structure that is passed-in.
  36307. If it returns false, then the index wasn't in range, and the structure won't
  36308. be affected.
  36309. @see getNumFiles, getFile
  36310. */
  36311. bool getFileInfo (const int index,
  36312. FileInfo& resultInfo) const;
  36313. /** Returns one of the files in the list.
  36314. @param index should be less than getNumFiles(). If this is out-of-range, the
  36315. return value will be File::nonexistent
  36316. @see getNumFiles, getFileInfo
  36317. */
  36318. const File getFile (const int index) const;
  36319. /** Returns the file filter being used.
  36320. The filter is specified in the constructor.
  36321. */
  36322. const FileFilter* getFilter() const throw() { return fileFilter; }
  36323. /** @internal */
  36324. bool useTimeSlice();
  36325. /** @internal */
  36326. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  36327. /** @internal */
  36328. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  36329. const DirectoryContentsList::FileInfo* const second) throw();
  36330. juce_UseDebuggingNewOperator
  36331. private:
  36332. File root;
  36333. const FileFilter* fileFilter;
  36334. TimeSliceThread& thread;
  36335. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  36336. CriticalSection fileListLock;
  36337. OwnedArray <FileInfo> files;
  36338. void* volatile fileFindHandle;
  36339. bool volatile shouldStop;
  36340. void changed();
  36341. bool checkNextFile (bool& hasChanged);
  36342. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  36343. const int64 fileSize, const Time& modTime,
  36344. const Time& creationTime, const bool isReadOnly);
  36345. DirectoryContentsList (const DirectoryContentsList&);
  36346. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  36347. };
  36348. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36349. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  36350. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  36351. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36352. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36353. /**
  36354. A listener for user selection events in a file browser.
  36355. This is used by a FileBrowserComponent or FileListComponent.
  36356. */
  36357. class JUCE_API FileBrowserListener
  36358. {
  36359. public:
  36360. /** Destructor. */
  36361. virtual ~FileBrowserListener();
  36362. /** Callback when the user selects a different file in the browser. */
  36363. virtual void selectionChanged() = 0;
  36364. /** Callback when the user clicks on a file in the browser. */
  36365. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36366. /** Callback when the user double-clicks on a file in the browser. */
  36367. virtual void fileDoubleClicked (const File& file) = 0;
  36368. };
  36369. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36370. /********* End of inlined file: juce_FileBrowserListener.h *********/
  36371. /**
  36372. A base class for components that display a list of the files in a directory.
  36373. @see DirectoryContentsList
  36374. */
  36375. class JUCE_API DirectoryContentsDisplayComponent
  36376. {
  36377. public:
  36378. /**
  36379. */
  36380. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36381. /** Destructor. */
  36382. virtual ~DirectoryContentsDisplayComponent();
  36383. /** Returns the file that the user has currently selected.
  36384. Returns File::nonexistent if none is selected.
  36385. */
  36386. virtual const File getSelectedFile() const = 0;
  36387. /** Scrolls this view to the top. */
  36388. virtual void scrollToTop() = 0;
  36389. /** Adds a listener to be told when files are selected or clicked.
  36390. @see removeListener
  36391. */
  36392. void addListener (FileBrowserListener* const listener) throw();
  36393. /** Removes a listener.
  36394. @see addListener
  36395. */
  36396. void removeListener (FileBrowserListener* const listener) throw();
  36397. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36398. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36399. methods.
  36400. Note that you can also use the constants from TextEditor::ColourIds to change the
  36401. colour of the text editor that is opened when a label is editable.
  36402. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36403. */
  36404. enum ColourIds
  36405. {
  36406. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36407. textColourId = 0x1000541, /**< The colour for the text. */
  36408. };
  36409. /** @internal */
  36410. void sendSelectionChangeMessage();
  36411. /** @internal */
  36412. void sendDoubleClickMessage (const File& file);
  36413. /** @internal */
  36414. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36415. juce_UseDebuggingNewOperator
  36416. protected:
  36417. DirectoryContentsList& fileList;
  36418. SortedSet <void*> listeners;
  36419. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36420. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36421. };
  36422. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36423. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36424. #endif
  36425. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36426. #endif
  36427. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36428. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  36429. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36430. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36431. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  36432. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36433. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36434. /**
  36435. Base class for components that live inside a file chooser dialog box and
  36436. show previews of the files that get selected.
  36437. One of these allows special extra information to be displayed for files
  36438. in a dialog box as the user selects them. Each time the current file or
  36439. directory is changed, the selectedFileChanged() method will be called
  36440. to allow it to update itself appropriately.
  36441. @see FileChooser, ImagePreviewComponent
  36442. */
  36443. class JUCE_API FilePreviewComponent : public Component
  36444. {
  36445. public:
  36446. /** Creates a FilePreviewComponent. */
  36447. FilePreviewComponent();
  36448. /** Destructor. */
  36449. ~FilePreviewComponent();
  36450. /** Called to indicate that the user's currently selected file has changed.
  36451. @param newSelectedFile the newly selected file or directory, which may be
  36452. File::nonexistent if none is selected.
  36453. */
  36454. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36455. juce_UseDebuggingNewOperator
  36456. private:
  36457. FilePreviewComponent (const FilePreviewComponent&);
  36458. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  36459. };
  36460. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36461. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  36462. /**
  36463. A component for browsing and selecting a file or directory to open or save.
  36464. This contains a FileListComponent and adds various boxes and controls for
  36465. navigating and selecting a file. It can work in different modes so that it can
  36466. be used for loading or saving a file, or for choosing a directory.
  36467. @see FileChooserDialogBox, FileChooser, FileListComponent
  36468. */
  36469. class JUCE_API FileBrowserComponent : public Component,
  36470. public ChangeBroadcaster,
  36471. private FileBrowserListener,
  36472. private TextEditorListener,
  36473. private ButtonListener,
  36474. private ComboBoxListener
  36475. {
  36476. public:
  36477. /** Various modes that the browser can be used in.
  36478. One of these is passed into the constructor.
  36479. */
  36480. enum FileChooserMode
  36481. {
  36482. loadFileMode, /**< the component should allow the user to choose an existing
  36483. file with the intention of opening it. */
  36484. saveFileMode, /**< the component should allow the user to specify the name of
  36485. a file that will be used to save something. */
  36486. chooseDirectoryMode /**< the component should allow the user to select an existing
  36487. directory. */
  36488. };
  36489. /** Creates a FileBrowserComponent.
  36490. @param browserMode The intended purpose for the browser - see the
  36491. FileChooserMode enum for the various options
  36492. @param initialFileOrDirectory The file or directory that should be selected when
  36493. the component begins. If this is File::nonexistent,
  36494. a default directory will be chosen.
  36495. @param fileFilter an optional filter to use to determine which files
  36496. are shown. If this is 0 then all files are displayed. Note
  36497. that a pointer is kept internally to this object, so
  36498. make sure that it is not deleted before the browser object
  36499. is deleted.
  36500. @param previewComp an optional preview component that will be used to
  36501. show previews of files that the user selects
  36502. @param useTreeView if this is false, the files are shown in a list; if true,
  36503. they are shown in a treeview
  36504. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  36505. text into the filename box.
  36506. */
  36507. FileBrowserComponent (FileChooserMode browserMode,
  36508. const File& initialFileOrDirectory,
  36509. const FileFilter* fileFilter,
  36510. FilePreviewComponent* previewComp,
  36511. const bool useTreeView = false,
  36512. const bool filenameTextBoxIsReadOnly = false);
  36513. /** Destructor. */
  36514. ~FileBrowserComponent();
  36515. /**
  36516. */
  36517. const File getCurrentFile() const throw();
  36518. /** Returns true if the current file is usable.
  36519. This can be used to decide whether the user can press "ok" for the
  36520. current file. What it does depends on the mode, so for example in an "open"
  36521. mode, the current file is only valid if one has been selected and if the file
  36522. exists. In a "save" mode, a non-existent file would also be valid.
  36523. */
  36524. bool currentFileIsValid() const;
  36525. /** Returns the directory whose contents are currently being shown in the listbox. */
  36526. const File getRoot() const;
  36527. /** Changes the directory that's being shown in the listbox. */
  36528. void setRoot (const File& newRootDirectory);
  36529. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36530. void goUp();
  36531. /** Refreshes the directory that's currently being listed. */
  36532. void refresh();
  36533. /** Returns the browser's current mode. */
  36534. FileChooserMode getMode() const throw() { return mode; }
  36535. /** Returns a verb to describe what should happen when the file is accepted.
  36536. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36537. mode, it'll be "Save", etc.
  36538. */
  36539. virtual const String getActionVerb() const;
  36540. /** Adds a listener to be told when the user selects and clicks on files.
  36541. @see removeListener
  36542. */
  36543. void addListener (FileBrowserListener* const listener) throw();
  36544. /** Removes a listener.
  36545. @see addListener
  36546. */
  36547. void removeListener (FileBrowserListener* const listener) throw();
  36548. /** @internal */
  36549. void resized();
  36550. /** @internal */
  36551. void buttonClicked (Button* b);
  36552. /** @internal */
  36553. void comboBoxChanged (ComboBox*);
  36554. /** @internal */
  36555. void textEditorTextChanged (TextEditor& editor);
  36556. /** @internal */
  36557. void textEditorReturnKeyPressed (TextEditor& editor);
  36558. /** @internal */
  36559. void textEditorEscapeKeyPressed (TextEditor& editor);
  36560. /** @internal */
  36561. void textEditorFocusLost (TextEditor& editor);
  36562. /** @internal */
  36563. void selectionChanged();
  36564. /** @internal */
  36565. void fileClicked (const File& f, const MouseEvent& e);
  36566. /** @internal */
  36567. void fileDoubleClicked (const File& f);
  36568. /** @internal */
  36569. FilePreviewComponent* getPreviewComponent() const throw();
  36570. juce_UseDebuggingNewOperator
  36571. protected:
  36572. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  36573. private:
  36574. DirectoryContentsList* fileList;
  36575. FileFilter* directoriesOnlyFilter;
  36576. FileChooserMode mode;
  36577. File currentRoot;
  36578. SortedSet <void*> listeners;
  36579. DirectoryContentsDisplayComponent* fileListComponent;
  36580. FilePreviewComponent* previewComp;
  36581. ComboBox* currentPathBox;
  36582. TextEditor* filenameBox;
  36583. Button* goUpButton;
  36584. TimeSliceThread thread;
  36585. void sendListenerChangeMessage();
  36586. FileBrowserComponent (const FileBrowserComponent&);
  36587. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  36588. };
  36589. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36590. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  36591. #endif
  36592. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36593. #endif
  36594. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36595. /********* Start of inlined file: juce_FileChooser.h *********/
  36596. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36597. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36598. /**
  36599. Creates a dialog box to choose a file or directory to load or save.
  36600. To use a FileChooser:
  36601. - create one (as a local stack variable is the neatest way)
  36602. - call one of its browseFor.. methods
  36603. - if this returns true, the user has selected a file, so you can retrieve it
  36604. with the getResult() method.
  36605. e.g. @code
  36606. void loadMooseFile()
  36607. {
  36608. FileChooser myChooser ("Please select the moose you want to load...",
  36609. File::getSpecialLocation (File::userHomeDirectory),
  36610. "*.moose");
  36611. if (myChooser.browseForFileToOpen())
  36612. {
  36613. File mooseFile (myChooser.getResult());
  36614. loadMoose (mooseFile);
  36615. }
  36616. }
  36617. @endcode
  36618. */
  36619. class JUCE_API FileChooser
  36620. {
  36621. public:
  36622. /** Creates a FileChooser.
  36623. After creating one of these, use one of the browseFor... methods to display it.
  36624. @param dialogBoxTitle a text string to display in the dialog box to
  36625. tell the user what's going on
  36626. @param initialFileOrDirectory the file or directory that should be selected when
  36627. the dialog box opens. If this parameter is set to
  36628. File::nonexistent, a sensible default directory
  36629. will be used instead.
  36630. @param filePatternsAllowed a set of file patterns to specify which files can be
  36631. selected - each pattern should be separated by a
  36632. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36633. empty string means that all files are allowed
  36634. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36635. possible; if false, then a Juce-based browser dialog
  36636. box will always be used
  36637. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36638. */
  36639. FileChooser (const String& dialogBoxTitle,
  36640. const File& initialFileOrDirectory = File::nonexistent,
  36641. const String& filePatternsAllowed = String::empty,
  36642. const bool useOSNativeDialogBox = true);
  36643. /** Destructor. */
  36644. ~FileChooser();
  36645. /** Shows a dialog box to choose a file to open.
  36646. This will display the dialog box modally, using an "open file" mode, so that
  36647. it won't allow non-existent files or directories to be chosen.
  36648. @param previewComponent an optional component to display inside the dialog
  36649. box to show special info about the files that the user
  36650. is browsing. The component will not be deleted by this
  36651. object, so the caller must take care of it.
  36652. @returns true if the user selected a file, in which case, use the getResult()
  36653. method to find out what it was. Returns false if they cancelled instead.
  36654. @see browseForFileToSave, browseForDirectory
  36655. */
  36656. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36657. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36658. The files that are returned can be obtained by calling getResults(). See
  36659. browseForFileToOpen() for more info about the behaviour of this method.
  36660. */
  36661. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36662. /** Shows a dialog box to choose a file to save.
  36663. This will display the dialog box modally, using an "save file" mode, so it
  36664. will allow non-existent files to be chosen, but not directories.
  36665. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36666. the user if they're sure they want to overwrite a file that already
  36667. exists
  36668. @returns true if the user chose a file and pressed 'ok', in which case, use
  36669. the getResult() method to find out what the file was. Returns false
  36670. if they cancelled instead.
  36671. @see browseForFileToOpen, browseForDirectory
  36672. */
  36673. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  36674. /** Shows a dialog box to choose a directory.
  36675. This will display the dialog box modally, using an "open directory" mode, so it
  36676. will only allow directories to be returned, not files.
  36677. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36678. the getResult() method to find out what they chose. Returns false
  36679. if they cancelled instead.
  36680. @see browseForFileToOpen, browseForFileToSave
  36681. */
  36682. bool browseForDirectory();
  36683. /** Returns the last file that was chosen by one of the browseFor methods.
  36684. After calling the appropriate browseFor... method, this method lets you
  36685. find out what file or directory they chose.
  36686. Note that the file returned is only valid if the browse method returned true (i.e.
  36687. if the user pressed 'ok' rather than cancelling).
  36688. If you're using a multiple-file select, then use the getResults() method instead,
  36689. to obtain the list of all files chosen.
  36690. @see getResults
  36691. */
  36692. const File getResult() const;
  36693. /** Returns a list of all the files that were chosen during the last call to a
  36694. browse method.
  36695. This array may be empty if no files were chosen, or can contain multiple entries
  36696. if multiple files were chosen.
  36697. @see getResult
  36698. */
  36699. const OwnedArray <File>& getResults() const;
  36700. juce_UseDebuggingNewOperator
  36701. private:
  36702. String title, filters;
  36703. File startingFile;
  36704. OwnedArray <File> results;
  36705. bool useNativeDialogBox;
  36706. bool showDialog (const bool isDirectory,
  36707. const bool isSave,
  36708. const bool warnAboutOverwritingExistingFiles,
  36709. const bool selectMultipleFiles,
  36710. FilePreviewComponent* const previewComponent);
  36711. static void showPlatformDialog (OwnedArray<File>& results,
  36712. const String& title,
  36713. const File& file,
  36714. const String& filters,
  36715. bool isDirectory,
  36716. bool isSave,
  36717. bool warnAboutOverwritingExistingFiles,
  36718. bool selectMultipleFiles,
  36719. FilePreviewComponent* previewComponent);
  36720. };
  36721. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36722. /********* End of inlined file: juce_FileChooser.h *********/
  36723. #endif
  36724. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36725. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  36726. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36727. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36728. /**
  36729. A file open/save dialog box.
  36730. This is a Juce-based file dialog box; to use a native file chooser, see the
  36731. FileChooser class.
  36732. To use one of these, create it and call its show() method. e.g.
  36733. @code
  36734. {
  36735. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  36736. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  36737. File::nonexistent,
  36738. &wildcardFilter,
  36739. 0);
  36740. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  36741. T("Please choose some kind of file that you want to open..."),
  36742. browser,
  36743. getLookAndFeel().alertWindowBackground);
  36744. if (dialogBox.show())
  36745. {
  36746. File selectedFile = browser.getCurrentFile();
  36747. ...
  36748. }
  36749. }
  36750. @endcode
  36751. @see FileChooser
  36752. */
  36753. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  36754. public ButtonListener,
  36755. public FileBrowserListener
  36756. {
  36757. public:
  36758. /** Creates a file chooser box.
  36759. @param title the main title to show at the top of the box
  36760. @param instructions an optional longer piece of text to show below the title in
  36761. a smaller font, describing in more detail what's required.
  36762. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  36763. box. Make sure you delete this after (but not before!) the
  36764. dialog box has been deleted.
  36765. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  36766. if they try to select a file that already exists. (This
  36767. flag is only used when saving files)
  36768. @param backgroundColour the background colour for the top level window
  36769. @see FileBrowserComponent, FilePreviewComponent
  36770. */
  36771. FileChooserDialogBox (const String& title,
  36772. const String& instructions,
  36773. FileBrowserComponent& browserComponent,
  36774. const bool warnAboutOverwritingExistingFiles,
  36775. const Colour& backgroundColour);
  36776. /** Destructor. */
  36777. ~FileChooserDialogBox();
  36778. /** Displays and runs the dialog box modally.
  36779. This will show the box with the specified size, returning true if the user
  36780. pressed 'ok', or false if they cancelled.
  36781. Leave the width or height as 0 to use the default size
  36782. */
  36783. bool show (int width = 0,int height = 0);
  36784. /** @internal */
  36785. void buttonClicked (Button* button);
  36786. /** @internal */
  36787. void closeButtonPressed();
  36788. /** @internal */
  36789. void selectionChanged();
  36790. /** @internal */
  36791. void fileClicked (const File& file, const MouseEvent& e);
  36792. /** @internal */
  36793. void fileDoubleClicked (const File& file);
  36794. juce_UseDebuggingNewOperator
  36795. private:
  36796. class ContentComponent : public Component
  36797. {
  36798. public:
  36799. ContentComponent();
  36800. ~ContentComponent();
  36801. void paint (Graphics& g);
  36802. void resized();
  36803. String instructions;
  36804. GlyphArrangement text;
  36805. FileBrowserComponent* chooserComponent;
  36806. FilePreviewComponent* previewComponent;
  36807. TextButton* okButton;
  36808. TextButton* cancelButton;
  36809. };
  36810. ContentComponent* content;
  36811. const bool warnAboutOverwritingExistingFiles;
  36812. FileChooserDialogBox (const FileChooserDialogBox&);
  36813. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  36814. };
  36815. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36816. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  36817. #endif
  36818. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36819. #endif
  36820. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36821. /********* Start of inlined file: juce_FileListComponent.h *********/
  36822. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36823. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36824. /**
  36825. A component that displays the files in a directory as a listbox.
  36826. This implements the DirectoryContentsDisplayComponent base class so that
  36827. it can be used in a FileBrowserComponent.
  36828. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  36829. class and the FileBrowserListener class.
  36830. @see DirectoryContentsList, FileTreeComponent
  36831. */
  36832. class JUCE_API FileListComponent : public ListBox,
  36833. public DirectoryContentsDisplayComponent,
  36834. private ListBoxModel,
  36835. private ChangeListener
  36836. {
  36837. public:
  36838. /** Creates a listbox to show the contents of a specified directory.
  36839. */
  36840. FileListComponent (DirectoryContentsList& listToShow);
  36841. /** Destructor. */
  36842. ~FileListComponent();
  36843. /** Returns the file that the user has currently selected.
  36844. Returns File::nonexistent if none is selected.
  36845. */
  36846. const File getSelectedFile() const;
  36847. /** Scrolls to the top of the list. */
  36848. void scrollToTop();
  36849. /** @internal */
  36850. void changeListenerCallback (void*);
  36851. /** @internal */
  36852. int getNumRows();
  36853. /** @internal */
  36854. void paintListBoxItem (int, Graphics&, int, int, bool);
  36855. /** @internal */
  36856. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  36857. /** @internal */
  36858. void selectedRowsChanged (int lastRowSelected);
  36859. /** @internal */
  36860. void deleteKeyPressed (int currentSelectedRow);
  36861. /** @internal */
  36862. void returnKeyPressed (int currentSelectedRow);
  36863. juce_UseDebuggingNewOperator
  36864. private:
  36865. FileListComponent (const FileListComponent&);
  36866. const FileListComponent& operator= (const FileListComponent&);
  36867. File lastDirectory;
  36868. };
  36869. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36870. /********* End of inlined file: juce_FileListComponent.h *********/
  36871. #endif
  36872. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36873. /********* Start of inlined file: juce_FilenameComponent.h *********/
  36874. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36875. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36876. class FilenameComponent;
  36877. /**
  36878. Listens for events happening to a FilenameComponent.
  36879. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  36880. register one of these objects for event callbacks when the filename is changed.
  36881. @See FilenameComponent
  36882. */
  36883. class JUCE_API FilenameComponentListener
  36884. {
  36885. public:
  36886. /** Destructor. */
  36887. virtual ~FilenameComponentListener() {}
  36888. /** This method is called after the FilenameComponent's file has been changed. */
  36889. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  36890. };
  36891. /**
  36892. Shows a filename as an editable text box, with a 'browse' button and a
  36893. drop-down list for recently selected files.
  36894. A handy component for dialogue boxes where you want the user to be able to
  36895. select a file or directory.
  36896. Attach an FilenameComponentListener using the addListener() method, and it will
  36897. get called each time the user changes the filename, either by browsing for a file
  36898. and clicking 'ok', or by typing a new filename into the box and pressing return.
  36899. @see FileChooser, ComboBox
  36900. */
  36901. class JUCE_API FilenameComponent : public Component,
  36902. public SettableTooltipClient,
  36903. public FileDragAndDropTarget,
  36904. private AsyncUpdater,
  36905. private ButtonListener,
  36906. private ComboBoxListener
  36907. {
  36908. public:
  36909. /** Creates a FilenameComponent.
  36910. @param name the name for this component.
  36911. @param currentFile the file to initially show in the box
  36912. @param canEditFilename if true, the user can manually edit the filename; if false,
  36913. they can only change it by browsing for a new file
  36914. @param isDirectory if true, the file will be treated as a directory, and
  36915. an appropriate directory browser used
  36916. @param isForSaving if true, the file browser will allow non-existent files to
  36917. be picked, as the file is assumed to be used for saving rather
  36918. than loading
  36919. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  36920. If an empty string is passed in, then the pattern is assumed to be "*"
  36921. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  36922. to any filenames that are entered or chosen
  36923. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  36924. will only appear if the initial file isn't valid)
  36925. */
  36926. FilenameComponent (const String& name,
  36927. const File& currentFile,
  36928. const bool canEditFilename,
  36929. const bool isDirectory,
  36930. const bool isForSaving,
  36931. const String& fileBrowserWildcard,
  36932. const String& enforcedSuffix,
  36933. const String& textWhenNothingSelected);
  36934. /** Destructor. */
  36935. ~FilenameComponent();
  36936. /** Returns the currently displayed filename. */
  36937. const File getCurrentFile() const;
  36938. /** Changes the current filename.
  36939. If addToRecentlyUsedList is true, the filename will also be added to the
  36940. drop-down list of recent files.
  36941. If sendChangeNotification is false, then the listeners won't be told of the
  36942. change.
  36943. */
  36944. void setCurrentFile (File newFile,
  36945. const bool addToRecentlyUsedList,
  36946. const bool sendChangeNotification = true);
  36947. /** Changes whether the use can type into the filename box.
  36948. */
  36949. void setFilenameIsEditable (const bool shouldBeEditable);
  36950. /** Sets a file or directory to be the default starting point for the browser to show.
  36951. This is only used if the current file hasn't been set.
  36952. */
  36953. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  36954. /** Returns all the entries on the recent files list.
  36955. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  36956. state of this list.
  36957. @see setRecentlyUsedFilenames
  36958. */
  36959. const StringArray getRecentlyUsedFilenames() const;
  36960. /** Sets all the entries on the recent files list.
  36961. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  36962. state of this list.
  36963. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  36964. */
  36965. void setRecentlyUsedFilenames (const StringArray& filenames);
  36966. /** Adds an entry to the recently-used files dropdown list.
  36967. If the file is already in the list, it will be moved to the top. A limit
  36968. is also placed on the number of items that are kept in the list.
  36969. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  36970. */
  36971. void addRecentlyUsedFile (const File& file);
  36972. /** Changes the limit for the number of files that will be stored in the recent-file list.
  36973. */
  36974. void setMaxNumberOfRecentFiles (const int newMaximum);
  36975. /** Changes the text shown on the 'browse' button.
  36976. By default this button just says "..." but you can change it. The button itself
  36977. can be changed using the look-and-feel classes, so it might not actually have any
  36978. text on it.
  36979. */
  36980. void setBrowseButtonText (const String& browseButtonText);
  36981. /** Adds a listener that will be called when the selected file is changed. */
  36982. void addListener (FilenameComponentListener* const listener) throw();
  36983. /** Removes a previously-registered listener. */
  36984. void removeListener (FilenameComponentListener* const listener) throw();
  36985. /** Gives the component a tooltip. */
  36986. void setTooltip (const String& newTooltip);
  36987. /** @internal */
  36988. void paintOverChildren (Graphics& g);
  36989. /** @internal */
  36990. void resized();
  36991. /** @internal */
  36992. void lookAndFeelChanged();
  36993. /** @internal */
  36994. bool isInterestedInFileDrag (const StringArray& files);
  36995. /** @internal */
  36996. void filesDropped (const StringArray& files, int, int);
  36997. /** @internal */
  36998. void fileDragEnter (const StringArray& files, int, int);
  36999. /** @internal */
  37000. void fileDragExit (const StringArray& files);
  37001. juce_UseDebuggingNewOperator
  37002. private:
  37003. ComboBox* filenameBox;
  37004. String lastFilename;
  37005. Button* browseButton;
  37006. int maxRecentFiles;
  37007. bool isDir, isSaving, isFileDragOver;
  37008. String wildcard, enforcedSuffix, browseButtonText;
  37009. SortedSet <void*> listeners;
  37010. File defaultBrowseFile;
  37011. void comboBoxChanged (ComboBox*);
  37012. void buttonClicked (Button* button);
  37013. void handleAsyncUpdate();
  37014. FilenameComponent (const FilenameComponent&);
  37015. const FilenameComponent& operator= (const FilenameComponent&);
  37016. };
  37017. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37018. /********* End of inlined file: juce_FilenameComponent.h *********/
  37019. #endif
  37020. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37021. #endif
  37022. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37023. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37024. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37025. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37026. /**
  37027. Shows a set of file paths in a list, allowing them to be added, removed or
  37028. re-ordered.
  37029. @see FileSearchPath
  37030. */
  37031. class JUCE_API FileSearchPathListComponent : public Component,
  37032. public SettableTooltipClient,
  37033. public FileDragAndDropTarget,
  37034. private ButtonListener,
  37035. private ListBoxModel
  37036. {
  37037. public:
  37038. /** Creates an empty FileSearchPathListComponent.
  37039. */
  37040. FileSearchPathListComponent();
  37041. /** Destructor. */
  37042. ~FileSearchPathListComponent();
  37043. /** Returns the path as it is currently shown. */
  37044. const FileSearchPath& getPath() const throw() { return path; }
  37045. /** Changes the current path. */
  37046. void setPath (const FileSearchPath& newPath);
  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. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37052. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37053. methods.
  37054. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37055. */
  37056. enum ColourIds
  37057. {
  37058. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37059. Make this transparent if you don't want the background to be filled. */
  37060. };
  37061. /** @internal */
  37062. int getNumRows();
  37063. /** @internal */
  37064. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37065. /** @internal */
  37066. void deleteKeyPressed (int lastRowSelected);
  37067. /** @internal */
  37068. void returnKeyPressed (int lastRowSelected);
  37069. /** @internal */
  37070. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37071. /** @internal */
  37072. void selectedRowsChanged (int lastRowSelected);
  37073. /** @internal */
  37074. void resized();
  37075. /** @internal */
  37076. void paint (Graphics& g);
  37077. /** @internal */
  37078. bool isInterestedInFileDrag (const StringArray& files);
  37079. /** @internal */
  37080. void filesDropped (const StringArray& files, int, int);
  37081. /** @internal */
  37082. void buttonClicked (Button* button);
  37083. juce_UseDebuggingNewOperator
  37084. private:
  37085. FileSearchPath path;
  37086. File defaultBrowseTarget;
  37087. ListBox* listBox;
  37088. Button* addButton;
  37089. Button* removeButton;
  37090. Button* changeButton;
  37091. Button* upButton;
  37092. Button* downButton;
  37093. void changed() throw();
  37094. void updateButtons() throw();
  37095. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37096. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37097. };
  37098. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37099. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37100. #endif
  37101. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37102. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37103. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37104. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37105. /**
  37106. A component that displays the files in a directory as a treeview.
  37107. This implements the DirectoryContentsDisplayComponent base class so that
  37108. it can be used in a FileBrowserComponent.
  37109. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37110. class and the FileBrowserListener class.
  37111. @see DirectoryContentsList, FileListComponent
  37112. */
  37113. class JUCE_API FileTreeComponent : public TreeView,
  37114. public DirectoryContentsDisplayComponent
  37115. {
  37116. public:
  37117. /** Creates a listbox to show the contents of a specified directory.
  37118. */
  37119. FileTreeComponent (DirectoryContentsList& listToShow);
  37120. /** Destructor. */
  37121. ~FileTreeComponent();
  37122. /** Returns the number of selected files in the tree.
  37123. */
  37124. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37125. /** Returns one of the files that the user has currently selected.
  37126. Returns File::nonexistent if none is selected.
  37127. */
  37128. const File getSelectedFile (int index) const throw();
  37129. /** Returns the first of the files that the user has currently selected.
  37130. Returns File::nonexistent if none is selected.
  37131. */
  37132. const File getSelectedFile() const;
  37133. /** Scrolls the list to the top. */
  37134. void scrollToTop();
  37135. /** Setting a name for this allows tree items to be dragged.
  37136. The string that you pass in here will be returned by the getDragSourceDescription()
  37137. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37138. */
  37139. void setDragAndDropDescription (const String& description) throw();
  37140. /** Returns the last value that was set by setDragAndDropDescription().
  37141. */
  37142. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37143. juce_UseDebuggingNewOperator
  37144. private:
  37145. String dragAndDropDescription;
  37146. FileTreeComponent (const FileTreeComponent&);
  37147. const FileTreeComponent& operator= (const FileTreeComponent&);
  37148. };
  37149. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37150. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37151. #endif
  37152. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37153. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37154. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37155. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37156. /**
  37157. A simple preview component that shows thumbnails of image files.
  37158. @see FileChooserDialogBox, FilePreviewComponent
  37159. */
  37160. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37161. private Timer
  37162. {
  37163. public:
  37164. /** Creates an ImagePreviewComponent. */
  37165. ImagePreviewComponent();
  37166. /** Destructor. */
  37167. ~ImagePreviewComponent();
  37168. /** @internal */
  37169. void selectedFileChanged (const File& newSelectedFile);
  37170. /** @internal */
  37171. void paint (Graphics& g);
  37172. /** @internal */
  37173. void timerCallback();
  37174. juce_UseDebuggingNewOperator
  37175. private:
  37176. File fileToLoad;
  37177. Image* currentThumbnail;
  37178. String currentDetails;
  37179. void getThumbSize (int& w, int& h) const;
  37180. ImagePreviewComponent (const ImagePreviewComponent&);
  37181. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37182. };
  37183. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37184. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37185. #endif
  37186. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37187. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37188. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37189. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37190. /**
  37191. A type of FileFilter that works by wildcard pattern matching.
  37192. This filter only allows files that match one of the specified patterns, but
  37193. allows all directories through.
  37194. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37195. */
  37196. class JUCE_API WildcardFileFilter : public FileFilter
  37197. {
  37198. public:
  37199. /**
  37200. Creates a wildcard filter for one or more patterns.
  37201. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37202. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37203. or .aiff.
  37204. The description is a name to show the user in a list of possible patterns, so
  37205. for the wav/aiff example, your description might be "audio files".
  37206. */
  37207. WildcardFileFilter (const String& wildcardPatterns,
  37208. const String& description);
  37209. /** Destructor. */
  37210. ~WildcardFileFilter();
  37211. /** Returns true if the filename matches one of the patterns specified. */
  37212. bool isFileSuitable (const File& file) const;
  37213. /** This always returns true. */
  37214. bool isDirectorySuitable (const File& file) const;
  37215. juce_UseDebuggingNewOperator
  37216. private:
  37217. StringArray wildcards;
  37218. };
  37219. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37220. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37221. #endif
  37222. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37223. /********* Start of inlined file: juce_AlertWindow.h *********/
  37224. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37225. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37226. /** A window that displays a message and has buttons for the user to react to it.
  37227. For simple dialog boxes with just a couple of buttons on them, there are
  37228. some static methods for running these.
  37229. For more complex dialogs, an AlertWindow can be created, then it can have some
  37230. buttons and components added to it, and its runModalLoop() method is then used to
  37231. show it. The value returned by runModalLoop() shows which button the
  37232. user pressed to dismiss the box.
  37233. @see ThreadWithProgressWindow
  37234. */
  37235. class JUCE_API AlertWindow : public TopLevelWindow,
  37236. private ButtonListener
  37237. {
  37238. public:
  37239. /** The type of icon to show in the dialog box. */
  37240. enum AlertIconType
  37241. {
  37242. NoIcon, /**< No icon will be shown on the dialog box. */
  37243. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37244. user to answer a question. */
  37245. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37246. warning about something and shouldn't be ignored. */
  37247. InfoIcon /**< An icon that indicates that the dialog box is just
  37248. giving the user some information, which doesn't require
  37249. a response from them. */
  37250. };
  37251. /** Creates an AlertWindow.
  37252. @param title the headline to show at the top of the dialog box
  37253. @param message a longer, more descriptive message to show underneath the
  37254. headline
  37255. @param iconType the type of icon to display
  37256. */
  37257. AlertWindow (const String& title,
  37258. const String& message,
  37259. AlertIconType iconType);
  37260. /** Destroys the AlertWindow */
  37261. ~AlertWindow();
  37262. /** Returns the type of alert icon that was specified when the window
  37263. was created. */
  37264. AlertIconType getAlertType() const throw() { return alertIconType; }
  37265. /** Changes the dialog box's message.
  37266. This will also resize the window to fit the new message if required.
  37267. */
  37268. void setMessage (const String& message);
  37269. /** Adds a button to the window.
  37270. @param name the text to show on the button
  37271. @param returnValue the value that should be returned from runModalLoop()
  37272. if this is the button that the user presses.
  37273. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37274. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37275. */
  37276. void addButton (const String& name,
  37277. const int returnValue,
  37278. const KeyPress& shortcutKey1 = KeyPress(),
  37279. const KeyPress& shortcutKey2 = KeyPress());
  37280. /** Returns the number of buttons that the window currently has. */
  37281. int getNumButtons() const;
  37282. /** Adds a textbox to the window for entering strings.
  37283. @param name an internal name for the text-box. This is the name to pass to
  37284. the getTextEditorContents() method to find out what the
  37285. user typed-in.
  37286. @param initialContents a string to show in the text box when it's first shown
  37287. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37288. text-box to label it.
  37289. @param isPasswordBox if true, the text editor will display asterisks instead of
  37290. the actual text
  37291. @see getTextEditorContents
  37292. */
  37293. void addTextEditor (const String& name,
  37294. const String& initialContents,
  37295. const String& onScreenLabel = String::empty,
  37296. const bool isPasswordBox = false);
  37297. /** Returns the contents of a named textbox.
  37298. After showing an AlertWindow that contains a text editor, this can be
  37299. used to find out what the user has typed into it.
  37300. @param nameOfTextEditor the name of the text box that you're interested in
  37301. @see addTextEditor
  37302. */
  37303. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37304. /** Adds a drop-down list of choices to the box.
  37305. After the box has been shown, the getComboBoxComponent() method can
  37306. be used to find out which item the user picked.
  37307. @param name the label to use for the drop-down list
  37308. @param items the list of items to show in it
  37309. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37310. combo-box to label it.
  37311. @see getComboBoxComponent
  37312. */
  37313. void addComboBox (const String& name,
  37314. const StringArray& items,
  37315. const String& onScreenLabel = String::empty);
  37316. /** Returns a drop-down list that was added to the AlertWindow.
  37317. @param nameOfList the name that was passed into the addComboBox() method
  37318. when creating the drop-down
  37319. @returns the ComboBox component, or 0 if none was found for the given name.
  37320. */
  37321. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37322. /** Adds a block of text.
  37323. This is handy for adding a multi-line note next to a textbox or combo-box,
  37324. to provide more details about what's going on.
  37325. */
  37326. void addTextBlock (const String& text);
  37327. /** Adds a progress-bar to the window.
  37328. @param progressValue a variable that will be repeatedly checked while the
  37329. dialog box is visible, to see how far the process has
  37330. got. The value should be in the range 0 to 1.0
  37331. */
  37332. void addProgressBarComponent (double& progressValue);
  37333. /** Adds a user-defined component to the dialog box.
  37334. @param component the component to add - its size should be set up correctly
  37335. before it is passed in. The caller is responsible for deleting
  37336. the component later on - the AlertWindow won't delete it.
  37337. */
  37338. void addCustomComponent (Component* const component);
  37339. /** Returns the number of custom components in the dialog box.
  37340. @see getCustomComponent, addCustomComponent
  37341. */
  37342. int getNumCustomComponents() const;
  37343. /** Returns one of the custom components in the dialog box.
  37344. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37345. will return 0
  37346. @see getNumCustomComponents, addCustomComponent
  37347. */
  37348. Component* getCustomComponent (const int index) const;
  37349. /** Removes one of the custom components in the dialog box.
  37350. Note that this won't delete it, it just removes the component from the window
  37351. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37352. will return 0
  37353. @returns the component that was removed (or zero)
  37354. @see getNumCustomComponents, addCustomComponent
  37355. */
  37356. Component* removeCustomComponent (const int index);
  37357. /** Returns true if the window contains any components other than just buttons.*/
  37358. bool containsAnyExtraComponents() const;
  37359. // easy-to-use message box functions:
  37360. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37361. The box is shown modally, and the method returns after the user
  37362. has clicked the button (or pressed the escape or return keys).
  37363. @param iconType the type of icon to show
  37364. @param title the headline to show at the top of the box
  37365. @param message a longer, more descriptive message to show underneath the
  37366. headline
  37367. @param buttonText the text to show in the button - if this string is empty, the
  37368. default string "ok" (or a localised version) will be used.
  37369. */
  37370. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37371. const String& title,
  37372. const String& message,
  37373. const String& buttonText = String::empty);
  37374. /** Shows a dialog box with two buttons.
  37375. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37376. to trigger the first button, and the escape key for the second button.
  37377. @param iconType the type of icon to show
  37378. @param title the headline to show at the top of the box
  37379. @param message a longer, more descriptive message to show underneath the
  37380. headline
  37381. @param button1Text the text to show in the first button - if this string is
  37382. empty, the default string "ok" (or a localised version of it)
  37383. will be used.
  37384. @param button2Text the text to show in the second button - if this string is
  37385. empty, the default string "cancel" (or a localised version of it)
  37386. will be used.
  37387. @returns true if button 1 was clicked, false if it was button 2
  37388. */
  37389. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37390. const String& title,
  37391. const String& message,
  37392. const String& button1Text = String::empty,
  37393. const String& button2Text = String::empty);
  37394. /** Shows a dialog box with three buttons.
  37395. Ideal for yes/no/cancel boxes.
  37396. The escape key can be used to trigger the third button.
  37397. @param iconType the type of icon to show
  37398. @param title the headline to show at the top of the box
  37399. @param message a longer, more descriptive message to show underneath the
  37400. headline
  37401. @param button1Text the text to show in the first button - if an empty string, then
  37402. "yes" will be used (or a localised version of it)
  37403. @param button2Text the text to show in the first button - if an empty string, then
  37404. "no" will be used (or a localised version of it)
  37405. @param button3Text the text to show in the first button - if an empty string, then
  37406. "cancel" will be used (or a localised version of it)
  37407. @returns one of the following values:
  37408. - 0 if the third button was pressed (normally used for 'cancel')
  37409. - 1 if the first button was pressed (normally used for 'yes')
  37410. - 2 if the middle button was pressed (normally used for 'no')
  37411. */
  37412. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  37413. const String& title,
  37414. const String& message,
  37415. const String& button1Text = String::empty,
  37416. const String& button2Text = String::empty,
  37417. const String& button3Text = String::empty);
  37418. /** Shows an operating-system native dialog box.
  37419. @param title the title to use at the top
  37420. @param bodyText the longer message to show
  37421. @param isOkCancel if true, this will show an ok/cancel box, if false,
  37422. it'll show a box with just an ok button
  37423. @returns true if the ok button was pressed, false if they pressed cancel.
  37424. */
  37425. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  37426. const String& bodyText,
  37427. bool isOkCancel);
  37428. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  37429. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37430. methods.
  37431. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37432. */
  37433. enum ColourIds
  37434. {
  37435. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  37436. textColourId = 0x1001810, /**< The colour for the text. */
  37437. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  37438. };
  37439. juce_UseDebuggingNewOperator
  37440. protected:
  37441. /** @internal */
  37442. void paint (Graphics& g);
  37443. /** @internal */
  37444. void mouseDown (const MouseEvent& e);
  37445. /** @internal */
  37446. void mouseDrag (const MouseEvent& e);
  37447. /** @internal */
  37448. bool keyPressed (const KeyPress& key);
  37449. /** @internal */
  37450. void buttonClicked (Button* button);
  37451. /** @internal */
  37452. void lookAndFeelChanged();
  37453. private:
  37454. String text;
  37455. TextLayout textLayout;
  37456. AlertIconType alertIconType;
  37457. ComponentBoundsConstrainer constrainer;
  37458. ComponentDragger dragger;
  37459. Rectangle textArea;
  37460. VoidArray buttons, textBoxes, comboBoxes;
  37461. VoidArray progressBars, customComps, textBlocks, allComps;
  37462. StringArray textboxNames, comboBoxNames;
  37463. Font font;
  37464. void updateLayout (const bool onlyIncreaseSize);
  37465. // disable copy constructor
  37466. AlertWindow (const AlertWindow&);
  37467. const AlertWindow& operator= (const AlertWindow&);
  37468. };
  37469. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  37470. /********* End of inlined file: juce_AlertWindow.h *********/
  37471. #endif
  37472. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  37473. #endif
  37474. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37475. /********* Start of inlined file: juce_DialogWindow.h *********/
  37476. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37477. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  37478. /**
  37479. A dialog-box style window.
  37480. This class is a convenient way of creating a DocumentWindow with a close button
  37481. that can be triggered by pressing the escape key.
  37482. Any of the methods available to a DocumentWindow or ResizableWindow are also
  37483. available to this, so it can be made resizable, have a menu bar, etc.
  37484. To add items to the box, see the ResizableWindow::setContentComponent() method.
  37485. Don't add components directly to this class - always put them in a content component!
  37486. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  37487. the user clicking the close button - for more info, see the DocumentWindow
  37488. help.
  37489. @see DocumentWindow, ResizableWindow
  37490. */
  37491. class JUCE_API DialogWindow : public DocumentWindow
  37492. {
  37493. public:
  37494. /** Creates a DialogWindow.
  37495. @param name the name to give the component - this is also
  37496. the title shown at the top of the window. To change
  37497. this later, use setName()
  37498. @param backgroundColour the colour to use for filling the window's background.
  37499. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37500. close button to be triggered
  37501. @param addToDesktop if true, the window will be automatically added to the
  37502. desktop; if false, you can use it as a child component
  37503. */
  37504. DialogWindow (const String& name,
  37505. const Colour& backgroundColour,
  37506. const bool escapeKeyTriggersCloseButton,
  37507. const bool addToDesktop = true);
  37508. /** Destructor.
  37509. If a content component has been set with setContentComponent(), it
  37510. will be deleted.
  37511. */
  37512. ~DialogWindow();
  37513. /** Easy way of quickly showing a dialog box containing a given component.
  37514. This will open and display a DialogWindow containing a given component, returning
  37515. when the user clicks its close button.
  37516. It returns the value that was returned by the dialog box's runModalLoop() call.
  37517. To close the dialog programatically, you should call exitModalState (returnValue) on
  37518. the DialogWindow that is created. To find a pointer to this window from your
  37519. contentComponent, you can do something like this:
  37520. @code
  37521. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  37522. if (dw != 0)
  37523. dw->exitModalState (1234);
  37524. @endcode
  37525. @param dialogTitle the dialog box's title
  37526. @param contentComponent the content component for the dialog box. Make sure
  37527. that this has been set to the size you want it to
  37528. be before calling this method. The component won't
  37529. be deleted by this call, so you can re-use it or delete
  37530. it afterwards
  37531. @param componentToCentreAround if this is non-zero, it indicates a component that
  37532. you'd like to show this dialog box in front of. See the
  37533. DocumentWindow::centreAroundComponent() method for more
  37534. info on this parameter
  37535. @param backgroundColour a colour to use for the dialog box's background colour
  37536. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37537. close button to be triggered
  37538. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  37539. a corner resizer
  37540. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  37541. to use a border or corner resizer component. See ResizableWindow::setResizable()
  37542. */
  37543. static int showModalDialog (const String& dialogTitle,
  37544. Component* contentComponent,
  37545. Component* componentToCentreAround,
  37546. const Colour& backgroundColour,
  37547. const bool escapeKeyTriggersCloseButton,
  37548. const bool shouldBeResizable = false,
  37549. const bool useBottomRightCornerResizer = false);
  37550. juce_UseDebuggingNewOperator
  37551. protected:
  37552. /** @internal */
  37553. void resized();
  37554. private:
  37555. bool escapeKeyTriggersCloseButton;
  37556. DialogWindow (const DialogWindow&);
  37557. const DialogWindow& operator= (const DialogWindow&);
  37558. };
  37559. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  37560. /********* End of inlined file: juce_DialogWindow.h *********/
  37561. #endif
  37562. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37563. #endif
  37564. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37565. #endif
  37566. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37567. /********* Start of inlined file: juce_SplashScreen.h *********/
  37568. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37569. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  37570. /** A component for showing a splash screen while your app starts up.
  37571. This will automatically position itself, and delete itself when the app has
  37572. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  37573. this).
  37574. To use it, just create one of these in your JUCEApplication::initialise() method,
  37575. call its show() method and let the object delete itself later.
  37576. E.g. @code
  37577. void MyApp::initialise (const String& commandLine)
  37578. {
  37579. SplashScreen* splash = new SplashScreen();
  37580. splash->show (T("welcome to my app"),
  37581. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  37582. 4000, false);
  37583. .. no need to delete the splash screen - it'll do that itself.
  37584. }
  37585. @endcode
  37586. */
  37587. class JUCE_API SplashScreen : public Component,
  37588. public Timer,
  37589. private DeletedAtShutdown
  37590. {
  37591. public:
  37592. /** Creates a SplashScreen object.
  37593. After creating one of these (or your subclass of it), call one of the show()
  37594. methods to display it.
  37595. */
  37596. SplashScreen();
  37597. /** Destructor. */
  37598. ~SplashScreen();
  37599. /** Creates a SplashScreen object that will display an image.
  37600. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37601. screen. This method will also dispatch any pending messages to make sure that when
  37602. it returns, the splash screen has been completely drawn, and your initialisation
  37603. code can carry on.
  37604. @param title the name to give the component
  37605. @param backgroundImage an image to draw on the component. The component's size
  37606. will be set to the size of this image, and if the image is
  37607. semi-transparent, the component will be made semi-transparent
  37608. too. This image will be deleted (or released from the ImageCache
  37609. if that's how it was created) by the splash screen object when
  37610. it is itself deleted.
  37611. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37612. should stay visible for. If the initialisation takes longer than
  37613. this time, the splash screen will wait for it to finish before
  37614. disappearing, but if initialisation is very quick, this lets
  37615. you make sure that people get a good look at your splash.
  37616. @param useDropShadow if true, the window will have a drop shadow
  37617. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37618. the mouse (anywhere)
  37619. */
  37620. void show (const String& title,
  37621. Image* const backgroundImage,
  37622. const int minimumTimeToDisplayFor,
  37623. const bool useDropShadow,
  37624. const bool removeOnMouseClick = true);
  37625. /** Creates a SplashScreen object with a specified size.
  37626. For a custom splash screen, you can use this method to display it at a certain size
  37627. and then override the paint() method yourself to do whatever's necessary.
  37628. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37629. screen. This method will also dispatch any pending messages to make sure that when
  37630. it returns, the splash screen has been completely drawn, and your initialisation
  37631. code can carry on.
  37632. @param title the name to give the component
  37633. @param width the width to use
  37634. @param height the height to use
  37635. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37636. should stay visible for. If the initialisation takes longer than
  37637. this time, the splash screen will wait for it to finish before
  37638. disappearing, but if initialisation is very quick, this lets
  37639. you make sure that people get a good look at your splash.
  37640. @param useDropShadow if true, the window will have a drop shadow
  37641. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37642. the mouse (anywhere)
  37643. */
  37644. void show (const String& title,
  37645. const int width,
  37646. const int height,
  37647. const int minimumTimeToDisplayFor,
  37648. const bool useDropShadow,
  37649. const bool removeOnMouseClick = true);
  37650. /** @internal */
  37651. void paint (Graphics& g);
  37652. /** @internal */
  37653. void timerCallback();
  37654. juce_UseDebuggingNewOperator
  37655. private:
  37656. Image* backgroundImage;
  37657. Time earliestTimeToDelete;
  37658. int originalClickCounter;
  37659. bool isImageInCache;
  37660. SplashScreen (const SplashScreen&);
  37661. const SplashScreen& operator= (const SplashScreen&);
  37662. };
  37663. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  37664. /********* End of inlined file: juce_SplashScreen.h *********/
  37665. #endif
  37666. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37667. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  37668. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37669. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37670. /**
  37671. A thread that automatically pops up a modal dialog box with a progress bar
  37672. and cancel button while it's busy running.
  37673. These are handy for performing some sort of task while giving the user feedback
  37674. about how long there is to go, etc.
  37675. E.g. @code
  37676. class MyTask : public ThreadWithProgressWindow
  37677. {
  37678. public:
  37679. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  37680. {
  37681. }
  37682. ~MyTask()
  37683. {
  37684. }
  37685. void run()
  37686. {
  37687. for (int i = 0; i < thingsToDo; ++i)
  37688. {
  37689. // must check this as often as possible, because this is
  37690. // how we know if the user's pressed 'cancel'
  37691. if (threadShouldExit())
  37692. break;
  37693. // this will update the progress bar on the dialog box
  37694. setProgress (i / (double) thingsToDo);
  37695. // ... do the business here...
  37696. }
  37697. }
  37698. };
  37699. void doTheTask()
  37700. {
  37701. MyTask m;
  37702. if (m.runThread())
  37703. {
  37704. // thread finished normally..
  37705. }
  37706. else
  37707. {
  37708. // user pressed the cancel button..
  37709. }
  37710. }
  37711. @endcode
  37712. @see Thread, AlertWindow
  37713. */
  37714. class JUCE_API ThreadWithProgressWindow : public Thread,
  37715. private Timer
  37716. {
  37717. public:
  37718. /** Creates the thread.
  37719. Initially, the dialog box won't be visible, it'll only appear when the
  37720. runThread() method is called.
  37721. @param windowTitle the title to go at the top of the dialog box
  37722. @param hasProgressBar whether the dialog box should have a progress bar (see
  37723. setProgress() )
  37724. @param hasCancelButton whether the dialog box should have a cancel button
  37725. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  37726. the thread to stop before killing it forcibly (see
  37727. Thread::stopThread() )
  37728. @param cancelButtonText the text that should be shown in the cancel button
  37729. (if it has one)
  37730. */
  37731. ThreadWithProgressWindow (const String& windowTitle,
  37732. const bool hasProgressBar,
  37733. const bool hasCancelButton,
  37734. const int timeOutMsWhenCancelling = 10000,
  37735. const String& cancelButtonText = JUCE_T("Cancel"));
  37736. /** Destructor. */
  37737. ~ThreadWithProgressWindow();
  37738. /** Starts the thread and waits for it to finish.
  37739. This will start the thread, make the dialog box appear, and wait until either
  37740. the thread finishes normally, or until the cancel button is pressed.
  37741. Before returning, the dialog box will be hidden.
  37742. @param threadPriority the priority to use when starting the thread - see
  37743. Thread::startThread() for values
  37744. @returns true if the thread finished normally; false if the user pressed cancel
  37745. */
  37746. bool runThread (const int threadPriority = 5);
  37747. /** The thread should call this periodically to update the position of the progress bar.
  37748. @param newProgress the progress, from 0.0 to 1.0
  37749. @see setStatusMessage
  37750. */
  37751. void setProgress (const double newProgress);
  37752. /** The thread can call this to change the message that's displayed in the dialog box.
  37753. */
  37754. void setStatusMessage (const String& newStatusMessage);
  37755. juce_UseDebuggingNewOperator
  37756. private:
  37757. void timerCallback();
  37758. double progress;
  37759. AlertWindow alertWindow;
  37760. String message;
  37761. CriticalSection messageLock;
  37762. const int timeOutMsWhenCancelling;
  37763. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  37764. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  37765. };
  37766. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37767. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  37768. #endif
  37769. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  37770. #endif
  37771. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37772. #endif
  37773. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37774. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  37775. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37776. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37777. #if JUCE_WIN32 || DOXYGEN
  37778. /**
  37779. A Windows-specific class that can create and embed an ActiveX control inside
  37780. itself.
  37781. To use it, create one of these, put it in place and make sure it's visible in a
  37782. window, then use createControl() to instantiate an ActiveX control. The control
  37783. will then be moved and resized to follow the movements of this component.
  37784. Of course, since the control is a heavyweight window, it'll obliterate any
  37785. juce components that may overlap this component, but that's life.
  37786. */
  37787. class JUCE_API ActiveXControlComponent : public Component
  37788. {
  37789. public:
  37790. /** Create an initially-empty container. */
  37791. ActiveXControlComponent();
  37792. /** Destructor. */
  37793. ~ActiveXControlComponent();
  37794. /** Tries to create an ActiveX control and embed it in this peer.
  37795. The peer controlIID is a pointer to an IID structure - it's treated
  37796. as a void* because when including the Juce headers, you might not always
  37797. have included windows.h first, in which case IID wouldn't be defined.
  37798. e.g. @code
  37799. const IID myIID = __uuidof (QTControl);
  37800. myControlComp->createControl (&myIID);
  37801. @endcode
  37802. */
  37803. bool createControl (const void* controlIID);
  37804. /** Deletes the ActiveX control, if one has been created.
  37805. */
  37806. void deleteControl();
  37807. /** Returns true if a control is currently in use. */
  37808. bool isControlOpen() const throw() { return control != 0; }
  37809. /** Does a QueryInterface call on the embedded control object.
  37810. This allows you to cast the control to whatever type of COM object you need.
  37811. The iid parameter is a pointer to an IID structure - it's treated
  37812. as a void* because when including the Juce headers, you might not always
  37813. have included windows.h first, in which case IID wouldn't be defined, but
  37814. you should just pass a pointer to an IID.
  37815. e.g. @code
  37816. const IID iid = __uuidof (IOleWindow);
  37817. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  37818. if (oleWindow != 0)
  37819. {
  37820. HWND hwnd;
  37821. oleWindow->GetWindow (&hwnd);
  37822. ...
  37823. oleWindow->Release();
  37824. }
  37825. @endcode
  37826. */
  37827. void* queryInterface (const void* iid) const;
  37828. /** Set this to false to stop mouse events being allowed through to the control.
  37829. */
  37830. void setMouseEventsAllowed (const bool eventsCanReachControl);
  37831. /** Returns true if mouse events are allowed to get through to the control.
  37832. */
  37833. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  37834. /** @internal */
  37835. void paint (Graphics& g);
  37836. /** @internal */
  37837. void* originalWndProc;
  37838. juce_UseDebuggingNewOperator
  37839. private:
  37840. friend class ActiveXControlData;
  37841. void* control;
  37842. bool mouseEventsAllowed;
  37843. ActiveXControlComponent (const ActiveXControlComponent&);
  37844. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  37845. void setControlBounds (const Rectangle& bounds) const;
  37846. void setControlVisible (const bool b) const;
  37847. };
  37848. #endif
  37849. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37850. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  37851. #endif
  37852. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37853. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  37854. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37855. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37856. class MidiInputSelectorComponentListBox;
  37857. /**
  37858. A component containing controls to let the user change the audio settings of
  37859. an AudioDeviceManager object.
  37860. Very easy to use - just create one of these and show it to the user.
  37861. @see AudioDeviceManager
  37862. */
  37863. class JUCE_API AudioDeviceSelectorComponent : public Component,
  37864. public ComboBoxListener,
  37865. public ButtonListener,
  37866. public ChangeListener
  37867. {
  37868. public:
  37869. /** Creates the component.
  37870. If your app needs only output channels, you might ask for a maximum of 0 input
  37871. channels, and the component won't display any options for choosing the input
  37872. channels. And likewise if you're doing an input-only app.
  37873. @param deviceManager the device manager that this component should control
  37874. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  37875. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  37876. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  37877. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  37878. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  37879. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  37880. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  37881. treated as a set of separate mono channels.
  37882. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  37883. are shown, with an "advanced" button that shows the rest of them
  37884. */
  37885. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  37886. const int minAudioInputChannels,
  37887. const int maxAudioInputChannels,
  37888. const int minAudioOutputChannels,
  37889. const int maxAudioOutputChannels,
  37890. const bool showMidiInputOptions,
  37891. const bool showMidiOutputSelector,
  37892. const bool showChannelsAsStereoPairs,
  37893. const bool hideAdvancedOptionsWithButton);
  37894. /** Destructor */
  37895. ~AudioDeviceSelectorComponent();
  37896. /** @internal */
  37897. void resized();
  37898. /** @internal */
  37899. void comboBoxChanged (ComboBox*);
  37900. /** @internal */
  37901. void buttonClicked (Button*);
  37902. /** @internal */
  37903. void changeListenerCallback (void*);
  37904. juce_UseDebuggingNewOperator
  37905. private:
  37906. AudioDeviceManager& deviceManager;
  37907. ComboBox* deviceTypeDropDown;
  37908. Label* deviceTypeDropDownLabel;
  37909. Component* audioDeviceSettingsComp;
  37910. String audioDeviceSettingsCompType;
  37911. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  37912. const bool showChannelsAsStereoPairs;
  37913. const bool hideAdvancedOptionsWithButton;
  37914. MidiInputSelectorComponentListBox* midiInputsList;
  37915. Label* midiInputsLabel;
  37916. ComboBox* midiOutputSelector;
  37917. Label* midiOutputLabel;
  37918. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  37919. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  37920. };
  37921. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37922. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  37923. #endif
  37924. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  37925. /********* Start of inlined file: juce_BubbleComponent.h *********/
  37926. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  37927. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  37928. /**
  37929. A component for showing a message or other graphics inside a speech-bubble-shaped
  37930. outline, pointing at a location on the screen.
  37931. This is a base class that just draws and positions the bubble shape, but leaves
  37932. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  37933. that draws a text message.
  37934. To use it, create your subclass, then either add it to a parent component or
  37935. put it on the desktop with addToDesktop (0), use setPosition() to
  37936. resize and position it, then make it visible.
  37937. @see BubbleMessageComponent
  37938. */
  37939. class JUCE_API BubbleComponent : public Component
  37940. {
  37941. protected:
  37942. /** Creates a BubbleComponent.
  37943. Your subclass will need to implement the getContentSize() and paintContent()
  37944. methods to draw the bubble's contents.
  37945. */
  37946. BubbleComponent();
  37947. public:
  37948. /** Destructor. */
  37949. ~BubbleComponent();
  37950. /** A list of permitted placements for the bubble, relative to the co-ordinates
  37951. at which it should be pointing.
  37952. @see setAllowedPlacement
  37953. */
  37954. enum BubblePlacement
  37955. {
  37956. above = 1,
  37957. below = 2,
  37958. left = 4,
  37959. right = 8
  37960. };
  37961. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  37962. point at which it's pointing.
  37963. By default when setPosition() is called, the bubble will place itself either
  37964. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  37965. the values in BubblePlacement to restrict this choice.
  37966. E.g. if you only want your bubble to appear above or below the target area,
  37967. use setAllowedPlacement (above | below);
  37968. @see BubblePlacement
  37969. */
  37970. void setAllowedPlacement (const int newPlacement);
  37971. /** Moves and resizes the bubble to point at a given component.
  37972. This will resize the bubble to fit its content, then find a position for it
  37973. so that it's next to, but doesn't overlap the given component.
  37974. It'll put itself either above, below, or to the side of the component depending
  37975. on where there's the most space, honouring any restrictions that were set
  37976. with setAllowedPlacement().
  37977. */
  37978. void setPosition (Component* componentToPointTo);
  37979. /** Moves and resizes the bubble to point at a given point.
  37980. This will resize the bubble to fit its content, then position it
  37981. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  37982. are relative to either the bubble component's parent component if it has one, or
  37983. they are screen co-ordinates if not.
  37984. It'll put itself either above, below, or to the side of this point, depending
  37985. on where there's the most space, honouring any restrictions that were set
  37986. with setAllowedPlacement().
  37987. */
  37988. void setPosition (const int arrowTipX,
  37989. const int arrowTipY);
  37990. /** Moves and resizes the bubble to point at a given rectangle.
  37991. This will resize the bubble to fit its content, then find a position for it
  37992. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  37993. co-ordinates are relative to either the bubble component's parent component
  37994. if it has one, or they are screen co-ordinates if not.
  37995. It'll put itself either above, below, or to the side of the component depending
  37996. on where there's the most space, honouring any restrictions that were set
  37997. with setAllowedPlacement().
  37998. */
  37999. void setPosition (const Rectangle& rectangleToPointTo);
  38000. protected:
  38001. /** Subclasses should override this to return the size of the content they
  38002. want to draw inside the bubble.
  38003. */
  38004. virtual void getContentSize (int& width, int& height) = 0;
  38005. /** Subclasses should override this to draw their bubble's contents.
  38006. The graphics object's clip region and the dimensions passed in here are
  38007. set up to paint just the rectangle inside the bubble.
  38008. */
  38009. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38010. public:
  38011. /** @internal */
  38012. void paint (Graphics& g);
  38013. juce_UseDebuggingNewOperator
  38014. private:
  38015. Rectangle content;
  38016. int side, allowablePlacements;
  38017. float arrowTipX, arrowTipY;
  38018. DropShadowEffect shadow;
  38019. BubbleComponent (const BubbleComponent&);
  38020. const BubbleComponent& operator= (const BubbleComponent&);
  38021. };
  38022. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38023. /********* End of inlined file: juce_BubbleComponent.h *********/
  38024. #endif
  38025. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38026. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38027. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38028. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38029. /**
  38030. A speech-bubble component that displays a short message.
  38031. This can be used to show a message with the tail of the speech bubble
  38032. pointing to a particular component or location on the screen.
  38033. @see BubbleComponent
  38034. */
  38035. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38036. private Timer
  38037. {
  38038. public:
  38039. /** Creates a bubble component.
  38040. After creating one a BubbleComponent, do the following:
  38041. - add it to an appropriate parent component, or put it on the
  38042. desktop with Component::addToDesktop (0).
  38043. - use the showAt() method to show a message.
  38044. - it will make itself invisible after it times-out (and can optionally
  38045. also delete itself), or you can reuse it somewhere else by calling
  38046. showAt() again.
  38047. */
  38048. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38049. /** Destructor. */
  38050. ~BubbleMessageComponent();
  38051. /** Shows a message bubble at a particular position.
  38052. This shows the bubble with its stem pointing to the given location
  38053. (co-ordinates being relative to its parent component).
  38054. For details about exactly how it decides where to position itself, see
  38055. BubbleComponent::updatePosition().
  38056. @param x the x co-ordinate of end of the bubble's tail
  38057. @param y the y co-ordinate of end of the bubble's tail
  38058. @param message the text to display
  38059. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38060. from its parent compnent. If this is 0 or less, it
  38061. will stay there until manually removed.
  38062. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38063. mouse button is pressed (anywhere on the screen)
  38064. @param deleteSelfAfterUse if true, then the component will delete itself after
  38065. it becomes invisible
  38066. */
  38067. void showAt (int x, int y,
  38068. const String& message,
  38069. const int numMillisecondsBeforeRemoving,
  38070. const bool removeWhenMouseClicked = true,
  38071. const bool deleteSelfAfterUse = false);
  38072. /** Shows a message bubble next to a particular component.
  38073. This shows the bubble with its stem pointing at the given component.
  38074. For details about exactly how it decides where to position itself, see
  38075. BubbleComponent::updatePosition().
  38076. @param component the component that you want to point at
  38077. @param message the text to display
  38078. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38079. from its parent compnent. If this is 0 or less, it
  38080. will stay there until manually removed.
  38081. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38082. mouse button is pressed (anywhere on the screen)
  38083. @param deleteSelfAfterUse if true, then the component will delete itself after
  38084. it becomes invisible
  38085. */
  38086. void showAt (Component* const component,
  38087. const String& message,
  38088. const int numMillisecondsBeforeRemoving,
  38089. const bool removeWhenMouseClicked = true,
  38090. const bool deleteSelfAfterUse = false);
  38091. /** @internal */
  38092. void getContentSize (int& w, int& h);
  38093. /** @internal */
  38094. void paintContent (Graphics& g, int w, int h);
  38095. /** @internal */
  38096. void timerCallback();
  38097. juce_UseDebuggingNewOperator
  38098. private:
  38099. int fadeOutLength, mouseClickCounter;
  38100. TextLayout textLayout;
  38101. int64 expiryTime;
  38102. bool deleteAfterUse;
  38103. void init (const int numMillisecondsBeforeRemoving,
  38104. const bool removeWhenMouseClicked,
  38105. const bool deleteSelfAfterUse);
  38106. BubbleMessageComponent (const BubbleMessageComponent&);
  38107. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38108. };
  38109. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38110. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38111. #endif
  38112. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38113. /********* Start of inlined file: juce_ColourSelector.h *********/
  38114. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38115. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38116. /**
  38117. A component that lets the user choose a colour.
  38118. This shows RGB sliders and a colourspace that the user can pick colours from.
  38119. This class is also a ChangeBroadcaster, so listeners can register to be told
  38120. when the colour changes.
  38121. */
  38122. class JUCE_API ColourSelector : public Component,
  38123. public ChangeBroadcaster,
  38124. protected SliderListener
  38125. {
  38126. public:
  38127. /** Options for the type of selector to show. These are passed into the constructor. */
  38128. enum ColourSelectorOptions
  38129. {
  38130. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38131. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38132. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38133. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38134. };
  38135. /** Creates a ColourSelector object.
  38136. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38137. which of the selector's features should be visible.
  38138. The edgeGap value specifies the amount of space to leave around the edge.
  38139. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38140. colourspace and hue selector components.
  38141. */
  38142. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38143. const int edgeGap = 4,
  38144. const int gapAroundColourSpaceComponent = 7);
  38145. /** Destructor. */
  38146. ~ColourSelector();
  38147. /** Returns the colour that the user has currently selected.
  38148. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38149. register to be told when the colour changes.
  38150. @see setCurrentColour
  38151. */
  38152. const Colour getCurrentColour() const;
  38153. /** Changes the colour that is currently being shown.
  38154. */
  38155. void setCurrentColour (const Colour& newColour);
  38156. /** Tells the selector how many preset colour swatches you want to have on the component.
  38157. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38158. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38159. their values.
  38160. */
  38161. virtual int getNumSwatches() const;
  38162. /** Called by the selector to find out the colour of one of the swatches.
  38163. Your subclass should return the colour of the swatch with the given index.
  38164. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38165. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38166. their values.
  38167. */
  38168. virtual const Colour getSwatchColour (const int index) const;
  38169. /** Called by the selector when the user puts a new colour into one of the swatches.
  38170. Your subclass should change the colour of the swatch with the given index.
  38171. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38172. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38173. their values.
  38174. */
  38175. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38176. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38177. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38178. methods.
  38179. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38180. */
  38181. enum ColourIds
  38182. {
  38183. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38184. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38185. };
  38186. juce_UseDebuggingNewOperator
  38187. private:
  38188. friend class ColourSpaceView;
  38189. friend class HueSelectorComp;
  38190. Colour colour;
  38191. float h, s, v;
  38192. Slider* sliders[4];
  38193. Component* colourSpace;
  38194. Component* hueSelector;
  38195. VoidArray swatchComponents;
  38196. const int flags;
  38197. int topSpace, edgeGap;
  38198. void setHue (float newH);
  38199. void setSV (float newS, float newV);
  38200. void updateHSV();
  38201. void update();
  38202. void sliderValueChanged (Slider*);
  38203. void paint (Graphics& g);
  38204. void resized();
  38205. ColourSelector (const ColourSelector&);
  38206. const ColourSelector& operator= (const ColourSelector&);
  38207. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38208. // have changed - if you get an error here, update your code to use the new constructor instead..
  38209. // (xxx - note to self: remember to remove this at some point in the future)
  38210. ColourSelector (const bool);
  38211. };
  38212. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38213. /********* End of inlined file: juce_ColourSelector.h *********/
  38214. #endif
  38215. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  38216. #endif
  38217. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38218. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  38219. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38220. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38221. /**
  38222. A component that contains another component, and can magnify or shrink it.
  38223. This component will continually update its size so that it fits the zoomed
  38224. version of the content component that you put inside it, so don't try to
  38225. change the size of this component directly - instead change that of the
  38226. content component.
  38227. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  38228. to remap mouse events correctly. This means that the content component won't
  38229. appear to be a direct child of this component, and instead will think its
  38230. on the desktop.
  38231. */
  38232. class JUCE_API MagnifierComponent : public Component
  38233. {
  38234. public:
  38235. /** Creates a MagnifierComponent.
  38236. This component will continually update its size so that it fits the zoomed
  38237. version of the content component that you put inside it, so don't try to
  38238. change the size of this component directly - instead change that of the
  38239. content component.
  38240. @param contentComponent the component to add as the magnified one
  38241. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  38242. be deleted when this component is deleted. If false,
  38243. it's the caller's responsibility to delete it later.
  38244. */
  38245. MagnifierComponent (Component* const contentComponent,
  38246. const bool deleteContentCompWhenNoLongerNeeded);
  38247. /** Destructor. */
  38248. ~MagnifierComponent();
  38249. /** Returns the current content component. */
  38250. Component* getContentComponent() const throw() { return content; }
  38251. /** Changes the zoom level.
  38252. The scale factor must be greater than zero. Values less than 1 will shrink the
  38253. image; values greater than 1 will multiply its size by this amount.
  38254. When this is called, this component will change its size to fit the full extent
  38255. of the newly zoomed content.
  38256. */
  38257. void setScaleFactor (double newScaleFactor);
  38258. /** Returns the current zoom factor. */
  38259. double getScaleFactor() const throw() { return scaleFactor; }
  38260. juce_UseDebuggingNewOperator
  38261. /** @internal */
  38262. void childBoundsChanged (Component*);
  38263. private:
  38264. Component* content;
  38265. Component* holderComp;
  38266. double scaleFactor;
  38267. ComponentPeer* peer;
  38268. bool deleteContent;
  38269. void paint (Graphics& g);
  38270. void mouseDown (const MouseEvent& e);
  38271. void mouseUp (const MouseEvent& e);
  38272. void mouseDrag (const MouseEvent& e);
  38273. void mouseMove (const MouseEvent& e);
  38274. void mouseEnter (const MouseEvent& e);
  38275. void mouseExit (const MouseEvent& e);
  38276. void mouseWheelMove (const MouseEvent& e, float, float);
  38277. int scaleInt (const int n) const throw();
  38278. MagnifierComponent (const MagnifierComponent&);
  38279. const MagnifierComponent& operator= (const MagnifierComponent&);
  38280. };
  38281. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38282. /********* End of inlined file: juce_MagnifierComponent.h *********/
  38283. #endif
  38284. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38285. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  38286. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38287. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38288. /**
  38289. A component that displays a piano keyboard, whose notes can be clicked on.
  38290. This component will mimic a physical midi keyboard, showing the current state of
  38291. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  38292. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  38293. Another feature is that the computer keyboard can also be used to play notes. By
  38294. default it maps the top two rows of a standard querty keyboard to the notes, but
  38295. these can be remapped if needed. It will only respond to keypresses when it has
  38296. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  38297. The component is also a ChangeBroadcaster, so if you want to be informed when the
  38298. keyboard is scrolled, you can register a ChangeListener for callbacks.
  38299. @see MidiKeyboardState
  38300. */
  38301. class JUCE_API MidiKeyboardComponent : public Component,
  38302. public MidiKeyboardStateListener,
  38303. public ChangeBroadcaster,
  38304. private Timer,
  38305. private AsyncUpdater
  38306. {
  38307. public:
  38308. /** The direction of the keyboard.
  38309. @see setOrientation
  38310. */
  38311. enum Orientation
  38312. {
  38313. horizontalKeyboard,
  38314. verticalKeyboardFacingLeft,
  38315. verticalKeyboardFacingRight,
  38316. };
  38317. /** Creates a MidiKeyboardComponent.
  38318. @param state the midi keyboard model that this component will represent
  38319. @param orientation whether the keyboard is horizonal or vertical
  38320. */
  38321. MidiKeyboardComponent (MidiKeyboardState& state,
  38322. const Orientation orientation);
  38323. /** Destructor. */
  38324. ~MidiKeyboardComponent();
  38325. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  38326. on the component.
  38327. Values are 0 to 1.0, where 1.0 is the heaviest.
  38328. @see setMidiChannel
  38329. */
  38330. void setVelocity (const float velocity);
  38331. /** Changes the midi channel number that will be used for events triggered by clicking
  38332. on the component.
  38333. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  38334. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  38335. Although this is the channel used for outgoing events, the component can display
  38336. incoming events from more than one channel - see setMidiChannelsToDisplay()
  38337. @see setVelocity
  38338. */
  38339. void setMidiChannel (const int midiChannelNumber);
  38340. /** Returns the midi channel that the keyboard is using for midi messages.
  38341. @see setMidiChannel
  38342. */
  38343. int getMidiChannel() const throw() { return midiChannel; }
  38344. /** Sets a mask to indicate which incoming midi channels should be represented by
  38345. key movements.
  38346. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  38347. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  38348. in this mask, the on-screen keys will also go down.
  38349. By default, this mask is set to 0xffff (all channels displayed).
  38350. @see setMidiChannel
  38351. */
  38352. void setMidiChannelsToDisplay (const int midiChannelMask);
  38353. /** Returns the current set of midi channels represented by the component.
  38354. This is the value that was set with setMidiChannelsToDisplay().
  38355. */
  38356. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  38357. /** Changes the width used to draw the white keys. */
  38358. void setKeyWidth (const float widthInPixels);
  38359. /** Returns the width that was set by setKeyWidth(). */
  38360. float getKeyWidth() const throw() { return keyWidth; }
  38361. /** Changes the keyboard's current direction. */
  38362. void setOrientation (const Orientation newOrientation);
  38363. /** Returns the keyboard's current direction. */
  38364. const Orientation getOrientation() const throw() { return orientation; }
  38365. /** Sets the range of midi notes that the keyboard will be limited to.
  38366. By default the range is 0 to 127 (inclusive), but you can limit this if you
  38367. only want a restricted set of the keys to be shown.
  38368. Note that the values here are inclusive and must be between 0 and 127.
  38369. */
  38370. void setAvailableRange (const int lowestNote,
  38371. const int highestNote);
  38372. /** Returns the first note in the available range.
  38373. @see setAvailableRange
  38374. */
  38375. int getRangeStart() const throw() { return rangeStart; }
  38376. /** Returns the last note in the available range.
  38377. @see setAvailableRange
  38378. */
  38379. int getRangeEnd() const throw() { return rangeEnd; }
  38380. /** If the keyboard extends beyond the size of the component, this will scroll
  38381. it to show the given key at the start.
  38382. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  38383. base class to send a callback to any ChangeListeners that have been registered.
  38384. */
  38385. void setLowestVisibleKey (int noteNumber);
  38386. /** Returns the number of the first key shown in the component.
  38387. @see setLowestVisibleKey
  38388. */
  38389. int getLowestVisibleKey() const throw() { return firstKey; }
  38390. /** If set to true, then scroll buttons will appear at either end of the keyboard
  38391. if there are too many notes to fit them all in the component at once.
  38392. */
  38393. void setScrollButtonsVisible (const bool canScroll);
  38394. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38395. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38396. methods.
  38397. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38398. */
  38399. enum ColourIds
  38400. {
  38401. whiteNoteColourId = 0x1005000,
  38402. blackNoteColourId = 0x1005001,
  38403. keySeparatorLineColourId = 0x1005002,
  38404. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  38405. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  38406. textLabelColourId = 0x1005005,
  38407. upDownButtonBackgroundColourId = 0x1005006,
  38408. upDownButtonArrowColourId = 0x1005007
  38409. };
  38410. /** Returns the position within the component of the left-hand edge of a key.
  38411. Depending on the keyboard's orientation, this may be a horizontal or vertical
  38412. distance, in either direction.
  38413. */
  38414. int getKeyStartPosition (const int midiNoteNumber) const;
  38415. /** Deletes all key-mappings.
  38416. @see setKeyPressForNote
  38417. */
  38418. void clearKeyMappings();
  38419. /** Maps a key-press to a given note.
  38420. @param key the key that should trigger the note
  38421. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  38422. be. The actual midi note that gets played will be
  38423. this value + (12 * the current base octave). To change
  38424. the base octave, see setKeyPressBaseOctave()
  38425. */
  38426. void setKeyPressForNote (const KeyPress& key,
  38427. const int midiNoteOffsetFromC);
  38428. /** Removes any key-mappings for a given note.
  38429. For a description of what the note number means, see setKeyPressForNote().
  38430. */
  38431. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  38432. /** Changes the base note above which key-press-triggered notes are played.
  38433. The set of key-mappings that trigger notes can be moved up and down to cover
  38434. the entire scale using this method.
  38435. The value passed in is an octave number between 0 and 10 (inclusive), and
  38436. indicates which C is the base note to which the key-mapped notes are
  38437. relative.
  38438. */
  38439. void setKeyPressBaseOctave (const int newOctaveNumber);
  38440. /** This sets the octave number which is shown as the octave number for middle C.
  38441. This affects only the default implementation of getWhiteNoteText(), which
  38442. passes this octave number to MidiMessage::getMidiNoteName() in order to
  38443. get the note text. See MidiMessage::getMidiNoteName() for more info about
  38444. the parameter.
  38445. By default this value is set to 3.
  38446. @see getOctaveForMiddleC
  38447. */
  38448. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  38449. /** This returns the value set by setOctaveForMiddleC().
  38450. @see setOctaveForMiddleC
  38451. */
  38452. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  38453. /** @internal */
  38454. void paint (Graphics& g);
  38455. /** @internal */
  38456. void resized();
  38457. /** @internal */
  38458. void mouseMove (const MouseEvent& e);
  38459. /** @internal */
  38460. void mouseDrag (const MouseEvent& e);
  38461. /** @internal */
  38462. void mouseDown (const MouseEvent& e);
  38463. /** @internal */
  38464. void mouseUp (const MouseEvent& e);
  38465. /** @internal */
  38466. void mouseEnter (const MouseEvent& e);
  38467. /** @internal */
  38468. void mouseExit (const MouseEvent& e);
  38469. /** @internal */
  38470. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38471. /** @internal */
  38472. void timerCallback();
  38473. /** @internal */
  38474. bool keyStateChanged();
  38475. /** @internal */
  38476. void focusLost (FocusChangeType cause);
  38477. /** @internal */
  38478. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  38479. /** @internal */
  38480. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  38481. /** @internal */
  38482. void handleAsyncUpdate();
  38483. /** @internal */
  38484. void colourChanged();
  38485. juce_UseDebuggingNewOperator
  38486. protected:
  38487. friend class MidiKeyboardUpDownButton;
  38488. /** Draws a white note in the given rectangle.
  38489. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38490. currently pressed down.
  38491. When doing this, be sure to note the keyboard's orientation.
  38492. */
  38493. virtual void drawWhiteNote (int midiNoteNumber,
  38494. Graphics& g,
  38495. int x, int y, int w, int h,
  38496. bool isDown, bool isOver,
  38497. const Colour& lineColour,
  38498. const Colour& textColour);
  38499. /** Draws a black note in the given rectangle.
  38500. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38501. currently pressed down.
  38502. When doing this, be sure to note the keyboard's orientation.
  38503. */
  38504. virtual void drawBlackNote (int midiNoteNumber,
  38505. Graphics& g,
  38506. int x, int y, int w, int h,
  38507. bool isDown, bool isOver,
  38508. const Colour& noteFillColour);
  38509. /** Allows text to be drawn on the white notes.
  38510. By default this is used to label the C in each octave, but could be used for other things.
  38511. @see setOctaveForMiddleC
  38512. */
  38513. virtual const String getWhiteNoteText (const int midiNoteNumber);
  38514. /** Draws the up and down buttons that change the base note. */
  38515. virtual void drawUpDownButton (Graphics& g, int w, int h,
  38516. const bool isMouseOver,
  38517. const bool isButtonPressed,
  38518. const bool movesOctavesUp);
  38519. /** Callback when the mouse is clicked on a key.
  38520. You could use this to do things like handle right-clicks on keys, etc.
  38521. Return true if you want the click to trigger the note, or false if you
  38522. want to handle it yourself and not have the note played.
  38523. @see mouseDraggedToKey
  38524. */
  38525. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  38526. /** Callback when the mouse is dragged from one key onto another.
  38527. @see mouseDownOnKey
  38528. */
  38529. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  38530. /** Calculates the positon of a given midi-note.
  38531. This can be overridden to create layouts with custom key-widths.
  38532. @param midiNoteNumber the note to find
  38533. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  38534. @param x the x position of the left-hand edge of the key (this method
  38535. always works in terms of a horizontal keyboard)
  38536. @param w the width of the key
  38537. */
  38538. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  38539. int& x, int& w) const;
  38540. private:
  38541. MidiKeyboardState& state;
  38542. int xOffset, blackNoteLength;
  38543. float keyWidth;
  38544. Orientation orientation;
  38545. int midiChannel, midiInChannelMask;
  38546. float velocity;
  38547. int noteUnderMouse, mouseDownNote;
  38548. BitArray keysPressed, keysCurrentlyDrawnDown;
  38549. int rangeStart, rangeEnd, firstKey;
  38550. bool canScroll, mouseDragging;
  38551. Button* scrollDown;
  38552. Button* scrollUp;
  38553. Array <KeyPress> keyPresses;
  38554. Array <int> keyPressNotes;
  38555. int keyMappingOctave;
  38556. int octaveNumForMiddleC;
  38557. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  38558. int xyToNote (int x, int y);
  38559. int remappedXYToNote (int x, int y) const;
  38560. void resetAnyKeysInUse();
  38561. void updateNoteUnderMouse (int x, int y);
  38562. void repaintNote (const int midiNoteNumber);
  38563. MidiKeyboardComponent (const MidiKeyboardComponent&);
  38564. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  38565. };
  38566. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38567. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  38568. #endif
  38569. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38570. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  38571. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38572. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38573. // this is used to disable OpenGL, and is defined in juce_Config.h
  38574. #if JUCE_OPENGL || DOXYGEN
  38575. class OpenGLComponentWatcher;
  38576. /**
  38577. Represents the various properties of an OpenGL bitmap format.
  38578. @see OpenGLComponent::setPixelFormat
  38579. */
  38580. struct OpenGLPixelFormat
  38581. {
  38582. /** Creates an OpenGLPixelFormat.
  38583. The default constructor just initialises the object as a simple 8-bit
  38584. RGBA format.
  38585. */
  38586. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  38587. const int alphaBits = 8,
  38588. const int depthBufferBits = 16,
  38589. const int stencilBufferBits = 0) throw();
  38590. int redBits; /**< The number of bits per pixel to use for the red channel. */
  38591. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  38592. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  38593. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  38594. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  38595. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  38596. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  38597. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  38598. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  38599. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  38600. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  38601. /** Returns a list of all the pixel formats that can be used in this system.
  38602. A reference component is needed in case there are multiple screens with different
  38603. capabilities - in which case, the one that the component is on will be used.
  38604. */
  38605. static void getAvailablePixelFormats (Component* component,
  38606. OwnedArray <OpenGLPixelFormat>& results);
  38607. bool operator== (const OpenGLPixelFormat&) const throw();
  38608. juce_UseDebuggingNewOperator
  38609. };
  38610. /**
  38611. A base class for types of OpenGL context.
  38612. An OpenGLComponent will supply its own context for drawing in its window.
  38613. */
  38614. class OpenGLContext
  38615. {
  38616. public:
  38617. /** Destructor. */
  38618. virtual ~OpenGLContext();
  38619. /** Makes this context the currently active one. */
  38620. virtual bool makeActive() const throw() = 0;
  38621. /** If this context is currently active, it is disactivated. */
  38622. virtual bool makeInactive() const throw() = 0;
  38623. /** Returns true if this context is currently active. */
  38624. virtual bool isActive() const throw() = 0;
  38625. /** Swaps the buffers (if the context can do this). */
  38626. virtual void swapBuffers() = 0;
  38627. /** Sets whether the context checks the vertical sync before swapping.
  38628. The value is the number of frames to allow between buffer-swapping. This is
  38629. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  38630. and greater numbers indicate that it should swap less often.
  38631. Returns true if it sets the value successfully.
  38632. */
  38633. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  38634. /** Returns the current swap-sync interval.
  38635. See setSwapInterval() for info about the value returned.
  38636. */
  38637. virtual int getSwapInterval() const = 0;
  38638. /** Returns the pixel format being used by this context. */
  38639. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  38640. /** For windowed contexts, this moves the context within the bounds of
  38641. its parent window.
  38642. */
  38643. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  38644. /** For windowed contexts, this triggers a repaint of the window.
  38645. (Not relevent on all platforms).
  38646. */
  38647. virtual void repaint() = 0;
  38648. /** Returns an OS-dependent handle to the raw GL context.
  38649. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  38650. a GLXContext.
  38651. */
  38652. virtual void* getRawContext() const throw() = 0;
  38653. /** This tries to create a context that can be used for drawing into the
  38654. area occupied by the specified component.
  38655. Note that you probably shouldn't use this method directly unless you know what
  38656. you're doing - the OpenGLComponent calls this and manages the context for you.
  38657. */
  38658. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  38659. const OpenGLPixelFormat& pixelFormat,
  38660. const OpenGLContext* const contextToShareWith);
  38661. /** Returns the context that's currently in active use by the calling thread.
  38662. Returns 0 if there isn't an active context.
  38663. */
  38664. static OpenGLContext* getCurrentContext();
  38665. juce_UseDebuggingNewOperator
  38666. protected:
  38667. OpenGLContext() throw();
  38668. };
  38669. /**
  38670. A component that contains an OpenGL canvas.
  38671. Override this, add it to whatever component you want to, and use the renderOpenGL()
  38672. method to draw its contents.
  38673. */
  38674. class JUCE_API OpenGLComponent : public Component
  38675. {
  38676. public:
  38677. /** Creates an OpenGLComponent.
  38678. */
  38679. OpenGLComponent();
  38680. /** Destructor. */
  38681. ~OpenGLComponent();
  38682. /** Changes the pixel format used by this component.
  38683. @see OpenGLPixelFormat::getAvailablePixelFormats()
  38684. */
  38685. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  38686. /** Returns the pixel format that this component is currently using. */
  38687. const OpenGLPixelFormat getPixelFormat() const;
  38688. /** Specifies an OpenGL context which should be shared with the one that this
  38689. component is using.
  38690. This is an OpenGL feature that lets two contexts share their texture data.
  38691. Note that this pointer is stored by the component, and when the component
  38692. needs to recreate its internal context for some reason, the same context
  38693. will be used again to share lists. So if you pass a context in here,
  38694. don't delete the context while this component is still using it! You can
  38695. call shareWith (0) to stop this component from sharing with it.
  38696. */
  38697. void shareWith (OpenGLContext* contextToShareListsWith);
  38698. /** Returns the context that this component is sharing with.
  38699. @see shareWith
  38700. */
  38701. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  38702. /** Flips the openGL buffers over. */
  38703. void swapBuffers();
  38704. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  38705. When this is called, makeCurrentContextActive() will already have been called
  38706. for you, so you just need to draw.
  38707. */
  38708. virtual void renderOpenGL() = 0;
  38709. /** This method is called when the component creates a new OpenGL context.
  38710. A new context may be created when the component is first used, or when it
  38711. is moved to a different window, or when the window is hidden and re-shown,
  38712. etc.
  38713. You can use this callback as an opportunity to set up things like textures
  38714. that your context needs.
  38715. New contexts are created on-demand by the makeCurrentContextActive() method - so
  38716. if the context is deleted, e.g. by changing the pixel format or window, no context
  38717. will be created until the next call to makeCurrentContextActive(), which will
  38718. synchronously create one and call this method. This means that if you're using
  38719. a non-GUI thread for rendering, you can make sure this method is be called by
  38720. your renderer thread.
  38721. When this callback happens, the context will already have been made current
  38722. using the makeCurrentContextActive() method, so there's no need to call it
  38723. again in your code.
  38724. */
  38725. virtual void newOpenGLContextCreated() = 0;
  38726. /** Returns the context that will draw into this component.
  38727. This may return 0 if the component is currently invisible or hasn't currently
  38728. got a context. The context object can be deleted and a new one created during
  38729. the lifetime of this component, and there may be times when it doesn't have one.
  38730. @see newOpenGLContextCreated()
  38731. */
  38732. OpenGLContext* getCurrentContext() const throw() { return context; }
  38733. /** Makes this component the current openGL context.
  38734. You might want to use this in things like your resize() method, before calling
  38735. GL commands.
  38736. If this returns false, then the context isn't active, so you should avoid
  38737. making any calls.
  38738. This call may actually create a context if one isn't currently initialised. If
  38739. it does this, it will also synchronously call the newOpenGLContextCreated()
  38740. method to let you initialise it as necessary.
  38741. @see OpenGLContext::makeActive
  38742. */
  38743. bool makeCurrentContextActive();
  38744. /** Stops the current component being the active OpenGL context.
  38745. This is the opposite of makeCurrentContextActive()
  38746. @see OpenGLContext::makeInactive
  38747. */
  38748. void makeCurrentContextInactive();
  38749. /** Returns true if this component is the active openGL context for the
  38750. current thread.
  38751. @see OpenGLContext::isActive
  38752. */
  38753. bool isActiveContext() const throw();
  38754. /** Calls the rendering callback, and swaps the buffers afterwards.
  38755. This is called automatically by paint() when the component needs to be rendered.
  38756. It can be overridden if you need to decouple the rendering from the paint callback
  38757. and render with a custom thread.
  38758. Returns true if the operation succeeded.
  38759. */
  38760. virtual bool renderAndSwapBuffers();
  38761. /** This returns a critical section that can be used to lock the current context.
  38762. Because the context that is used by this component can change, e.g. when the
  38763. component is shown or hidden, then if you're rendering to it on a background
  38764. thread, this allows you to lock the context for the duration of your rendering
  38765. routine.
  38766. */
  38767. CriticalSection& getContextLock() throw() { return contextLock; }
  38768. /** @internal */
  38769. void paint (Graphics& g);
  38770. /** Returns the native handle of an embedded heavyweight window, if there is one.
  38771. E.g. On windows, this will return the HWND of the sub-window containing
  38772. the opengl context, on the mac it'll be the NSOpenGLView.
  38773. */
  38774. void* getNativeWindowHandle() const;
  38775. juce_UseDebuggingNewOperator
  38776. private:
  38777. friend class OpenGLComponentWatcher;
  38778. OpenGLComponentWatcher* componentWatcher;
  38779. OpenGLContext* context;
  38780. OpenGLContext* contextToShareListsWith;
  38781. CriticalSection contextLock;
  38782. OpenGLPixelFormat preferredPixelFormat;
  38783. bool needToUpdateViewport;
  38784. void deleteContext();
  38785. void updateContextPosition();
  38786. void internalRepaint (int x, int y, int w, int h);
  38787. OpenGLComponent (const OpenGLComponent&);
  38788. const OpenGLComponent& operator= (const OpenGLComponent&);
  38789. };
  38790. #endif
  38791. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38792. /********* End of inlined file: juce_OpenGLComponent.h *********/
  38793. #endif
  38794. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38795. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  38796. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38797. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38798. /**
  38799. A component with a set of buttons at the top for changing between pages of
  38800. preferences.
  38801. This is just a handy way of writing a Mac-style preferences panel where you
  38802. have a row of buttons along the top for the different preference categories,
  38803. each button having an icon above its name. Clicking these will show an
  38804. appropriate prefs page below it.
  38805. You can either put one of these inside your own component, or just use the
  38806. showInDialogBox() method to show it in a window and run it modally.
  38807. To use it, just add a set of named pages with the addSettingsPage() method,
  38808. and implement the createComponentForPage() method to create suitable components
  38809. for each of these pages.
  38810. */
  38811. class JUCE_API PreferencesPanel : public Component,
  38812. private ButtonListener
  38813. {
  38814. public:
  38815. /** Creates an empty panel.
  38816. Use addSettingsPage() to add some pages to it in your constructor.
  38817. */
  38818. PreferencesPanel();
  38819. /** Destructor. */
  38820. ~PreferencesPanel();
  38821. /** Creates a page using a set of drawables to define the page's icon.
  38822. Note that the other version of this method is much easier if you're using
  38823. an image instead of a custom drawable.
  38824. @param pageTitle the name of this preferences page - you'll need to
  38825. make sure your createComponentForPage() method creates
  38826. a suitable component when it is passed this name
  38827. @param normalIcon the drawable to display in the page's button normally
  38828. @param overIcon the drawable to display in the page's button when the mouse is over
  38829. @param downIcon the drawable to display in the page's button when the button is down
  38830. @see DrawableButton
  38831. */
  38832. void addSettingsPage (const String& pageTitle,
  38833. const Drawable* normalIcon,
  38834. const Drawable* overIcon,
  38835. const Drawable* downIcon);
  38836. /** Creates a page using a set of drawables to define the page's icon.
  38837. The other version of this method gives you more control over the icon, but this
  38838. one is much easier if you're just loading it from a file.
  38839. @param pageTitle the name of this preferences page - you'll need to
  38840. make sure your createComponentForPage() method creates
  38841. a suitable component when it is passed this name
  38842. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  38843. For this to look good, you'll probably want to use a nice
  38844. transparent png file.
  38845. @param imageDataSize the size of the image data, in bytes
  38846. */
  38847. void addSettingsPage (const String& pageTitle,
  38848. const char* imageData,
  38849. const int imageDataSize);
  38850. /** Utility method to display this panel in a DialogWindow.
  38851. Calling this will create a DialogWindow containing this panel with the
  38852. given size and title, and will run it modally, returning when the user
  38853. closes the dialog box.
  38854. */
  38855. void showInDialogBox (const String& dialogtitle,
  38856. int dialogWidth,
  38857. int dialogHeight,
  38858. const Colour& backgroundColour = Colours::white);
  38859. /** Subclasses must override this to return a component for each preferences page.
  38860. The subclass should return a pointer to a new component representing the named
  38861. page, which the panel will then display.
  38862. The panel will delete the component later when the user goes to another page
  38863. or deletes the panel.
  38864. */
  38865. virtual Component* createComponentForPage (const String& pageName) = 0;
  38866. /** Changes the current page being displayed. */
  38867. void setCurrentPage (const String& pageName);
  38868. /** @internal */
  38869. void resized();
  38870. /** @internal */
  38871. void paint (Graphics& g);
  38872. /** @internal */
  38873. void buttonClicked (Button* button);
  38874. juce_UseDebuggingNewOperator
  38875. private:
  38876. String currentPageName;
  38877. Component* currentPage;
  38878. int buttonSize;
  38879. PreferencesPanel (const PreferencesPanel&);
  38880. const PreferencesPanel& operator= (const PreferencesPanel&);
  38881. };
  38882. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38883. /********* End of inlined file: juce_PreferencesPanel.h *********/
  38884. #endif
  38885. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  38886. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  38887. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  38888. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  38889. // this is used to disable QuickTime, and is defined in juce_Config.h
  38890. #if JUCE_QUICKTIME || DOXYGEN
  38891. #if JUCE_WIN32
  38892. typedef ActiveXControlComponent QTCompBaseClass;
  38893. #else
  38894. /********* Start of inlined file: juce_NSViewComponent.h *********/
  38895. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38896. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38897. #if ! DOXYGEN
  38898. class NSViewComponentInternal;
  38899. #endif
  38900. #if JUCE_MAC || DOXYGEN
  38901. /**
  38902. A Mac-specific class that can create and embed an NSView inside itself.
  38903. To use it, create one of these, put it in place and make sure it's visible in a
  38904. window, then use setView() to assign an NSView to it. The view will then be
  38905. moved and resized to follow the movements of this component.
  38906. Of course, since the view is a native object, it'll obliterate any
  38907. juce components that may overlap this component, but that's life.
  38908. */
  38909. class JUCE_API NSViewComponent : public Component
  38910. {
  38911. public:
  38912. /** Create an initially-empty container. */
  38913. NSViewComponent();
  38914. /** Destructor. */
  38915. ~NSViewComponent();
  38916. /** Assigns an NSView to this peer.
  38917. The view will be retained and released by this component for as long as
  38918. it is needed. To remove the current view, just call setView (0).
  38919. Note: a void* is used here to avoid including the cocoa headers as
  38920. part of the juce.h, but the method expects an NSView*.
  38921. */
  38922. void setView (void* nsView);
  38923. /** Returns the current NSView.
  38924. Note: a void* is returned here to avoid including the cocoa headers as
  38925. a requirement of juce.h, so you should just cast the object to an NSView*.
  38926. */
  38927. void* getView() const;
  38928. /** @internal */
  38929. void paint (Graphics& g);
  38930. juce_UseDebuggingNewOperator
  38931. private:
  38932. friend class NSViewComponentInternal;
  38933. NSViewComponentInternal* info;
  38934. NSViewComponent (const NSViewComponent&);
  38935. const NSViewComponent& operator= (const NSViewComponent&);
  38936. };
  38937. #endif
  38938. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38939. /********* End of inlined file: juce_NSViewComponent.h *********/
  38940. typedef NSViewComponent QTCompBaseClass;
  38941. #endif
  38942. /**
  38943. A window that can play back a QuickTime movie.
  38944. */
  38945. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  38946. {
  38947. public:
  38948. /** Creates a QuickTimeMovieComponent, initially blank.
  38949. Use the loadMovie() method to load a movie once you've added the
  38950. component to a window, (or put it on the desktop as a heavyweight window).
  38951. Loading a movie when the component isn't visible can cause problems, as
  38952. QuickTime needs a window handle to initialise properly.
  38953. */
  38954. QuickTimeMovieComponent();
  38955. /** Destructor. */
  38956. ~QuickTimeMovieComponent();
  38957. /** Returns true if QT is installed and working on this machine.
  38958. */
  38959. static bool isQuickTimeAvailable() throw();
  38960. /** Tries to load a QuickTime movie into the player.
  38961. It's best to call this function once you've added the component to a window,
  38962. (or put it on the desktop as a heavyweight window). Loading a movie when the
  38963. component isn't visible can cause problems, because QuickTime needs a window
  38964. handle to do its stuff.
  38965. @param movieFile the .mov file to open
  38966. @param isControllerVisible whether to show a controller bar at the bottom
  38967. @returns true if the movie opens successfully
  38968. */
  38969. bool loadMovie (const File& movieFile,
  38970. const bool isControllerVisible);
  38971. bool loadMovie (InputStream* movieStream,
  38972. const bool isControllerVisible);
  38973. /** Closes the movie, if one is open. */
  38974. void closeMovie();
  38975. /** Returns the movie file that is currently open.
  38976. If there isn't one, this returns File::nonexistent
  38977. */
  38978. const File getCurrentMovieFile() const;
  38979. /** Returns true if there's currently a movie open. */
  38980. bool isMovieOpen() const;
  38981. /** Returns the length of the movie, in seconds. */
  38982. double getMovieDuration() const;
  38983. /** Returns the movie's natural size, in pixels.
  38984. You can use this to resize the component to show the movie at its preferred
  38985. scale.
  38986. If no movie is loaded, the size returned will be 0 x 0.
  38987. */
  38988. void getMovieNormalSize (int& width, int& height) const;
  38989. /** This will position the component within a given area, keeping its aspect
  38990. ratio correct according to the movie's normal size.
  38991. The component will be made as large as it can go within the space, and will
  38992. be aligned according to the justification value if this means there are gaps at
  38993. the top or sides.
  38994. */
  38995. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  38996. const RectanglePlacement& placement);
  38997. /** Starts the movie playing. */
  38998. void play();
  38999. /** Stops the movie playing. */
  39000. void stop();
  39001. /** Returns true if the movie is currently playing. */
  39002. bool isPlaying() const;
  39003. /** Moves the movie's position back to the start. */
  39004. void goToStart();
  39005. /** Sets the movie's position to a given time. */
  39006. void setPosition (const double seconds);
  39007. /** Returns the current play position of the movie. */
  39008. double getPosition() const;
  39009. /** Changes the movie playback rate.
  39010. A value of 1 is normal speed, greater values play it proportionately faster,
  39011. smaller values play it slower.
  39012. */
  39013. void setSpeed (const float newSpeed);
  39014. /** Changes the movie's playback volume.
  39015. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39016. */
  39017. void setMovieVolume (const float newVolume);
  39018. /** Returns the movie's playback volume.
  39019. @returns the volume in the range 0 (silent) to 1.0 (full)
  39020. */
  39021. float getMovieVolume() const;
  39022. /** Tells the movie whether it should loop. */
  39023. void setLooping (const bool shouldLoop);
  39024. /** Returns true if the movie is currently looping.
  39025. @see setLooping
  39026. */
  39027. bool isLooping() const;
  39028. /** True if the native QuickTime controller bar is shown in the window.
  39029. @see loadMovie
  39030. */
  39031. bool isControllerVisible() const;
  39032. /** @internal */
  39033. void paint (Graphics& g);
  39034. juce_UseDebuggingNewOperator
  39035. private:
  39036. File movieFile;
  39037. bool movieLoaded, controllerVisible, looping;
  39038. #if JUCE_WIN32
  39039. /** @internal */
  39040. void parentHierarchyChanged();
  39041. /** @internal */
  39042. void visibilityChanged();
  39043. void createControlIfNeeded();
  39044. bool isControlCreated() const;
  39045. void* internal;
  39046. #else
  39047. void* movie;
  39048. #endif
  39049. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39050. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39051. };
  39052. #endif
  39053. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39054. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39055. #endif
  39056. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39057. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  39058. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39059. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39060. #if JUCE_WIN32 || JUCE_LINUX
  39061. /**
  39062. On Windows only, this component sits in the taskbar tray as a small icon.
  39063. To use it, just create one of these components, but don't attempt to make it
  39064. visible, add it to a parent, or put it on the desktop.
  39065. You can then call setIconImage() to create an icon for it in the taskbar.
  39066. To change the icon's tooltip, you can use setIconTooltip().
  39067. To respond to mouse-events, you can override the normal mouseDown(),
  39068. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  39069. position will not be valid, you can use this to respond to clicks. Traditionally
  39070. you'd use a left-click to show your application's window, and a right-click
  39071. to show a pop-up menu.
  39072. */
  39073. class JUCE_API SystemTrayIconComponent : public Component
  39074. {
  39075. public:
  39076. SystemTrayIconComponent();
  39077. /** Destructor. */
  39078. ~SystemTrayIconComponent();
  39079. /** Changes the image shown in the taskbar.
  39080. */
  39081. void setIconImage (const Image& newImage);
  39082. /** Changes the tooltip that Windows shows above the icon. */
  39083. void setIconTooltip (const String& tooltip);
  39084. #if JUCE_LINUX
  39085. /** @internal */
  39086. void paint (Graphics& g);
  39087. #endif
  39088. juce_UseDebuggingNewOperator
  39089. private:
  39090. SystemTrayIconComponent (const SystemTrayIconComponent&);
  39091. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  39092. };
  39093. #endif
  39094. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39095. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  39096. #endif
  39097. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39098. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  39099. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39100. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39101. #if JUCE_WEB_BROWSER
  39102. class WebBrowserComponentInternal;
  39103. /**
  39104. A component that displays an embedded web browser.
  39105. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  39106. Windows, probably IE.
  39107. */
  39108. class WebBrowserComponent : public Component
  39109. {
  39110. public:
  39111. /** Creates a WebBrowserComponent.
  39112. Once it's created and visible, send the browser to a URL using goToURL().
  39113. */
  39114. WebBrowserComponent();
  39115. /** Destructor. */
  39116. ~WebBrowserComponent();
  39117. /** Sends the browser to a particular URL.
  39118. @param url the URL to go to.
  39119. @param headers an optional set of parameters to put in the HTTP header. If
  39120. you supply this, it should be a set of string in the form
  39121. "HeaderKey: HeaderValue"
  39122. @param postData an optional block of data that will be attached to the HTTP
  39123. POST request
  39124. */
  39125. void goToURL (const String& url,
  39126. const StringArray* headers = 0,
  39127. const MemoryBlock* postData = 0);
  39128. /** Stops the current page loading.
  39129. */
  39130. void stop();
  39131. /** Sends the browser back one page.
  39132. */
  39133. void goBack();
  39134. /** Sends the browser forward one page.
  39135. */
  39136. void goForward();
  39137. /** This callback is called when the browser is about to navigate
  39138. to a new location.
  39139. You can override this method to perform some action when the user
  39140. tries to go to a particular URL. To allow the operation to carry on,
  39141. return true, or return false to stop the navigation happening.
  39142. */
  39143. virtual bool pageAboutToLoad (const String& newURL);
  39144. /** @internal */
  39145. void paint (Graphics& g);
  39146. /** @internal */
  39147. void resized();
  39148. /** @internal */
  39149. void parentHierarchyChanged();
  39150. /** @internal */
  39151. void visibilityChanged();
  39152. juce_UseDebuggingNewOperator
  39153. private:
  39154. WebBrowserComponentInternal* browser;
  39155. bool blankPageShown;
  39156. String lastURL;
  39157. StringArray lastHeaders;
  39158. MemoryBlock lastPostData;
  39159. void reloadLastURL();
  39160. void checkWindowAssociation();
  39161. WebBrowserComponent (const WebBrowserComponent&);
  39162. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  39163. };
  39164. #endif
  39165. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39166. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  39167. #endif
  39168. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39169. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39170. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39171. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39172. class ToggleButton;
  39173. class TextButton;
  39174. class AlertWindow;
  39175. class TextLayout;
  39176. class ScrollBar;
  39177. class BubbleComponent;
  39178. class ComboBox;
  39179. class Button;
  39180. class FilenameComponent;
  39181. class DocumentWindow;
  39182. class ResizableWindow;
  39183. class GroupComponent;
  39184. class MenuBarComponent;
  39185. class DropShadower;
  39186. class GlyphArrangement;
  39187. class PropertyComponent;
  39188. class TableHeaderComponent;
  39189. class Toolbar;
  39190. class ToolbarItemComponent;
  39191. class PopupMenu;
  39192. class ProgressBar;
  39193. class FileBrowserComponent;
  39194. class DirectoryContentsDisplayComponent;
  39195. class FilePreviewComponent;
  39196. /**
  39197. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39198. can be used to apply different 'skins' to the application.
  39199. */
  39200. class JUCE_API LookAndFeel
  39201. {
  39202. public:
  39203. /** Creates the default JUCE look and feel. */
  39204. LookAndFeel();
  39205. /** Destructor. */
  39206. virtual ~LookAndFeel();
  39207. /** Returns the current default look-and-feel for a component to use when it
  39208. hasn't got one explicitly set.
  39209. @see setDefaultLookAndFeel
  39210. */
  39211. static LookAndFeel& getDefaultLookAndFeel() throw();
  39212. /** Changes the default look-and-feel.
  39213. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39214. set to 0, it will revert to using the default one. The
  39215. object passed-in must be deleted by the caller when
  39216. it's no longer needed.
  39217. @see getDefaultLookAndFeel
  39218. */
  39219. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39220. /** Looks for a colour that has been registered with the given colour ID number.
  39221. If a colour has been set for this ID number using setColour(), then it is
  39222. returned. If none has been set, it will just return Colours::black.
  39223. The colour IDs for various purposes are stored as enums in the components that
  39224. they are relevent to - for an example, see Slider::ColourIds,
  39225. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39226. If you're looking up a colour for use in drawing a component, it's usually
  39227. best not to call this directly, but to use the Component::findColour() method
  39228. instead. That will first check whether a suitable colour has been registered
  39229. directly with the component, and will fall-back on calling the component's
  39230. LookAndFeel's findColour() method if none is found.
  39231. @see setColour, Component::findColour, Component::setColour
  39232. */
  39233. const Colour findColour (const int colourId) const throw();
  39234. /** Registers a colour to be used for a particular purpose.
  39235. For more details, see the comments for findColour().
  39236. @see findColour, Component::findColour, Component::setColour
  39237. */
  39238. void setColour (const int colourId, const Colour& colour) throw();
  39239. /** Draws the lozenge-shaped background for a standard button. */
  39240. virtual void drawButtonBackground (Graphics& g,
  39241. Button& button,
  39242. const Colour& backgroundColour,
  39243. bool isMouseOverButton,
  39244. bool isButtonDown);
  39245. /** Draws the text for a TextButton. */
  39246. virtual void drawButtonText (Graphics& g,
  39247. TextButton& button,
  39248. bool isMouseOverButton,
  39249. bool isButtonDown);
  39250. /** Draws the contents of a standard ToggleButton. */
  39251. virtual void drawToggleButton (Graphics& g,
  39252. ToggleButton& button,
  39253. bool isMouseOverButton,
  39254. bool isButtonDown);
  39255. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39256. virtual void drawTickBox (Graphics& g,
  39257. Component& component,
  39258. int x, int y, int w, int h,
  39259. const bool ticked,
  39260. const bool isEnabled,
  39261. const bool isMouseOverButton,
  39262. const bool isButtonDown);
  39263. /** Draws the contents of a message box.
  39264. */
  39265. virtual void drawAlertBox (Graphics& g,
  39266. AlertWindow& alert,
  39267. const Rectangle& textArea,
  39268. TextLayout& textLayout);
  39269. virtual int getAlertBoxWindowFlags();
  39270. virtual int getAlertWindowButtonHeight();
  39271. virtual const Font getAlertWindowFont();
  39272. /** Draws a progress bar.
  39273. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39274. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39275. isn't known). It can use the current time as a basis for playing an animation.
  39276. (Used by progress bars in AlertWindow).
  39277. */
  39278. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39279. int width, int height,
  39280. double progress, const String& textToShow);
  39281. /** Draws one of the buttons on a scrollbar.
  39282. @param g the context to draw into
  39283. @param scrollbar the bar itself
  39284. @param width the width of the button
  39285. @param height the height of the button
  39286. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39287. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39288. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39289. @param isButtonDown whether the mouse button's held down
  39290. */
  39291. virtual void drawScrollbarButton (Graphics& g,
  39292. ScrollBar& scrollbar,
  39293. int width, int height,
  39294. int buttonDirection,
  39295. bool isScrollbarVertical,
  39296. bool isMouseOverButton,
  39297. bool isButtonDown);
  39298. /** Draws the thumb area of a scrollbar.
  39299. @param g the context to draw into
  39300. @param scrollbar the bar itself
  39301. @param x the x position of the left edge of the thumb area to draw in
  39302. @param y the y position of the top edge of the thumb area to draw in
  39303. @param width the width of the thumb area to draw in
  39304. @param height the height of the thumb area to draw in
  39305. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39306. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39307. thumb, or its x position for horizontal bars
  39308. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39309. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39310. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39311. currently dragging the thumb
  39312. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39313. */
  39314. virtual void drawScrollbar (Graphics& g,
  39315. ScrollBar& scrollbar,
  39316. int x, int y,
  39317. int width, int height,
  39318. bool isScrollbarVertical,
  39319. int thumbStartPosition,
  39320. int thumbSize,
  39321. bool isMouseOver,
  39322. bool isMouseDown);
  39323. /** Returns the component effect to use for a scrollbar */
  39324. virtual ImageEffectFilter* getScrollbarEffect();
  39325. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39326. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39327. /** Returns the default thickness to use for a scrollbar. */
  39328. virtual int getDefaultScrollbarWidth();
  39329. /** Returns the length in pixels to use for a scrollbar button. */
  39330. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39331. /** Returns a tick shape for use in yes/no boxes, etc. */
  39332. virtual const Path getTickShape (const float height);
  39333. /** Returns a cross shape for use in yes/no boxes, etc. */
  39334. virtual const Path getCrossShape (const float height);
  39335. /** Draws the + or - box in a treeview. */
  39336. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus);
  39337. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39338. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39339. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39340. virtual Image* getDefaultFolderImage();
  39341. virtual Image* getDefaultDocumentFileImage();
  39342. virtual void createFileChooserHeaderText (const String& title,
  39343. const String& instructions,
  39344. GlyphArrangement& destArrangement,
  39345. int width);
  39346. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39347. const String& filename, Image* icon,
  39348. const String& fileSizeDescription,
  39349. const String& fileTimeDescription,
  39350. const bool isDirectory,
  39351. const bool isItemSelected,
  39352. const int itemIndex);
  39353. virtual Button* createFileBrowserGoUpButton();
  39354. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39355. DirectoryContentsDisplayComponent* fileListComponent,
  39356. FilePreviewComponent* previewComp,
  39357. ComboBox* currentPathBox,
  39358. TextEditor* filenameBox,
  39359. Button* goUpButton);
  39360. virtual void drawBubble (Graphics& g,
  39361. float tipX, float tipY,
  39362. float boxX, float boxY, float boxW, float boxH);
  39363. /** Fills the background of a popup menu component. */
  39364. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39365. /** Draws one of the items in a popup menu. */
  39366. virtual void drawPopupMenuItem (Graphics& g,
  39367. int width, int height,
  39368. const bool isSeparator,
  39369. const bool isActive,
  39370. const bool isHighlighted,
  39371. const bool isTicked,
  39372. const bool hasSubMenu,
  39373. const String& text,
  39374. const String& shortcutKeyText,
  39375. Image* image,
  39376. const Colour* const textColour);
  39377. /** Returns the size and style of font to use in popup menus. */
  39378. virtual const Font getPopupMenuFont();
  39379. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  39380. int width, int height,
  39381. bool isScrollUpArrow);
  39382. /** Finds the best size for an item in a popup menu. */
  39383. virtual void getIdealPopupMenuItemSize (const String& text,
  39384. const bool isSeparator,
  39385. int standardMenuItemHeight,
  39386. int& idealWidth,
  39387. int& idealHeight);
  39388. virtual int getMenuWindowFlags();
  39389. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39390. bool isMouseOverBar,
  39391. MenuBarComponent& menuBar);
  39392. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39393. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39394. virtual void drawMenuBarItem (Graphics& g,
  39395. int width, int height,
  39396. int itemIndex,
  39397. const String& itemText,
  39398. bool isMouseOverItem,
  39399. bool isMenuOpen,
  39400. bool isMouseOverBar,
  39401. MenuBarComponent& menuBar);
  39402. virtual void drawComboBox (Graphics& g, int width, int height,
  39403. const bool isButtonDown,
  39404. int buttonX, int buttonY,
  39405. int buttonW, int buttonH,
  39406. ComboBox& box);
  39407. virtual const Font getComboBoxFont (ComboBox& box);
  39408. virtual Label* createComboBoxTextBox (ComboBox& box);
  39409. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  39410. virtual void drawLabel (Graphics& g, Label& label);
  39411. virtual void drawLinearSlider (Graphics& g,
  39412. int x, int y,
  39413. int width, int height,
  39414. float sliderPos,
  39415. float minSliderPos,
  39416. float maxSliderPos,
  39417. const Slider::SliderStyle style,
  39418. Slider& slider);
  39419. virtual void drawLinearSliderBackground (Graphics& g,
  39420. int x, int y,
  39421. int width, int height,
  39422. float sliderPos,
  39423. float minSliderPos,
  39424. float maxSliderPos,
  39425. const Slider::SliderStyle style,
  39426. Slider& slider);
  39427. virtual void drawLinearSliderThumb (Graphics& g,
  39428. int x, int y,
  39429. int width, int height,
  39430. float sliderPos,
  39431. float minSliderPos,
  39432. float maxSliderPos,
  39433. const Slider::SliderStyle style,
  39434. Slider& slider);
  39435. virtual int getSliderThumbRadius (Slider& slider);
  39436. virtual void drawRotarySlider (Graphics& g,
  39437. int x, int y,
  39438. int width, int height,
  39439. float sliderPosProportional,
  39440. const float rotaryStartAngle,
  39441. const float rotaryEndAngle,
  39442. Slider& slider);
  39443. virtual Button* createSliderButton (const bool isIncrement);
  39444. virtual Label* createSliderTextBox (Slider& slider);
  39445. virtual ImageEffectFilter* getSliderEffect();
  39446. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  39447. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  39448. virtual Button* createFilenameComponentBrowseButton (const String& text);
  39449. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  39450. ComboBox* filenameBox, Button* browseButton);
  39451. virtual void drawCornerResizer (Graphics& g,
  39452. int w, int h,
  39453. bool isMouseOver,
  39454. bool isMouseDragging);
  39455. virtual void drawResizableFrame (Graphics& g,
  39456. int w, int h,
  39457. const BorderSize& borders);
  39458. virtual void drawResizableWindowBorder (Graphics& g,
  39459. int w, int h,
  39460. const BorderSize& border,
  39461. ResizableWindow& window);
  39462. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  39463. Graphics& g, int w, int h,
  39464. int titleSpaceX, int titleSpaceW,
  39465. const Image* icon,
  39466. bool drawTitleTextOnLeft);
  39467. virtual Button* createDocumentWindowButton (int buttonType);
  39468. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39469. int titleBarX, int titleBarY,
  39470. int titleBarW, int titleBarH,
  39471. Button* minimiseButton,
  39472. Button* maximiseButton,
  39473. Button* closeButton,
  39474. bool positionTitleBarButtonsOnLeft);
  39475. virtual int getDefaultMenuBarHeight();
  39476. virtual DropShadower* createDropShadowerForComponent (Component* component);
  39477. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  39478. int w, int h,
  39479. bool isVerticalBar,
  39480. bool isMouseOver,
  39481. bool isMouseDragging);
  39482. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  39483. const String& text,
  39484. const Justification& position,
  39485. GroupComponent& group);
  39486. virtual void createTabButtonShape (Path& p,
  39487. int width, int height,
  39488. int tabIndex,
  39489. const String& text,
  39490. Button& button,
  39491. TabbedButtonBar::Orientation orientation,
  39492. const bool isMouseOver,
  39493. const bool isMouseDown,
  39494. const bool isFrontTab);
  39495. virtual void fillTabButtonShape (Graphics& g,
  39496. const Path& path,
  39497. const Colour& preferredBackgroundColour,
  39498. int tabIndex,
  39499. const String& text,
  39500. Button& button,
  39501. TabbedButtonBar::Orientation orientation,
  39502. const bool isMouseOver,
  39503. const bool isMouseDown,
  39504. const bool isFrontTab);
  39505. virtual void drawTabButtonText (Graphics& g,
  39506. int x, int y, int w, int h,
  39507. const Colour& preferredBackgroundColour,
  39508. int tabIndex,
  39509. const String& text,
  39510. Button& button,
  39511. TabbedButtonBar::Orientation orientation,
  39512. const bool isMouseOver,
  39513. const bool isMouseDown,
  39514. const bool isFrontTab);
  39515. virtual int getTabButtonOverlap (int tabDepth);
  39516. virtual int getTabButtonSpaceAroundImage();
  39517. virtual int getTabButtonBestWidth (int tabIndex,
  39518. const String& text,
  39519. int tabDepth,
  39520. Button& button);
  39521. virtual void drawTabButton (Graphics& g,
  39522. int w, int h,
  39523. const Colour& preferredColour,
  39524. int tabIndex,
  39525. const String& text,
  39526. Button& button,
  39527. TabbedButtonBar::Orientation orientation,
  39528. const bool isMouseOver,
  39529. const bool isMouseDown,
  39530. const bool isFrontTab);
  39531. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  39532. int w, int h,
  39533. TabbedButtonBar& tabBar,
  39534. TabbedButtonBar::Orientation orientation);
  39535. virtual Button* createTabBarExtrasButton();
  39536. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  39537. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  39538. int width, int height,
  39539. bool isMouseOver, bool isMouseDown,
  39540. int columnFlags);
  39541. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  39542. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  39543. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  39544. bool isMouseOver, bool isMouseDown,
  39545. ToolbarItemComponent& component);
  39546. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  39547. const String& text, ToolbarItemComponent& component);
  39548. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  39549. bool isOpen, int width, int height);
  39550. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  39551. PropertyComponent& component);
  39552. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  39553. PropertyComponent& component);
  39554. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  39555. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  39556. /**
  39557. */
  39558. virtual void playAlertSound();
  39559. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  39560. static void drawGlassSphere (Graphics& g,
  39561. const float x, const float y,
  39562. const float diameter,
  39563. const Colour& colour,
  39564. const float outlineThickness) throw();
  39565. static void drawGlassPointer (Graphics& g,
  39566. const float x, const float y,
  39567. const float diameter,
  39568. const Colour& colour, const float outlineThickness,
  39569. const int direction) throw();
  39570. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  39571. static void drawGlassLozenge (Graphics& g,
  39572. const float x, const float y,
  39573. const float width, const float height,
  39574. const Colour& colour,
  39575. const float outlineThickness,
  39576. const float cornerSize,
  39577. const bool flatOnLeft, const bool flatOnRight,
  39578. const bool flatOnTop, const bool flatOnBottom) throw();
  39579. juce_UseDebuggingNewOperator
  39580. protected:
  39581. // xxx the following methods are only here to cause a compiler error, because they've been
  39582. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  39583. // error if you try to build a subclass with the old versions.
  39584. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  39585. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  39586. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  39587. virtual void getTabButtonBestWidth (int, const String&, int) {}
  39588. private:
  39589. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  39590. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  39591. Array <int> colourIds;
  39592. Array <Colour> colours;
  39593. void drawShinyButtonShape (Graphics& g,
  39594. float x, float y, float w, float h, float maxCornerSize,
  39595. const Colour& baseColour,
  39596. const float strokeWidth,
  39597. const bool flatOnLeft,
  39598. const bool flatOnRight,
  39599. const bool flatOnTop,
  39600. const bool flatOnBottom) throw();
  39601. LookAndFeel (const LookAndFeel&);
  39602. const LookAndFeel& operator= (const LookAndFeel&);
  39603. };
  39604. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  39605. /********* End of inlined file: juce_LookAndFeel.h *********/
  39606. #endif
  39607. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39608. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39609. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39610. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39611. /**
  39612. The original Juce look-and-feel.
  39613. */
  39614. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  39615. {
  39616. public:
  39617. /** Creates the default JUCE look and feel. */
  39618. OldSchoolLookAndFeel();
  39619. /** Destructor. */
  39620. virtual ~OldSchoolLookAndFeel();
  39621. /** Draws the lozenge-shaped background for a standard button. */
  39622. virtual void drawButtonBackground (Graphics& g,
  39623. Button& button,
  39624. const Colour& backgroundColour,
  39625. bool isMouseOverButton,
  39626. bool isButtonDown);
  39627. /** Draws the contents of a standard ToggleButton. */
  39628. virtual void drawToggleButton (Graphics& g,
  39629. ToggleButton& button,
  39630. bool isMouseOverButton,
  39631. bool isButtonDown);
  39632. virtual void drawTickBox (Graphics& g,
  39633. Component& component,
  39634. int x, int y, int w, int h,
  39635. const bool ticked,
  39636. const bool isEnabled,
  39637. const bool isMouseOverButton,
  39638. const bool isButtonDown);
  39639. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39640. int width, int height,
  39641. double progress, const String& textToShow);
  39642. virtual void drawScrollbarButton (Graphics& g,
  39643. ScrollBar& scrollbar,
  39644. int width, int height,
  39645. int buttonDirection,
  39646. bool isScrollbarVertical,
  39647. bool isMouseOverButton,
  39648. bool isButtonDown);
  39649. virtual void drawScrollbar (Graphics& g,
  39650. ScrollBar& scrollbar,
  39651. int x, int y,
  39652. int width, int height,
  39653. bool isScrollbarVertical,
  39654. int thumbStartPosition,
  39655. int thumbSize,
  39656. bool isMouseOver,
  39657. bool isMouseDown);
  39658. virtual ImageEffectFilter* getScrollbarEffect();
  39659. virtual void drawTextEditorOutline (Graphics& g,
  39660. int width, int height,
  39661. TextEditor& textEditor);
  39662. /** Fills the background of a popup menu component. */
  39663. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39664. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39665. bool isMouseOverBar,
  39666. MenuBarComponent& menuBar);
  39667. virtual void drawComboBox (Graphics& g, int width, int height,
  39668. const bool isButtonDown,
  39669. int buttonX, int buttonY,
  39670. int buttonW, int buttonH,
  39671. ComboBox& box);
  39672. virtual const Font getComboBoxFont (ComboBox& box);
  39673. virtual void drawLinearSlider (Graphics& g,
  39674. int x, int y,
  39675. int width, int height,
  39676. float sliderPos,
  39677. float minSliderPos,
  39678. float maxSliderPos,
  39679. const Slider::SliderStyle style,
  39680. Slider& slider);
  39681. virtual int getSliderThumbRadius (Slider& slider);
  39682. virtual Button* createSliderButton (const bool isIncrement);
  39683. virtual ImageEffectFilter* getSliderEffect();
  39684. virtual void drawCornerResizer (Graphics& g,
  39685. int w, int h,
  39686. bool isMouseOver,
  39687. bool isMouseDragging);
  39688. virtual Button* createDocumentWindowButton (int buttonType);
  39689. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39690. int titleBarX, int titleBarY,
  39691. int titleBarW, int titleBarH,
  39692. Button* minimiseButton,
  39693. Button* maximiseButton,
  39694. Button* closeButton,
  39695. bool positionTitleBarButtonsOnLeft);
  39696. juce_UseDebuggingNewOperator
  39697. private:
  39698. DropShadowEffect scrollbarShadow;
  39699. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  39700. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  39701. };
  39702. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39703. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39704. #endif
  39705. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39706. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  39707. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39708. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39709. /**
  39710. A class to take care of the logic involved with the loading/saving of some kind
  39711. of document.
  39712. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  39713. functions you need for documents that get saved to a file, so this class attempts
  39714. to abstract most of the boring stuff.
  39715. Your subclass should just implement all the pure virtual methods, and you can
  39716. then use the higher-level public methods to do the load/save dialogs, to warn the user
  39717. about overwriting files, etc.
  39718. The document object keeps track of whether it has changed since it was last saved or
  39719. loaded, so when you change something, call its changed() method. This will set a
  39720. flag so it knows it needs saving, and will also broadcast a change message using the
  39721. ChangeBroadcaster base class.
  39722. @see ChangeBroadcaster
  39723. */
  39724. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  39725. {
  39726. public:
  39727. /** Creates a FileBasedDocument.
  39728. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  39729. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  39730. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  39731. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  39732. */
  39733. FileBasedDocument (const String& fileExtension,
  39734. const String& fileWildCard,
  39735. const String& openFileDialogTitle,
  39736. const String& saveFileDialogTitle);
  39737. /** Destructor. */
  39738. virtual ~FileBasedDocument();
  39739. /** Returns true if the changed() method has been called since the file was
  39740. last saved or loaded.
  39741. @see resetChangedFlag, changed
  39742. */
  39743. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  39744. /** Called to indicate that the document has changed and needs saving.
  39745. This method will also trigger a change message to be sent out using the
  39746. ChangeBroadcaster base class.
  39747. After calling the method, the hasChangedSinceSaved() method will return true, until
  39748. it is reset either by saving to a file or using the resetChangedFlag() method.
  39749. @see hasChangedSinceSaved, resetChangedFlag
  39750. */
  39751. virtual void changed();
  39752. /** Sets the state of the 'changed' flag.
  39753. The 'changed' flag is set to true when the changed() method is called - use this method
  39754. to reset it or to set it without also broadcasting a change message.
  39755. @see changed, hasChangedSinceSaved
  39756. */
  39757. void setChangedFlag (const bool hasChanged);
  39758. /** Tries to open a file.
  39759. If the file opens correctly, the document's file (see the getFile() method) is set
  39760. to this new one; if it fails, the document's file is left unchanged, and optionally
  39761. a message box is shown telling the user there was an error.
  39762. @returns true if the new file loaded successfully
  39763. @see loadDocument, loadFromUserSpecifiedFile
  39764. */
  39765. bool loadFrom (const File& fileToLoadFrom,
  39766. const bool showMessageOnFailure);
  39767. /** Asks the user for a file and tries to load it.
  39768. This will pop up a dialog box using the title, file extension and
  39769. wildcard specified in the document's constructor, and asks the user
  39770. for a file. If they pick one, the loadFrom() method is used to
  39771. try to load it, optionally showing a message if it fails.
  39772. @returns true if a file was loaded; false if the user cancelled or if they
  39773. picked a file which failed to load correctly
  39774. @see loadFrom
  39775. */
  39776. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  39777. /** A set of possible outcomes of one of the save() methods
  39778. */
  39779. enum SaveResult
  39780. {
  39781. savedOk = 0, /**< indicates that a file was saved successfully. */
  39782. userCancelledSave, /**< indicates that the user aborted the save operation. */
  39783. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  39784. };
  39785. /** Tries to save the document to the last file it was saved or loaded from.
  39786. This will always try to write to the file, even if the document isn't flagged as
  39787. having changed.
  39788. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  39789. true, it will prompt the user to pick a file, as if
  39790. saveAsInteractive() was called.
  39791. @param showMessageOnFailure if true it will show a warning message when if the
  39792. save operation fails
  39793. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  39794. */
  39795. SaveResult save (const bool askUserForFileIfNotSpecified,
  39796. const bool showMessageOnFailure);
  39797. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  39798. it if they say yes.
  39799. If you've got a document open and want to close it (e.g. to quit the app), this is the
  39800. method to call.
  39801. If the document doesn't need saving it'll return the value savedOk so
  39802. you can go ahead and delete the document.
  39803. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  39804. return savedOk, so again, you can safely delete the document.
  39805. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  39806. close-document operation.
  39807. And if they click "save changes", it'll try to save and either return savedOk, or
  39808. failedToWriteToFile if there was a problem.
  39809. @see save, saveAs, saveAsInteractive
  39810. */
  39811. SaveResult saveIfNeededAndUserAgrees();
  39812. /** Tries to save the document to a specified file.
  39813. If this succeeds, it'll also change the document's internal file (as returned by
  39814. the getFile() method). If it fails, the file will be left unchanged.
  39815. @param newFile the file to try to write to
  39816. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39817. the user first if they want to overwrite it
  39818. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  39819. use the saveAsInteractive() method to ask the user for a
  39820. filename
  39821. @param showMessageOnFailure if true and the write operation fails, it'll show
  39822. a message box to warn the user
  39823. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  39824. */
  39825. SaveResult saveAs (const File& newFile,
  39826. const bool warnAboutOverwritingExistingFiles,
  39827. const bool askUserForFileIfNotSpecified,
  39828. const bool showMessageOnFailure);
  39829. /** Prompts the user for a filename and tries to save to it.
  39830. This will pop up a dialog box using the title, file extension and
  39831. wildcard specified in the document's constructor, and asks the user
  39832. for a file. If they pick one, the saveAs() method is used to try to save
  39833. to this file.
  39834. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39835. the user first if they want to overwrite it
  39836. @see saveIfNeededAndUserAgrees, save, saveAs
  39837. */
  39838. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  39839. /** Returns the file that this document was last successfully saved or loaded from.
  39840. When the document object is created, this will be set to File::nonexistent.
  39841. It is changed when one of the load or save methods is used, or when setFile()
  39842. is used to explicitly set it.
  39843. */
  39844. const File getFile() const throw() { return documentFile; }
  39845. /** Sets the file that this document thinks it was loaded from.
  39846. This won't actually load anything - it just changes the file stored internally.
  39847. @see getFile
  39848. */
  39849. void setFile (const File& newFile);
  39850. protected:
  39851. /** Overload this to return the title of the document.
  39852. This is used in message boxes, filenames and file choosers, so it should be
  39853. something sensible.
  39854. */
  39855. virtual const String getDocumentTitle() = 0;
  39856. /** This method should try to load your document from the given file.
  39857. If it fails, it should return an error message. If it succeeds, it should return
  39858. an empty string.
  39859. */
  39860. virtual const String loadDocument (const File& file) = 0;
  39861. /** This method should try to write your document to the given file.
  39862. If it fails, it should return an error message. If it succeeds, it should return
  39863. an empty string.
  39864. */
  39865. virtual const String saveDocument (const File& file) = 0;
  39866. /** This is used for dialog boxes to make them open at the last folder you
  39867. were using.
  39868. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39869. the last document that was used - you might want to store this value
  39870. in a static variable, or even in your application's properties. It should
  39871. be a global setting rather than a property of this object.
  39872. This method works very well in conjunction with a RecentlyOpenedFilesList
  39873. object to manage your recent-files list.
  39874. As a default value, it's ok to return File::nonexistent, and the document
  39875. object will use a sensible one instead.
  39876. @see RecentlyOpenedFilesList
  39877. */
  39878. virtual const File getLastDocumentOpened() = 0;
  39879. /** This is used for dialog boxes to make them open at the last folder you
  39880. were using.
  39881. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39882. the last document that was used - you might want to store this value
  39883. in a static variable, or even in your application's properties. It should
  39884. be a global setting rather than a property of this object.
  39885. This method works very well in conjunction with a RecentlyOpenedFilesList
  39886. object to manage your recent-files list.
  39887. @see RecentlyOpenedFilesList
  39888. */
  39889. virtual void setLastDocumentOpened (const File& file) = 0;
  39890. public:
  39891. juce_UseDebuggingNewOperator
  39892. private:
  39893. File documentFile;
  39894. bool changedSinceSave;
  39895. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  39896. FileBasedDocument (const FileBasedDocument&);
  39897. const FileBasedDocument& operator= (const FileBasedDocument&);
  39898. };
  39899. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39900. /********* End of inlined file: juce_FileBasedDocument.h *********/
  39901. #endif
  39902. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39903. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  39904. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39905. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39906. /**
  39907. Manages a set of files for use as a list of recently-opened documents.
  39908. This is a handy class for holding your list of recently-opened documents, with
  39909. helpful methods for things like purging any non-existent files, automatically
  39910. adding them to a menu, and making persistence easy.
  39911. @see File, FileBasedDocument
  39912. */
  39913. class JUCE_API RecentlyOpenedFilesList
  39914. {
  39915. public:
  39916. /** Creates an empty list.
  39917. */
  39918. RecentlyOpenedFilesList();
  39919. /** Destructor. */
  39920. ~RecentlyOpenedFilesList();
  39921. /** Sets a limit for the number of files that will be stored in the list.
  39922. When addFile() is called, then if there is no more space in the list, the
  39923. least-recently added file will be dropped.
  39924. @see getMaxNumberOfItems
  39925. */
  39926. void setMaxNumberOfItems (const int newMaxNumber);
  39927. /** Returns the number of items that this list will store.
  39928. @see setMaxNumberOfItems
  39929. */
  39930. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  39931. /** Returns the number of files in the list.
  39932. The most recently added file is always at index 0.
  39933. */
  39934. int getNumFiles() const;
  39935. /** Returns one of the files in the list.
  39936. The most recently added file is always at index 0.
  39937. */
  39938. const File getFile (const int index) const;
  39939. /** Returns an array of all the absolute pathnames in the list.
  39940. */
  39941. const StringArray& getAllFilenames() const throw() { return files; }
  39942. /** Clears all the files from the list. */
  39943. void clear();
  39944. /** Adds a file to the list.
  39945. The file will be added at index 0. If this file is already in the list, it will
  39946. be moved up to index 0, but a file can only appear once in the list.
  39947. If the list already contains the maximum number of items that is permitted, the
  39948. least-recently added file will be dropped from the end.
  39949. */
  39950. void addFile (const File& file);
  39951. /** Checks each of the files in the list, removing any that don't exist.
  39952. You might want to call this after reloading a list of files, or before putting them
  39953. on a menu.
  39954. */
  39955. void removeNonExistentFiles();
  39956. /** Adds entries to a menu, representing each of the files in the list.
  39957. This is handy for creating an "open recent file..." menu in your app. The
  39958. menu items are numbered consecutively starting with the baseItemId value,
  39959. and can either be added as complete pathnames, or just the last part of the
  39960. filename.
  39961. If dontAddNonExistentFiles is true, then each file will be checked and only those
  39962. that exist will be added.
  39963. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  39964. pointers to file objects. Any files that appear in this list will not be added to the
  39965. menu - the reason for this is that you might have a number of files already open, so
  39966. might not want these to be shown in the menu.
  39967. It returns the number of items that were added.
  39968. */
  39969. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  39970. const int baseItemId,
  39971. const bool showFullPaths,
  39972. const bool dontAddNonExistentFiles,
  39973. const File** filesToAvoid = 0);
  39974. /** Returns a string that encapsulates all the files in the list.
  39975. The string that is returned can later be passed into restoreFromString() in
  39976. order to recreate the list. This is handy for persisting your list, e.g. in
  39977. a PropertiesFile object.
  39978. @see restoreFromString
  39979. */
  39980. const String toString() const;
  39981. /** Restores the list from a previously stringified version of the list.
  39982. Pass in a stringified version created with toString() in order to persist/restore
  39983. your list.
  39984. @see toString
  39985. */
  39986. void restoreFromString (const String& stringifiedVersion);
  39987. juce_UseDebuggingNewOperator
  39988. private:
  39989. StringArray files;
  39990. int maxNumberOfItems;
  39991. };
  39992. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39993. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  39994. #endif
  39995. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  39996. #endif
  39997. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  39998. #endif
  39999. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40000. #endif
  40001. #endif // __JUCE_APP_INCLUDES_JUCEHEADER__
  40002. /********* End of inlined file: juce_app_includes.h *********/
  40003. #endif
  40004. #if JUCE_MSVC
  40005. #pragma warning (pop)
  40006. #pragma pack (pop)
  40007. #endif
  40008. #if JUCE_MAC
  40009. #pragma align=reset
  40010. #endif
  40011. END_JUCE_NAMESPACE
  40012. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40013. #ifdef JUCE_NAMESPACE
  40014. // this will obviously save a lot of typing, but can be disabled by
  40015. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40016. using namespace JUCE_NAMESPACE;
  40017. /* On the Mac, these symbols are defined in the Mac libraries, so
  40018. these macros make it easier to reference them without writing out
  40019. the namespace every time.
  40020. If you run into difficulties where these macros interfere with the contents
  40021. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40022. the comments in that file for more information.
  40023. */
  40024. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40025. #define Component JUCE_NAMESPACE::Component
  40026. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40027. #define Point JUCE_NAMESPACE::Point
  40028. #define Button JUCE_NAMESPACE::Button
  40029. #endif
  40030. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40031. it easier to use the juce version explicitly.
  40032. If you run into difficulties where this macro interferes with other 3rd party header
  40033. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40034. file for more information.
  40035. */
  40036. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40037. #define Rectangle JUCE_NAMESPACE::Rectangle
  40038. #endif
  40039. #endif
  40040. #endif
  40041. /* Easy autolinking to the right JUCE libraries under win32.
  40042. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40043. including this header file.
  40044. */
  40045. #if JUCE_MSVC
  40046. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40047. /** If you want your application to link to Juce as a DLL instead of
  40048. a static library (on win32), just define the JUCE_DLL macro before
  40049. including juce.h
  40050. */
  40051. #ifdef JUCE_DLL
  40052. #ifdef JUCE_DEBUG
  40053. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40054. #else
  40055. #define AUTOLINKEDLIB "JUCE.lib"
  40056. #endif
  40057. #else
  40058. #ifdef JUCE_DEBUG
  40059. #ifdef _WIN64
  40060. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40061. #else
  40062. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40063. #endif
  40064. #else
  40065. #ifdef _WIN64
  40066. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40067. #else
  40068. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40069. #endif
  40070. #endif
  40071. #endif
  40072. #pragma comment(lib, AUTOLINKEDLIB)
  40073. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40074. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40075. #endif
  40076. // Auto-link the other win32 libs that are needed by library calls..
  40077. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40078. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40079. // Auto-links to various win32 libs that are needed by library calls..
  40080. #pragma comment(lib, "kernel32.lib")
  40081. #pragma comment(lib, "user32.lib")
  40082. #pragma comment(lib, "shell32.lib")
  40083. #pragma comment(lib, "gdi32.lib")
  40084. #pragma comment(lib, "vfw32.lib")
  40085. #pragma comment(lib, "comdlg32.lib")
  40086. #pragma comment(lib, "winmm.lib")
  40087. #pragma comment(lib, "wininet.lib")
  40088. #pragma comment(lib, "ole32.lib")
  40089. #pragma comment(lib, "advapi32.lib")
  40090. #pragma comment(lib, "ws2_32.lib")
  40091. #pragma comment(lib, "comsupp.lib")
  40092. #if JUCE_OPENGL
  40093. #pragma comment(lib, "OpenGL32.Lib")
  40094. #pragma comment(lib, "GlU32.Lib")
  40095. #endif
  40096. #if JUCE_QUICKTIME
  40097. #pragma comment (lib, "QTMLClient.lib")
  40098. #endif
  40099. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40100. #endif
  40101. #endif
  40102. #endif
  40103. /*
  40104. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40105. AppSubClass is the name of a class derived from JUCEApplication.
  40106. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40107. */
  40108. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40109. #define START_JUCE_APPLICATION(AppClass) \
  40110. int main (int argc, char* argv[]) \
  40111. { \
  40112. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40113. }
  40114. #elif JUCE_WIN32
  40115. #ifdef _CONSOLE
  40116. #define START_JUCE_APPLICATION(AppClass) \
  40117. int main (int, char* argv[]) \
  40118. { \
  40119. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40120. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40121. }
  40122. #elif ! defined (_AFXDLL)
  40123. #ifdef _WINDOWS_
  40124. #define START_JUCE_APPLICATION(AppClass) \
  40125. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40126. { \
  40127. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40128. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40129. }
  40130. #else
  40131. #define START_JUCE_APPLICATION(AppClass) \
  40132. int __stdcall WinMain (int, int, const char*, int) \
  40133. { \
  40134. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40135. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40136. }
  40137. #endif
  40138. #endif
  40139. #endif
  40140. #endif // __JUCE_JUCEHEADER__
  40141. /********* End of inlined file: juce.h *********/
  40142. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__