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.

53627 lines
1.9MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. ==============================================================================
  25. This header contains the entire Juce source tree, and can be #included in
  26. all your source files.
  27. As well as including this in your files, you should also add juce_inline.cpp
  28. to your project (or juce_inline.mm on the Mac).
  29. ==============================================================================
  30. */
  31. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  32. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  33. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  34. /********* Start of inlined file: juce.h *********/
  35. #ifndef __JUCE_JUCEHEADER__
  36. #define __JUCE_JUCEHEADER__
  37. /*
  38. This is the main JUCE header file that applications need to include.
  39. */
  40. // (this includes things that need defining outside of the JUCE namespace)
  41. /********* Start of inlined file: juce_StandardHeader.h *********/
  42. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  43. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  44. /** Current Juce version number.
  45. See also SystemStats::getJUCEVersion() for a string version.
  46. */
  47. #define JUCE_MAJOR_VERSION 1
  48. #define JUCE_MINOR_VERSION 46
  49. /** Current Juce version number.
  50. Bits 16 to 32 = major version.
  51. Bits 8 to 16 = minor version.
  52. Bits 0 to 8 = point release (not currently used).
  53. See also SystemStats::getJUCEVersion() for a string version.
  54. */
  55. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8))
  56. /********* Start of inlined file: juce_Config.h *********/
  57. #ifndef __JUCE_CONFIG_JUCEHEADER__
  58. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  59. /*
  60. This file contains macros that enable/disable various JUCE features.
  61. */
  62. /** The name of the namespace that all Juce classes and functions will be
  63. put inside. If this is not defined, no namespace will be used.
  64. */
  65. #ifndef JUCE_NAMESPACE
  66. #define JUCE_NAMESPACE juce
  67. #endif
  68. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  69. but if you define this value, you can override this can force it to be true or
  70. false.
  71. */
  72. #ifndef JUCE_FORCE_DEBUG
  73. //#define JUCE_FORCE_DEBUG 1
  74. #endif
  75. /** If this flag is enabled, the the jassert and jassertfalse macros will
  76. always use Logger::writeToLog() to write a message when an assertion happens.
  77. Enabling it will also leave this turned on in release builds. When it's disabled,
  78. however, the jassert and jassertfalse macros will not be compiled in a
  79. release build.
  80. @see jassert, jassertfalse, Logger
  81. */
  82. #ifndef JUCE_LOG_ASSERTIONS
  83. // #define JUCE_LOG_ASSERTIONS 1
  84. #endif
  85. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  86. which the ASIOAudioIODevice class can't be built. See the comments in the
  87. ASIOAudioIODevice class's header file for more info about this.
  88. (This only affects a Win32 build)
  89. */
  90. #ifndef JUCE_ASIO
  91. #define JUCE_ASIO 1
  92. #endif
  93. /** Comment out this macro to disable building of ALSA device support on Linux.
  94. */
  95. #ifndef JUCE_ALSA
  96. #define JUCE_ALSA 1
  97. #endif
  98. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  99. have the SDK installed.
  100. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  101. classes will be unavailable.
  102. On Windows, if you enable this, you'll need to have the QuickTime SDK
  103. installed, and its header files will need to be on your include path.
  104. */
  105. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  106. #define JUCE_QUICKTIME 1
  107. #endif
  108. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  109. have the appropriate headers and libraries available. If it's not enabled, the
  110. OpenGLComponent class will be unavailable.
  111. */
  112. #ifndef JUCE_OPENGL
  113. #define JUCE_OPENGL 1
  114. #endif
  115. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  116. If you're not going to need either of these formats, turn off the flags to
  117. avoid bloating your codebase with them.
  118. */
  119. #ifndef JUCE_USE_FLAC
  120. #define JUCE_USE_FLAC 1
  121. #endif
  122. #ifndef JUCE_USE_OGGVORBIS
  123. #define JUCE_USE_OGGVORBIS 1
  124. #endif
  125. /** This flag lets you enable support for CD-burning. You might want to disable
  126. it to build without the MS SDK under windows.
  127. */
  128. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  129. #define JUCE_USE_CDBURNER 1
  130. #endif
  131. /** Enabling this macro means that all regions that get repainted will have a coloured
  132. line drawn around them.
  133. This is handy if you're trying to optimise drawing, because it lets you easily see
  134. when anything is being repainted unnecessarily.
  135. */
  136. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  137. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  138. #endif
  139. /** Enable this under Linux to use Xinerama for multi-monitor support.
  140. */
  141. #ifndef JUCE_USE_XINERAMA
  142. #define JUCE_USE_XINERAMA 1
  143. #endif
  144. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  145. */
  146. #ifndef JUCE_USE_XSHM
  147. #define JUCE_USE_XSHM 1
  148. #endif
  149. /** Enabling this builds support for VST audio plugins.
  150. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  151. */
  152. #ifndef JUCE_PLUGINHOST_VST
  153. // #define JUCE_PLUGINHOST_VST 1
  154. #endif
  155. /** Enabling this builds support for AudioUnit audio plugins.
  156. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  157. */
  158. #ifndef JUCE_PLUGINHOST_AU
  159. // #define JUCE_PLUGINHOST_AU 1
  160. #endif
  161. /** Enabling this will avoid including any UI code in the build. This is handy for
  162. writing command-line utilities, e.g. on linux boxes which don't have some
  163. of the UI libraries installed.
  164. */
  165. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  166. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  167. #endif
  168. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  169. */
  170. #ifndef JUCE_WEB_BROWSER
  171. #define JUCE_WEB_BROWSER 1
  172. #endif
  173. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  174. codebase - you might need to use this if you're linking to some of these libraries
  175. yourself.
  176. */
  177. #ifndef JUCE_INCLUDE_ZLIB_CODE
  178. #define JUCE_INCLUDE_ZLIB_CODE 1
  179. #endif
  180. #ifndef JUCE_INCLUDE_FLAC_CODE
  181. #define JUCE_INCLUDE_FLAC_CODE 1
  182. #endif
  183. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  184. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  185. #endif
  186. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  187. #define JUCE_INCLUDE_PNGLIB_CODE 1
  188. #endif
  189. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  190. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  191. #endif
  192. /** Enable this to add extra memory-leak info to the new and delete operators.
  193. (Currently, this only affects Windows builds in debug mode).
  194. */
  195. #ifndef JUCE_CHECK_MEMORY_LEAKS
  196. #define JUCE_CHECK_MEMORY_LEAKS 1
  197. #endif
  198. /** Enable this to turn on juce's internal catching of exceptions.
  199. Turning it off will avoid any exception catching. With it on, all exceptions
  200. are passed to the JUCEApplication::unhandledException() callback for logging.
  201. */
  202. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  204. #endif
  205. /** If this macro is set, the Juce String class will use unicode as its
  206. internal representation. If it isn't set, it'll use ANSI.
  207. */
  208. #ifndef JUCE_STRINGS_ARE_UNICODE
  209. #define JUCE_STRINGS_ARE_UNICODE 1
  210. #endif
  211. #endif
  212. /********* End of inlined file: juce_Config.h *********/
  213. #ifdef JUCE_NAMESPACE
  214. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  215. #define END_JUCE_NAMESPACE }
  216. #else
  217. #define BEGIN_JUCE_NAMESPACE
  218. #define END_JUCE_NAMESPACE
  219. #endif
  220. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  221. /********* Start of inlined file: juce_PlatformDefs.h *********/
  222. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  223. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  224. /* This file figures out which platform is being built, and defines some macros
  225. that the rest of the code can use for OS-specific compilation.
  226. Macros that will be set here are:
  227. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  228. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  229. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  230. - Either JUCE_INTEL or JUCE_PPC
  231. - Either JUCE_GCC or JUCE_MSVC
  232. On the Mac, it also defines MACOS_10_2_OR_EARLIER if the build is targeting OSX10.2,
  233. and MACOS_10_3_OR_EARLIER if it is targeting either 10.2 or 10.3
  234. It also includes a set of macros for debug console output and assertions.
  235. */
  236. #if (defined (_WIN32) || defined (_WIN64))
  237. #define JUCE_WIN32 1
  238. #else
  239. #ifdef LINUX
  240. #define JUCE_LINUX 1
  241. #else
  242. #define JUCE_MAC 1
  243. #endif
  244. #endif
  245. #if JUCE_WIN32
  246. #ifdef _MSC_VER
  247. #ifdef _WIN64
  248. #define JUCE_64BIT 1
  249. #else
  250. #define JUCE_32BIT 1
  251. #endif
  252. #endif
  253. #ifdef _DEBUG
  254. #define JUCE_DEBUG 1
  255. #endif
  256. /** If defined, this indicates that the processor is little-endian. */
  257. #define JUCE_LITTLE_ENDIAN 1
  258. #define JUCE_INTEL 1
  259. #endif
  260. #if JUCE_MAC
  261. #include <CoreServices/CoreServices.h>
  262. #ifndef NDEBUG
  263. #define JUCE_DEBUG 1
  264. #endif
  265. #ifdef __LITTLE_ENDIAN__
  266. #define JUCE_LITTLE_ENDIAN 1
  267. #else
  268. #define JUCE_BIG_ENDIAN 1
  269. #endif
  270. #if defined (__ppc__) || defined (__ppc64__)
  271. #define JUCE_PPC 1
  272. #else
  273. #define JUCE_INTEL 1
  274. #endif
  275. #ifdef __LP64__
  276. #define JUCE_64BIT 1
  277. #else
  278. #define JUCE_32BIT 1
  279. #endif
  280. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  281. #define MACOS_10_2_OR_EARLIER 1
  282. #endif
  283. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  284. #define MACOS_10_3_OR_EARLIER 1
  285. #endif
  286. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  287. #define MACOS_10_4_OR_EARLIER 1
  288. #endif
  289. #endif
  290. #if JUCE_LINUX
  291. #ifdef _DEBUG
  292. #define JUCE_DEBUG 1
  293. #endif
  294. // Allow override for big-endian Linux platforms
  295. #ifndef JUCE_BIG_ENDIAN
  296. #define JUCE_LITTLE_ENDIAN 1
  297. #endif
  298. #if defined (__LP64__) || defined (_LP64)
  299. #define JUCE_64BIT 1
  300. #else
  301. #define JUCE_32BIT 1
  302. #endif
  303. #define JUCE_INTEL 1
  304. #endif
  305. #ifdef JUCE_FORCE_DEBUG
  306. #undef JUCE_DEBUG
  307. #if JUCE_FORCE_DEBUG
  308. #define JUCE_DEBUG 1
  309. #endif
  310. #endif
  311. // Compiler type macros.
  312. #ifdef __GNUC__
  313. #define JUCE_GCC 1
  314. #elif defined (_MSC_VER)
  315. #define JUCE_MSVC 1
  316. #if _MSC_VER >= 1400
  317. #define JUCE_USE_INTRINSICS 1
  318. #endif
  319. #else
  320. #error unknown compiler
  321. #endif
  322. /** This macro defines the C calling convention used as the standard for Juce calls. */
  323. #if JUCE_MSVC
  324. #define JUCE_CALLTYPE __stdcall
  325. #else
  326. #define JUCE_CALLTYPE
  327. #endif
  328. // Debugging and assertion macros
  329. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  330. #if JUCE_LOG_ASSERTIONS
  331. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  332. #elif defined (JUCE_DEBUG)
  333. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  334. #else
  335. #define juce_LogCurrentAssertion
  336. #endif
  337. #ifdef JUCE_DEBUG
  338. // If debugging is enabled..
  339. /** Writes a string to the standard error stream.
  340. This is only compiled in a debug build.
  341. @see Logger::outputDebugString
  342. */
  343. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  344. /** Printf's a string to the standard error stream.
  345. This is only compiled in a debug build.
  346. @see Logger::outputDebugString
  347. */
  348. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  349. // Assertions..
  350. #if JUCE_WIN32 || DOXYGEN
  351. #if JUCE_USE_INTRINSICS
  352. #pragma intrinsic (__debugbreak)
  353. /** This will try to break the debugger if one is currently hosting this app.
  354. @see jassert()
  355. */
  356. #define juce_breakDebugger __debugbreak();
  357. #elif JUCE_GCC
  358. /** This will try to break the debugger if one is currently hosting this app.
  359. @see jassert()
  360. */
  361. #define juce_breakDebugger asm("int $3");
  362. #else
  363. /** This will try to break the debugger if one is currently hosting this app.
  364. @see jassert()
  365. */
  366. #define juce_breakDebugger { __asm int 3 }
  367. #endif
  368. #elif JUCE_MAC
  369. #define juce_breakDebugger Debugger();
  370. #elif JUCE_LINUX
  371. #define juce_breakDebugger kill (0, SIGTRAP);
  372. #endif
  373. /** This will always cause an assertion failure.
  374. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  375. in juce_Config.h).
  376. @see jassert()
  377. */
  378. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  379. /** Platform-independent assertion macro.
  380. This gets optimised out when not being built with debugging turned on.
  381. Be careful not to call any functions within its arguments that are vital to
  382. the behaviour of the program, because these won't get called in the release
  383. build.
  384. @see jassertfalse
  385. */
  386. #define jassert(expression) { if (! (expression)) jassertfalse }
  387. #else
  388. // If debugging is disabled, these dummy debug and assertion macros are used..
  389. #define DBG(dbgtext)
  390. #define DBG_PRINTF(dbgprintf)
  391. #define jassertfalse { juce_LogCurrentAssertion }
  392. #if JUCE_LOG_ASSERTIONS
  393. #define jassert(expression) { if (! (expression)) jassertfalse }
  394. #else
  395. #define jassert(a) { }
  396. #endif
  397. #endif
  398. #ifndef DOXYGEN
  399. template <bool b> struct JuceStaticAssert;
  400. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  401. #endif
  402. /** A compile-time assertion macro.
  403. If the expression parameter is false, the macro will cause a compile error.
  404. */
  405. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  406. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  407. #define JUCE_TRY try
  408. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  409. object so they can be logged by the application if it wants to.
  410. */
  411. #define JUCE_CATCH_EXCEPTION \
  412. catch (const std::exception& e) \
  413. { \
  414. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  415. } \
  416. catch (...) \
  417. { \
  418. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  419. }
  420. #define JUCE_CATCH_ALL catch (...) {}
  421. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  422. #else
  423. #define JUCE_TRY
  424. #define JUCE_CATCH_EXCEPTION
  425. #define JUCE_CATCH_ALL
  426. #define JUCE_CATCH_ALL_ASSERT
  427. #endif
  428. // Macros for inlining.
  429. #if JUCE_MSVC
  430. /** A platform-independent way of forcing an inline function.
  431. Use the syntax: @code
  432. forcedinline void myfunction (int x)
  433. @endcode
  434. */
  435. #ifdef JUCE_DEBUG
  436. #define forcedinline __forceinline
  437. #else
  438. #define forcedinline inline
  439. #endif
  440. /** A platform-independent way of stopping the compiler inlining a function.
  441. Use the syntax: @code
  442. juce_noinline void myfunction (int x)
  443. @endcode
  444. */
  445. #define juce_noinline
  446. #else
  447. /** A platform-independent way of forcing an inline function.
  448. Use the syntax: @code
  449. forcedinline void myfunction (int x)
  450. @endcode
  451. */
  452. #ifndef JUCE_DEBUG
  453. #define forcedinline inline __attribute__((always_inline))
  454. #else
  455. #define forcedinline inline
  456. #endif
  457. /** A platform-independent way of stopping the compiler inlining a function.
  458. Use the syntax: @code
  459. juce_noinline void myfunction (int x)
  460. @endcode
  461. */
  462. #define juce_noinline __attribute__((noinline))
  463. #endif
  464. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  465. /********* End of inlined file: juce_PlatformDefs.h *********/
  466. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  467. #if JUCE_MSVC
  468. #pragma warning (push)
  469. #pragma warning (disable: 4514 4245 4100)
  470. #endif
  471. #include <cstdlib>
  472. #include <cstdarg>
  473. #include <climits>
  474. #include <cmath>
  475. #include <cwchar>
  476. #include <stdexcept>
  477. #include <typeinfo>
  478. #include <cstring>
  479. #include <cstdio>
  480. #if JUCE_MAC || JUCE_LINUX
  481. #include <pthread.h>
  482. #endif
  483. #if JUCE_USE_INTRINSICS
  484. #include <intrin.h>
  485. #endif
  486. #if JUCE_MAC && ! MACOS_10_3_OR_EARLIER
  487. #include <libkern/OSAtomic.h>
  488. #endif
  489. #if JUCE_LINUX
  490. #include <signal.h>
  491. #endif
  492. #if JUCE_MSVC && JUCE_DEBUG
  493. #include <crtdbg.h>
  494. #endif
  495. #if JUCE_MSVC
  496. #pragma warning (pop)
  497. #endif
  498. // DLL building settings on Win32
  499. #if JUCE_MSVC
  500. #ifdef JUCE_DLL_BUILD
  501. #define JUCE_API __declspec (dllexport)
  502. #pragma warning (disable: 4251)
  503. #elif defined (JUCE_DLL)
  504. #define JUCE_API __declspec (dllimport)
  505. #pragma warning (disable: 4251)
  506. #endif
  507. #endif
  508. #ifndef JUCE_API
  509. /** This macro is added to all juce public class declarations. */
  510. #define JUCE_API
  511. #endif
  512. /** This macro is added to all juce public function declarations. */
  513. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  514. // Now include some basics that are needed by most of the Juce classes...
  515. BEGIN_JUCE_NAMESPACE
  516. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  517. #if JUCE_LOG_ASSERTIONS
  518. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  519. #endif
  520. /********* Start of inlined file: juce_Memory.h *********/
  521. #ifndef __JUCE_MEMORY_JUCEHEADER__
  522. #define __JUCE_MEMORY_JUCEHEADER__
  523. /*
  524. This file defines the various juce_malloc(), juce_free() macros that should be used in
  525. preference to the standard calls.
  526. */
  527. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  528. #ifndef JUCE_DLL
  529. // Win32 debug non-DLL versions..
  530. /** This should be used instead of calling malloc directly. */
  531. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  532. /** This should be used instead of calling calloc directly. */
  533. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  534. /** This should be used instead of calling realloc directly. */
  535. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  536. /** This should be used instead of calling free directly. */
  537. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  538. #else
  539. // Win32 debug DLL versions..
  540. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  541. // way all juce calls in the DLL and in the host API will all use the same allocator.
  542. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  543. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  544. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  545. extern JUCE_API void juce_DebugFree (void* const block);
  546. /** This should be used instead of calling malloc directly. */
  547. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  548. /** This should be used instead of calling calloc directly. */
  549. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  550. /** This should be used instead of calling realloc directly. */
  551. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  552. /** This should be used instead of calling free directly. */
  553. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  554. #endif
  555. #if ! defined (_AFXDLL)
  556. /** This macro can be added to classes to add extra debugging information to the memory
  557. allocated for them, so you can see the type of objects involved when there's a dump
  558. of leaked objects at program shutdown. (Only works on win32 at the moment).
  559. */
  560. #define juce_UseDebuggingNewOperator \
  561. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  562. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  563. static void operator delete (void* p) { juce_free (p); }
  564. #endif
  565. #elif defined (JUCE_DLL)
  566. // Win32 DLL (release) versions..
  567. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  568. // way all juce calls in the DLL and in the host API will all use the same allocator.
  569. extern JUCE_API void* juce_Malloc (const int size);
  570. extern JUCE_API void* juce_Calloc (const int size);
  571. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  572. extern JUCE_API void juce_Free (void* const block);
  573. /** This should be used instead of calling malloc directly. */
  574. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  575. /** This should be used instead of calling calloc directly. */
  576. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  577. /** This should be used instead of calling realloc directly. */
  578. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  579. /** This should be used instead of calling free directly. */
  580. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  581. #define juce_UseDebuggingNewOperator \
  582. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  583. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  584. static void operator delete (void* p) { juce_free (p); }
  585. #else
  586. // Mac, Linux and Win32 (release) versions..
  587. /** This should be used instead of calling malloc directly. */
  588. #define juce_malloc(numBytes) malloc (numBytes)
  589. /** This should be used instead of calling calloc directly. */
  590. #define juce_calloc(numBytes) calloc (1, numBytes)
  591. /** This should be used instead of calling realloc directly. */
  592. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  593. /** This should be used instead of calling free directly. */
  594. #define juce_free(location) free (location)
  595. #endif
  596. /** This macro can be added to classes to add extra debugging information to the memory
  597. allocated for them, so you can see the type of objects involved when there's a dump
  598. of leaked objects at program shutdown. (Only works on win32 at the moment).
  599. Note that if you create a class that inherits from a class that uses this macro,
  600. your class must also use the macro, otherwise you'll probably get compile errors
  601. because of ambiguous new operators.
  602. Most of the JUCE classes use it, so see these for examples of where it should go.
  603. */
  604. #ifndef juce_UseDebuggingNewOperator
  605. #define juce_UseDebuggingNewOperator
  606. #endif
  607. #if JUCE_MSVC
  608. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  609. E.g.
  610. @code
  611. juce_ThreadLocal int myVariable;
  612. @endcode
  613. */
  614. #define juce_ThreadLocal __declspec(thread)
  615. #else
  616. #define juce_ThreadLocal __thread
  617. #endif
  618. /** Clears a block of memory. */
  619. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  620. /** Clears a reference to a local structure. */
  621. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  622. /** A handy macro that calls delete on a pointer if it's non-zero, and
  623. then sets the pointer to null.
  624. */
  625. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  626. #endif // __JUCE_MEMORY_JUCEHEADER__
  627. /********* End of inlined file: juce_Memory.h *********/
  628. /********* Start of inlined file: juce_MathsFunctions.h *********/
  629. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  630. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  631. /*
  632. This file sets up some handy mathematical typdefs and functions.
  633. */
  634. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  635. /** A platform-independent 8-bit signed integer type. */
  636. typedef signed char int8;
  637. /** A platform-independent 8-bit unsigned integer type. */
  638. typedef unsigned char uint8;
  639. /** A platform-independent 16-bit signed integer type. */
  640. typedef signed short int16;
  641. /** A platform-independent 16-bit unsigned integer type. */
  642. typedef unsigned short uint16;
  643. /** A platform-independent 32-bit signed integer type. */
  644. typedef signed int int32;
  645. /** A platform-independent 32-bit unsigned integer type. */
  646. typedef unsigned int uint32;
  647. #if JUCE_MSVC
  648. /** A platform-independent 64-bit integer type. */
  649. typedef __int64 int64;
  650. /** A platform-independent 64-bit unsigned integer type. */
  651. typedef unsigned __int64 uint64;
  652. /** A platform-independent macro for writing 64-bit literals, needed because
  653. different compilers have different syntaxes for this.
  654. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  655. GCC, or 0x1000000000 for MSVC.
  656. */
  657. #define literal64bit(longLiteral) ((__int64) longLiteral)
  658. #else
  659. /** A platform-independent 64-bit integer type. */
  660. typedef long long int64;
  661. /** A platform-independent 64-bit unsigned integer type. */
  662. typedef unsigned long long uint64;
  663. /** A platform-independent macro for writing 64-bit literals, needed because
  664. different compilers have different syntaxes for this.
  665. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  666. GCC, or 0x1000000000 for MSVC.
  667. */
  668. #define literal64bit(longLiteral) (longLiteral##LL)
  669. #endif
  670. #if JUCE_64BIT
  671. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  672. typedef int64 pointer_sized_int;
  673. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  674. typedef uint64 pointer_sized_uint;
  675. #elif _MSC_VER >= 1300
  676. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  677. typedef _W64 int pointer_sized_int;
  678. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  679. typedef _W64 unsigned int pointer_sized_uint;
  680. #else
  681. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  682. typedef int pointer_sized_int;
  683. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  684. typedef unsigned int pointer_sized_uint;
  685. #endif
  686. /** A platform-independent unicode character type. */
  687. typedef wchar_t juce_wchar;
  688. // Some indispensible min/max functions
  689. /** Returns the larger of two values. */
  690. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  691. /** Returns the larger of two values. */
  692. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  693. /** Returns the larger of two values. */
  694. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  695. /** Returns the larger of two values. */
  696. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  697. /** Returns the larger of three values. */
  698. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  699. /** Returns the larger of three values. */
  700. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  701. /** Returns the larger of three values. */
  702. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  703. /** Returns the larger of three values. */
  704. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  705. /** Returns the larger of four values. */
  706. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  707. /** Returns the larger of four values. */
  708. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  709. /** Returns the larger of four values. */
  710. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  711. /** Returns the larger of four values. */
  712. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  713. /** Returns the smaller of two values. */
  714. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  715. /** Returns the smaller of two values. */
  716. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  717. /** Returns the smaller of two values. */
  718. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  719. /** Returns the smaller of two values. */
  720. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  721. /** Returns the smaller of three values. */
  722. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  723. /** Returns the smaller of three values. */
  724. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  725. /** Returns the smaller of three values. */
  726. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  727. /** Returns the smaller of three values. */
  728. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  729. /** Returns the smaller of four values. */
  730. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  731. /** Returns the smaller of four values. */
  732. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  733. /** Returns the smaller of four values. */
  734. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  735. /** Returns the smaller of four values. */
  736. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  737. /** Constrains a value to keep it within a given range.
  738. This will check that the specified value lies between the lower and upper bounds
  739. specified, and if not, will return the nearest value that would be in-range. Effectively,
  740. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  741. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  742. the results will be unpredictable.
  743. @param lowerLimit the minimum value to return
  744. @param upperLimit the maximum value to return
  745. @param valueToConstrain the value to try to return
  746. @returns the closest value to valueToConstrain which lies between lowerLimit
  747. and upperLimit (inclusive)
  748. @see jlimit0To, jmin, jmax
  749. */
  750. template <class Type>
  751. inline Type jlimit (const Type lowerLimit,
  752. const Type upperLimit,
  753. const Type valueToConstrain) throw()
  754. {
  755. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  756. return (valueToConstrain < lowerLimit) ? lowerLimit
  757. : ((valueToConstrain > upperLimit) ? upperLimit
  758. : valueToConstrain);
  759. }
  760. /** Handy function to swap two values over.
  761. */
  762. template <class Type>
  763. inline void swapVariables (Type& variable1, Type& variable2) throw()
  764. {
  765. const Type tempVal = variable1;
  766. variable1 = variable2;
  767. variable2 = tempVal;
  768. }
  769. /** Handy macro for getting the number of elements in a simple const C array.
  770. E.g.
  771. @code
  772. static int myArray[] = { 1, 2, 3 };
  773. int numElements = numElementsInArray (myArray) // returns 3
  774. @endcode
  775. */
  776. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  777. // Some useful maths functions that aren't always present with all compilers and build settings.
  778. #if JUCE_WIN32 || defined (DOXYGEN)
  779. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  780. versions of these functions of various platforms and compilers. */
  781. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  782. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  783. versions of these functions of various platforms and compilers. */
  784. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  785. #elif MACOS_10_2_OR_EARLIER
  786. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  787. versions of these functions of various platforms and compilers. */
  788. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  789. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  790. versions of these functions of various platforms and compilers. */
  791. forcedinline float juce_hypotf (float a, float b) { return (float) hypot (a, b); }
  792. forcedinline float sinf (const float a) { return (float) sin (a); }
  793. forcedinline float cosf (const float a) { return (float) cos (a); }
  794. forcedinline float tanf (const float a) { return (float) tan (a); }
  795. forcedinline float atan2f (const float a, const float b) { return (float) atan2 (a, b); }
  796. forcedinline float sqrtf (const float a) { return (float) sqrt (a); }
  797. forcedinline float logf (const float a) { return (float) log (a); }
  798. forcedinline float powf (const float a, const float b) { return (float) pow (a, b); }
  799. forcedinline float expf (const float a) { return (float) exp (a); }
  800. #else
  801. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  802. versions of these functions of various platforms and compilers. */
  803. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  804. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  805. versions of these functions of various platforms and compilers. */
  806. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  807. #endif
  808. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  809. /** A predefined value for Pi, at double-precision.
  810. @see float_Pi
  811. */
  812. const double double_Pi = 3.1415926535897932384626433832795;
  813. /** A predefined value for Pi, at sngle-precision.
  814. @see double_Pi
  815. */
  816. const float float_Pi = 3.14159265358979323846f;
  817. /** The isfinite() method seems to vary greatly between platforms, so this is a
  818. platform-independent macro for it.
  819. */
  820. #if JUCE_LINUX
  821. #define juce_isfinite(v) std::isfinite(v)
  822. #elif JUCE_MAC
  823. #if MACOS_10_2_OR_EARLIER
  824. #define juce_isfinite(v) __isfinite(v)
  825. #elif MACOS_10_3_OR_EARLIER
  826. #ifdef isfinite
  827. #define juce_isfinite(v) isfinite(v)
  828. #else
  829. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  830. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  831. #endif
  832. #else
  833. #define juce_isfinite(v) std::isfinite(v)
  834. #endif
  835. #elif JUCE_WIN32 && ! defined (isfinite)
  836. #define juce_isfinite(v) _finite(v)
  837. #else
  838. #define juce_isfinite(v) isfinite(v)
  839. #endif
  840. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  841. /********* End of inlined file: juce_MathsFunctions.h *********/
  842. /********* Start of inlined file: juce_DataConversions.h *********/
  843. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  844. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  845. #if JUCE_USE_INTRINSICS
  846. #pragma intrinsic (_byteswap_ulong)
  847. #endif
  848. // Endianness conversions..
  849. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  850. forcedinline uint32 swapByteOrder (uint32 n) throw()
  851. {
  852. #if JUCE_MAC
  853. // Mac version
  854. return CFSwapInt32 (n);
  855. #elif JUCE_GCC
  856. // Inpenetrable GCC version..
  857. asm("bswap %%eax" : "=a"(n) : "a"(n));
  858. return n;
  859. #elif JUCE_USE_INTRINSICS
  860. // Win32 intrinsics version..
  861. return _byteswap_ulong (n);
  862. #else
  863. // Win32 version..
  864. __asm {
  865. mov eax, n
  866. bswap eax
  867. mov n, eax
  868. }
  869. return n;
  870. #endif
  871. }
  872. /** Swaps the byte-order of a 16-bit short. */
  873. inline uint16 swapByteOrder (const uint16 n) throw()
  874. {
  875. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  876. // Win32 intrinsics version..
  877. return (uint16) _byteswap_ushort (n);
  878. #else
  879. return (uint16) ((n << 8) | (n >> 8));
  880. #endif
  881. }
  882. inline uint64 swapByteOrder (const uint64 value) throw()
  883. {
  884. #if JUCE_MAC
  885. return CFSwapInt64 (value);
  886. #elif JUCE_USE_INTRINSICS
  887. return _byteswap_uint64 (value);
  888. #else
  889. return (((int64) swapByteOrder ((uint32) value)) << 32)
  890. | swapByteOrder ((uint32) (value >> 32));
  891. #endif
  892. }
  893. #if JUCE_LITTLE_ENDIAN
  894. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  895. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  896. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  897. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  898. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  899. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  900. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  901. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  902. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  903. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  904. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  905. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  906. /** Turns 4 bytes into a little-endian integer. */
  907. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  908. /** Turns 2 bytes into a little-endian integer. */
  909. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  910. /** Turns 4 bytes into a big-endian integer. */
  911. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  912. /** Turns 2 bytes into a big-endian integer. */
  913. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  914. #else
  915. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  916. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  917. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  918. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  919. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  920. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  921. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  922. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  923. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  924. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  925. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  926. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  927. /** Turns 4 bytes into a little-endian integer. */
  928. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  929. /** Turns 2 bytes into a little-endian integer. */
  930. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  931. /** Turns 4 bytes into a big-endian integer. */
  932. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  933. /** Turns 2 bytes into a big-endian integer. */
  934. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  935. #endif
  936. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  937. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  938. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  939. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  940. /** Copies a 24-bit number to 3 little-endian bytes. */
  941. 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); }
  942. /** Copies a 24-bit number to 3 big-endian bytes. */
  943. 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); }
  944. /** Fast floating-point-to-integer conversion.
  945. This is faster than using the normal c++ cast to convert a double to an int, and
  946. it will round the value to the nearest integer, rather than rounding it down
  947. like the normal cast does.
  948. Note that this routine gets its speed at the expense of some accuracy, and when
  949. rounding values whose floating point component is exactly 0.5, odd numbers and
  950. even numbers will be rounded up or down differently. For a more accurate conversion,
  951. see roundDoubleToIntAccurate().
  952. */
  953. inline int roundDoubleToInt (const double value) throw()
  954. {
  955. union { int asInt[2]; double asDouble; } n;
  956. n.asDouble = value + 6755399441055744.0;
  957. #if JUCE_BIG_ENDIAN
  958. return n.asInt [1];
  959. #else
  960. return n.asInt [0];
  961. #endif
  962. }
  963. /** Fast floating-point-to-integer conversion.
  964. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  965. fine for values above zero, but negative numbers are rounded the wrong way.
  966. */
  967. inline int roundDoubleToIntAccurate (const double value) throw()
  968. {
  969. return roundDoubleToInt (value + 1.5e-8);
  970. }
  971. /** Fast floating-point-to-integer conversion.
  972. This is faster than using the normal c++ cast to convert a float to an int, and
  973. it will round the value to the nearest integer, rather than rounding it down
  974. like the normal cast does.
  975. Note that this routine gets its speed at the expense of some accuracy, and when
  976. rounding values whose floating point component is exactly 0.5, odd numbers and
  977. even numbers will be rounded up or down differently.
  978. */
  979. inline int roundFloatToInt (const float value) throw()
  980. {
  981. union { int asInt[2]; double asDouble; } n;
  982. n.asDouble = value + 6755399441055744.0;
  983. #if JUCE_BIG_ENDIAN
  984. return n.asInt [1];
  985. #else
  986. return n.asInt [0];
  987. #endif
  988. }
  989. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  990. /********* End of inlined file: juce_DataConversions.h *********/
  991. /********* Start of inlined file: juce_Logger.h *********/
  992. #ifndef __JUCE_LOGGER_JUCEHEADER__
  993. #define __JUCE_LOGGER_JUCEHEADER__
  994. /********* Start of inlined file: juce_String.h *********/
  995. #ifndef __JUCE_STRING_JUCEHEADER__
  996. #define __JUCE_STRING_JUCEHEADER__
  997. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  998. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  999. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1000. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1001. (in the default system encoding) as its internal representation.
  1002. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1003. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1004. literals in the T("abcd") macro, so that it all works nicely either way round.
  1005. */
  1006. #if JUCE_STRINGS_ARE_UNICODE
  1007. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1008. typedef juce_wchar tchar;
  1009. #define juce_tcharToWideChar(c) (c)
  1010. #else
  1011. #define JUCE_T(stringLiteral) (stringLiteral)
  1012. typedef char tchar;
  1013. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1014. #endif
  1015. #if ! JUCE_DONT_DEFINE_MACROS
  1016. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1017. or unicode.
  1018. If you write your string literals in the form T("xyz"), this will either be compiled
  1019. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1020. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1021. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1022. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1023. the juce/src directory) to avoid defining this macro. See the comments in
  1024. juce_withoutMacros.h for more info.
  1025. */
  1026. #define T(stringLiteral) JUCE_T(stringLiteral)
  1027. #endif
  1028. /**
  1029. A set of methods for manipulating characters and character strings, with
  1030. duplicate methods to handle 8-bit and unicode characters.
  1031. These are defined as wrappers around the basic C string handlers, to provide
  1032. a clean, cross-platform layer, (because various platforms differ in the
  1033. range of C library calls that they provide).
  1034. @see String
  1035. */
  1036. class JUCE_API CharacterFunctions
  1037. {
  1038. public:
  1039. static int length (const char* const s) throw();
  1040. static int length (const juce_wchar* const s) throw();
  1041. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1042. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1043. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1044. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1045. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1046. static void append (char* dest, const char* src) throw();
  1047. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1048. static int compare (const char* const s1, const char* const s2) throw();
  1049. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1050. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1051. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1052. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1053. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1054. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1055. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1056. static const char* find (const char* const haystack, const char* const needle) throw();
  1057. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1058. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1059. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1060. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1061. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1062. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1063. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1064. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1065. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1066. static int getIntValue (const char* const s) throw();
  1067. static int getIntValue (const juce_wchar* s) throw();
  1068. static int64 getInt64Value (const char* s) throw();
  1069. static int64 getInt64Value (const juce_wchar* s) throw();
  1070. static double getDoubleValue (const char* const s) throw();
  1071. static double getDoubleValue (const juce_wchar* const s) throw();
  1072. static char toUpperCase (const char character) throw();
  1073. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1074. static void toUpperCase (char* s) throw();
  1075. static void toUpperCase (juce_wchar* s) throw();
  1076. static bool isUpperCase (const char character) throw();
  1077. static bool isUpperCase (const juce_wchar character) throw();
  1078. static char toLowerCase (const char character) throw();
  1079. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1080. static void toLowerCase (char* s) throw();
  1081. static void toLowerCase (juce_wchar* s) throw();
  1082. static bool isLowerCase (const char character) throw();
  1083. static bool isLowerCase (const juce_wchar character) throw();
  1084. static bool isWhitespace (const char character) throw();
  1085. static bool isWhitespace (const juce_wchar character) throw();
  1086. static bool isDigit (const char character) throw();
  1087. static bool isDigit (const juce_wchar character) throw();
  1088. static bool isLetter (const char character) throw();
  1089. static bool isLetter (const juce_wchar character) throw();
  1090. static bool isLetterOrDigit (const char character) throw();
  1091. static bool isLetterOrDigit (const juce_wchar character) throw();
  1092. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1093. hex digit.
  1094. */
  1095. static int getHexDigitValue (const tchar digit) throw();
  1096. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1097. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1098. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1099. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1100. };
  1101. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1102. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1103. /**
  1104. The JUCE String class!
  1105. Using a reference-counted internal representation, these strings are fast
  1106. and efficient, and there are methods to do just about any operation you'll ever
  1107. dream of.
  1108. @see StringArray, StringPairArray
  1109. */
  1110. class JUCE_API String
  1111. {
  1112. public:
  1113. /** Creates an empty string.
  1114. @see empty
  1115. */
  1116. String() throw();
  1117. /** Creates a copy of another string. */
  1118. String (const String& other) throw();
  1119. /** Creates a string from a zero-terminated text string.
  1120. The string is assumed to be stored in the default system encoding.
  1121. */
  1122. String (const char* const text) throw();
  1123. /** Creates a string from an string of characters.
  1124. This will use up the the first maxChars characters of the string (or
  1125. less if the string is actually shorter)
  1126. */
  1127. String (const char* const text,
  1128. const int maxChars) throw();
  1129. /** Creates a string from a zero-terminated unicode text string. */
  1130. String (const juce_wchar* const unicodeText) throw();
  1131. /** Creates a string from a unicode text string.
  1132. This will use up the the first maxChars characters of the string (or
  1133. less if the string is actually shorter)
  1134. */
  1135. String (const juce_wchar* const unicodeText,
  1136. const int maxChars) throw();
  1137. /** Creates a string from a single character. */
  1138. static const String charToString (const tchar character) throw();
  1139. /** Destructor. */
  1140. ~String() throw();
  1141. /** This is an empty string that can be used whenever one is needed.
  1142. It's better to use this than String() because it explains what's going on
  1143. and is more efficient.
  1144. */
  1145. static const String empty;
  1146. /** Generates a probably-unique 32-bit hashcode from this string. */
  1147. int hashCode() const throw();
  1148. /** Generates a probably-unique 64-bit hashcode from this string. */
  1149. int64 hashCode64() const throw();
  1150. /** Returns the number of characters in the string. */
  1151. int length() const throw();
  1152. // Assignment and concatenation operators..
  1153. /** Replaces this string's contents with another string. */
  1154. const String& operator= (const tchar* const other) throw();
  1155. /** Replaces this string's contents with another string. */
  1156. const String& operator= (const String& other) throw();
  1157. /** Appends another string at the end of this one. */
  1158. const String& operator+= (const tchar* const textToAppend) throw();
  1159. /** Appends another string at the end of this one. */
  1160. const String& operator+= (const String& stringToAppend) throw();
  1161. /** Appends a character at the end of this string. */
  1162. const String& operator+= (const char characterToAppend) throw();
  1163. /** Appends a character at the end of this string. */
  1164. const String& operator+= (const juce_wchar characterToAppend) throw();
  1165. /** Appends a string at the end of this one.
  1166. @param textToAppend the string to add
  1167. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1168. */
  1169. void append (const tchar* const textToAppend,
  1170. const int maxCharsToTake) throw();
  1171. /** Appends a string at the end of this one.
  1172. @returns the concatenated string
  1173. */
  1174. const String operator+ (const String& stringToAppend) const throw();
  1175. /** Appends a string at the end of this one.
  1176. @returns the concatenated string
  1177. */
  1178. const String operator+ (const tchar* const textToAppend) const throw();
  1179. /** Appends a character at the end of this one.
  1180. @returns the concatenated string
  1181. */
  1182. const String operator+ (const tchar characterToAppend) const throw();
  1183. /** Appends a character at the end of this string. */
  1184. String& operator<< (const char n) throw();
  1185. /** Appends a character at the end of this string. */
  1186. String& operator<< (const juce_wchar n) throw();
  1187. /** Appends another string at the end of this one. */
  1188. String& operator<< (const char* const text) throw();
  1189. /** Appends another string at the end of this one. */
  1190. String& operator<< (const juce_wchar* const text) throw();
  1191. /** Appends another string at the end of this one. */
  1192. String& operator<< (const String& text) throw();
  1193. /** Appends a decimal number at the end of this string. */
  1194. String& operator<< (const short number) throw();
  1195. /** Appends a decimal number at the end of this string. */
  1196. String& operator<< (const int number) throw();
  1197. /** Appends a decimal number at the end of this string. */
  1198. String& operator<< (const unsigned int number) throw();
  1199. /** Appends a decimal number at the end of this string. */
  1200. String& operator<< (const float number) throw();
  1201. /** Appends a decimal number at the end of this string. */
  1202. String& operator<< (const double number) throw();
  1203. // Comparison methods..
  1204. /** Returns true if the string contains no characters.
  1205. Note that there's also an isNotEmpty() method to help write readable code.
  1206. */
  1207. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1208. /** Returns true if the string contains at least one character.
  1209. Note that there's also an isEmpty() method to help write readable code.
  1210. */
  1211. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1212. /** Case-sensitive comparison with another string. */
  1213. bool operator== (const String& other) const throw();
  1214. /** Case-sensitive comparison with another string. */
  1215. bool operator== (const tchar* const other) const throw();
  1216. /** Case-sensitive comparison with another string. */
  1217. bool operator!= (const String& other) const throw();
  1218. /** Case-sensitive comparison with another string. */
  1219. bool operator!= (const tchar* const other) const throw();
  1220. /** Case-insensitive comparison with another string. */
  1221. bool equalsIgnoreCase (const String& other) const throw();
  1222. /** Case-insensitive comparison with another string. */
  1223. bool equalsIgnoreCase (const tchar* const other) const throw();
  1224. /** Case-sensitive comparison with another string. */
  1225. bool operator> (const String& other) const throw();
  1226. /** Case-sensitive comparison with another string. */
  1227. bool operator< (const tchar* const other) const throw();
  1228. /** Case-sensitive comparison with another string. */
  1229. bool operator>= (const String& other) const throw();
  1230. /** Case-sensitive comparison with another string. */
  1231. bool operator<= (const tchar* const other) const throw();
  1232. /** Case-sensitive comparison with another string.
  1233. @returns 0 if the two strings are identical; negative if this string
  1234. comes before the other one alphabetically, or positive if it
  1235. comes after it.
  1236. */
  1237. int compare (const tchar* const other) const throw();
  1238. /** Case-insensitive comparison with another string.
  1239. @returns 0 if the two strings are identical; negative if this string
  1240. comes before the other one alphabetically, or positive if it
  1241. comes after it.
  1242. */
  1243. int compareIgnoreCase (const tchar* const other) const throw();
  1244. /** Lexicographic comparison with another string.
  1245. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1246. characters, making it good for sorting human-readable strings.
  1247. @returns 0 if the two strings are identical; negative if this string
  1248. comes before the other one alphabetically, or positive if it
  1249. comes after it.
  1250. */
  1251. int compareLexicographically (const tchar* const other) const throw();
  1252. /** Tests whether the string begins with another string.
  1253. Uses a case-sensitive comparison.
  1254. */
  1255. bool startsWith (const tchar* const text) const throw();
  1256. /** Tests whether the string begins with a particular character.
  1257. Uses a case-sensitive comparison.
  1258. */
  1259. bool startsWithChar (const tchar character) const throw();
  1260. /** Tests whether the string begins with another string.
  1261. Uses a case-insensitive comparison.
  1262. */
  1263. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1264. /** Tests whether the string ends with another string.
  1265. Uses a case-sensitive comparison.
  1266. */
  1267. bool endsWith (const tchar* const text) const throw();
  1268. /** Tests whether the string ends with a particular character.
  1269. Uses a case-sensitive comparison.
  1270. */
  1271. bool endsWithChar (const tchar character) const throw();
  1272. /** Tests whether the string ends with another string.
  1273. Uses a case-insensitive comparison.
  1274. */
  1275. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1276. /** Tests whether the string contains another substring.
  1277. Uses a case-sensitive comparison.
  1278. */
  1279. bool contains (const tchar* const text) const throw();
  1280. /** Tests whether the string contains a particular character.
  1281. Uses a case-sensitive comparison.
  1282. */
  1283. bool containsChar (const tchar character) const throw();
  1284. /** Tests whether the string contains another substring.
  1285. Uses a case-insensitive comparison.
  1286. */
  1287. bool containsIgnoreCase (const tchar* const text) const throw();
  1288. /** Tests whether the string contains another substring as a distict word.
  1289. @returns true if the string contains this word, surrounded by
  1290. non-alphanumeric characters
  1291. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1292. */
  1293. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1294. /** Tests whether the string contains another substring as a distict word.
  1295. @returns true if the string contains this word, surrounded by
  1296. non-alphanumeric characters
  1297. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1298. */
  1299. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1300. /** Finds an instance of another substring if it exists as a distict word.
  1301. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1302. then this will return the index of the start of the substring. If it isn't
  1303. found, then it will return -1
  1304. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1305. */
  1306. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1307. /** Finds an instance of another substring if it exists as a distict word.
  1308. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1309. then this will return the index of the start of the substring. If it isn't
  1310. found, then it will return -1
  1311. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1312. */
  1313. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1314. /** Looks for any of a set of characters in the string.
  1315. Uses a case-sensitive comparison.
  1316. @returns true if the string contains any of the characters from
  1317. the string that is passed in.
  1318. */
  1319. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1320. /** Looks for a set of characters in the string.
  1321. Uses a case-sensitive comparison.
  1322. @returns true if the all the characters in the string are also found in the
  1323. string that is passed in.
  1324. */
  1325. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1326. /** Returns true if the string matches this simple wildcard expression.
  1327. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1328. This isn't a full-blown regex though! The only wildcard characters supported
  1329. are "*" and "?". It's mainly intended for filename pattern matching.
  1330. */
  1331. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1332. // Substring location methods..
  1333. /** Searches for a character inside this string.
  1334. Uses a case-sensitive comparison.
  1335. @returns the index of the first occurrence of the character in this
  1336. string, or -1 if it's not found.
  1337. */
  1338. int indexOfChar (const tchar characterToLookFor) const throw();
  1339. /** Searches for a character inside this string.
  1340. Uses a case-sensitive comparison.
  1341. @param startIndex the index from which the search should proceed
  1342. @param characterToLookFor the character to look for
  1343. @returns the index of the first occurrence of the character in this
  1344. string, or -1 if it's not found.
  1345. */
  1346. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1347. /** Returns the index of the first character that matches one of the characters
  1348. passed-in to this method.
  1349. This scans the string, beginning from the startIndex supplied, and if it finds
  1350. a character that appears in the string charactersToLookFor, it returns its index.
  1351. If none of these characters are found, it returns -1.
  1352. If ignoreCase is true, the comparison will be case-insensitive.
  1353. @see indexOfChar, lastIndexOfAnyOf
  1354. */
  1355. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1356. const int startIndex = 0,
  1357. const bool ignoreCase = false) const throw();
  1358. /** Searches for a substring within this string.
  1359. Uses a case-sensitive comparison.
  1360. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1361. */
  1362. int indexOf (const tchar* const text) const throw();
  1363. /** Searches for a substring within this string.
  1364. Uses a case-sensitive comparison.
  1365. @param startIndex the index from which the search should proceed
  1366. @param textToLookFor the string to search for
  1367. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1368. */
  1369. int indexOf (const int startIndex,
  1370. const tchar* const textToLookFor) const throw();
  1371. /** Searches for a substring within this string.
  1372. Uses a case-insensitive comparison.
  1373. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1374. */
  1375. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1376. /** Searches for a substring within this string.
  1377. Uses a case-insensitive comparison.
  1378. @param startIndex the index from which the search should proceed
  1379. @param textToLookFor the string to search for
  1380. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1381. */
  1382. int indexOfIgnoreCase (const int startIndex,
  1383. const tchar* const textToLookFor) const throw();
  1384. /** Searches for a character inside this string (working backwards from the end of the string).
  1385. Uses a case-sensitive comparison.
  1386. @returns the index of the last occurrence of the character in this
  1387. string, or -1 if it's not found.
  1388. */
  1389. int lastIndexOfChar (const tchar character) const throw();
  1390. /** Searches for a substring inside this string (working backwards from the end of the string).
  1391. Uses a case-sensitive comparison.
  1392. @returns the index of the start of the last occurrence of the
  1393. substring within this string, or -1 if it's not found.
  1394. */
  1395. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1396. /** Searches for a substring inside this string (working backwards from the end of the string).
  1397. Uses a case-insensitive comparison.
  1398. @returns the index of the start of the last occurrence of the
  1399. substring within this string, or -1 if it's not found.
  1400. */
  1401. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1402. /** Returns the index of the last character in this string that matches one of the
  1403. characters passed-in to this method.
  1404. This scans the string backwards, starting from its end, and if it finds
  1405. a character that appears in the string charactersToLookFor, it returns its index.
  1406. If none of these characters are found, it returns -1.
  1407. If ignoreCase is true, the comparison will be case-insensitive.
  1408. @see lastIndexOf, indexOfAnyOf
  1409. */
  1410. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1411. const bool ignoreCase = false) const throw();
  1412. // Substring extraction and manipulation methods..
  1413. /** Returns the character at this index in the string.
  1414. No checks are made to see if the index is within a valid range, so be careful!
  1415. */
  1416. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1417. /** Returns a character from the string such that it can also be altered.
  1418. This can be used as a way of easily changing characters in the string.
  1419. Note that the index passed-in is not checked to see whether it's in-range, so
  1420. be careful when using this.
  1421. */
  1422. tchar& operator[] (const int index) throw();
  1423. /** Returns the final character of the string.
  1424. If the string is empty this will return 0.
  1425. */
  1426. tchar getLastCharacter() const throw();
  1427. /** Returns a subsection of the string.
  1428. If the range specified is beyond the limits of the string, as much as
  1429. possible is returned.
  1430. @param startIndex the index of the start of the substring needed
  1431. @param endIndex all characters from startIndex up to (but not including)
  1432. this index are returned
  1433. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1434. */
  1435. const String substring (int startIndex,
  1436. int endIndex) const throw();
  1437. /** Returns a section of the string, starting from a given position.
  1438. @param startIndex the first character to include. If this is beyond the end
  1439. of the string, an empty string is returned. If it is zero or
  1440. less, the whole string is returned.
  1441. @returns the substring from startIndex up to the end of the string
  1442. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1443. */
  1444. const String substring (const int startIndex) const throw();
  1445. /** Returns a version of this string with a number of characters removed
  1446. from the end.
  1447. @param numberToDrop the number of characters to drop from the end of the
  1448. string. If this is greater than the length of the string,
  1449. an empty string will be returned. If zero or less, the
  1450. original string will be returned.
  1451. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1452. */
  1453. const String dropLastCharacters (const int numberToDrop) const throw();
  1454. /** Returns a section of the string starting from a given substring.
  1455. This will search for the first occurrence of the given substring, and
  1456. return the section of the string starting from the point where this is
  1457. found (optionally not including the substring itself).
  1458. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1459. fromFirstOccurrenceOf ("34", false) would return "56".
  1460. If the substring isn't found, the method will return an empty string.
  1461. If ignoreCase is true, the comparison will be case-insensitive.
  1462. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1463. */
  1464. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1465. const bool includeSubStringInResult,
  1466. const bool ignoreCase) const throw();
  1467. /** Returns a section of the string starting from the last occurrence of a given substring.
  1468. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1469. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1470. return the whole of the original string.
  1471. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1472. */
  1473. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1474. const bool includeSubStringInResult,
  1475. const bool ignoreCase) const throw();
  1476. /** Returns the start of this string, up to the first occurrence of a substring.
  1477. This will search for the first occurrence of a given substring, and then
  1478. return a copy of the string, up to the position of this substring,
  1479. optionally including or excluding the substring itself in the result.
  1480. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1481. upTo ("34", true) would return "1234".
  1482. If the substring isn't found, this will return the whole of the original string.
  1483. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1484. */
  1485. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1486. const bool includeSubStringInResult,
  1487. const bool ignoreCase) const throw();
  1488. /** Returns the start of this string, up to the last occurrence of a substring.
  1489. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1490. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1491. */
  1492. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1493. const bool includeSubStringInResult,
  1494. const bool ignoreCase) const throw();
  1495. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1496. const String trim() const throw();
  1497. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1498. const String trimStart() const throw();
  1499. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1500. const String trimEnd() const throw();
  1501. /** Returns an upper-case version of this string. */
  1502. const String toUpperCase() const throw();
  1503. /** Returns an lower-case version of this string. */
  1504. const String toLowerCase() const throw();
  1505. /** Replaces a sub-section of the string with another string.
  1506. This will return a copy of this string, with a set of characters
  1507. from startIndex to startIndex + numCharsToReplace removed, and with
  1508. a new string inserted in their place.
  1509. Note that this is a const method, and won't alter the string itself.
  1510. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1511. it will be constrained to a valid range.
  1512. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1513. characters will be taken out.
  1514. @param stringToInsert the new string to insert at startIndex after the characters have been
  1515. removed.
  1516. */
  1517. const String replaceSection (int startIndex,
  1518. int numCharactersToReplace,
  1519. const tchar* const stringToInsert) const throw();
  1520. /** Replaces all occurrences of a substring with another string.
  1521. Returns a copy of this string, with any occurrences of stringToReplace
  1522. swapped for stringToInsertInstead.
  1523. Note that this is a const method, and won't alter the string itself.
  1524. */
  1525. const String replace (const tchar* const stringToReplace,
  1526. const tchar* const stringToInsertInstead,
  1527. const bool ignoreCase = false) const throw();
  1528. /** Returns a string with all occurrences of a character replaced with a different one. */
  1529. const String replaceCharacter (const tchar characterToReplace,
  1530. const tchar characterToInsertInstead) const throw();
  1531. /** Replaces a set of characters with another set.
  1532. Returns a string in which each character from charactersToReplace has been replaced
  1533. by the character at the equivalent position in newCharacters (so the two strings
  1534. passed in must be the same length).
  1535. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1536. Note that this is a const method, and won't affect the string itself.
  1537. */
  1538. const String replaceCharacters (const String& charactersToReplace,
  1539. const tchar* const charactersToInsertInstead) const throw();
  1540. /** Returns a version of this string that only retains a fixed set of characters.
  1541. This will return a copy of this string, omitting any characters which are not
  1542. found in the string passed-in.
  1543. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1544. Note that this is a const method, and won't alter the string itself.
  1545. */
  1546. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1547. /** Returns a version of this string with a set of characters removed.
  1548. This will return a copy of this string, omitting any characters which are
  1549. found in the string passed-in.
  1550. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1551. Note that this is a const method, and won't alter the string itself.
  1552. */
  1553. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1554. /** Returns a section from the start of the string that only contains a certain set of characters.
  1555. This returns the leftmost section of the string, up to (and not including) the
  1556. first character that doesn't appear in the string passed in.
  1557. */
  1558. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1559. /** Returns a section from the start of the string that only contains a certain set of characters.
  1560. This returns the leftmost section of the string, up to (and not including) the
  1561. first character that occurs in the string passed in.
  1562. */
  1563. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1564. /** Checks whether the string might be in quotation marks.
  1565. @returns true if the string begins with a quote character (either a double or single quote).
  1566. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1567. @see unquoted, quoted
  1568. */
  1569. bool isQuotedString() const throw();
  1570. /** Removes quotation marks from around the string, (if there are any).
  1571. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1572. at the ends of the string are not affected. If there aren't any quotes, the original string
  1573. is returned.
  1574. Note that this is a const method, and won't alter the string itself.
  1575. @see isQuotedString, quoted
  1576. */
  1577. const String unquoted() const throw();
  1578. /** Adds quotation marks around a string.
  1579. This will return a copy of the string with a quote at the start and end, (but won't
  1580. add the quote if there's already one there, so it's safe to call this on strings that
  1581. may already have quotes around them).
  1582. Note that this is a const method, and won't alter the string itself.
  1583. @param quoteCharacter the character to add at the start and end
  1584. @see isQuotedString, unquoted
  1585. */
  1586. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1587. /** Writes text into this string, using printf style-arguments.
  1588. This will replace the contents of the string with the output of this
  1589. formatted printf.
  1590. Note that using the %s token with a juce string is probably a bad idea, as
  1591. this may expect differect encodings on different platforms.
  1592. @see formatted
  1593. */
  1594. void printf (const tchar* const format, ...) throw();
  1595. /** Returns a string, created using arguments in the style of printf.
  1596. This will return a string which is the result of a sprintf using the
  1597. arguments passed-in.
  1598. Note that using the %s token with a juce string is probably a bad idea, as
  1599. this may expect differect encodings on different platforms.
  1600. @see printf, vprintf
  1601. */
  1602. static const String formatted (const tchar* const format, ...) throw();
  1603. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1604. This will replace the contents of the string with the output of this
  1605. formatted printf. Used by other methods, this is public in case it's
  1606. useful for other purposes where you want to pass a va_list through directly.
  1607. Note that using the %s token with a juce string is probably a bad idea, as
  1608. this may expect differect encodings on different platforms.
  1609. @see printf, formatted
  1610. */
  1611. void vprintf (const tchar* const format, va_list& args) throw();
  1612. /** Creates a string which is a version of a string repeated and joined together.
  1613. @param stringToRepeat the string to repeat
  1614. @param numberOfTimesToRepeat how many times to repeat it
  1615. */
  1616. static const String repeatedString (const tchar* const stringToRepeat,
  1617. int numberOfTimesToRepeat) throw();
  1618. /** Creates a string from data in an unknown format.
  1619. This looks at some binary data and tries to guess whether it's Unicode
  1620. or 8-bit characters, then returns a string that represents it correctly.
  1621. Should be able to handle Unicode endianness correctly, by looking at
  1622. the first two bytes.
  1623. */
  1624. static const String createStringFromData (const void* const data,
  1625. const int size) throw();
  1626. // Numeric conversions..
  1627. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1628. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1629. */
  1630. explicit String (const int decimalInteger) throw();
  1631. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1632. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1633. */
  1634. explicit String (const unsigned int decimalInteger) throw();
  1635. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1636. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1637. */
  1638. explicit String (const short decimalInteger) throw();
  1639. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1640. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1641. */
  1642. explicit String (const unsigned short decimalInteger) throw();
  1643. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1644. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1645. */
  1646. explicit String (const int64 largeIntegerValue) throw();
  1647. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1648. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1649. */
  1650. explicit String (const uint64 largeIntegerValue) throw();
  1651. /** Creates a string representing this floating-point number.
  1652. @param floatValue the value to convert to a string
  1653. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1654. decimal places, and will not use exponent notation. If 0 or
  1655. less, it will use exponent notation if necessary.
  1656. @see getDoubleValue, getIntValue
  1657. */
  1658. explicit String (const float floatValue,
  1659. const int numberOfDecimalPlaces = 0) throw();
  1660. /** Creates a string representing this floating-point number.
  1661. @param doubleValue the value to convert to a string
  1662. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1663. decimal places, and will not use exponent notation. If 0 or
  1664. less, it will use exponent notation if necessary.
  1665. @see getFloatValue, getIntValue
  1666. */
  1667. explicit String (const double doubleValue,
  1668. const int numberOfDecimalPlaces = 0) throw();
  1669. /** Parses this string to find its numerical value (up to 32 bits in size).
  1670. @returns the value of the string as a 32 bit signed base-10 integer.
  1671. @see getTrailingIntValue, getHexValue32, getHexValue64
  1672. */
  1673. int getIntValue() const throw();
  1674. /** Parses this string to find its numerical value (up to 64 bits in size).
  1675. @returns the value of the string as a 64 bit signed base-10 integer.
  1676. */
  1677. int64 getLargeIntValue() const throw();
  1678. /** Parses a decimal number from the end of the string.
  1679. This will look for a value at the end of the string.
  1680. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1681. Negative numbers are not handled, so "xyz-5" returns 5.
  1682. @see getIntValue
  1683. */
  1684. int getTrailingIntValue() const throw();
  1685. /** Parses this string as a floating point number.
  1686. @returns the value of the string as a 32-bit floating point value.
  1687. @see getDoubleValue
  1688. */
  1689. float getFloatValue() const throw();
  1690. /** Parses this string as a floating point number.
  1691. @returns the value of the string as a 64-bit floating point value.
  1692. @see getFloatValue
  1693. */
  1694. double getDoubleValue() const throw();
  1695. /** Parses the string as a hexadecimal number.
  1696. Non-hexadecimal characters in the string are ignored.
  1697. If the string contains too many characters, then the lowest significant
  1698. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1699. @returns a 32-bit number which is the value of the string in hex.
  1700. */
  1701. int getHexValue32() const throw();
  1702. /** Parses the string as a hexadecimal number.
  1703. Non-hexadecimal characters in the string are ignored.
  1704. If the string contains too many characters, then the lowest significant
  1705. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1706. @returns a 64-bit number which is the value of the string in hex.
  1707. */
  1708. int64 getHexValue64() const throw();
  1709. /** Creates a string representing this 32-bit value in hexadecimal. */
  1710. static const String toHexString (const int number) throw();
  1711. /** Creates a string representing this 64-bit value in hexadecimal. */
  1712. static const String toHexString (const int64 number) throw();
  1713. /** Creates a string representing this 16-bit value in hexadecimal. */
  1714. static const String toHexString (const short number) throw();
  1715. /** Creates a string containing a hex dump of a block of binary data.
  1716. @param data the binary data to use as input
  1717. @param size how many bytes of data to use
  1718. @param groupSize how many bytes are grouped together before inserting a
  1719. space into the output. e.g. group size 0 has no spaces,
  1720. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1721. like "bea1 c2ff".
  1722. */
  1723. static const String toHexString (const unsigned char* data,
  1724. const int size,
  1725. const int groupSize = 1) throw();
  1726. // Casting to character arrays..
  1727. #if JUCE_STRINGS_ARE_UNICODE
  1728. /** Returns a version of this string using the default 8-bit system encoding.
  1729. Because it returns a reference to the string's internal data, the pointer
  1730. that is returned must not be stored anywhere, as it can be deleted whenever the
  1731. string changes.
  1732. */
  1733. operator const char*() const throw();
  1734. /** Returns a unicode version of this string.
  1735. Because it returns a reference to the string's internal data, the pointer
  1736. that is returned must not be stored anywhere, as it can be deleted whenever the
  1737. string changes.
  1738. */
  1739. inline operator const juce_wchar*() const throw() { return text->text; }
  1740. #else
  1741. /** Returns a version of this string using the default 8-bit system encoding.
  1742. Because it returns a reference to the string's internal data, the pointer
  1743. that is returned must not be stored anywhere, as it can be deleted whenever the
  1744. string changes.
  1745. */
  1746. inline operator const char*() const throw() { return text->text; }
  1747. /** Returns a unicode version of this string.
  1748. Because it returns a reference to the string's internal data, the pointer
  1749. that is returned must not be stored anywhere, as it can be deleted whenever the
  1750. string changes.
  1751. */
  1752. operator const juce_wchar*() const throw();
  1753. #endif
  1754. /** Copies the string to a buffer.
  1755. @param destBuffer the place to copy it to
  1756. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1757. not including the tailing zero, so this shouldn't be
  1758. larger than the size of your destination buffer - 1
  1759. */
  1760. void copyToBuffer (char* const destBuffer,
  1761. const int maxCharsToCopy) const throw();
  1762. /** Copies the string to a unicode buffer.
  1763. @param destBuffer the place to copy it to
  1764. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1765. not including the tailing zero, so this shouldn't be
  1766. larger than the size of your destination buffer - 1
  1767. */
  1768. void copyToBuffer (juce_wchar* const destBuffer,
  1769. const int maxCharsToCopy) const throw();
  1770. /** Copies the string to a buffer as UTF-8 characters.
  1771. Returns the number of bytes copied to the buffer, including the terminating null
  1772. character.
  1773. @param destBuffer the place to copy it to; if this is a null pointer,
  1774. the method just returns the number of bytes required
  1775. (including the terminating null character).
  1776. */
  1777. int copyToUTF8 (uint8* const destBuffer) const throw();
  1778. /** Returns a pointer to a UTF-8 version of this string.
  1779. Because it returns a reference to the string's internal data, the pointer
  1780. that is returned must not be stored anywhere, as it can be deleted whenever the
  1781. string changes.
  1782. */
  1783. const char* toUTF8() const throw();
  1784. /** Creates a String from a UTF-8 encoded buffer.
  1785. If the size is < 0, it'll keep reading until it hits a zero.
  1786. */
  1787. static const String fromUTF8 (const uint8* const utf8buffer,
  1788. int bufferSizeBytes = -1) throw();
  1789. /** Increases the string's internally allocated storage.
  1790. Although the string's contents won't be affected by this call, it will
  1791. increase the amount of memory allocated internally for the string to grow into.
  1792. If you're about to make a large number of calls to methods such
  1793. as += or <<, it's more efficient to preallocate enough extra space
  1794. beforehand, so that these methods won't have to keep resizing the string
  1795. to append the extra characters.
  1796. @param numCharsNeeded the number of characters to allocate storage for. If this
  1797. value is less than the currently allocated size, it will
  1798. have no effect.
  1799. */
  1800. void preallocateStorage (const int numCharsNeeded) throw();
  1801. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1802. private:
  1803. struct InternalRefCountedStringHolder
  1804. {
  1805. int refCount;
  1806. int allocatedNumChars;
  1807. #if JUCE_STRINGS_ARE_UNICODE
  1808. wchar_t text[1];
  1809. #else
  1810. char text[1];
  1811. #endif
  1812. };
  1813. InternalRefCountedStringHolder* text;
  1814. static InternalRefCountedStringHolder emptyString;
  1815. // internal constructor that preallocates a certain amount of memory
  1816. String (const int numChars, const int dummyVariable) throw();
  1817. void deleteInternal() throw();
  1818. void createInternal (const int numChars) throw();
  1819. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1820. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1821. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1822. void dupeInternalIfMultiplyReferenced() throw();
  1823. };
  1824. /** Global operator to allow a String to be appended to a string literal.
  1825. This allows the use of expressions such as "abc" + String (x)
  1826. @see String
  1827. */
  1828. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1829. const String& string2) throw();
  1830. /** Global operator to allow a String to be appended to a string literal.
  1831. This allows the use of expressions such as "abc" + String (x)
  1832. @see String
  1833. */
  1834. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1835. const String& string2) throw();
  1836. #endif // __JUCE_STRING_JUCEHEADER__
  1837. /********* End of inlined file: juce_String.h *********/
  1838. /**
  1839. Acts as an application-wide logging class.
  1840. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1841. method and this will then be used by all calls to writeToLog.
  1842. The logger class also contains methods for writing messages to the debugger's
  1843. output stream.
  1844. @see FileLogger
  1845. */
  1846. class JUCE_API Logger
  1847. {
  1848. public:
  1849. /** Destructor. */
  1850. virtual ~Logger();
  1851. /** Sets the current logging class to use.
  1852. Note that the object passed in won't be deleted when no longer needed.
  1853. A null pointer can be passed-in to disable any logging.
  1854. If deleteOldLogger is set to true, the existing logger will be
  1855. deleted (if there is one).
  1856. */
  1857. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1858. const bool deleteOldLogger = false);
  1859. /** Writes a string to the current logger.
  1860. This will pass the string to the logger's logMessage() method if a logger
  1861. has been set.
  1862. @see logMessage
  1863. */
  1864. static void JUCE_CALLTYPE writeToLog (const String& message);
  1865. /** Writes a message to the standard error stream.
  1866. This can be called directly, or by using the DBG() macro in
  1867. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1868. */
  1869. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1870. /** Writes a message to the standard error stream.
  1871. This can be called directly, or by using the DBG_PRINTF() macro in
  1872. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1873. */
  1874. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1875. protected:
  1876. Logger();
  1877. /** This is overloaded by subclasses to implement custom logging behaviour.
  1878. @see setCurrentLogger
  1879. */
  1880. virtual void logMessage (const String& message) = 0;
  1881. };
  1882. #endif // __JUCE_LOGGER_JUCEHEADER__
  1883. /********* End of inlined file: juce_Logger.h *********/
  1884. END_JUCE_NAMESPACE
  1885. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1886. /********* End of inlined file: juce_StandardHeader.h *********/
  1887. BEGIN_JUCE_NAMESPACE
  1888. #if JUCE_MSVC
  1889. // this is set explicitly in case the app is using a different packing size.
  1890. #pragma pack (push, 8)
  1891. #pragma warning (push)
  1892. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1893. #endif
  1894. #if JUCE_MAC
  1895. #pragma align=natural
  1896. #endif
  1897. #define JUCE_PUBLIC_INCLUDES
  1898. // this is where all the class header files get brought in..
  1899. /********* Start of inlined file: juce_core_includes.h *********/
  1900. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1901. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1902. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1903. /********* Start of inlined file: juce_Atomic.h *********/
  1904. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1905. #define __JUCE_ATOMIC_JUCEHEADER__
  1906. // Atomic increment/decrement operations..
  1907. #if JUCE_MAC && ! DOXYGEN
  1908. #if ! MACOS_10_3_OR_EARLIER
  1909. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1910. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1911. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1912. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1913. #else
  1914. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  1915. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  1916. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1917. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1918. #endif
  1919. #elif JUCE_GCC
  1920. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1921. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1922. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1923. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1924. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1925. #else
  1926. /** Increments an integer in a thread-safe way. */
  1927. forcedinline void atomicIncrement (int& variable) throw()
  1928. {
  1929. __asm__ __volatile__ (
  1930. #if JUCE_64BIT
  1931. "lock incl (%%rax)"
  1932. :
  1933. : "a" (&variable)
  1934. : "cc", "memory");
  1935. #else
  1936. "lock incl %0"
  1937. : "=m" (variable)
  1938. : "m" (variable));
  1939. #endif
  1940. }
  1941. /** Increments an integer in a thread-safe way and returns the incremented value. */
  1942. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  1943. {
  1944. int result;
  1945. __asm__ __volatile__ (
  1946. #if JUCE_64BIT
  1947. "lock xaddl %%ebx, (%%rax) \n\
  1948. incl %%ebx"
  1949. : "=b" (result)
  1950. : "a" (&variable), "b" (1)
  1951. : "cc", "memory");
  1952. #else
  1953. "lock xaddl %%eax, (%%ecx) \n\
  1954. incl %%eax"
  1955. : "=a" (result)
  1956. : "c" (&variable), "a" (1)
  1957. : "memory");
  1958. #endif
  1959. return result;
  1960. }
  1961. /** Decrememts an integer in a thread-safe way. */
  1962. forcedinline void atomicDecrement (int& variable) throw()
  1963. {
  1964. __asm__ __volatile__ (
  1965. #if JUCE_64BIT
  1966. "lock decl (%%rax)"
  1967. :
  1968. : "a" (&variable)
  1969. : "cc", "memory");
  1970. #else
  1971. "lock decl %0"
  1972. : "=m" (variable)
  1973. : "m" (variable));
  1974. #endif
  1975. }
  1976. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  1977. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  1978. {
  1979. int result;
  1980. __asm__ __volatile__ (
  1981. #if JUCE_64BIT
  1982. "lock xaddl %%ebx, (%%rax) \n\
  1983. decl %%ebx"
  1984. : "=b" (result)
  1985. : "a" (&variable), "b" (-1)
  1986. : "cc", "memory");
  1987. #else
  1988. "lock xaddl %%eax, (%%ecx) \n\
  1989. decl %%eax"
  1990. : "=a" (result)
  1991. : "c" (&variable), "a" (-1)
  1992. : "memory");
  1993. #endif
  1994. return result;
  1995. }
  1996. #endif
  1997. #elif JUCE_USE_INTRINSICS
  1998. #pragma intrinsic (_InterlockedIncrement)
  1999. #pragma intrinsic (_InterlockedDecrement)
  2000. /** Increments an integer in a thread-safe way. */
  2001. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2002. {
  2003. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2004. }
  2005. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2006. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2007. {
  2008. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2009. }
  2010. /** Decrememts an integer in a thread-safe way. */
  2011. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2012. {
  2013. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2014. }
  2015. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2016. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2017. {
  2018. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2019. }
  2020. #else
  2021. /** Increments an integer in a thread-safe way. */
  2022. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2023. {
  2024. __asm {
  2025. mov ecx, dword ptr [variable]
  2026. lock inc dword ptr [ecx]
  2027. }
  2028. }
  2029. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2030. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2031. {
  2032. int result;
  2033. __asm {
  2034. mov ecx, dword ptr [variable]
  2035. mov eax, 1
  2036. lock xadd dword ptr [ecx], eax
  2037. inc eax
  2038. mov result, eax
  2039. }
  2040. return result;
  2041. }
  2042. /** Decrememts an integer in a thread-safe way. */
  2043. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2044. {
  2045. __asm {
  2046. mov ecx, dword ptr [variable]
  2047. lock dec dword ptr [ecx]
  2048. }
  2049. }
  2050. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2051. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2052. {
  2053. int result;
  2054. __asm {
  2055. mov ecx, dword ptr [variable]
  2056. mov eax, -1
  2057. lock xadd dword ptr [ecx], eax
  2058. dec eax
  2059. mov result, eax
  2060. }
  2061. return result;
  2062. }
  2063. #endif
  2064. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2065. /********* End of inlined file: juce_Atomic.h *********/
  2066. #endif
  2067. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2068. #endif
  2069. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2070. /********* Start of inlined file: juce_FileLogger.h *********/
  2071. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2072. #define __JUCE_FILELOGGER_JUCEHEADER__
  2073. /********* Start of inlined file: juce_File.h *********/
  2074. #ifndef __JUCE_FILE_JUCEHEADER__
  2075. #define __JUCE_FILE_JUCEHEADER__
  2076. /********* Start of inlined file: juce_OwnedArray.h *********/
  2077. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2078. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2079. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2080. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2081. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2082. /** The default size of chunk in which arrays increase their storage.
  2083. Used by ArrayAllocationBase and its subclasses.
  2084. */
  2085. const int juceDefaultArrayGranularity = 8;
  2086. /**
  2087. Implements some basic array storage allocation functions.
  2088. This class isn't really for public use - it's used by the other
  2089. array classes, but might come in handy for some purposes.
  2090. @see Array, OwnedArray, ReferenceCountedArray
  2091. */
  2092. template <class ElementType>
  2093. class ArrayAllocationBase
  2094. {
  2095. protected:
  2096. /** Creates an empty array.
  2097. @param granularity_ this is the size of increment by which the internal storage
  2098. will be increased.
  2099. */
  2100. ArrayAllocationBase (const int granularity_) throw()
  2101. : elements (0),
  2102. numAllocated (0),
  2103. granularity (granularity_)
  2104. {
  2105. }
  2106. /** Destructor. */
  2107. ~ArrayAllocationBase() throw()
  2108. {
  2109. delete[] elements;
  2110. }
  2111. /** Changes the amount of storage allocated.
  2112. This will retain any data currently held in the array, and either add or
  2113. remove extra space at the end.
  2114. @param numElements the number of elements that are needed
  2115. */
  2116. void setAllocatedSize (const int numElements) throw()
  2117. {
  2118. if (numAllocated != numElements)
  2119. {
  2120. if (numElements > 0)
  2121. {
  2122. ElementType* const newElements = new ElementType [numElements];
  2123. const int itemsToRetain = jmin (numElements, numAllocated);
  2124. for (int i = 0; i < itemsToRetain; ++i)
  2125. newElements[i] = elements[i];
  2126. delete[] elements;
  2127. elements = newElements;
  2128. }
  2129. else if (elements != 0)
  2130. {
  2131. delete[] elements;
  2132. elements = 0;
  2133. }
  2134. numAllocated = numElements;
  2135. }
  2136. }
  2137. /** Increases the amount of storage allocated if it is less than a given amount.
  2138. This will retain any data currently held in the array, but will add
  2139. extra space at the end to make sure there it's at least as big as the size
  2140. passed in. If it's already bigger, no action is taken.
  2141. @param minNumElements the minimum number of elements that are needed
  2142. */
  2143. void ensureAllocatedSize (int minNumElements) throw()
  2144. {
  2145. if (minNumElements > numAllocated)
  2146. {
  2147. // for arrays with small granularity that get big, start
  2148. // increasing the size in bigger jumps
  2149. if (minNumElements > (granularity << 6))
  2150. {
  2151. minNumElements += (minNumElements / granularity);
  2152. if (minNumElements > (granularity << 8))
  2153. minNumElements += granularity << 6;
  2154. else
  2155. minNumElements += granularity << 5;
  2156. }
  2157. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2158. }
  2159. }
  2160. ElementType* elements;
  2161. int numAllocated, granularity;
  2162. private:
  2163. ArrayAllocationBase (const ArrayAllocationBase&);
  2164. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2165. };
  2166. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2167. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2168. /********* Start of inlined file: juce_ElementComparator.h *********/
  2169. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2170. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2171. /**
  2172. Sorts a range of elements in an array.
  2173. The comparator object that is passed-in must define a public method with the following
  2174. signature:
  2175. @code
  2176. int compareElements (ElementType first, ElementType second);
  2177. @endcode
  2178. ..and this method must return:
  2179. - a value of < 0 if the first comes before the second
  2180. - a value of 0 if the two objects are equivalent
  2181. - a value of > 0 if the second comes before the first
  2182. To improve performance, the compareElements() method can be declared as static or const.
  2183. @param comparator an object which defines a compareElements() method
  2184. @param array the array to sort
  2185. @param firstElement the index of the first element of the range to be sorted
  2186. @param lastElement the index of the last element in the range that needs
  2187. sorting (this is inclusive)
  2188. @param retainOrderOfEquivalentItems if true, the order of items that the
  2189. comparator deems the same will be maintained - this will be
  2190. a slower algorithm than if they are allowed to be moved around.
  2191. @see sortArrayRetainingOrder
  2192. */
  2193. template <class ElementType, class ElementComparator>
  2194. static void sortArray (ElementComparator& comparator,
  2195. ElementType* const array,
  2196. int firstElement,
  2197. int lastElement,
  2198. const bool retainOrderOfEquivalentItems)
  2199. {
  2200. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2201. // avoids getting warning messages about the parameter being unused
  2202. if (lastElement > firstElement)
  2203. {
  2204. if (retainOrderOfEquivalentItems)
  2205. {
  2206. for (int i = firstElement; i < lastElement; ++i)
  2207. {
  2208. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2209. {
  2210. const ElementType temp = array [i];
  2211. array [i] = array[i + 1];
  2212. array [i + 1] = temp;
  2213. if (i > firstElement)
  2214. i -= 2;
  2215. }
  2216. }
  2217. }
  2218. else
  2219. {
  2220. int fromStack[30], toStack[30];
  2221. int stackIndex = 0;
  2222. for (;;)
  2223. {
  2224. const int size = (lastElement - firstElement) + 1;
  2225. if (size <= 8)
  2226. {
  2227. int j = lastElement;
  2228. int maxIndex;
  2229. while (j > firstElement)
  2230. {
  2231. maxIndex = firstElement;
  2232. for (int k = firstElement + 1; k <= j; ++k)
  2233. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2234. maxIndex = k;
  2235. const ElementType temp = array [maxIndex];
  2236. array [maxIndex] = array[j];
  2237. array [j] = temp;
  2238. --j;
  2239. }
  2240. }
  2241. else
  2242. {
  2243. const int mid = firstElement + (size >> 1);
  2244. ElementType temp = array [mid];
  2245. array [mid] = array [firstElement];
  2246. array [firstElement] = temp;
  2247. int i = firstElement;
  2248. int j = lastElement + 1;
  2249. for (;;)
  2250. {
  2251. while (++i <= lastElement
  2252. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2253. {}
  2254. while (--j > firstElement
  2255. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2256. {}
  2257. if (j < i)
  2258. break;
  2259. temp = array[i];
  2260. array[i] = array[j];
  2261. array[j] = temp;
  2262. }
  2263. temp = array [firstElement];
  2264. array [firstElement] = array[j];
  2265. array [j] = temp;
  2266. if (j - 1 - firstElement >= lastElement - i)
  2267. {
  2268. if (firstElement + 1 < j)
  2269. {
  2270. fromStack [stackIndex] = firstElement;
  2271. toStack [stackIndex] = j - 1;
  2272. ++stackIndex;
  2273. }
  2274. if (i < lastElement)
  2275. {
  2276. firstElement = i;
  2277. continue;
  2278. }
  2279. }
  2280. else
  2281. {
  2282. if (i < lastElement)
  2283. {
  2284. fromStack [stackIndex] = i;
  2285. toStack [stackIndex] = lastElement;
  2286. ++stackIndex;
  2287. }
  2288. if (firstElement + 1 < j)
  2289. {
  2290. lastElement = j - 1;
  2291. continue;
  2292. }
  2293. }
  2294. }
  2295. if (--stackIndex < 0)
  2296. break;
  2297. jassert (stackIndex < numElementsInArray (fromStack));
  2298. firstElement = fromStack [stackIndex];
  2299. lastElement = toStack [stackIndex];
  2300. }
  2301. }
  2302. }
  2303. }
  2304. /**
  2305. Searches a sorted array of elements, looking for the index at which a specified value
  2306. should be inserted for it to be in the correct order.
  2307. The comparator object that is passed-in must define a public method with the following
  2308. signature:
  2309. @code
  2310. int compareElements (ElementType first, ElementType second);
  2311. @endcode
  2312. ..and this method must return:
  2313. - a value of < 0 if the first comes before the second
  2314. - a value of 0 if the two objects are equivalent
  2315. - a value of > 0 if the second comes before the first
  2316. To improve performance, the compareElements() method can be declared as static or const.
  2317. @param comparator an object which defines a compareElements() method
  2318. @param array the array to search
  2319. @param newElement the value that is going to be inserted
  2320. @param firstElement the index of the first element to search
  2321. @param lastElement the index of the last element in the range (this is non-inclusive)
  2322. */
  2323. template <class ElementType, class ElementComparator>
  2324. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2325. ElementType* const array,
  2326. const ElementType newElement,
  2327. int firstElement,
  2328. int lastElement)
  2329. {
  2330. jassert (firstElement <= lastElement);
  2331. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2332. // avoids getting warning messages about the parameter being unused
  2333. while (firstElement < lastElement)
  2334. {
  2335. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2336. {
  2337. ++firstElement;
  2338. break;
  2339. }
  2340. else
  2341. {
  2342. const int halfway = (firstElement + lastElement) >> 1;
  2343. if (halfway == firstElement)
  2344. {
  2345. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2346. ++firstElement;
  2347. break;
  2348. }
  2349. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2350. {
  2351. firstElement = halfway;
  2352. }
  2353. else
  2354. {
  2355. lastElement = halfway;
  2356. }
  2357. }
  2358. }
  2359. return firstElement;
  2360. }
  2361. /**
  2362. A simple ElementComparator class that can be used to sort an array of
  2363. integer primitive objects.
  2364. Example: @code
  2365. Array <int> myArray;
  2366. IntegerElementComparator<int> sorter;
  2367. myArray.sort (sorter);
  2368. @endcode
  2369. For floating point values, see the FloatElementComparator class instead.
  2370. @see FloatElementComparator, ElementComparator
  2371. */
  2372. template <class ElementType>
  2373. class IntegerElementComparator
  2374. {
  2375. public:
  2376. static int compareElements (const ElementType first,
  2377. const ElementType second) throw()
  2378. {
  2379. return first - second;
  2380. }
  2381. };
  2382. /**
  2383. A simple ElementComparator class that can be used to sort an array of numeric
  2384. double or floating point primitive objects.
  2385. Example: @code
  2386. Array <double> myArray;
  2387. FloatElementComparator<double> sorter;
  2388. myArray.sort (sorter);
  2389. @endcode
  2390. For integer values, see the IntegerElementComparator class instead.
  2391. @see IntegerElementComparator, ElementComparator
  2392. */
  2393. template <class ElementType>
  2394. class FloatElementComparator
  2395. {
  2396. public:
  2397. static int compareElements (const ElementType first,
  2398. const ElementType second) throw()
  2399. {
  2400. return (first < second) ? -1
  2401. : ((first == second) ? 0
  2402. : 1);
  2403. }
  2404. };
  2405. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2406. /********* End of inlined file: juce_ElementComparator.h *********/
  2407. /********* Start of inlined file: juce_CriticalSection.h *********/
  2408. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2409. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2410. /**
  2411. Prevents multiple threads from accessing shared objects at the same time.
  2412. @see ScopedLock, Thread, InterProcessLock
  2413. */
  2414. class JUCE_API CriticalSection
  2415. {
  2416. public:
  2417. /**
  2418. Creates a CriticalSection object
  2419. */
  2420. CriticalSection() throw();
  2421. /** Destroys a CriticalSection object.
  2422. If the critical section is deleted whilst locked, its subsequent behaviour
  2423. is unpredictable.
  2424. */
  2425. ~CriticalSection() throw();
  2426. /** Locks this critical section.
  2427. If the lock is currently held by another thread, this will wait until it
  2428. becomes free.
  2429. If the lock is already held by the caller thread, the method returns immediately.
  2430. @see exit, ScopedLock
  2431. */
  2432. void enter() const throw();
  2433. /** Attempts to lock this critical section without blocking.
  2434. This method behaves identically to CriticalSection::enter, except that the caller thread
  2435. does not wait if the lock is currently held by another thread but returns false immediately.
  2436. @returns false if the lock is currently held by another thread, true otherwise.
  2437. @see enter
  2438. */
  2439. bool tryEnter() const throw();
  2440. /** Releases the lock.
  2441. If the caller thread hasn't got the lock, this can have unpredictable results.
  2442. If the enter() method has been called multiple times by the thread, each
  2443. call must be matched by a call to exit() before other threads will be allowed
  2444. to take over the lock.
  2445. @see enter, ScopedLock
  2446. */
  2447. void exit() const throw();
  2448. juce_UseDebuggingNewOperator
  2449. private:
  2450. #if JUCE_WIN32
  2451. #if JUCE_64BIT
  2452. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2453. // block of memory here that's big enough to be used internally as a windows critical
  2454. // section object.
  2455. uint8 internal [44];
  2456. #else
  2457. uint8 internal [24];
  2458. #endif
  2459. #else
  2460. mutable pthread_mutex_t internal;
  2461. #endif
  2462. CriticalSection (const CriticalSection&);
  2463. const CriticalSection& operator= (const CriticalSection&);
  2464. };
  2465. /**
  2466. A class that can be used in place of a real CriticalSection object.
  2467. This is currently used by some templated array classes, and should get
  2468. optimised out by the compiler.
  2469. @see Array, OwnedArray, ReferenceCountedArray
  2470. */
  2471. class JUCE_API DummyCriticalSection
  2472. {
  2473. public:
  2474. forcedinline DummyCriticalSection() throw() {}
  2475. forcedinline ~DummyCriticalSection() throw() {}
  2476. forcedinline void enter() const throw() {}
  2477. forcedinline void exit() const throw() {}
  2478. };
  2479. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2480. /********* End of inlined file: juce_CriticalSection.h *********/
  2481. /** An array designed for holding objects.
  2482. This holds a list of pointers to objects, and will automatically
  2483. delete the objects when they are removed from the array, or when the
  2484. array is itself deleted.
  2485. Declare it in the form: OwnedArray<MyObjectClass>
  2486. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2487. After adding objects, they are 'owned' by the array and will be deleted when
  2488. removed or replaced.
  2489. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2490. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2491. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2492. */
  2493. template <class ObjectClass,
  2494. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2495. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2496. {
  2497. public:
  2498. /** Creates an empty array.
  2499. @param granularity this is the size of increment by which the internal storage
  2500. used by the array will grow. Only change it from the default if you know the
  2501. array is going to be very big and needs to be able to grow efficiently.
  2502. @see ArrayAllocationBase
  2503. */
  2504. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2505. : ArrayAllocationBase <ObjectClass*> (granularity),
  2506. numUsed (0)
  2507. {
  2508. }
  2509. /** Deletes the array and also deletes any objects inside it.
  2510. To get rid of the array without deleting its objects, use its
  2511. clear (false) method before deleting it.
  2512. */
  2513. ~OwnedArray()
  2514. {
  2515. clear (true);
  2516. }
  2517. /** Clears the array, optionally deleting the objects inside it first. */
  2518. void clear (const bool deleteObjects = true)
  2519. {
  2520. lock.enter();
  2521. if (deleteObjects)
  2522. {
  2523. while (numUsed > 0)
  2524. delete this->elements [--numUsed];
  2525. }
  2526. this->setAllocatedSize (0);
  2527. numUsed = 0;
  2528. lock.exit();
  2529. }
  2530. /** Returns the number of items currently in the array.
  2531. @see operator[]
  2532. */
  2533. inline int size() const throw()
  2534. {
  2535. return numUsed;
  2536. }
  2537. /** Returns a pointer to the object at this index in the array.
  2538. If the index is out-of-range, this will return a null pointer, (and
  2539. it could be null anyway, because it's ok for the array to hold null
  2540. pointers as well as objects).
  2541. @see getUnchecked
  2542. */
  2543. inline ObjectClass* operator[] (const int index) const throw()
  2544. {
  2545. lock.enter();
  2546. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2547. ? this->elements [index]
  2548. : (ObjectClass*) 0;
  2549. lock.exit();
  2550. return result;
  2551. }
  2552. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2553. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2554. it can be used when you're sure the index if always going to be legal.
  2555. */
  2556. inline ObjectClass* getUnchecked (const int index) const throw()
  2557. {
  2558. lock.enter();
  2559. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2560. ObjectClass* const result = this->elements [index];
  2561. lock.exit();
  2562. return result;
  2563. }
  2564. /** Returns a pointer to the first object in the array.
  2565. This will return a null pointer if the array's empty.
  2566. @see getLast
  2567. */
  2568. inline ObjectClass* getFirst() const throw()
  2569. {
  2570. lock.enter();
  2571. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2572. : (ObjectClass*) 0;
  2573. lock.exit();
  2574. return result;
  2575. }
  2576. /** Returns a pointer to the last object in the array.
  2577. This will return a null pointer if the array's empty.
  2578. @see getFirst
  2579. */
  2580. inline ObjectClass* getLast() const throw()
  2581. {
  2582. lock.enter();
  2583. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2584. : (ObjectClass*) 0;
  2585. lock.exit();
  2586. return result;
  2587. }
  2588. /** Finds the index of an object which might be in the array.
  2589. @param objectToLookFor the object to look for
  2590. @returns the index at which the object was found, or -1 if it's not found
  2591. */
  2592. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2593. {
  2594. int result = -1;
  2595. lock.enter();
  2596. ObjectClass* const* e = this->elements;
  2597. for (int i = numUsed; --i >= 0;)
  2598. {
  2599. if (objectToLookFor == *e)
  2600. {
  2601. result = (int) (e - this->elements);
  2602. break;
  2603. }
  2604. ++e;
  2605. }
  2606. lock.exit();
  2607. return result;
  2608. }
  2609. /** Returns true if the array contains a specified object.
  2610. @param objectToLookFor the object to look for
  2611. @returns true if the object is in the array
  2612. */
  2613. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2614. {
  2615. lock.enter();
  2616. ObjectClass* const* e = this->elements;
  2617. int i = numUsed;
  2618. while (i >= 4)
  2619. {
  2620. if (objectToLookFor == *e
  2621. || objectToLookFor == *++e
  2622. || objectToLookFor == *++e
  2623. || objectToLookFor == *++e)
  2624. {
  2625. lock.exit();
  2626. return true;
  2627. }
  2628. i -= 4;
  2629. ++e;
  2630. }
  2631. while (i > 0)
  2632. {
  2633. if (objectToLookFor == *e)
  2634. {
  2635. lock.exit();
  2636. return true;
  2637. }
  2638. --i;
  2639. ++e;
  2640. }
  2641. lock.exit();
  2642. return false;
  2643. }
  2644. /** Appends a new object to the end of the array.
  2645. Note that the this object will be deleted by the OwnedArray when it
  2646. is removed, so be careful not to delete it somewhere else.
  2647. Also be careful not to add the same object to the array more than once,
  2648. as this will obviously cause deletion of dangling pointers.
  2649. @param newObject the new object to add to the array
  2650. @see set, insert, addIfNotAlreadyThere, addSorted
  2651. */
  2652. void add (const ObjectClass* const newObject) throw()
  2653. {
  2654. lock.enter();
  2655. this->ensureAllocatedSize (numUsed + 1);
  2656. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2657. lock.exit();
  2658. }
  2659. /** Inserts a new object into the array at the given index.
  2660. Note that the this object will be deleted by the OwnedArray when it
  2661. is removed, so be careful not to delete it somewhere else.
  2662. If the index is less than 0 or greater than the size of the array, the
  2663. element will be added to the end of the array.
  2664. Otherwise, it will be inserted into the array, moving all the later elements
  2665. along to make room.
  2666. Be careful not to add the same object to the array more than once,
  2667. as this will obviously cause deletion of dangling pointers.
  2668. @param indexToInsertAt the index at which the new element should be inserted
  2669. @param newObject the new object to add to the array
  2670. @see add, addSorted, addIfNotAlreadyThere, set
  2671. */
  2672. void insert (int indexToInsertAt,
  2673. const ObjectClass* const newObject) throw()
  2674. {
  2675. if (indexToInsertAt >= 0)
  2676. {
  2677. lock.enter();
  2678. if (indexToInsertAt > numUsed)
  2679. indexToInsertAt = numUsed;
  2680. this->ensureAllocatedSize (numUsed + 1);
  2681. ObjectClass** const e = this->elements + indexToInsertAt;
  2682. const int numToMove = numUsed - indexToInsertAt;
  2683. if (numToMove > 0)
  2684. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2685. *e = const_cast <ObjectClass*> (newObject);
  2686. ++numUsed;
  2687. lock.exit();
  2688. }
  2689. else
  2690. {
  2691. add (newObject);
  2692. }
  2693. }
  2694. /** Appends a new object at the end of the array as long as the array doesn't
  2695. already contain it.
  2696. If the array already contains a matching object, nothing will be done.
  2697. @param newObject the new object to add to the array
  2698. */
  2699. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2700. {
  2701. lock.enter();
  2702. if (! contains (newObject))
  2703. add (newObject);
  2704. lock.exit();
  2705. }
  2706. /** Replaces an object in the array with a different one.
  2707. If the index is less than zero, this method does nothing.
  2708. If the index is beyond the end of the array, the new object is added to the end of the array.
  2709. Be careful not to add the same object to the array more than once,
  2710. as this will obviously cause deletion of dangling pointers.
  2711. @param indexToChange the index whose value you want to change
  2712. @param newObject the new value to set for this index.
  2713. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2714. @see add, insert, remove
  2715. */
  2716. void set (const int indexToChange,
  2717. const ObjectClass* const newObject,
  2718. const bool deleteOldElement = true)
  2719. {
  2720. if (indexToChange >= 0)
  2721. {
  2722. ObjectClass* toDelete = 0;
  2723. lock.enter();
  2724. if (indexToChange < numUsed)
  2725. {
  2726. if (deleteOldElement)
  2727. toDelete = this->elements [indexToChange];
  2728. if (toDelete == newObject)
  2729. toDelete = 0;
  2730. else
  2731. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2732. }
  2733. else
  2734. {
  2735. this->ensureAllocatedSize (numUsed + 1);
  2736. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2737. }
  2738. lock.exit();
  2739. delete toDelete;
  2740. }
  2741. }
  2742. /** Inserts a new object into the array assuming that the array is sorted.
  2743. This will use a comparator to find the position at which the new object
  2744. should go. If the array isn't sorted, the behaviour of this
  2745. method will be unpredictable.
  2746. @param comparator the comparator to use to compare the elements - see the sort method
  2747. for details about this object's structure
  2748. @param newObject the new object to insert to the array
  2749. @see add, sort, indexOfSorted
  2750. */
  2751. template <class ElementComparator>
  2752. void addSorted (ElementComparator& comparator,
  2753. ObjectClass* const newObject) throw()
  2754. {
  2755. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2756. // avoids getting warning messages about the parameter being unused
  2757. lock.enter();
  2758. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2759. lock.exit();
  2760. }
  2761. /** Finds the index of an object in the array, assuming that the array is sorted.
  2762. This will use a comparator to do a binary-chop to find the index of the given
  2763. element, if it exists. If the array isn't sorted, the behaviour of this
  2764. method will be unpredictable.
  2765. @param comparator the comparator to use to compare the elements - see the sort()
  2766. method for details about the form this object should take
  2767. @param objectToLookFor the object to search for
  2768. @returns the index of the element, or -1 if it's not found
  2769. @see addSorted, sort
  2770. */
  2771. template <class ElementComparator>
  2772. int indexOfSorted (ElementComparator& comparator,
  2773. const ObjectClass* const objectToLookFor) const throw()
  2774. {
  2775. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2776. // avoids getting warning messages about the parameter being unused
  2777. lock.enter();
  2778. int start = 0;
  2779. int end = numUsed;
  2780. for (;;)
  2781. {
  2782. if (start >= end)
  2783. {
  2784. lock.exit();
  2785. return -1;
  2786. }
  2787. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2788. {
  2789. lock.exit();
  2790. return start;
  2791. }
  2792. else
  2793. {
  2794. const int halfway = (start + end) >> 1;
  2795. if (halfway == start)
  2796. {
  2797. lock.exit();
  2798. return -1;
  2799. }
  2800. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2801. start = halfway;
  2802. else
  2803. end = halfway;
  2804. }
  2805. }
  2806. }
  2807. /** Removes an object from the array.
  2808. This will remove the object at a given index (optionally also
  2809. deleting it) and move back all the subsequent objects to close the gap.
  2810. If the index passed in is out-of-range, nothing will happen.
  2811. @param indexToRemove the index of the element to remove
  2812. @param deleteObject whether to delete the object that is removed
  2813. @see removeObject, removeRange
  2814. */
  2815. void remove (const int indexToRemove,
  2816. const bool deleteObject = true)
  2817. {
  2818. lock.enter();
  2819. ObjectClass* toDelete = 0;
  2820. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2821. {
  2822. ObjectClass** const e = this->elements + indexToRemove;
  2823. if (deleteObject)
  2824. toDelete = *e;
  2825. --numUsed;
  2826. const int numToShift = numUsed - indexToRemove;
  2827. if (numToShift > 0)
  2828. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2829. if ((numUsed << 1) < this->numAllocated)
  2830. minimiseStorageOverheads();
  2831. }
  2832. lock.exit();
  2833. delete toDelete;
  2834. }
  2835. /** Removes a specified object from the array.
  2836. If the item isn't found, no action is taken.
  2837. @param objectToRemove the object to try to remove
  2838. @param deleteObject whether to delete the object (if it's found)
  2839. @see remove, removeRange
  2840. */
  2841. void removeObject (const ObjectClass* const objectToRemove,
  2842. const bool deleteObject = true)
  2843. {
  2844. lock.enter();
  2845. ObjectClass** e = this->elements;
  2846. for (int i = numUsed; --i >= 0;)
  2847. {
  2848. if (objectToRemove == *e)
  2849. {
  2850. remove ((int) (e - this->elements), deleteObject);
  2851. break;
  2852. }
  2853. ++e;
  2854. }
  2855. lock.exit();
  2856. }
  2857. /** Removes a range of objects from the array.
  2858. This will remove a set of objects, starting from the given index,
  2859. and move any subsequent elements down to close the gap.
  2860. If the range extends beyond the bounds of the array, it will
  2861. be safely clipped to the size of the array.
  2862. @param startIndex the index of the first object to remove
  2863. @param numberToRemove how many objects should be removed
  2864. @param deleteObjects whether to delete the objects that get removed
  2865. @see remove, removeObject
  2866. */
  2867. void removeRange (int startIndex,
  2868. const int numberToRemove,
  2869. const bool deleteObjects = true)
  2870. {
  2871. lock.enter();
  2872. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2873. startIndex = jlimit (0, numUsed, startIndex);
  2874. if (endIndex > startIndex)
  2875. {
  2876. if (deleteObjects)
  2877. {
  2878. for (int i = startIndex; i < endIndex; ++i)
  2879. {
  2880. delete this->elements [i];
  2881. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2882. }
  2883. }
  2884. const int rangeSize = endIndex - startIndex;
  2885. ObjectClass** e = this->elements + startIndex;
  2886. int numToShift = numUsed - endIndex;
  2887. numUsed -= rangeSize;
  2888. while (--numToShift >= 0)
  2889. {
  2890. *e = e [rangeSize];
  2891. ++e;
  2892. }
  2893. if ((numUsed << 1) < this->numAllocated)
  2894. minimiseStorageOverheads();
  2895. }
  2896. lock.exit();
  2897. }
  2898. /** Removes the last n objects from the array.
  2899. @param howManyToRemove how many objects to remove from the end of the array
  2900. @param deleteObjects whether to also delete the objects that are removed
  2901. @see remove, removeObject, removeRange
  2902. */
  2903. void removeLast (int howManyToRemove = 1,
  2904. const bool deleteObjects = true)
  2905. {
  2906. lock.enter();
  2907. if (howManyToRemove >= numUsed)
  2908. {
  2909. clear (deleteObjects);
  2910. }
  2911. else
  2912. {
  2913. while (--howManyToRemove >= 0)
  2914. remove (numUsed - 1, deleteObjects);
  2915. }
  2916. lock.exit();
  2917. }
  2918. /** Swaps a pair of objects in the array.
  2919. If either of the indexes passed in is out-of-range, nothing will happen,
  2920. otherwise the two objects at these positions will be exchanged.
  2921. */
  2922. void swap (const int index1,
  2923. const int index2) throw()
  2924. {
  2925. lock.enter();
  2926. if (((unsigned int) index1) < (unsigned int) numUsed
  2927. && ((unsigned int) index2) < (unsigned int) numUsed)
  2928. {
  2929. swapVariables (this->elements [index1],
  2930. this->elements [index2]);
  2931. }
  2932. lock.exit();
  2933. }
  2934. /** Moves one of the objects to a different position.
  2935. This will move the object to a specified index, shuffling along
  2936. any intervening elements as required.
  2937. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  2938. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  2939. @param currentIndex the index of the object to be moved. If this isn't a
  2940. valid index, then nothing will be done
  2941. @param newIndex the index at which you'd like this object to end up. If this
  2942. is less than zero, it will be moved to the end of the array
  2943. */
  2944. void move (const int currentIndex,
  2945. int newIndex) throw()
  2946. {
  2947. if (currentIndex != newIndex)
  2948. {
  2949. lock.enter();
  2950. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  2951. {
  2952. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  2953. newIndex = numUsed - 1;
  2954. ObjectClass* const value = this->elements [currentIndex];
  2955. if (newIndex > currentIndex)
  2956. {
  2957. memmove (this->elements + currentIndex,
  2958. this->elements + currentIndex + 1,
  2959. (newIndex - currentIndex) * sizeof (ObjectClass*));
  2960. }
  2961. else
  2962. {
  2963. memmove (this->elements + newIndex + 1,
  2964. this->elements + newIndex,
  2965. (currentIndex - newIndex) * sizeof (ObjectClass*));
  2966. }
  2967. this->elements [newIndex] = value;
  2968. }
  2969. lock.exit();
  2970. }
  2971. }
  2972. /** This swaps the contents of this array with those of another array.
  2973. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2974. because it just swaps their internal pointers.
  2975. */
  2976. template <class OtherArrayType>
  2977. void swapWithArray (OtherArrayType& otherArray) throw()
  2978. {
  2979. lock.enter();
  2980. otherArray.lock.enter();
  2981. swapVariables <int> (this->numUsed, otherArray.numUsed);
  2982. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  2983. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  2984. otherArray.lock.exit();
  2985. lock.exit();
  2986. }
  2987. /** Reduces the amount of storage being used by the array.
  2988. Arrays typically allocate slightly more storage than they need, and after
  2989. removing elements, they may have quite a lot of unused space allocated.
  2990. This method will reduce the amount of allocated storage to a minimum.
  2991. */
  2992. void minimiseStorageOverheads() throw()
  2993. {
  2994. lock.enter();
  2995. if (numUsed == 0)
  2996. {
  2997. this->setAllocatedSize (0);
  2998. }
  2999. else
  3000. {
  3001. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3002. if (newAllocation < this->numAllocated)
  3003. this->setAllocatedSize (newAllocation);
  3004. }
  3005. lock.exit();
  3006. }
  3007. /** Increases the array's internal storage to hold a minimum number of elements.
  3008. Calling this before adding a large known number of elements means that
  3009. the array won't have to keep dynamically resizing itself as the elements
  3010. are added, and it'll therefore be more efficient.
  3011. */
  3012. void ensureStorageAllocated (const int minNumElements) throw()
  3013. {
  3014. this->ensureAllocatedSize (minNumElements);
  3015. }
  3016. /** Sorts the elements in the array.
  3017. This will use a comparator object to sort the elements into order. The object
  3018. passed must have a method of the form:
  3019. @code
  3020. int compareElements (ElementType first, ElementType second);
  3021. @endcode
  3022. ..and this method must return:
  3023. - a value of < 0 if the first comes before the second
  3024. - a value of 0 if the two objects are equivalent
  3025. - a value of > 0 if the second comes before the first
  3026. To improve performance, the compareElements() method can be declared as static or const.
  3027. @param comparator the comparator to use for comparing elements.
  3028. @param retainOrderOfEquivalentItems if this is true, then items
  3029. which the comparator says are equivalent will be
  3030. kept in the order in which they currently appear
  3031. in the array. This is slower to perform, but may
  3032. be important in some cases. If it's false, a faster
  3033. algorithm is used, but equivalent elements may be
  3034. rearranged.
  3035. @see sortArray, indexOfSorted
  3036. */
  3037. template <class ElementComparator>
  3038. void sort (ElementComparator& comparator,
  3039. const bool retainOrderOfEquivalentItems = false) const throw()
  3040. {
  3041. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3042. // avoids getting warning messages about the parameter being unused
  3043. lock.enter();
  3044. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3045. lock.exit();
  3046. }
  3047. /** Locks the array's CriticalSection.
  3048. Of course if the type of section used is a DummyCriticalSection, this won't
  3049. have any effect.
  3050. @see unlockArray
  3051. */
  3052. void lockArray() const throw()
  3053. {
  3054. lock.enter();
  3055. }
  3056. /** Unlocks the array's CriticalSection.
  3057. Of course if the type of section used is a DummyCriticalSection, this won't
  3058. have any effect.
  3059. @see lockArray
  3060. */
  3061. void unlockArray() const throw()
  3062. {
  3063. lock.exit();
  3064. }
  3065. juce_UseDebuggingNewOperator
  3066. private:
  3067. int numUsed;
  3068. TypeOfCriticalSectionToUse lock;
  3069. // disallow copy constructor and assignment
  3070. OwnedArray (const OwnedArray&);
  3071. const OwnedArray& operator= (const OwnedArray&);
  3072. };
  3073. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3074. /********* End of inlined file: juce_OwnedArray.h *********/
  3075. /********* Start of inlined file: juce_Time.h *********/
  3076. #ifndef __JUCE_TIME_JUCEHEADER__
  3077. #define __JUCE_TIME_JUCEHEADER__
  3078. /********* Start of inlined file: juce_RelativeTime.h *********/
  3079. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3080. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3081. /** A relative measure of time.
  3082. The time is stored as a number of seconds, at double-precision floating
  3083. point accuracy, and may be positive or negative.
  3084. If you need an absolute time, (i.e. a date + time), see the Time class.
  3085. */
  3086. class JUCE_API RelativeTime
  3087. {
  3088. public:
  3089. /** Creates a RelativeTime.
  3090. @param seconds the number of seconds, which may be +ve or -ve.
  3091. @see milliseconds, minutes, hours, days, weeks
  3092. */
  3093. explicit RelativeTime (const double seconds = 0.0) throw();
  3094. /** Copies another relative time. */
  3095. RelativeTime (const RelativeTime& other) throw();
  3096. /** Copies another relative time. */
  3097. const RelativeTime& operator= (const RelativeTime& other) throw();
  3098. /** Destructor. */
  3099. ~RelativeTime() throw();
  3100. /** Creates a new RelativeTime object representing a number of milliseconds.
  3101. @see minutes, hours, days, weeks
  3102. */
  3103. static const RelativeTime milliseconds (const int milliseconds) throw();
  3104. /** Creates a new RelativeTime object representing a number of milliseconds.
  3105. @see minutes, hours, days, weeks
  3106. */
  3107. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3108. /** Creates a new RelativeTime object representing a number of minutes.
  3109. @see milliseconds, hours, days, weeks
  3110. */
  3111. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3112. /** Creates a new RelativeTime object representing a number of hours.
  3113. @see milliseconds, minutes, days, weeks
  3114. */
  3115. static const RelativeTime hours (const double numberOfHours) throw();
  3116. /** Creates a new RelativeTime object representing a number of days.
  3117. @see milliseconds, minutes, hours, weeks
  3118. */
  3119. static const RelativeTime days (const double numberOfDays) throw();
  3120. /** Creates a new RelativeTime object representing a number of weeks.
  3121. @see milliseconds, minutes, hours, days
  3122. */
  3123. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3124. /** Returns the number of milliseconds this time represents.
  3125. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3126. */
  3127. int64 inMilliseconds() const throw();
  3128. /** Returns the number of seconds this time represents.
  3129. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3130. */
  3131. double inSeconds() const throw() { return seconds; }
  3132. /** Returns the number of minutes this time represents.
  3133. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3134. */
  3135. double inMinutes() const throw();
  3136. /** Returns the number of hours this time represents.
  3137. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3138. */
  3139. double inHours() const throw();
  3140. /** Returns the number of days this time represents.
  3141. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3142. */
  3143. double inDays() const throw();
  3144. /** Returns the number of weeks this time represents.
  3145. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3146. */
  3147. double inWeeks() const throw();
  3148. /** Returns a readable textual description of the time.
  3149. The exact format of the string returned will depend on
  3150. the magnitude of the time - e.g.
  3151. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3152. so that only the two most significant units are printed.
  3153. The returnValueForZeroTime value is the result that is returned if the
  3154. length is zero. Depending on your application you might want to use this
  3155. to return something more relevant like "empty" or "0 secs", etc.
  3156. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3157. */
  3158. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3159. /** Compares two RelativeTimes. */
  3160. bool operator== (const RelativeTime& other) const throw();
  3161. /** Compares two RelativeTimes. */
  3162. bool operator!= (const RelativeTime& other) const throw();
  3163. /** Compares two RelativeTimes. */
  3164. bool operator> (const RelativeTime& other) const throw();
  3165. /** Compares two RelativeTimes. */
  3166. bool operator< (const RelativeTime& other) const throw();
  3167. /** Compares two RelativeTimes. */
  3168. bool operator>= (const RelativeTime& other) const throw();
  3169. /** Compares two RelativeTimes. */
  3170. bool operator<= (const RelativeTime& other) const throw();
  3171. /** Adds another RelativeTime to this one and returns the result. */
  3172. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3173. /** Subtracts another RelativeTime from this one and returns the result. */
  3174. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3175. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3176. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3177. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3178. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3179. /** Adds another RelativeTime to this one. */
  3180. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3181. /** Subtracts another RelativeTime from this one. */
  3182. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3183. /** Adds a number of seconds to this time. */
  3184. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3185. /** Subtracts a number of seconds from this time. */
  3186. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3187. juce_UseDebuggingNewOperator
  3188. private:
  3189. double seconds;
  3190. };
  3191. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3192. /********* End of inlined file: juce_RelativeTime.h *********/
  3193. /**
  3194. Holds an absolute date and time.
  3195. Internally, the time is stored at millisecond precision.
  3196. @see RelativeTime
  3197. */
  3198. class JUCE_API Time
  3199. {
  3200. public:
  3201. /** Creates a Time object.
  3202. This default constructor creates a time of 1st January 1970, (which is
  3203. represented internally as 0ms).
  3204. To create a time object representing the current time, use getCurrentTime().
  3205. @see getCurrentTime
  3206. */
  3207. Time() throw();
  3208. /** Creates a copy of another Time object. */
  3209. Time (const Time& other) throw();
  3210. /** Creates a time based on a number of milliseconds.
  3211. The internal millisecond count is set to 0 (1st January 1970). To create a
  3212. time object set to the current time, use getCurrentTime().
  3213. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3214. 'epoch' (midnight Jan 1st 1970).
  3215. @see getCurrentTime, currentTimeMillis
  3216. */
  3217. Time (const int64 millisecondsSinceEpoch) throw();
  3218. /** Creates a time from a set of date components.
  3219. The timezone is assumed to be whatever the system is using as its locale.
  3220. @param year the year, in 4-digit format, e.g. 2004
  3221. @param month the month, in the range 0 to 11
  3222. @param day the day of the month, in the range 1 to 31
  3223. @param hours hours in 24-hour clock format, 0 to 23
  3224. @param minutes minutes 0 to 59
  3225. @param seconds seconds 0 to 59
  3226. @param milliseconds milliseconds 0 to 999
  3227. @param useLocalTime if true, encode using the current machine's local time; if
  3228. false, it will always work in GMT.
  3229. */
  3230. Time (const int year,
  3231. const int month,
  3232. const int day,
  3233. const int hours,
  3234. const int minutes,
  3235. const int seconds = 0,
  3236. const int milliseconds = 0,
  3237. const bool useLocalTime = true) throw();
  3238. /** Destructor. */
  3239. ~Time() throw();
  3240. /** Copies this time from another one. */
  3241. const Time& operator= (const Time& other) throw();
  3242. /** Returns a Time object that is set to the current system time.
  3243. @see currentTimeMillis
  3244. */
  3245. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3246. /** Returns the time as a number of milliseconds.
  3247. @returns the number of milliseconds this Time object represents, since
  3248. midnight jan 1st 1970.
  3249. @see getMilliseconds
  3250. */
  3251. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3252. /** Returns the year.
  3253. A 4-digit format is used, e.g. 2004.
  3254. */
  3255. int getYear() const throw();
  3256. /** Returns the number of the month.
  3257. The value returned is in the range 0 to 11.
  3258. @see getMonthName
  3259. */
  3260. int getMonth() const throw();
  3261. /** Returns the name of the month.
  3262. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3263. it'll return the long form, e.g. "January"
  3264. @see getMonth
  3265. */
  3266. const String getMonthName (const bool threeLetterVersion) const throw();
  3267. /** Returns the day of the month.
  3268. The value returned is in the range 1 to 31.
  3269. */
  3270. int getDayOfMonth() const throw();
  3271. /** Returns the number of the day of the week.
  3272. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3273. */
  3274. int getDayOfWeek() const throw();
  3275. /** Returns the name of the weekday.
  3276. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3277. false, it'll return the full version, e.g. "Tuesday".
  3278. */
  3279. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3280. /** Returns the number of hours since midnight.
  3281. This is in 24-hour clock format, in the range 0 to 23.
  3282. @see getHoursInAmPmFormat, isAfternoon
  3283. */
  3284. int getHours() const throw();
  3285. /** Returns true if the time is in the afternoon.
  3286. So it returns true for "PM", false for "AM".
  3287. @see getHoursInAmPmFormat, getHours
  3288. */
  3289. bool isAfternoon() const throw();
  3290. /** Returns the hours in 12-hour clock format.
  3291. This will return a value 1 to 12 - use isAfternoon() to find out
  3292. whether this is in the afternoon or morning.
  3293. @see getHours, isAfternoon
  3294. */
  3295. int getHoursInAmPmFormat() const throw();
  3296. /** Returns the number of minutes, 0 to 59. */
  3297. int getMinutes() const throw();
  3298. /** Returns the number of seconds, 0 to 59. */
  3299. int getSeconds() const throw();
  3300. /** Returns the number of milliseconds, 0 to 999.
  3301. Unlike toMilliseconds(), this just returns the position within the
  3302. current second rather than the total number since the epoch.
  3303. @see toMilliseconds
  3304. */
  3305. int getMilliseconds() const throw();
  3306. /** Returns true if the local timezone uses a daylight saving correction. */
  3307. bool isDaylightSavingTime() const throw();
  3308. /** Returns a 3-character string to indicate the local timezone. */
  3309. const String getTimeZone() const throw();
  3310. /** Quick way of getting a string version of a date and time.
  3311. For a more powerful way of formatting the date and time, see the formatted() method.
  3312. @param includeDate whether to include the date in the string
  3313. @param includeTime whether to include the time in the string
  3314. @param includeSeconds if the time is being included, this provides an option not to include
  3315. the seconds in it
  3316. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3317. hour notation.
  3318. @see formatted
  3319. */
  3320. const String toString (const bool includeDate,
  3321. const bool includeTime,
  3322. const bool includeSeconds = true,
  3323. const bool use24HourClock = false) const throw();
  3324. /** Converts this date/time to a string with a user-defined format.
  3325. This uses the C strftime() function to format this time as a string. To save you
  3326. looking it up, these are the escape codes that strftime uses (other codes might
  3327. work on some platforms and not others, but these are the common ones):
  3328. %a is replaced by the locale's abbreviated weekday name.
  3329. %A is replaced by the locale's full weekday name.
  3330. %b is replaced by the locale's abbreviated month name.
  3331. %B is replaced by the locale's full month name.
  3332. %c is replaced by the locale's appropriate date and time representation.
  3333. %d is replaced by the day of the month as a decimal number [01,31].
  3334. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3335. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3336. %j is replaced by the day of the year as a decimal number [001,366].
  3337. %m is replaced by the month as a decimal number [01,12].
  3338. %M is replaced by the minute as a decimal number [00,59].
  3339. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3340. %S is replaced by the second as a decimal number [00,61].
  3341. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3342. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3343. %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.
  3344. %x is replaced by the locale's appropriate date representation.
  3345. %X is replaced by the locale's appropriate time representation.
  3346. %y is replaced by the year without century as a decimal number [00,99].
  3347. %Y is replaced by the year with century as a decimal number.
  3348. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3349. %% is replaced by %.
  3350. @see toString
  3351. */
  3352. const String formatted (const tchar* const format) const throw();
  3353. /** Adds a RelativeTime to this time and returns the result. */
  3354. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3355. /** Subtracts a RelativeTime from this time and returns the result. */
  3356. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3357. /** Returns the relative time difference between this time and another one. */
  3358. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3359. /** Compares two Time objects. */
  3360. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3361. /** Compares two Time objects. */
  3362. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3363. /** Compares two Time objects. */
  3364. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3365. /** Compares two Time objects. */
  3366. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3367. /** Compares two Time objects. */
  3368. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3369. /** Compares two Time objects. */
  3370. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3371. /** Tries to set the computer's clock.
  3372. @returns true if this succeeds, although depending on the system, the
  3373. application might not have sufficient privileges to do this.
  3374. */
  3375. bool setSystemTimeToThisTime() const throw();
  3376. /** Returns the name of a day of the week.
  3377. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3378. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3379. false, it'll return the full version, e.g. "Tuesday".
  3380. */
  3381. static const String getWeekdayName (int dayNumber,
  3382. const bool threeLetterVersion) throw();
  3383. /** Returns the name of one of the months.
  3384. @param monthNumber the month, 0 to 11
  3385. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3386. it'll return the long form, e.g. "January"
  3387. */
  3388. static const String getMonthName (int monthNumber,
  3389. const bool threeLetterVersion) throw();
  3390. // Static methods for getting system timers directly..
  3391. /** Returns the current system time.
  3392. Returns the number of milliseconds since midnight jan 1st 1970.
  3393. Should be accurate to within a few millisecs, depending on platform,
  3394. hardware, etc.
  3395. */
  3396. static int64 currentTimeMillis() throw();
  3397. /** Returns the number of millisecs since system startup.
  3398. Should be accurate to within a few millisecs, depending on platform,
  3399. hardware, etc.
  3400. @see getApproximateMillisecondCounter
  3401. */
  3402. static uint32 getMillisecondCounter() throw();
  3403. /** Returns the number of millisecs since system startup.
  3404. Same as getMillisecondCounter(), but returns a more accurate value, using
  3405. the high-res timer.
  3406. @see getMillisecondCounter
  3407. */
  3408. static double getMillisecondCounterHiRes() throw();
  3409. /** Waits until the getMillisecondCounter() reaches a given value.
  3410. This will make the thread sleep as efficiently as it can while it's waiting.
  3411. */
  3412. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3413. /** Less-accurate but faster version of getMillisecondCounter().
  3414. This will return the last value that getMillisecondCounter() returned, so doesn't
  3415. need to make a system call, but is less accurate - it shouldn't be more than
  3416. 100ms away from the correct time, though, so is still accurate enough for a
  3417. lot of purposes.
  3418. @see getMillisecondCounter
  3419. */
  3420. static uint32 getApproximateMillisecondCounter() throw();
  3421. // High-resolution timers..
  3422. /** Returns the current high-resolution counter's tick-count.
  3423. This is a similar idea to getMillisecondCounter(), but with a higher
  3424. resolution.
  3425. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3426. secondsToHighResolutionTicks
  3427. */
  3428. static int64 getHighResolutionTicks() throw();
  3429. /** Returns the resolution of the high-resolution counter in ticks per second.
  3430. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3431. secondsToHighResolutionTicks
  3432. */
  3433. static int64 getHighResolutionTicksPerSecond() throw();
  3434. /** Converts a number of high-resolution ticks into seconds.
  3435. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3436. secondsToHighResolutionTicks
  3437. */
  3438. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3439. /** Converts a number seconds into high-resolution ticks.
  3440. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3441. highResolutionTicksToSeconds
  3442. */
  3443. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3444. private:
  3445. int64 millisSinceEpoch;
  3446. };
  3447. #endif // __JUCE_TIME_JUCEHEADER__
  3448. /********* End of inlined file: juce_Time.h *********/
  3449. /********* Start of inlined file: juce_StringArray.h *********/
  3450. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3451. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3452. /********* Start of inlined file: juce_VoidArray.h *********/
  3453. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3454. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3455. /********* Start of inlined file: juce_Array.h *********/
  3456. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3457. #define __JUCE_ARRAY_JUCEHEADER__
  3458. /**
  3459. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3460. Examples of arrays are: Array<int> or Array<MyClass*>
  3461. Note that when holding pointers to objects, the array doesn't take any ownership
  3462. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3463. If you're using a class or struct as the element type, it must be
  3464. capable of being copied or moved with a straightforward memcpy, rather than
  3465. needing construction and destruction code.
  3466. For holding lists of strings, use the specialised class StringArray.
  3467. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3468. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3469. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3470. */
  3471. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3472. class Array : private ArrayAllocationBase <ElementType>
  3473. {
  3474. public:
  3475. /** Creates an empty array.
  3476. @param granularity this is the size of increment by which the internal storage
  3477. used by the array will grow. Only change it from the default if you know the
  3478. array is going to be very big and needs to be able to grow efficiently.
  3479. @see ArrayAllocationBase
  3480. */
  3481. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3482. : ArrayAllocationBase <ElementType> (granularity),
  3483. numUsed (0)
  3484. {
  3485. }
  3486. /** Creates a copy of another array.
  3487. @param other the array to copy
  3488. */
  3489. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3490. : ArrayAllocationBase <ElementType> (other.granularity)
  3491. {
  3492. other.lockArray();
  3493. numUsed = other.numUsed;
  3494. this->setAllocatedSize (other.numUsed);
  3495. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3496. other.unlockArray();
  3497. }
  3498. /** Initalises from a null-terminated C array of values.
  3499. @param values the array to copy from
  3500. */
  3501. Array (const ElementType* values) throw()
  3502. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3503. numUsed (0)
  3504. {
  3505. while (*values != 0)
  3506. add (*values++);
  3507. }
  3508. /** Initalises from a C array of values.
  3509. @param values the array to copy from
  3510. @param numValues the number of values in the array
  3511. */
  3512. Array (const ElementType* values, int numValues) throw()
  3513. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3514. numUsed (numValues)
  3515. {
  3516. this->setAllocatedSize (numValues);
  3517. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3518. }
  3519. /** Destructor. */
  3520. ~Array() throw()
  3521. {
  3522. }
  3523. /** Copies another array.
  3524. @param other the array to copy
  3525. */
  3526. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3527. {
  3528. if (this != &other)
  3529. {
  3530. other.lockArray();
  3531. lock.enter();
  3532. this->granularity = other.granularity;
  3533. this->ensureAllocatedSize (other.size());
  3534. numUsed = other.numUsed;
  3535. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3536. minimiseStorageOverheads();
  3537. lock.exit();
  3538. other.unlockArray();
  3539. }
  3540. return *this;
  3541. }
  3542. /** Compares this array to another one.
  3543. Two arrays are considered equal if they both contain the same set of
  3544. elements, in the same order.
  3545. @param other the other array to compare with
  3546. */
  3547. template <class OtherArrayType>
  3548. bool operator== (const OtherArrayType& other) const throw()
  3549. {
  3550. lock.enter();
  3551. if (this->numUsed != other.numUsed)
  3552. {
  3553. lock.exit();
  3554. return false;
  3555. }
  3556. for (int i = numUsed; --i >= 0;)
  3557. {
  3558. if (this->elements [i] != other.elements [i])
  3559. {
  3560. lock.exit();
  3561. return false;
  3562. }
  3563. }
  3564. lock.exit();
  3565. return true;
  3566. }
  3567. /** Compares this array to another one.
  3568. Two arrays are considered equal if they both contain the same set of
  3569. elements, in the same order.
  3570. @param other the other array to compare with
  3571. */
  3572. template <class OtherArrayType>
  3573. bool operator!= (const OtherArrayType& other) const throw()
  3574. {
  3575. return ! operator== (other);
  3576. }
  3577. /** Removes all elements from the array.
  3578. This will remove all the elements, and free any storage that the array is
  3579. using. To clear the array without freeing the storage, use the clearQuick()
  3580. method instead.
  3581. @see clearQuick
  3582. */
  3583. void clear() throw()
  3584. {
  3585. lock.enter();
  3586. this->setAllocatedSize (0);
  3587. numUsed = 0;
  3588. lock.exit();
  3589. }
  3590. /** Removes all elements from the array without freeing the array's allocated storage.
  3591. @see clear
  3592. */
  3593. void clearQuick() throw()
  3594. {
  3595. lock.enter();
  3596. numUsed = 0;
  3597. lock.exit();
  3598. }
  3599. /** Returns the current number of elements in the array.
  3600. */
  3601. inline int size() const throw()
  3602. {
  3603. return numUsed;
  3604. }
  3605. /** Returns one of the elements in the array.
  3606. If the index passed in is beyond the range of valid elements, this
  3607. will return zero.
  3608. If you're certain that the index will always be a valid element, you
  3609. can call getUnchecked() instead, which is faster.
  3610. @param index the index of the element being requested (0 is the first element in the array)
  3611. @see getUnchecked, getFirst, getLast
  3612. */
  3613. inline ElementType operator[] (const int index) const throw()
  3614. {
  3615. lock.enter();
  3616. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3617. ? this->elements [index]
  3618. : ElementType();
  3619. lock.exit();
  3620. return result;
  3621. }
  3622. /** Returns one of the elements in the array, without checking the index passed in.
  3623. Unlike the operator[] method, this will try to return an element without
  3624. checking that the index is within the bounds of the array, so should only
  3625. be used when you're confident that it will always be a valid index.
  3626. @param index the index of the element being requested (0 is the first element in the array)
  3627. @see operator[], getFirst, getLast
  3628. */
  3629. inline ElementType getUnchecked (const int index) const throw()
  3630. {
  3631. lock.enter();
  3632. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3633. const ElementType result = this->elements [index];
  3634. lock.exit();
  3635. return result;
  3636. }
  3637. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3638. This is like getUnchecked, but returns a direct reference to the element, so that
  3639. you can alter it directly. Obviously this can be dangerous, so only use it when
  3640. absolutely necessary.
  3641. @param index the index of the element being requested (0 is the first element in the array)
  3642. @see operator[], getFirst, getLast
  3643. */
  3644. inline ElementType& getReference (const int index) const throw()
  3645. {
  3646. lock.enter();
  3647. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3648. ElementType& result = this->elements [index];
  3649. lock.exit();
  3650. return result;
  3651. }
  3652. /** Returns the first element in the array, or 0 if the array is empty.
  3653. @see operator[], getUnchecked, getLast
  3654. */
  3655. inline ElementType getFirst() const throw()
  3656. {
  3657. lock.enter();
  3658. const ElementType result = (numUsed > 0) ? this->elements [0]
  3659. : ElementType();
  3660. lock.exit();
  3661. return result;
  3662. }
  3663. /** Returns the last element in the array, or 0 if the array is empty.
  3664. @see operator[], getUnchecked, getFirst
  3665. */
  3666. inline ElementType getLast() const throw()
  3667. {
  3668. lock.enter();
  3669. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3670. : ElementType();
  3671. lock.exit();
  3672. return result;
  3673. }
  3674. /** Finds the index of the first element which matches the value passed in.
  3675. This will search the array for the given object, and return the index
  3676. of its first occurrence. If the object isn't found, the method will return -1.
  3677. @param elementToLookFor the value or object to look for
  3678. @returns the index of the object, or -1 if it's not found
  3679. */
  3680. int indexOf (const ElementType elementToLookFor) const throw()
  3681. {
  3682. int result = -1;
  3683. lock.enter();
  3684. const ElementType* e = this->elements;
  3685. for (int i = numUsed; --i >= 0;)
  3686. {
  3687. if (elementToLookFor == *e)
  3688. {
  3689. result = (int) (e - this->elements);
  3690. break;
  3691. }
  3692. ++e;
  3693. }
  3694. lock.exit();
  3695. return result;
  3696. }
  3697. /** Returns true if the array contains at least one occurrence of an object.
  3698. @param elementToLookFor the value or object to look for
  3699. @returns true if the item is found
  3700. */
  3701. bool contains (const ElementType elementToLookFor) const throw()
  3702. {
  3703. lock.enter();
  3704. const ElementType* e = this->elements;
  3705. int num = numUsed;
  3706. while (num >= 4)
  3707. {
  3708. if (*e == elementToLookFor
  3709. || *++e == elementToLookFor
  3710. || *++e == elementToLookFor
  3711. || *++e == elementToLookFor)
  3712. {
  3713. lock.exit();
  3714. return true;
  3715. }
  3716. num -= 4;
  3717. ++e;
  3718. }
  3719. while (num > 0)
  3720. {
  3721. if (elementToLookFor == *e)
  3722. {
  3723. lock.exit();
  3724. return true;
  3725. }
  3726. --num;
  3727. ++e;
  3728. }
  3729. lock.exit();
  3730. return false;
  3731. }
  3732. /** Appends a new element at the end of the array.
  3733. @param newElement the new object to add to the array
  3734. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3735. */
  3736. void add (const ElementType newElement) throw()
  3737. {
  3738. lock.enter();
  3739. this->ensureAllocatedSize (numUsed + 1);
  3740. this->elements [numUsed++] = newElement;
  3741. lock.exit();
  3742. }
  3743. /** Inserts a new element into the array at a given position.
  3744. If the index is less than 0 or greater than the size of the array, the
  3745. element will be added to the end of the array.
  3746. Otherwise, it will be inserted into the array, moving all the later elements
  3747. along to make room.
  3748. @param indexToInsertAt the index at which the new element should be
  3749. inserted (pass in -1 to add it to the end)
  3750. @param newElement the new object to add to the array
  3751. @see add, addSorted, set
  3752. */
  3753. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3754. {
  3755. lock.enter();
  3756. this->ensureAllocatedSize (numUsed + 1);
  3757. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3758. {
  3759. ElementType* const insertPos = this->elements + indexToInsertAt;
  3760. const int numberToMove = numUsed - indexToInsertAt;
  3761. if (numberToMove > 0)
  3762. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3763. *insertPos = newElement;
  3764. ++numUsed;
  3765. }
  3766. else
  3767. {
  3768. this->elements [numUsed++] = newElement;
  3769. }
  3770. lock.exit();
  3771. }
  3772. /** Inserts multiple copies of an element into the array at a given position.
  3773. If the index is less than 0 or greater than the size of the array, the
  3774. element will be added to the end of the array.
  3775. Otherwise, it will be inserted into the array, moving all the later elements
  3776. along to make room.
  3777. @param indexToInsertAt the index at which the new element should be inserted
  3778. @param newElement the new object to add to the array
  3779. @param numberOfTimesToInsertIt how many copies of the value to insert
  3780. @see insert, add, addSorted, set
  3781. */
  3782. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3783. int numberOfTimesToInsertIt) throw()
  3784. {
  3785. if (numberOfTimesToInsertIt > 0)
  3786. {
  3787. lock.enter();
  3788. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3789. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3790. {
  3791. ElementType* insertPos = this->elements + indexToInsertAt;
  3792. const int numberToMove = numUsed - indexToInsertAt;
  3793. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3794. numUsed += numberOfTimesToInsertIt;
  3795. while (--numberOfTimesToInsertIt >= 0)
  3796. *insertPos++ = newElement;
  3797. }
  3798. else
  3799. {
  3800. while (--numberOfTimesToInsertIt >= 0)
  3801. this->elements [numUsed++] = newElement;
  3802. }
  3803. lock.exit();
  3804. }
  3805. }
  3806. /** Inserts an array of values into this array at a given position.
  3807. If the index is less than 0 or greater than the size of the array, the
  3808. new elements will be added to the end of the array.
  3809. Otherwise, they will be inserted into the array, moving all the later elements
  3810. along to make room.
  3811. @param indexToInsertAt the index at which the first new element should be inserted
  3812. @param newElements the new values to add to the array
  3813. @param numberOfElements how many items are in the array
  3814. @see insert, add, addSorted, set
  3815. */
  3816. void insertArray (int indexToInsertAt,
  3817. const ElementType* newElements,
  3818. int numberOfElements) throw()
  3819. {
  3820. if (numberOfElements > 0)
  3821. {
  3822. lock.enter();
  3823. this->ensureAllocatedSize (numUsed + numberOfElements);
  3824. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3825. {
  3826. ElementType* insertPos = this->elements + indexToInsertAt;
  3827. const int numberToMove = numUsed - indexToInsertAt;
  3828. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3829. numUsed += numberOfElements;
  3830. while (--numberOfElements >= 0)
  3831. *insertPos++ = *newElements++;
  3832. }
  3833. else
  3834. {
  3835. while (--numberOfElements >= 0)
  3836. this->elements [numUsed++] = *newElements++;
  3837. }
  3838. lock.exit();
  3839. }
  3840. }
  3841. /** Appends a new element at the end of the array as long as the array doesn't
  3842. already contain it.
  3843. If the array already contains an element that matches the one passed in, nothing
  3844. will be done.
  3845. @param newElement the new object to add to the array
  3846. */
  3847. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3848. {
  3849. lock.enter();
  3850. if (! contains (newElement))
  3851. add (newElement);
  3852. lock.exit();
  3853. }
  3854. /** Replaces an element with a new value.
  3855. If the index is less than zero, this method does nothing.
  3856. If the index is beyond the end of the array, the item is added to the end of the array.
  3857. @param indexToChange the index whose value you want to change
  3858. @param newValue the new value to set for this index.
  3859. @see add, insert
  3860. */
  3861. void set (const int indexToChange,
  3862. const ElementType newValue) throw()
  3863. {
  3864. jassert (indexToChange >= 0);
  3865. if (indexToChange >= 0)
  3866. {
  3867. lock.enter();
  3868. if (indexToChange < numUsed)
  3869. {
  3870. this->elements [indexToChange] = newValue;
  3871. }
  3872. else
  3873. {
  3874. this->ensureAllocatedSize (numUsed + 1);
  3875. this->elements [numUsed++] = newValue;
  3876. }
  3877. lock.exit();
  3878. }
  3879. }
  3880. /** Replaces an element with a new value without doing any bounds-checking.
  3881. This just sets a value directly in the array's internal storage, so you'd
  3882. better make sure it's in range!
  3883. @param indexToChange the index whose value you want to change
  3884. @param newValue the new value to set for this index.
  3885. @see set, getUnchecked
  3886. */
  3887. void setUnchecked (const int indexToChange,
  3888. const ElementType newValue) throw()
  3889. {
  3890. lock.enter();
  3891. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3892. this->elements [indexToChange] = newValue;
  3893. lock.exit();
  3894. }
  3895. /** Adds elements from an array to the end of this array.
  3896. @param elementsToAdd the array of elements to add
  3897. @param numElementsToAdd how many elements are in this other array
  3898. @see add
  3899. */
  3900. void addArray (const ElementType* elementsToAdd,
  3901. int numElementsToAdd) throw()
  3902. {
  3903. lock.enter();
  3904. if (numElementsToAdd > 0)
  3905. {
  3906. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3907. while (--numElementsToAdd >= 0)
  3908. this->elements [numUsed++] = *elementsToAdd++;
  3909. }
  3910. lock.exit();
  3911. }
  3912. /** This swaps the contents of this array with those of another array.
  3913. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3914. because it just swaps their internal pointers.
  3915. */
  3916. template <class OtherArrayType>
  3917. void swapWithArray (OtherArrayType& otherArray) throw()
  3918. {
  3919. lock.enter();
  3920. otherArray.lock.enter();
  3921. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3922. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3923. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3924. otherArray.lock.exit();
  3925. lock.exit();
  3926. }
  3927. /** Adds elements from another array to the end of this array.
  3928. @param arrayToAddFrom the array from which to copy the elements
  3929. @param startIndex the first element of the other array to start copying from
  3930. @param numElementsToAdd how many elements to add from the other array. If this
  3931. value is negative or greater than the number of available elements,
  3932. all available elements will be copied.
  3933. @see add
  3934. */
  3935. template <class OtherArrayType>
  3936. void addArray (const OtherArrayType& arrayToAddFrom,
  3937. int startIndex = 0,
  3938. int numElementsToAdd = -1) throw()
  3939. {
  3940. arrayToAddFrom.lockArray();
  3941. lock.enter();
  3942. jassert (this != &arrayToAddFrom);
  3943. if (startIndex < 0)
  3944. {
  3945. jassertfalse
  3946. startIndex = 0;
  3947. }
  3948. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3949. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3950. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  3951. lock.exit();
  3952. arrayToAddFrom.unlockArray();
  3953. }
  3954. /** Inserts a new element into the array, assuming that the array is sorted.
  3955. This will use a comparator to find the position at which the new element
  3956. should go. If the array isn't sorted, the behaviour of this
  3957. method will be unpredictable.
  3958. @param comparator the comparator to use to compare the elements - see the sort()
  3959. method for details about the form this object should take
  3960. @param newElement the new element to insert to the array
  3961. @see add, sort
  3962. */
  3963. template <class ElementComparator>
  3964. void addSorted (ElementComparator& comparator,
  3965. const ElementType newElement) throw()
  3966. {
  3967. lock.enter();
  3968. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  3969. lock.exit();
  3970. }
  3971. /** Finds the index of an element in the array, assuming that the array is sorted.
  3972. This will use a comparator to do a binary-chop to find the index of the given
  3973. element, if it exists. If the array isn't sorted, the behaviour of this
  3974. method will be unpredictable.
  3975. @param comparator the comparator to use to compare the elements - see the sort()
  3976. method for details about the form this object should take
  3977. @param elementToLookFor the element to search for
  3978. @returns the index of the element, or -1 if it's not found
  3979. @see addSorted, sort
  3980. */
  3981. template <class ElementComparator>
  3982. int indexOfSorted (ElementComparator& comparator,
  3983. const ElementType elementToLookFor) const throw()
  3984. {
  3985. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3986. // avoids getting warning messages about the parameter being unused
  3987. lock.enter();
  3988. int start = 0;
  3989. int end = numUsed;
  3990. for (;;)
  3991. {
  3992. if (start >= end)
  3993. {
  3994. lock.exit();
  3995. return -1;
  3996. }
  3997. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  3998. {
  3999. lock.exit();
  4000. return start;
  4001. }
  4002. else
  4003. {
  4004. const int halfway = (start + end) >> 1;
  4005. if (halfway == start)
  4006. {
  4007. lock.exit();
  4008. return -1;
  4009. }
  4010. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4011. start = halfway;
  4012. else
  4013. end = halfway;
  4014. }
  4015. }
  4016. }
  4017. /** Removes an element from the array.
  4018. This will remove the element at a given index, and move back
  4019. all the subsequent elements to close the gap.
  4020. If the index passed in is out-of-range, nothing will happen.
  4021. @param indexToRemove the index of the element to remove
  4022. @returns the element that has been removed
  4023. @see removeValue, removeRange
  4024. */
  4025. ElementType remove (const int indexToRemove) throw()
  4026. {
  4027. lock.enter();
  4028. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4029. {
  4030. --numUsed;
  4031. ElementType* const e = this->elements + indexToRemove;
  4032. ElementType const removed = *e;
  4033. const int numberToShift = numUsed - indexToRemove;
  4034. if (numberToShift > 0)
  4035. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4036. if ((numUsed << 1) < this->numAllocated)
  4037. minimiseStorageOverheads();
  4038. lock.exit();
  4039. return removed;
  4040. }
  4041. else
  4042. {
  4043. lock.exit();
  4044. return ElementType();
  4045. }
  4046. }
  4047. /** Removes an item from the array.
  4048. This will remove the first occurrence of the given element from the array.
  4049. If the item isn't found, no action is taken.
  4050. @param valueToRemove the object to try to remove
  4051. @see remove, removeRange
  4052. */
  4053. void removeValue (const ElementType valueToRemove) throw()
  4054. {
  4055. lock.enter();
  4056. ElementType* e = this->elements;
  4057. for (int i = numUsed; --i >= 0;)
  4058. {
  4059. if (valueToRemove == *e)
  4060. {
  4061. remove ((int) (e - this->elements));
  4062. break;
  4063. }
  4064. ++e;
  4065. }
  4066. lock.exit();
  4067. }
  4068. /** Removes a range of elements from the array.
  4069. This will remove a set of elements, starting from the given index,
  4070. and move subsequent elements down to close the gap.
  4071. If the range extends beyond the bounds of the array, it will
  4072. be safely clipped to the size of the array.
  4073. @param startIndex the index of the first element to remove
  4074. @param numberToRemove how many elements should be removed
  4075. @see remove, removeValue
  4076. */
  4077. void removeRange (int startIndex,
  4078. const int numberToRemove) throw()
  4079. {
  4080. lock.enter();
  4081. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4082. startIndex = jlimit (0, numUsed, startIndex);
  4083. if (endIndex > startIndex)
  4084. {
  4085. const int rangeSize = endIndex - startIndex;
  4086. ElementType* e = this->elements + startIndex;
  4087. int numToShift = numUsed - endIndex;
  4088. numUsed -= rangeSize;
  4089. while (--numToShift >= 0)
  4090. {
  4091. *e = e [rangeSize];
  4092. ++e;
  4093. }
  4094. if ((numUsed << 1) < this->numAllocated)
  4095. minimiseStorageOverheads();
  4096. }
  4097. lock.exit();
  4098. }
  4099. /** Removes the last n elements from the array.
  4100. @param howManyToRemove how many elements to remove from the end of the array
  4101. @see remove, removeValue, removeRange
  4102. */
  4103. void removeLast (const int howManyToRemove = 1) throw()
  4104. {
  4105. lock.enter();
  4106. numUsed = jmax (0, numUsed - howManyToRemove);
  4107. if ((numUsed << 1) < this->numAllocated)
  4108. minimiseStorageOverheads();
  4109. lock.exit();
  4110. }
  4111. /** Removes any elements which are also in another array.
  4112. @param otherArray the other array in which to look for elements to remove
  4113. @see removeValuesNotIn, remove, removeValue, removeRange
  4114. */
  4115. template <class OtherArrayType>
  4116. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4117. {
  4118. otherArray.lockArray();
  4119. lock.enter();
  4120. if (this == &otherArray)
  4121. {
  4122. clear();
  4123. }
  4124. else
  4125. {
  4126. if (otherArray.size() > 0)
  4127. {
  4128. for (int i = numUsed; --i >= 0;)
  4129. if (otherArray.contains (this->elements [i]))
  4130. remove (i);
  4131. }
  4132. }
  4133. lock.exit();
  4134. otherArray.unlockArray();
  4135. }
  4136. /** Removes any elements which are not found in another array.
  4137. Only elements which occur in this other array will be retained.
  4138. @param otherArray the array in which to look for elements NOT to remove
  4139. @see removeValuesIn, remove, removeValue, removeRange
  4140. */
  4141. template <class OtherArrayType>
  4142. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4143. {
  4144. otherArray.lockArray();
  4145. lock.enter();
  4146. if (this != &otherArray)
  4147. {
  4148. if (otherArray.size() <= 0)
  4149. {
  4150. clear();
  4151. }
  4152. else
  4153. {
  4154. for (int i = numUsed; --i >= 0;)
  4155. if (! otherArray.contains (this->elements [i]))
  4156. remove (i);
  4157. }
  4158. }
  4159. lock.exit();
  4160. otherArray.unlockArray();
  4161. }
  4162. /** Swaps over two elements in the array.
  4163. This swaps over the elements found at the two indexes passed in.
  4164. If either index is out-of-range, this method will do nothing.
  4165. @param index1 index of one of the elements to swap
  4166. @param index2 index of the other element to swap
  4167. */
  4168. void swap (const int index1,
  4169. const int index2) throw()
  4170. {
  4171. lock.enter();
  4172. if (((unsigned int) index1) < (unsigned int) numUsed
  4173. && ((unsigned int) index2) < (unsigned int) numUsed)
  4174. {
  4175. swapVariables (this->elements [index1],
  4176. this->elements [index2]);
  4177. }
  4178. lock.exit();
  4179. }
  4180. /** Moves one of the values to a different position.
  4181. This will move the value to a specified index, shuffling along
  4182. any intervening elements as required.
  4183. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4184. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4185. @param currentIndex the index of the value to be moved. If this isn't a
  4186. valid index, then nothing will be done
  4187. @param newIndex the index at which you'd like this value to end up. If this
  4188. is less than zero, the value will be moved to the end
  4189. of the array
  4190. */
  4191. void move (const int currentIndex,
  4192. int newIndex) throw()
  4193. {
  4194. if (currentIndex != newIndex)
  4195. {
  4196. lock.enter();
  4197. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4198. {
  4199. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4200. newIndex = numUsed - 1;
  4201. const ElementType value = this->elements [currentIndex];
  4202. if (newIndex > currentIndex)
  4203. {
  4204. memmove (this->elements + currentIndex,
  4205. this->elements + currentIndex + 1,
  4206. (newIndex - currentIndex) * sizeof (ElementType));
  4207. }
  4208. else
  4209. {
  4210. memmove (this->elements + newIndex + 1,
  4211. this->elements + newIndex,
  4212. (currentIndex - newIndex) * sizeof (ElementType));
  4213. }
  4214. this->elements [newIndex] = value;
  4215. }
  4216. lock.exit();
  4217. }
  4218. }
  4219. /** Reduces the amount of storage being used by the array.
  4220. Arrays typically allocate slightly more storage than they need, and after
  4221. removing elements, they may have quite a lot of unused space allocated.
  4222. This method will reduce the amount of allocated storage to a minimum.
  4223. */
  4224. void minimiseStorageOverheads() throw()
  4225. {
  4226. lock.enter();
  4227. if (numUsed == 0)
  4228. {
  4229. this->setAllocatedSize (0);
  4230. }
  4231. else
  4232. {
  4233. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4234. if (newAllocation < this->numAllocated)
  4235. this->setAllocatedSize (newAllocation);
  4236. }
  4237. lock.exit();
  4238. }
  4239. /** Increases the array's internal storage to hold a minimum number of elements.
  4240. Calling this before adding a large known number of elements means that
  4241. the array won't have to keep dynamically resizing itself as the elements
  4242. are added, and it'll therefore be more efficient.
  4243. */
  4244. void ensureStorageAllocated (const int minNumElements) throw()
  4245. {
  4246. this->ensureAllocatedSize (minNumElements);
  4247. }
  4248. /** Sorts the elements in the array.
  4249. This will use a comparator object to sort the elements into order. The object
  4250. passed must have a method of the form:
  4251. @code
  4252. int compareElements (ElementType first, ElementType second);
  4253. @endcode
  4254. ..and this method must return:
  4255. - a value of < 0 if the first comes before the second
  4256. - a value of 0 if the two objects are equivalent
  4257. - a value of > 0 if the second comes before the first
  4258. To improve performance, the compareElements() method can be declared as static or const.
  4259. @param comparator the comparator to use for comparing elements.
  4260. @param retainOrderOfEquivalentItems if this is true, then items
  4261. which the comparator says are equivalent will be
  4262. kept in the order in which they currently appear
  4263. in the array. This is slower to perform, but may
  4264. be important in some cases. If it's false, a faster
  4265. algorithm is used, but equivalent elements may be
  4266. rearranged.
  4267. @see addSorted, indexOfSorted, sortArray
  4268. */
  4269. template <class ElementComparator>
  4270. void sort (ElementComparator& comparator,
  4271. const bool retainOrderOfEquivalentItems = false) const throw()
  4272. {
  4273. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4274. // avoids getting warning messages about the parameter being unused
  4275. lock.enter();
  4276. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4277. lock.exit();
  4278. }
  4279. /** Locks the array's CriticalSection.
  4280. Of course if the type of section used is a DummyCriticalSection, this won't
  4281. have any effect.
  4282. @see unlockArray
  4283. */
  4284. void lockArray() const throw()
  4285. {
  4286. lock.enter();
  4287. }
  4288. /** Unlocks the array's CriticalSection.
  4289. Of course if the type of section used is a DummyCriticalSection, this won't
  4290. have any effect.
  4291. @see lockArray
  4292. */
  4293. void unlockArray() const throw()
  4294. {
  4295. lock.exit();
  4296. }
  4297. juce_UseDebuggingNewOperator
  4298. private:
  4299. int numUsed;
  4300. TypeOfCriticalSectionToUse lock;
  4301. };
  4302. #endif // __JUCE_ARRAY_JUCEHEADER__
  4303. /********* End of inlined file: juce_Array.h *********/
  4304. /**
  4305. A typedef for an Array of void*'s.
  4306. VoidArrays are used in various places throughout the library instead of
  4307. more strongly-typed arrays, to keep code-size low.
  4308. */
  4309. typedef Array <void*> VoidArray;
  4310. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4311. /********* End of inlined file: juce_VoidArray.h *********/
  4312. #ifndef DOXYGEN
  4313. // (used in StringArray::appendNumbersToDuplicates)
  4314. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4315. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4316. #endif
  4317. /**
  4318. A special array for holding a list of strings.
  4319. @see String, StringPairArray
  4320. */
  4321. class JUCE_API StringArray
  4322. {
  4323. public:
  4324. /** Creates an empty string array */
  4325. StringArray() throw();
  4326. /** Creates a copy of another string array */
  4327. StringArray (const StringArray& other) throw();
  4328. /** Creates a copy of an array of string literals.
  4329. @param strings an array of strings to add. Null pointers in the array will be
  4330. treated as empty strings
  4331. @param numberOfStrings how many items there are in the array
  4332. */
  4333. StringArray (const juce_wchar** const strings,
  4334. const int numberOfStrings) throw();
  4335. /** Creates a copy of an array of string literals.
  4336. @param strings an array of strings to add. Null pointers in the array will be
  4337. treated as empty strings
  4338. @param numberOfStrings how many items there are in the array
  4339. */
  4340. StringArray (const char** const strings,
  4341. const int numberOfStrings) throw();
  4342. /** Creates a copy of a null-terminated array of string literals.
  4343. Each item from the array passed-in is added, until it encounters a null pointer,
  4344. at which point it stops.
  4345. */
  4346. StringArray (const juce_wchar** const strings) throw();
  4347. /** Creates a copy of a null-terminated array of string literals.
  4348. Each item from the array passed-in is added, until it encounters a null pointer,
  4349. at which point it stops.
  4350. */
  4351. StringArray (const char** const strings) throw();
  4352. /** Destructor. */
  4353. virtual ~StringArray() throw();
  4354. /** Copies the contents of another string array into this one */
  4355. const StringArray& operator= (const StringArray& other) throw();
  4356. /** Compares two arrays.
  4357. Comparisons are case-sensitive.
  4358. @returns true only if the other array contains exactly the same strings in the same order
  4359. */
  4360. bool operator== (const StringArray& other) const throw();
  4361. /** Compares two arrays.
  4362. Comparisons are case-sensitive.
  4363. @returns false if the other array contains exactly the same strings in the same order
  4364. */
  4365. bool operator!= (const StringArray& other) const throw();
  4366. /** Returns the number of strings in the array */
  4367. inline int size() const throw() { return strings.size(); };
  4368. /** Returns one of the strings from the array.
  4369. If the index is out-of-range, an empty string is returned.
  4370. Obviously the reference returned shouldn't be stored for later use, as the
  4371. string it refers to may disappear when the array changes.
  4372. */
  4373. const String& operator[] (const int index) const throw();
  4374. /** Searches for a string in the array.
  4375. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4376. @returns true if the string is found inside the array
  4377. */
  4378. bool contains (const String& stringToLookFor,
  4379. const bool ignoreCase = false) const throw();
  4380. /** Searches for a string in the array.
  4381. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4382. @param stringToLookFor the string to try to find
  4383. @param ignoreCase whether the comparison should be case-insensitive
  4384. @param startIndex the first index to start searching from
  4385. @returns the index of the first occurrence of the string in this array,
  4386. or -1 if it isn't found.
  4387. */
  4388. int indexOf (const String& stringToLookFor,
  4389. const bool ignoreCase = false,
  4390. int startIndex = 0) const throw();
  4391. /** Appends a string at the end of the array. */
  4392. void add (const String& stringToAdd) throw();
  4393. /** Inserts a string into the array.
  4394. This will insert a string into the array at the given index, moving
  4395. up the other elements to make room for it.
  4396. If the index is less than zero or greater than the size of the array,
  4397. the new string will be added to the end of the array.
  4398. */
  4399. void insert (const int index,
  4400. const String& stringToAdd) throw();
  4401. /** Adds a string to the array as long as it's not already in there.
  4402. The search can optionally be case-insensitive.
  4403. */
  4404. void addIfNotAlreadyThere (const String& stringToAdd,
  4405. const bool ignoreCase = false) throw();
  4406. /** Replaces one of the strings in the array with another one.
  4407. If the index is higher than the array's size, the new string will be
  4408. added to the end of the array; if it's less than zero nothing happens.
  4409. */
  4410. void set (const int index,
  4411. const String& newString) throw();
  4412. /** Appends some strings from another array to the end of this one.
  4413. @param other the array to add
  4414. @param startIndex the first element of the other array to add
  4415. @param numElementsToAdd the maximum number of elements to add (if this is
  4416. less than zero, they are all added)
  4417. */
  4418. void addArray (const StringArray& other,
  4419. int startIndex = 0,
  4420. int numElementsToAdd = -1) throw();
  4421. /** Breaks up a string into tokens and adds them to this array.
  4422. This will tokenise the given string using whitespace characters as the
  4423. token delimiters, and will add these tokens to the end of the array.
  4424. @returns the number of tokens added
  4425. */
  4426. int addTokens (const tchar* const stringToTokenise,
  4427. const bool preserveQuotedStrings) throw();
  4428. /** Breaks up a string into tokens and adds them to this array.
  4429. This will tokenise the given string (using the string passed in to define the
  4430. token delimiters), and will add these tokens to the end of the array.
  4431. @param stringToTokenise the string to tokenise
  4432. @param breakCharacters a string of characters, any of which will be considered
  4433. to be a token delimiter.
  4434. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4435. which are treated as quotes. Any text occurring
  4436. between quotes is not broken up into tokens.
  4437. @returns the number of tokens added
  4438. */
  4439. int addTokens (const tchar* const stringToTokenise,
  4440. const tchar* breakCharacters,
  4441. const tchar* quoteCharacters) throw();
  4442. /** Breaks up a string into lines and adds them to this array.
  4443. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4444. to the array. Line-break characters are omitted from the strings that are added to
  4445. the array.
  4446. */
  4447. int addLines (const tchar* stringToBreakUp) throw();
  4448. /** Removes all elements from the array. */
  4449. void clear() throw();
  4450. /** Removes a string from the array.
  4451. If the index is out-of-range, no action will be taken.
  4452. */
  4453. void remove (const int index) throw();
  4454. /** Finds a string in the array and removes it.
  4455. This will remove the first occurrence of the given string from the array. The
  4456. comparison may be case-insensitive depending on the ignoreCase parameter.
  4457. */
  4458. void removeString (const String& stringToRemove,
  4459. const bool ignoreCase = false) throw();
  4460. /** Removes any duplicated elements from the array.
  4461. If any string appears in the array more than once, only the first occurrence of
  4462. it will be retained.
  4463. @param ignoreCase whether to use a case-insensitive comparison
  4464. */
  4465. void removeDuplicates (const bool ignoreCase) throw();
  4466. /** Removes empty strings from the array.
  4467. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4468. characters will also be removed
  4469. */
  4470. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4471. /** Moves one of the strings to a different position.
  4472. This will move the string to a specified index, shuffling along
  4473. any intervening elements as required.
  4474. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4475. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4476. @param currentIndex the index of the value to be moved. If this isn't a
  4477. valid index, then nothing will be done
  4478. @param newIndex the index at which you'd like this value to end up. If this
  4479. is less than zero, the value will be moved to the end
  4480. of the array
  4481. */
  4482. void move (const int currentIndex, int newIndex) throw();
  4483. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4484. void trim() throw();
  4485. /** Adds numbers to the strings in the array, to make each string unique.
  4486. This will add numbers to the ends of groups of similar strings.
  4487. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4488. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4489. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4490. also has a number appended to it.
  4491. @param preNumberString when adding a number, this string is added before the number
  4492. @param postNumberString this string is appended after any numbers that are added
  4493. */
  4494. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4495. const bool appendNumberToFirstInstance,
  4496. const tchar* const preNumberString = defaultPreNumberString,
  4497. const tchar* const postNumberString = defaultPostNumberString) throw();
  4498. /** Joins the strings in the array together into one string.
  4499. This will join a range of elements from the array into a string, separating
  4500. them with a given string.
  4501. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4502. @param separatorString the string to insert between all the strings
  4503. @param startIndex the first element to join
  4504. @param numberOfElements how many elements to join together. If this is less
  4505. than zero, all available elements will be used.
  4506. */
  4507. const String joinIntoString (const String& separatorString,
  4508. int startIndex = 0,
  4509. int numberOfElements = -1) const throw();
  4510. /** Sorts the array into alphabetical order.
  4511. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4512. */
  4513. void sort (const bool ignoreCase) throw();
  4514. /** Reduces the amount of storage being used by the array.
  4515. Arrays typically allocate slightly more storage than they need, and after
  4516. removing elements, they may have quite a lot of unused space allocated.
  4517. This method will reduce the amount of allocated storage to a minimum.
  4518. */
  4519. void minimiseStorageOverheads() throw();
  4520. juce_UseDebuggingNewOperator
  4521. private:
  4522. VoidArray strings;
  4523. };
  4524. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4525. /********* End of inlined file: juce_StringArray.h *********/
  4526. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4527. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4528. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4529. /**
  4530. A class to hold a resizable block of raw data.
  4531. */
  4532. class JUCE_API MemoryBlock
  4533. {
  4534. public:
  4535. /** Create an uninitialised block with 0 size. */
  4536. MemoryBlock() throw();
  4537. /** Creates a memory block with a given initial size.
  4538. @param initialSize the size of block to create
  4539. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4540. */
  4541. MemoryBlock (const int initialSize,
  4542. const bool initialiseToZero = false) throw();
  4543. /** Creates a copy of another memory block. */
  4544. MemoryBlock (const MemoryBlock& other) throw();
  4545. /** Creates a memory block using a copy of a block of data.
  4546. @param dataToInitialiseFrom some data to copy into this block
  4547. @param sizeInBytes how much space to use
  4548. */
  4549. MemoryBlock (const void* const dataToInitialiseFrom,
  4550. const int sizeInBytes) throw();
  4551. /** Destructor. */
  4552. ~MemoryBlock() throw();
  4553. /** Copies another memory block onto this one.
  4554. This block will be resized and copied to exactly match the other one.
  4555. */
  4556. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4557. /** Compares two memory blocks.
  4558. @returns true only if the two blocks are the same size and have identical contents.
  4559. */
  4560. bool operator== (const MemoryBlock& other) const throw();
  4561. /** Compares two memory blocks.
  4562. @returns true if the two blocks are different sizes or have different contents.
  4563. */
  4564. bool operator!= (const MemoryBlock& other) const throw();
  4565. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4566. Note that the pointer returned will probably become invalid when the
  4567. block is resized.
  4568. */
  4569. template <class DataType>
  4570. operator DataType*() const throw() { return (DataType*) data; }
  4571. /** Returns a void pointer to the data.
  4572. Note that the pointer returned will probably become invalid when the
  4573. block is resized.
  4574. */
  4575. void* getData() const throw() { return data; }
  4576. /** Returns a byte from the memory block.
  4577. This returns a reference, so you can also use it to set a byte.
  4578. */
  4579. char& operator[] (const int offset) const throw() { return data [offset]; }
  4580. /** Returns the block's current allocated size, in bytes. */
  4581. int getSize() const throw() { return size; }
  4582. /** Resizes the memory block.
  4583. This will try to keep as much of the block's current content as it can,
  4584. and can optionally be made to clear any new space that gets allocated at
  4585. the end of the block.
  4586. @param newSize the new desired size for the block
  4587. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4588. whether to clear the new section or just leave it
  4589. uninitialised
  4590. @see ensureSize
  4591. */
  4592. void setSize (const int newSize,
  4593. const bool initialiseNewSpaceToZero = false) throw();
  4594. /** Increases the block's size only if it's smaller than a given size.
  4595. @param minimumSize if the block is already bigger than this size, no action
  4596. will be taken; otherwise it will be increased to this size
  4597. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4598. whether to clear the new section or just leave it
  4599. uninitialised
  4600. @see setSize
  4601. */
  4602. void ensureSize (const int minimumSize,
  4603. const bool initialiseNewSpaceToZero = false) throw();
  4604. /** Fills the entire memory block with a repeated byte value.
  4605. This is handy for clearing a block of memory to zero.
  4606. */
  4607. void fillWith (const uint8 valueToUse) throw();
  4608. /** Adds another block of data to the end of this one.
  4609. This block's size will be increased accordingly.
  4610. */
  4611. void append (const void* const data,
  4612. const int numBytes) throw();
  4613. /** Copies data into this MemoryBlock from a memory address.
  4614. @param srcData the memory location of the data to copy into this block
  4615. @param destinationOffset the offset in this block at which the data being copied should begin
  4616. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4617. it will be clipped so not to do anything nasty)
  4618. */
  4619. void copyFrom (const void* srcData,
  4620. int destinationOffset,
  4621. int numBytes) throw();
  4622. /** Copies data from this MemoryBlock to a memory address.
  4623. @param destData the memory location to write to
  4624. @param sourceOffset the offset within this block from which the copied data will be read
  4625. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4626. zeros will be used for that portion of the data)
  4627. */
  4628. void copyTo (void* destData,
  4629. int sourceOffset,
  4630. int numBytes) const throw();
  4631. /** Chops out a section of the block.
  4632. This will remove a section of the memory block and close the gap around it,
  4633. shifting any subsequent data downwards and reducing the size of the block.
  4634. If the range specified goes beyond the size of the block, it will be clipped.
  4635. */
  4636. void removeSection (int startByte, int numBytesToRemove) throw();
  4637. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4638. characters in the system's default encoding. */
  4639. const String toString() const throw();
  4640. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4641. The block will be resized to the number of valid bytes read from the string.
  4642. Non-hex characters in the string will be ignored.
  4643. @see String::toHexString()
  4644. */
  4645. void loadFromHexString (const String& sourceHexString) throw();
  4646. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4647. void setBitRange (int bitRangeStart,
  4648. int numBits,
  4649. int binaryNumberToApply) throw();
  4650. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4651. int getBitRange (int bitRangeStart,
  4652. int numBitsToRead) const throw();
  4653. /** Returns a string of characters that represent the binary contents of this block.
  4654. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4655. of simple non-extended characters, e.g. for storage in XML.
  4656. @see fromBase64Encoding
  4657. */
  4658. const String toBase64Encoding() const throw();
  4659. /** Takes a string of encoded characters and turns it into binary data.
  4660. The string passed in must have been created by to64BitEncoding(), and this
  4661. block will be resized to recreate the original data block.
  4662. @see toBase64Encoding
  4663. */
  4664. bool fromBase64Encoding (const String& encodedString) throw();
  4665. juce_UseDebuggingNewOperator
  4666. private:
  4667. char* data;
  4668. int size;
  4669. };
  4670. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4671. /********* End of inlined file: juce_MemoryBlock.h *********/
  4672. class FileInputStream;
  4673. class FileOutputStream;
  4674. /**
  4675. Represents a local file or directory.
  4676. This class encapsulates the absolute pathname of a file or directory, and
  4677. has methods for finding out about the file and changing its properties.
  4678. To read or write to the file, there are methods for returning an input or
  4679. output stream.
  4680. @see FileInputStream, FileOutputStream
  4681. */
  4682. class JUCE_API File
  4683. {
  4684. public:
  4685. /** Creates an (invalid) file object.
  4686. The file is initially set to an empty path, so getFullPath() will return
  4687. an empty string, and comparing the file to File::nonexistent will return
  4688. true.
  4689. You can use its operator= method to point it at a proper file.
  4690. */
  4691. File() throw() {}
  4692. /** Creates a file from an absolute path.
  4693. If the path supplied is a relative path, it is taken to be relative
  4694. to the current working directory (see File::getCurrentWorkingDirectory()),
  4695. but this isn't a recommended way of creating a file, because you
  4696. never know what the CWD is going to be.
  4697. On the Mac/Linux, the path can include "~" notation for referring to
  4698. user home directories.
  4699. */
  4700. File (const String& path) throw();
  4701. /** Creates a copy of another file object. */
  4702. File (const File& other) throw();
  4703. /** Destructor. */
  4704. ~File() throw() {}
  4705. /** Sets the file based on an absolute pathname.
  4706. If the path supplied is a relative path, it is taken to be relative
  4707. to the current working directory (see File::getCurrentWorkingDirectory()),
  4708. but this isn't a recommended way of creating a file, because you
  4709. never know what the CWD is going to be.
  4710. On the Mac/Linux, the path can include "~" notation for referring to
  4711. user home directories.
  4712. */
  4713. const File& operator= (const String& newFilePath) throw();
  4714. /** Copies from another file object. */
  4715. const File& operator= (const File& otherFile) throw();
  4716. /** This static constant is used for referring to an 'invalid' file. */
  4717. static const File nonexistent;
  4718. /** Checks whether the file actually exists.
  4719. @returns true if the file exists, either as a file or a directory.
  4720. @see existsAsFile, isDirectory
  4721. */
  4722. bool exists() const throw();
  4723. /** Checks whether the file exists and is a file rather than a directory.
  4724. @returns true only if this is a real file, false if it's a directory
  4725. or doesn't exist
  4726. @see exists, isDirectory
  4727. */
  4728. bool existsAsFile() const throw();
  4729. /** Checks whether the file is a directory that exists.
  4730. @returns true only if the file is a directory which actually exists, so
  4731. false if it's a file or doesn't exist at all
  4732. @see exists, existsAsFile
  4733. */
  4734. bool isDirectory() const throw();
  4735. /** Returns the size of the file in bytes.
  4736. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4737. */
  4738. int64 getSize() const throw();
  4739. /** Utility function to convert a file size in bytes to a neat string description.
  4740. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4741. 2000000 would produce "2 MB", etc.
  4742. */
  4743. static const String descriptionOfSizeInBytes (const int64 bytes);
  4744. /** Returns the complete, absolute path of this file.
  4745. This includes the filename and all its parent folders. On Windows it'll
  4746. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4747. path starting from the root folder.
  4748. If you just want the file's name, you should use getFileName() or
  4749. getFileNameWithoutExtension().
  4750. @see getFileName, getRelativePathFrom
  4751. */
  4752. const String& getFullPathName() const throw() { return fullPath; }
  4753. /** Returns the last section of the pathname.
  4754. Returns just the final part of the path - e.g. if the whole path
  4755. is "/moose/fish/foo.txt" this will return "foo.txt".
  4756. For a directory, it returns the final part of the path - e.g. for the
  4757. directory "/moose/fish" it'll return "fish".
  4758. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4759. "/moose/.fish", it'll return ".fish"
  4760. @see getFullPathName, getFileNameWithoutExtension
  4761. */
  4762. const String getFileName() const throw();
  4763. /** Creates a relative path that refers to a file relatively to a given directory.
  4764. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4765. would return "../../foo.txt".
  4766. If it's not possible to navigate from one file to the other, an absolute
  4767. path is returned. If the paths are invalid, an empty string may also be
  4768. returned.
  4769. @param directoryToBeRelativeTo the directory which the resultant string will
  4770. be relative to. If this is actually a file rather than
  4771. a directory, its parent directory will be used instead.
  4772. If it doesn't exist, it's assumed to be a directory.
  4773. @see getChildFile, isAbsolutePath
  4774. */
  4775. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4776. /** Returns the file's extension.
  4777. Returns the file extension of this file, also including the dot.
  4778. e.g. "/moose/fish/foo.txt" would return ".txt"
  4779. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4780. */
  4781. const String getFileExtension() const throw();
  4782. /** Checks whether the file has a given extension.
  4783. @param extensionToTest the extension to look for - it doesn't matter whether or
  4784. not this string has a dot at the start, so ".wav" and "wav"
  4785. will have the same effect. The comparison used is
  4786. case-insensitve.
  4787. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4788. */
  4789. bool hasFileExtension (const String& extensionToTest) const throw();
  4790. /** Returns a version of this file with a different file extension.
  4791. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4792. @param newExtension the new extension, either with or without a dot at the start (this
  4793. doesn't make any difference). To get remove a file's extension altogether,
  4794. pass an empty string into this function.
  4795. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4796. */
  4797. const File withFileExtension (const String& newExtension) const throw();
  4798. /** Returns the last part of the filename, without its file extension.
  4799. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4800. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4801. */
  4802. const String getFileNameWithoutExtension() const throw();
  4803. /** Returns a 32-bit hash-code that identifies this file.
  4804. This is based on the filename. Obviously it's possible, although unlikely, that
  4805. two files will have the same hash-code.
  4806. */
  4807. int hashCode() const throw();
  4808. /** Returns a 64-bit hash-code that identifies this file.
  4809. This is based on the filename. Obviously it's possible, although unlikely, that
  4810. two files will have the same hash-code.
  4811. */
  4812. int64 hashCode64() const throw();
  4813. /** Returns a file based on a relative path.
  4814. This will find a child file or directory of the current object.
  4815. e.g.
  4816. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4817. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4818. If the string is actually an absolute path, it will be treated as such, e.g.
  4819. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4820. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4821. */
  4822. const File getChildFile (String relativePath) const throw();
  4823. /** Returns a file which is in the same directory as this one.
  4824. This is equivalent to getParentDirectory().getChildFile (name).
  4825. @see getChildFile, getParentDirectory
  4826. */
  4827. const File getSiblingFile (const String& siblingFileName) const throw();
  4828. /** Returns the directory that contains this file or directory.
  4829. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4830. */
  4831. const File getParentDirectory() const throw();
  4832. /** Checks whether a file is somewhere inside a directory.
  4833. Returns true if this file is somewhere inside a subdirectory of the directory
  4834. that is passed in. Neither file actually has to exist, because the function
  4835. just checks the paths for similarities.
  4836. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4837. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4838. */
  4839. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4840. /** Chooses a filename relative to this one that doesn't already exist.
  4841. If this file is a directory, this will return a child file of this
  4842. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4843. it finds one that isn't already there.
  4844. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4845. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4846. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4847. @param prefix the string to use for the filename before the number
  4848. @param suffix the string to add to the filename after the number
  4849. @param putNumbersInBrackets if true, this will create filenames in the
  4850. format "prefix(number)suffix", if false, it will leave the
  4851. brackets out.
  4852. */
  4853. const File getNonexistentChildFile (const String& prefix,
  4854. const String& suffix,
  4855. bool putNumbersInBrackets = true) const throw();
  4856. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4857. If this file doesn't exist, this will just return itself, otherwise it
  4858. will return an appropriate sibling that doesn't exist, e.g. if a file
  4859. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4860. @param putNumbersInBrackets whether to add brackets around the numbers that
  4861. get appended to the new filename.
  4862. */
  4863. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4864. /** Compares the pathnames for two files. */
  4865. bool operator== (const File& otherFile) const throw();
  4866. /** Compares the pathnames for two files. */
  4867. bool operator!= (const File& otherFile) const throw();
  4868. /** Checks whether a file can be created or written to.
  4869. @returns true if it's possible to create and write to this file. If the file
  4870. doesn't already exist, this will check its parent directory to
  4871. see if writing is allowed.
  4872. @see setReadOnly
  4873. */
  4874. bool hasWriteAccess() const throw();
  4875. /** Changes the write-permission of a file or directory.
  4876. @param shouldBeReadOnly whether to add or remove write-permission
  4877. @param applyRecursively if the file is a directory and this is true, it will
  4878. recurse through all the subfolders changing the permissions
  4879. of all files
  4880. @returns true if it manages to change the file's permissions.
  4881. @see hasWriteAccess
  4882. */
  4883. bool setReadOnly (const bool shouldBeReadOnly,
  4884. const bool applyRecursively = false) const throw();
  4885. /** Returns true if this file is a hidden or system file.
  4886. The criteria for deciding whether a file is hidden are platform-dependent.
  4887. */
  4888. bool isHidden() const throw();
  4889. /** Returns the last modification time of this file.
  4890. @returns the time, or an invalid time if the file doesn't exist.
  4891. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4892. */
  4893. const Time getLastModificationTime() const throw();
  4894. /** Returns the last time this file was accessed.
  4895. @returns the time, or an invalid time if the file doesn't exist.
  4896. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4897. */
  4898. const Time getLastAccessTime() const throw();
  4899. /** Returns the time that this file was created.
  4900. @returns the time, or an invalid time if the file doesn't exist.
  4901. @see getLastModificationTime, getLastAccessTime
  4902. */
  4903. const Time getCreationTime() const throw();
  4904. /** Changes the modification time for this file.
  4905. @param newTime the time to apply to the file
  4906. @returns true if it manages to change the file's time.
  4907. @see getLastModificationTime, setLastAccessTime, setCreationTime
  4908. */
  4909. bool setLastModificationTime (const Time& newTime) const throw();
  4910. /** Changes the last-access time for this file.
  4911. @param newTime the time to apply to the file
  4912. @returns true if it manages to change the file's time.
  4913. @see getLastAccessTime, setLastModificationTime, setCreationTime
  4914. */
  4915. bool setLastAccessTime (const Time& newTime) const throw();
  4916. /** Changes the creation date for this file.
  4917. @param newTime the time to apply to the file
  4918. @returns true if it manages to change the file's time.
  4919. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4920. */
  4921. bool setCreationTime (const Time& newTime) const throw();
  4922. /** Creates an empty file if it doesn't already exist.
  4923. If the file that this object refers to doesn't exist, this will create a file
  4924. of zero size.
  4925. If it already exists or is a directory, this method will do nothing.
  4926. @returns true if the file has been created (or if it already existed).
  4927. @see createDirectory
  4928. */
  4929. bool create() const throw();
  4930. /** Creates a new directory for this filename.
  4931. This will try to create the file as a directory, and fill also create
  4932. any parent directories it needs in order to complete the operation.
  4933. @returns true if the directory has been created successfully, (or if it
  4934. already existed beforehand).
  4935. @see create
  4936. */
  4937. bool createDirectory() const throw();
  4938. /** Deletes a file.
  4939. If this file is actually a directory, it may not be deleted correctly if it
  4940. contains files. See deleteRecursively() as a better way of deleting directories.
  4941. @returns true if the file has been successfully deleted (or if it didn't exist to
  4942. begin with).
  4943. @see deleteRecursively
  4944. */
  4945. bool deleteFile() const throw();
  4946. /** Deletes a file or directory and all its subdirectories.
  4947. If this file is a directory, this will try to delete it and all its subfolders. If
  4948. it's just a file, it will just try to delete the file.
  4949. @returns true if the file and all its subfolders have been successfully deleted
  4950. (or if it didn't exist to begin with).
  4951. @see deleteFile
  4952. */
  4953. bool deleteRecursively() const throw();
  4954. /** Moves or renames a file.
  4955. Tries to move a file to a different location.
  4956. If the target file already exists, this will attempt to delete it first, and
  4957. will fail if this can't be done.
  4958. Note that the destination file isn't the directory to put it in, it's the actual
  4959. filename that you want the new file to have.
  4960. @returns true if the operation succeeds
  4961. */
  4962. bool moveFileTo (const File& targetLocation) const throw();
  4963. /** Copies a file.
  4964. Tries to copy a file to a different location.
  4965. If the target file already exists, this will attempt to delete it first, and
  4966. will fail if this can't be done.
  4967. @returns true if the operation succeeds
  4968. */
  4969. bool copyFileTo (const File& targetLocation) const throw();
  4970. /** Copies a directory.
  4971. Tries to copy an entire directory, recursively.
  4972. If this file isn't a directory or if any target files can't be created, this
  4973. will return false.
  4974. @param newDirectory the directory that this one should be copied to. Note that this
  4975. is the name of the actual directory to create, not the directory
  4976. into which the new one should be placed, so there must be enough
  4977. write privileges to create it if it doesn't exist. Any files inside
  4978. it will be overwritten by similarly named ones that are copied.
  4979. */
  4980. bool copyDirectoryTo (const File& newDirectory) const throw();
  4981. /** Used in file searching, to specify whether to return files, directories, or both.
  4982. */
  4983. enum TypesOfFileToFind
  4984. {
  4985. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  4986. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  4987. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  4988. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  4989. };
  4990. /** Searches inside a directory for files matching a wildcard pattern.
  4991. Assuming that this file is a directory, this method will search it
  4992. for either files or subdirectories whose names match a filename pattern.
  4993. @param results an array to which File objects will be added for the
  4994. files that the search comes up with
  4995. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  4996. return files, directories, or both. If the ignoreHiddenFiles flag
  4997. is also added to this value, hidden files won't be returned
  4998. @param searchRecursively if true, all subdirectories will be recursed into to do
  4999. an exhaustive search
  5000. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5001. @returns the number of results that have been found
  5002. @see getNumberOfChildFiles, DirectoryIterator
  5003. */
  5004. int findChildFiles (OwnedArray<File>& results,
  5005. const int whatToLookFor,
  5006. const bool searchRecursively,
  5007. const String& wildCardPattern = JUCE_T("*")) const throw();
  5008. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5009. Assuming that this file is a directory, this method will search it
  5010. for either files or subdirectories whose names match a filename pattern,
  5011. and will return the number of matches found.
  5012. This isn't a recursive call, and will only search this directory, not
  5013. its children.
  5014. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5015. count files, directories, or both. If the ignoreHiddenFiles flag
  5016. is also added to this value, hidden files won't be counted
  5017. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5018. @returns the number of matches found
  5019. @see findChildFiles, DirectoryIterator
  5020. */
  5021. int getNumberOfChildFiles (const int whatToLookFor,
  5022. const String& wildCardPattern = JUCE_T("*")) const throw();
  5023. /** Creates a stream to read from this file.
  5024. @returns a stream that will read from this file (initially positioned at the
  5025. start of the file), or 0 if the file can't be opened for some reason
  5026. @see createOutputStream, loadFileAsData
  5027. */
  5028. FileInputStream* createInputStream() const throw();
  5029. /** Creates a stream to write to this file.
  5030. If the file exists, the stream that is returned will be positioned ready for
  5031. writing at the end of the file, so you might want to use deleteFile() first
  5032. to write to an empty file.
  5033. @returns a stream that will write to this file (initially positioned at the
  5034. end of the file), or 0 if the file can't be opened for some reason
  5035. @see createInputStream, printf, appendData, appendText
  5036. */
  5037. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5038. /** Loads a file's contents into memory as a block of binary data.
  5039. Of course, trying to load a very large file into memory will blow up, so
  5040. it's better to check first.
  5041. @param result the data block to which the file's contents should be appended - note
  5042. that if the memory block might already contain some data, you
  5043. might want to clear it first
  5044. @returns true if the file could all be read into memory
  5045. */
  5046. bool loadFileAsData (MemoryBlock& result) const throw();
  5047. /** Reads a file into memory as a string.
  5048. Attempts to load the entire file as a zero-terminated string.
  5049. This makes use of InputStream::readEntireStreamAsString, which should
  5050. automatically cope with unicode/acsii file formats.
  5051. */
  5052. const String loadFileAsString() const throw();
  5053. /** Writes text to the end of the file.
  5054. This will try to do a printf to the file.
  5055. @returns false if it can't write to the file for some reason
  5056. */
  5057. bool printf (const tchar* format, ...) const throw();
  5058. /** Appends a block of binary data to the end of the file.
  5059. This will try to write the given buffer to the end of the file.
  5060. @returns false if it can't write to the file for some reason
  5061. */
  5062. bool appendData (const void* const dataToAppend,
  5063. const int numberOfBytes) const throw();
  5064. /** Replaces this file's contents with a given block of data.
  5065. This will delete the file and replace it with the given data.
  5066. A nice feature of this method is that it's safe - instead of deleting
  5067. the file first and then re-writing it, it creates a new temporary file,
  5068. writes the data to that, and then moves the new file to replace the existing
  5069. file. This means that if the power gets pulled out or something crashes,
  5070. you're a lot less likely to end up with an empty file..
  5071. Returns true if the operation succeeds, or false if it fails.
  5072. @see appendText
  5073. */
  5074. bool replaceWithData (const void* const dataToWrite,
  5075. const int numberOfBytes) const throw();
  5076. /** Appends a string to the end of the file.
  5077. This will try to append a text string to the file, as either 16-bit unicode
  5078. or 8-bit characters in the default system encoding.
  5079. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5080. the endianness of the file.
  5081. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5082. @see replaceWithText
  5083. */
  5084. bool appendText (const String& textToAppend,
  5085. const bool asUnicode = false,
  5086. const bool writeUnicodeHeaderBytes = false) const throw();
  5087. /** Replaces this file's contents with a given text string.
  5088. This will delete the file and replace it with the given text.
  5089. A nice feature of this method is that it's safe - instead of deleting
  5090. the file first and then re-writing it, it creates a new temporary file,
  5091. writes the text to that, and then moves the new file to replace the existing
  5092. file. This means that if the power gets pulled out or something crashes,
  5093. you're a lot less likely to end up with an empty file..
  5094. For an explanation of the parameters here, see the appendText() method.
  5095. Returns true if the operation succeeds, or false if it fails.
  5096. @see appendText
  5097. */
  5098. bool replaceWithText (const String& textToWrite,
  5099. const bool asUnicode = false,
  5100. const bool writeUnicodeHeaderBytes = false) const throw();
  5101. /** Creates a set of files to represent each file root.
  5102. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5103. to which ones are available. On the Mac/Linux, this will probably
  5104. just add a single entry for "/".
  5105. */
  5106. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5107. /** Finds the name of the drive on which this file lives.
  5108. @returns the volume label of the drive, or an empty string if this isn't possible
  5109. */
  5110. const String getVolumeLabel() const throw();
  5111. /** Returns the serial number of the volume on which this file lives.
  5112. @returns the serial number, or zero if there's a problem doing this
  5113. */
  5114. int getVolumeSerialNumber() const throw();
  5115. /** Returns the number of bytes free on the drive that this file lives on.
  5116. @returns the number of bytes free, or 0 if there's a problem finding this out
  5117. */
  5118. int64 getBytesFreeOnVolume() const throw();
  5119. /** Returns true if this file is on a CD or DVD drive. */
  5120. bool isOnCDRomDrive() const throw();
  5121. /** Returns true if this file is on a hard disk.
  5122. This will fail if it's a network drive, but will still be true for
  5123. removable hard-disks.
  5124. */
  5125. bool isOnHardDisk() const throw();
  5126. /** Returns true if this file is on a removable disk drive.
  5127. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5128. */
  5129. bool isOnRemovableDrive() const throw();
  5130. /** Launches the file as a process.
  5131. - if the file is executable, this will run it.
  5132. - if it's a document of some kind, it will launch the document with its
  5133. default viewer application.
  5134. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5135. */
  5136. bool startAsProcess (const String& parameters = String::empty) const throw();
  5137. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5138. */
  5139. enum SpecialLocationType
  5140. {
  5141. /** The user's home folder. This is the same as using File ("~"). */
  5142. userHomeDirectory,
  5143. /** The user's default documents folder. On Windows, this might be the user's
  5144. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5145. doesn't tend to have one of these, so it might just return their home folder.
  5146. */
  5147. userDocumentsDirectory,
  5148. /** The folder that contains the user's desktop objects. */
  5149. userDesktopDirectory,
  5150. /** The folder in which applications store their persistent user-specific settings.
  5151. On Windows, this might be "\Documents and Settings\username\Application Data".
  5152. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5153. always create your own sub-folder to put them in, to avoid making a mess.
  5154. */
  5155. userApplicationDataDirectory,
  5156. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5157. of the computer, rather than just the current user.
  5158. On the Mac it'll be "/Library", on Windows, it could be something like
  5159. "\Documents and Settings\All Users\Application Data".
  5160. Depending on the setup, this folder may be read-only.
  5161. */
  5162. commonApplicationDataDirectory,
  5163. /** The folder that should be used for temporary files.
  5164. Always delete them when you're finished, to keep the user's computer tidy!
  5165. */
  5166. tempDirectory,
  5167. /** Returns this application's executable file.
  5168. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5169. host app.
  5170. On the mac this will return the unix binary, not the package folder - see
  5171. currentApplicationFile for that.
  5172. */
  5173. currentExecutableFile,
  5174. /** Returns this application's location.
  5175. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5176. host app.
  5177. On the mac this will return the package folder (if it's in one), not the unix binary
  5178. that's inside it - compare with currentExecutableFile.
  5179. */
  5180. currentApplicationFile,
  5181. /** The directory in which applications normally get installed.
  5182. So on windows, this would be something like "c:\program files", on the
  5183. Mac "/Applications", or "/usr" on linux.
  5184. */
  5185. globalApplicationsDirectory,
  5186. /** The most likely place where a user might store their music files.
  5187. */
  5188. userMusicDirectory,
  5189. /** The most likely place where a user might store their movie files.
  5190. */
  5191. userMoviesDirectory,
  5192. };
  5193. /** Finds the location of a special type of file or directory, such as a home folder or
  5194. documents folder.
  5195. @see SpecialLocationType
  5196. */
  5197. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5198. /** Returns a temporary file in the system's temp directory.
  5199. This will try to return the name of a non-existent temp file.
  5200. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5201. */
  5202. static const File createTempFile (const String& fileNameEnding) throw();
  5203. /** Returns the current working directory.
  5204. @see setAsCurrentWorkingDirectory
  5205. */
  5206. static const File getCurrentWorkingDirectory() throw();
  5207. /** Sets the current working directory to be this file.
  5208. For this to work the file must point to a valid directory.
  5209. @returns true if the current directory has been changed.
  5210. @see getCurrentWorkingDirectory
  5211. */
  5212. bool setAsCurrentWorkingDirectory() const throw();
  5213. /** The system-specific file separator character.
  5214. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5215. */
  5216. static const tchar separator;
  5217. /** The system-specific file separator character, as a string.
  5218. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5219. */
  5220. static const tchar* separatorString;
  5221. /** Removes illegal characters from a filename.
  5222. This will return a copy of the given string after removing characters
  5223. that are not allowed in a legal filename, and possibly shortening the
  5224. string if it's too long.
  5225. Because this will remove slashes, don't use it on an absolute pathname.
  5226. @see createLegalPathName
  5227. */
  5228. static const String createLegalFileName (const String& fileNameToFix) throw();
  5229. /** Removes illegal characters from a pathname.
  5230. Similar to createLegalFileName(), but this won't remove slashes, so can
  5231. be used on a complete pathname.
  5232. @see createLegalFileName
  5233. */
  5234. static const String createLegalPathName (const String& pathNameToFix) throw();
  5235. /** Indicates whether filenames are case-sensitive on the current operating system.
  5236. */
  5237. static bool areFileNamesCaseSensitive();
  5238. /** Returns true if the string seems to be a fully-specified absolute path.
  5239. */
  5240. static bool isAbsolutePath (const String& path) throw();
  5241. juce_UseDebuggingNewOperator
  5242. private:
  5243. String fullPath;
  5244. // internal way of contructing a file without checking the path
  5245. friend class DirectoryIterator;
  5246. File (const String&, int) throw();
  5247. const String getPathUpToLastSlash() const throw();
  5248. };
  5249. #endif // __JUCE_FILE_JUCEHEADER__
  5250. /********* End of inlined file: juce_File.h *********/
  5251. /**
  5252. A simple implemenation of a Logger that writes to a file.
  5253. @see Logger
  5254. */
  5255. class JUCE_API FileLogger : public Logger
  5256. {
  5257. public:
  5258. /** Creates a FileLogger for a given file.
  5259. @param fileToWriteTo the file that to use - new messages will be appended
  5260. to the file. If the file doesn't exist, it will be created,
  5261. along with any parent directories that are needed.
  5262. @param welcomeMessage when opened, the logger will write a header to the log, along
  5263. with the current date and time, and this welcome message
  5264. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5265. but is larger than this number of bytes, then the start of the
  5266. file will be truncated to keep the size down. This prevents a log
  5267. file getting ridiculously large over time. The file will be truncated
  5268. at a new-line boundary. If this value is less than zero, no size limit
  5269. will be imposed; if it's zero, the file will always be deleted. Note that
  5270. the size is only checked once when this object is created - any logging
  5271. that is done later will be appended without any checking
  5272. */
  5273. FileLogger (const File& fileToWriteTo,
  5274. const String& welcomeMessage,
  5275. const int maxInitialFileSizeBytes = 128 * 1024);
  5276. /** Destructor. */
  5277. ~FileLogger();
  5278. void logMessage (const String& message);
  5279. /** Helper function to create a log file in the correct place for this platform.
  5280. On Windows this will return a logger with a path such as:
  5281. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5282. On the Mac it'll create something like:
  5283. ~/Library/Logs/[logFileName]
  5284. The method might return 0 if the file can't be created for some reason.
  5285. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5286. it's best to use the something like the name of your application here.
  5287. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5288. call it "log.txt" because if it goes in a directory with logs
  5289. from other applications (as it will do on the Mac) then no-one
  5290. will know which one is yours!
  5291. @param welcomeMessage a message that will be written to the log when it's opened.
  5292. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5293. */
  5294. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5295. const String& logFileName,
  5296. const String& welcomeMessage,
  5297. const int maxInitialFileSizeBytes = 128 * 1024);
  5298. juce_UseDebuggingNewOperator
  5299. private:
  5300. File logFile;
  5301. CriticalSection logLock;
  5302. FileOutputStream* logStream;
  5303. void trimFileSize (int maxFileSizeBytes) const;
  5304. FileLogger (const FileLogger&);
  5305. const FileLogger& operator= (const FileLogger&);
  5306. };
  5307. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5308. /********* End of inlined file: juce_FileLogger.h *********/
  5309. #endif
  5310. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5311. /********* Start of inlined file: juce_Initialisation.h *********/
  5312. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5313. #define __JUCE_INITIALISATION_JUCEHEADER__
  5314. /** Initialises Juce's GUI classes.
  5315. If you're embedding Juce into an application that uses its own event-loop rather
  5316. than using the START_JUCE_APPLICATION macro, call this function before making any
  5317. Juce calls, to make sure things are initialised correctly.
  5318. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5319. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5320. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5321. */
  5322. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5323. /** Clears up any static data being used by Juce's GUI classes.
  5324. If you're embedding Juce into an application that uses its own event-loop rather
  5325. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5326. code to clean up any juce objects that might be lying around.
  5327. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5328. */
  5329. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5330. /** Initialises the core parts of Juce.
  5331. If you're embedding Juce into either a command-line program, call this function
  5332. at the start of your main() function to make sure that Juce is initialised correctly.
  5333. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5334. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5335. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5336. */
  5337. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5338. /** Clears up any static data being used by Juce's non-gui core classes.
  5339. If you're embedding Juce into either a command-line program, call this function
  5340. at the end of your main() function if you want to make sure any Juce objects are
  5341. cleaned up correctly.
  5342. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5343. */
  5344. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5345. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5346. /********* End of inlined file: juce_Initialisation.h *********/
  5347. #endif
  5348. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5349. #endif
  5350. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  5351. #endif
  5352. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5353. #endif
  5354. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5355. #endif
  5356. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5357. /********* Start of inlined file: juce_Random.h *********/
  5358. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5359. #define __JUCE_RANDOM_JUCEHEADER__
  5360. /**
  5361. A simple pseudo-random number generator.
  5362. */
  5363. class JUCE_API Random
  5364. {
  5365. public:
  5366. /** Creates a Random object based on a seed value.
  5367. For a given seed value, the subsequent numbers generated by this object
  5368. will be predictable, so a good idea is to set this value based
  5369. on the time, e.g.
  5370. new Random (Time::currentTimeMillis())
  5371. */
  5372. Random (const int64 seedValue) throw();
  5373. /** Destructor. */
  5374. ~Random() throw();
  5375. /** Returns the next random 32 bit integer.
  5376. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5377. */
  5378. int nextInt() throw();
  5379. /** Returns the next random number, limited to a given range.
  5380. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5381. */
  5382. int nextInt (const int maxValue) throw();
  5383. /** Returns the next 64-bit random number.
  5384. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5385. */
  5386. int64 nextInt64() throw();
  5387. /** Returns the next random floating-point number.
  5388. @returns a random value in the range 0 to 1.0
  5389. */
  5390. float nextFloat() throw();
  5391. /** Returns the next random floating-point number.
  5392. @returns a random value in the range 0 to 1.0
  5393. */
  5394. double nextDouble() throw();
  5395. /** Returns the next random boolean value.
  5396. */
  5397. bool nextBool() throw();
  5398. /** To avoid the overhead of having to create a new Random object whenever
  5399. you need a number, this is a shared application-wide object that
  5400. can be used.
  5401. It's not thread-safe though, so threads should use their own Random object.
  5402. */
  5403. static Random& getSystemRandom() throw();
  5404. /** Resets this Random object to a given seed value. */
  5405. void setSeed (const int64 newSeed) throw();
  5406. juce_UseDebuggingNewOperator
  5407. private:
  5408. int64 seed;
  5409. };
  5410. #endif // __JUCE_RANDOM_JUCEHEADER__
  5411. /********* End of inlined file: juce_Random.h *********/
  5412. #endif
  5413. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5414. #endif
  5415. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5416. /********* Start of inlined file: juce_Singleton.h *********/
  5417. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5418. #define __JUCE_SINGLETON_JUCEHEADER__
  5419. /********* Start of inlined file: juce_ScopedLock.h *********/
  5420. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5421. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5422. /**
  5423. Automatically locks and unlocks a CriticalSection object.
  5424. Use one of these as a local variable to control access to a CriticalSection.
  5425. e.g. @code
  5426. CriticalSection myCriticalSection;
  5427. for (;;)
  5428. {
  5429. const ScopedLock myScopedLock (myCriticalSection);
  5430. // myCriticalSection is now locked
  5431. ...do some stuff...
  5432. // myCriticalSection gets unlocked here.
  5433. }
  5434. @endcode
  5435. @see CriticalSection, ScopedUnlock
  5436. */
  5437. class JUCE_API ScopedLock
  5438. {
  5439. public:
  5440. /** Creates a ScopedLock.
  5441. As soon as it is created, this will lock the CriticalSection, and
  5442. when the ScopedLock object is deleted, the CriticalSection will
  5443. be unlocked.
  5444. Make sure this object is created and deleted by the same thread,
  5445. otherwise there are no guarantees what will happen! Best just to use it
  5446. as a local stack object, rather than creating one with the new() operator.
  5447. */
  5448. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5449. /** Destructor.
  5450. The CriticalSection will be unlocked when the destructor is called.
  5451. Make sure this object is created and deleted by the same thread,
  5452. otherwise there are no guarantees what will happen!
  5453. */
  5454. inline ~ScopedLock() throw() { lock_.exit(); }
  5455. private:
  5456. const CriticalSection& lock_;
  5457. ScopedLock (const ScopedLock&);
  5458. const ScopedLock& operator= (const ScopedLock&);
  5459. };
  5460. /**
  5461. Automatically unlocks and re-locks a CriticalSection object.
  5462. This is the reverse of a ScopedLock object - instead of locking the critical
  5463. section for the lifetime of this object, it unlocks it.
  5464. Make sure you don't try to unlock critical sections that aren't actually locked!
  5465. e.g. @code
  5466. CriticalSection myCriticalSection;
  5467. for (;;)
  5468. {
  5469. const ScopedLock myScopedLock (myCriticalSection);
  5470. // myCriticalSection is now locked
  5471. ... do some stuff with it locked ..
  5472. while (xyz)
  5473. {
  5474. ... do some stuff with it locked ..
  5475. const ScopedUnlock unlocker (myCriticalSection);
  5476. // myCriticalSection is now unlocked for the remainder of this block,
  5477. // and re-locked at the end.
  5478. ...do some stuff with it unlocked ...
  5479. }
  5480. // myCriticalSection gets unlocked here.
  5481. }
  5482. @endcode
  5483. @see CriticalSection, ScopedLock
  5484. */
  5485. class ScopedUnlock
  5486. {
  5487. public:
  5488. /** Creates a ScopedUnlock.
  5489. As soon as it is created, this will unlock the CriticalSection, and
  5490. when the ScopedLock object is deleted, the CriticalSection will
  5491. be re-locked.
  5492. Make sure this object is created and deleted by the same thread,
  5493. otherwise there are no guarantees what will happen! Best just to use it
  5494. as a local stack object, rather than creating one with the new() operator.
  5495. */
  5496. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5497. /** Destructor.
  5498. The CriticalSection will be unlocked when the destructor is called.
  5499. Make sure this object is created and deleted by the same thread,
  5500. otherwise there are no guarantees what will happen!
  5501. */
  5502. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5503. private:
  5504. const CriticalSection& lock_;
  5505. ScopedUnlock (const ScopedLock&);
  5506. const ScopedUnlock& operator= (const ScopedUnlock&);
  5507. };
  5508. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5509. /********* End of inlined file: juce_ScopedLock.h *********/
  5510. /**
  5511. Macro to declare member variables and methods for a singleton class.
  5512. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  5513. to the class's definition.
  5514. If allowOnlyOneInstance == true, it won't allow the object to be created
  5515. more than once in the process's lifetime.
  5516. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5517. implementation code.
  5518. Clients can then call the static MyClass::getInstance() to get a pointer to the
  5519. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  5520. is currently extant
  5521. it's a very good idea to also add the call clearSingletonInstance() to the
  5522. destructor of the class, in case it is deleted by other means than deleteInstance()
  5523. e.g. @code
  5524. class MySingleton
  5525. {
  5526. public:
  5527. MySingleton()
  5528. {
  5529. }
  5530. ~MySingleton()
  5531. {
  5532. // this ensures that no dangling pointers are left when the
  5533. // singleton is deleted.
  5534. clearSingletonInstance();
  5535. }
  5536. juce_DeclareSingleton (MySingleton, false)
  5537. };
  5538. juce_ImplementSingleton (MySingleton)
  5539. // example of usage:
  5540. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5541. ...
  5542. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5543. @endcode
  5544. If you know that your object will only be created and deleted by a single thread, you
  5545. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5546. of this one.
  5547. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5548. */
  5549. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  5550. \
  5551. static classname* _singletonInstance; \
  5552. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5553. \
  5554. static classname* getInstance() \
  5555. { \
  5556. if (_singletonInstance == 0) \
  5557. {\
  5558. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5559. \
  5560. if (_singletonInstance == 0) \
  5561. { \
  5562. static bool alreadyInside = false; \
  5563. static bool createdOnceAlready = false; \
  5564. \
  5565. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5566. jassert (! problem); \
  5567. if (! problem) \
  5568. { \
  5569. createdOnceAlready = true; \
  5570. alreadyInside = true; \
  5571. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5572. alreadyInside = false; \
  5573. \
  5574. _singletonInstance = newObject; \
  5575. } \
  5576. } \
  5577. } \
  5578. \
  5579. return _singletonInstance; \
  5580. } \
  5581. \
  5582. static inline classname* getInstanceWithoutCreating() throw() \
  5583. { \
  5584. return _singletonInstance; \
  5585. } \
  5586. \
  5587. static void deleteInstance() \
  5588. { \
  5589. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5590. if (_singletonInstance != 0) \
  5591. { \
  5592. classname* const old = _singletonInstance; \
  5593. _singletonInstance = 0; \
  5594. delete old; \
  5595. } \
  5596. } \
  5597. \
  5598. void clearSingletonInstance() throw() \
  5599. { \
  5600. if (_singletonInstance == this) \
  5601. _singletonInstance = 0; \
  5602. }
  5603. /** This is a counterpart to the juce_DeclareSingleton macro.
  5604. After adding the juce_DeclareSingleton to the class definition, this macro has
  5605. to be used in the cpp file.
  5606. */
  5607. #define juce_ImplementSingleton(classname) \
  5608. \
  5609. classname* classname::_singletonInstance = 0; \
  5610. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5611. /**
  5612. Macro to declare member variables and methods for a singleton class.
  5613. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5614. section to make access to it thread-safe. If you know that your object will
  5615. only ever be created or deleted by a single thread, then this is a
  5616. more efficient version to use.
  5617. See the documentation for juce_DeclareSingleton for more information about
  5618. how to use it, the only difference being that you have to use
  5619. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5620. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5621. */
  5622. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  5623. \
  5624. static classname* _singletonInstance; \
  5625. \
  5626. static classname* getInstance() \
  5627. { \
  5628. if (_singletonInstance == 0) \
  5629. { \
  5630. static bool alreadyInside = false; \
  5631. static bool createdOnceAlready = false; \
  5632. \
  5633. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5634. jassert (! problem); \
  5635. if (! problem) \
  5636. { \
  5637. createdOnceAlready = true; \
  5638. alreadyInside = true; \
  5639. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5640. alreadyInside = false; \
  5641. \
  5642. _singletonInstance = newObject; \
  5643. } \
  5644. } \
  5645. \
  5646. return _singletonInstance; \
  5647. } \
  5648. \
  5649. static inline classname* getInstanceWithoutCreating() throw() \
  5650. { \
  5651. return _singletonInstance; \
  5652. } \
  5653. \
  5654. static void deleteInstance() \
  5655. { \
  5656. if (_singletonInstance != 0) \
  5657. { \
  5658. classname* const old = _singletonInstance; \
  5659. _singletonInstance = 0; \
  5660. delete old; \
  5661. } \
  5662. } \
  5663. \
  5664. void clearSingletonInstance() throw() \
  5665. { \
  5666. if (_singletonInstance == this) \
  5667. _singletonInstance = 0; \
  5668. }
  5669. /**
  5670. Macro to declare member variables and methods for a singleton class.
  5671. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5672. for recursion or repeated instantiation. It's intended for use as a lightweight
  5673. version of a singleton, where you're using it in very straightforward
  5674. circumstances and don't need the extra checking.
  5675. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  5676. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  5677. See the documentation for juce_DeclareSingleton for more information about
  5678. how to use it, the only difference being that you have to use
  5679. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5680. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  5681. */
  5682. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  5683. \
  5684. static classname* _singletonInstance; \
  5685. \
  5686. static classname* getInstance() \
  5687. { \
  5688. if (_singletonInstance == 0) \
  5689. _singletonInstance = new classname(); \
  5690. \
  5691. return _singletonInstance; \
  5692. } \
  5693. \
  5694. static inline classname* getInstanceWithoutCreating() throw() \
  5695. { \
  5696. return _singletonInstance; \
  5697. } \
  5698. \
  5699. static void deleteInstance() \
  5700. { \
  5701. if (_singletonInstance != 0) \
  5702. { \
  5703. classname* const old = _singletonInstance; \
  5704. _singletonInstance = 0; \
  5705. delete old; \
  5706. } \
  5707. } \
  5708. \
  5709. void clearSingletonInstance() throw() \
  5710. { \
  5711. if (_singletonInstance == this) \
  5712. _singletonInstance = 0; \
  5713. }
  5714. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  5715. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  5716. to the class definition, this macro has to be used somewhere in the cpp file.
  5717. */
  5718. #define juce_ImplementSingleton_SingleThreaded(classname) \
  5719. \
  5720. classname* classname::_singletonInstance = 0;
  5721. #endif // __JUCE_SINGLETON_JUCEHEADER__
  5722. /********* End of inlined file: juce_Singleton.h *********/
  5723. #endif
  5724. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  5725. #endif
  5726. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5727. /********* Start of inlined file: juce_SystemStats.h *********/
  5728. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5729. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  5730. /**
  5731. Contains methods for finding out about the current hardware and OS configuration.
  5732. */
  5733. class JUCE_API SystemStats
  5734. {
  5735. public:
  5736. /** Returns the current version of JUCE,
  5737. (just in case you didn't already know at compile-time.)
  5738. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  5739. */
  5740. static const String getJUCEVersion() throw();
  5741. /** The set of possible results of the getOperatingSystemType() method.
  5742. */
  5743. enum OperatingSystemType
  5744. {
  5745. UnknownOS = 0,
  5746. MacOSX = 0x1000,
  5747. Linux = 0x2000,
  5748. Win95 = 0x4001,
  5749. Win98 = 0x4002,
  5750. WinNT351 = 0x4103,
  5751. WinNT40 = 0x4104,
  5752. Win2000 = 0x4105,
  5753. WinXP = 0x4106,
  5754. WinVista = 0x4107,
  5755. Windows = 0x4000, /**< To test whether any version of Windows is running,
  5756. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  5757. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  5758. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  5759. };
  5760. /** Returns the type of operating system we're running on.
  5761. @returns one of the values from the OperatingSystemType enum.
  5762. @see getOperatingSystemName
  5763. */
  5764. static OperatingSystemType getOperatingSystemType() throw();
  5765. /** Returns the name of the type of operating system we're running on.
  5766. @returns a string describing the OS type.
  5767. @see getOperatingSystemType
  5768. */
  5769. static const String getOperatingSystemName() throw();
  5770. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  5771. */
  5772. static bool isOperatingSystem64Bit() throw();
  5773. // CPU and memory information..
  5774. /** Returns the approximate CPU speed.
  5775. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  5776. what year you're reading this...)
  5777. */
  5778. static int getCpuSpeedInMegaherz() throw();
  5779. /** Returns a string to indicate the CPU vendor.
  5780. Might not be known on some systems.
  5781. */
  5782. static const String getCpuVendor() throw();
  5783. /** Checks whether Intel MMX instructions are available. */
  5784. static bool hasMMX() throw();
  5785. /** Checks whether Intel SSE instructions are available. */
  5786. static bool hasSSE() throw();
  5787. /** Checks whether Intel SSE2 instructions are available. */
  5788. static bool hasSSE2() throw();
  5789. /** Checks whether AMD 3DNOW instructions are available. */
  5790. static bool has3DNow() throw();
  5791. /** Returns the number of CPUs.
  5792. */
  5793. static int getNumCpus() throw();
  5794. /** Returns a clock-cycle tick counter, if available.
  5795. If the machine can do it, this will return a tick-count
  5796. where each tick is one cpu clock cycle - used for profiling
  5797. code.
  5798. @returns the tick count, or zero if not available.
  5799. */
  5800. static int64 getClockCycleCounter() throw();
  5801. /** Finds out how much RAM is in the machine.
  5802. @returns the approximate number of megabytes of memory, or zero if
  5803. something goes wrong when finding out.
  5804. */
  5805. static int getMemorySizeInMegabytes() throw();
  5806. /** Returns the system page-size.
  5807. This is only used by programmers with beards.
  5808. */
  5809. static int getPageSize() throw();
  5810. /** Returns a list of MAC addresses found on this machine.
  5811. @param addresses an array into which the MAC addresses should be copied
  5812. @param maxNum the number of elements in this array
  5813. @param littleEndian the endianness of the numbers to return. Note that
  5814. the default values of this parameter are different on
  5815. Mac/PC to avoid breaking old software that was written
  5816. before this parameter was added (when the two systems
  5817. defaulted to using different endiannesses). In newer
  5818. software you probably want to specify an explicit value
  5819. for this.
  5820. @returns the number of MAC addresses that were found
  5821. */
  5822. static int getMACAddresses (int64* addresses, int maxNum,
  5823. #if JUCE_MAC
  5824. const bool littleEndian = true) throw();
  5825. #else
  5826. const bool littleEndian = false) throw();
  5827. #endif
  5828. // not-for-public-use platform-specific method gets called at startup to initialise things.
  5829. static void initialiseStats() throw();
  5830. };
  5831. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  5832. /********* End of inlined file: juce_SystemStats.h *********/
  5833. #endif
  5834. #ifndef __JUCE_TIME_JUCEHEADER__
  5835. #endif
  5836. #ifndef __JUCE_ARRAY_JUCEHEADER__
  5837. #endif
  5838. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  5839. #endif
  5840. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5841. /********* Start of inlined file: juce_BitArray.h *********/
  5842. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5843. #define __JUCE_BITARRAY_JUCEHEADER__
  5844. class MemoryBlock;
  5845. /**
  5846. An array of on/off bits, also usable to store large binary integers.
  5847. A BitArray acts like an arbitrarily large integer whose bits can be set or
  5848. cleared, and some basic mathematical operations can be done on the number as
  5849. a whole.
  5850. */
  5851. class JUCE_API BitArray
  5852. {
  5853. public:
  5854. /** Creates an empty BitArray */
  5855. BitArray() throw();
  5856. /** Creates a BitArray containing an integer value in its low bits.
  5857. The low 32 bits of the array are initialised with this value.
  5858. */
  5859. BitArray (const unsigned int value) throw();
  5860. /** Creates a BitArray containing an integer value in its low bits.
  5861. The low 32 bits of the array are initialised with the absolute value
  5862. passed in, and its sign is set to reflect the sign of the number.
  5863. */
  5864. BitArray (const int value) throw();
  5865. /** Creates a BitArray containing an integer value in its low bits.
  5866. The low 64 bits of the array are initialised with the absolute value
  5867. passed in, and its sign is set to reflect the sign of the number.
  5868. */
  5869. BitArray (int64 value) throw();
  5870. /** Creates a copy of another BitArray. */
  5871. BitArray (const BitArray& other) throw();
  5872. /** Destructor. */
  5873. ~BitArray() throw();
  5874. /** Copies another BitArray onto this one. */
  5875. const BitArray& operator= (const BitArray& other) throw();
  5876. /** Two arrays are the same if the same bits are set. */
  5877. bool operator== (const BitArray& other) const throw();
  5878. /** Two arrays are the same if the same bits are set. */
  5879. bool operator!= (const BitArray& other) const throw();
  5880. /** Clears all bits in the BitArray to 0. */
  5881. void clear() throw();
  5882. /** Clears a particular bit in the array. */
  5883. void clearBit (const int bitNumber) throw();
  5884. /** Sets a specified bit to 1.
  5885. If the bit number is high, this will grow the array to accomodate it.
  5886. */
  5887. void setBit (const int bitNumber) throw();
  5888. /** Sets or clears a specified bit. */
  5889. void setBit (const int bitNumber,
  5890. const bool shouldBeSet) throw();
  5891. /** Sets a range of bits to be either on or off.
  5892. @param startBit the first bit to change
  5893. @param numBits the number of bits to change
  5894. @param shouldBeSet whether to turn these bits on or off
  5895. */
  5896. void setRange (int startBit,
  5897. int numBits,
  5898. const bool shouldBeSet) throw();
  5899. /** Inserts a bit an a given position, shifting up any bits above it. */
  5900. void insertBit (const int bitNumber,
  5901. const bool shouldBeSet) throw();
  5902. /** Returns the value of a specified bit in the array.
  5903. If the index is out-of-range, the result will be false.
  5904. */
  5905. bool operator[] (const int bit) const throw();
  5906. /** Returns true if no bits are set. */
  5907. bool isEmpty() const throw();
  5908. /** Returns a range of bits in the array as an integer value.
  5909. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  5910. Asking for more than 32 bits isn't allowed (obviously).
  5911. */
  5912. int getBitRangeAsInt (int startBit, int numBits) const throw();
  5913. /** Sets a range of bits in the array based on an integer value.
  5914. Copies the given integer into the array, starting at startBit,
  5915. and only using up to numBits of the available bits.
  5916. */
  5917. void setBitRangeAsInt (int startBit, int numBits,
  5918. unsigned int valueToSet) throw();
  5919. /** Performs a bitwise OR with another BitArray.
  5920. The result ends up in this array.
  5921. */
  5922. void orWith (const BitArray& other) throw();
  5923. /** Performs a bitwise AND with another BitArray.
  5924. The result ends up in this array.
  5925. */
  5926. void andWith (const BitArray& other) throw();
  5927. /** Performs a bitwise XOR with another BitArray.
  5928. The result ends up in this array.
  5929. */
  5930. void xorWith (const BitArray& other) throw();
  5931. /** Adds another BitArray's value to this one.
  5932. Treating the two arrays as large positive integers, this
  5933. adds them up and puts the result in this array.
  5934. */
  5935. void add (const BitArray& other) throw();
  5936. /** Subtracts another BitArray's value from this one.
  5937. Treating the two arrays as large positive integers, this
  5938. subtracts them and puts the result in this array.
  5939. Note that if the result should be negative, this won't be
  5940. handled correctly.
  5941. */
  5942. void subtract (const BitArray& other) throw();
  5943. /** Multiplies another BitArray's value with this one.
  5944. Treating the two arrays as large positive integers, this
  5945. multiplies them and puts the result in this array.
  5946. */
  5947. void multiplyBy (const BitArray& other) throw();
  5948. /** Divides another BitArray's value into this one and also produces a remainder.
  5949. Treating the two arrays as large positive integers, this
  5950. divides this value by the other, leaving the quotient in this
  5951. array, and the remainder is copied into the other BitArray passed in.
  5952. */
  5953. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  5954. /** Returns the largest value that will divide both this value and the one
  5955. passed-in.
  5956. */
  5957. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  5958. /** Performs a modulo operation on this value.
  5959. The result is stored in this value.
  5960. */
  5961. void modulo (const BitArray& divisor) throw();
  5962. /** Performs a combined exponent and modulo operation.
  5963. This BitArray's value becomes (this ^ exponent) % modulus.
  5964. */
  5965. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  5966. /** Performs an inverse modulo on the value.
  5967. i.e. the result is (this ^ -1) mod (modulus).
  5968. */
  5969. void inverseModulo (const BitArray& modulus) throw();
  5970. /** Shifts a section of bits left or right.
  5971. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  5972. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  5973. */
  5974. void shiftBits (int howManyBitsLeft,
  5975. int startBit = 0) throw();
  5976. /** Does a signed comparison of two BitArrays.
  5977. Return values are:
  5978. - 0 if the numbers are the same
  5979. - < 0 if this number is smaller than the other
  5980. - > 0 if this number is bigger than the other
  5981. */
  5982. int compare (const BitArray& other) const throw();
  5983. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  5984. Return values are:
  5985. - 0 if the numbers are the same
  5986. - < 0 if this number is smaller than the other
  5987. - > 0 if this number is bigger than the other
  5988. */
  5989. int compareAbsolute (const BitArray& other) const throw();
  5990. /** Returns true if the value is less than zero.
  5991. @see setNegative, negate
  5992. */
  5993. bool isNegative() const throw();
  5994. /** Changes the sign of the number to be positive or negative.
  5995. @see isNegative, negate
  5996. */
  5997. void setNegative (const bool shouldBeNegative) throw();
  5998. /** Inverts the sign of the number.
  5999. @see isNegative, setNegative
  6000. */
  6001. void negate() throw();
  6002. /** Counts the total number of set bits in the array. */
  6003. int countNumberOfSetBits() const throw();
  6004. /** Looks for the index of the next set bit after a given starting point.
  6005. searches from startIndex (inclusive) upwards for the first set bit,
  6006. and returns its index.
  6007. If no set bits are found, it returns -1.
  6008. */
  6009. int findNextSetBit (int startIndex = 0) const throw();
  6010. /** Looks for the index of the next clear bit after a given starting point.
  6011. searches from startIndex (inclusive) upwards for the first clear bit,
  6012. and returns its index.
  6013. */
  6014. int findNextClearBit (int startIndex = 0) const throw();
  6015. /** Returns the index of the highest set bit in the array.
  6016. If the array is empty, this will return -1.
  6017. */
  6018. int getHighestBit() const throw();
  6019. /** Sets a range of bits to random values. */
  6020. void fillBitsRandomly (int startBit, int numBits) throw();
  6021. /** Turns this value into a random number less than the given value. */
  6022. void createRandomNumber (const BitArray& maximumValue) throw();
  6023. /** Converts the array to a number string.
  6024. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  6025. */
  6026. const String toString (const int base) const throw();
  6027. /** Converts a number string to an array.
  6028. Any non-valid characters will be ignored.
  6029. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  6030. */
  6031. void parseString (const String& text,
  6032. const int base) throw();
  6033. /** Turns the array into a block of binary data.
  6034. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  6035. of the array, and so on.
  6036. @see loadFromMemoryBlock
  6037. */
  6038. const MemoryBlock toMemoryBlock() const throw();
  6039. /** Copies a block of raw data onto this array.
  6040. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  6041. of the array, and so on.
  6042. @see toMemoryBlock
  6043. */
  6044. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  6045. juce_UseDebuggingNewOperator
  6046. private:
  6047. void ensureSize (const int numVals) throw();
  6048. unsigned int* values;
  6049. int numValues, highestBit;
  6050. bool negative;
  6051. };
  6052. #endif // __JUCE_BITARRAY_JUCEHEADER__
  6053. /********* End of inlined file: juce_BitArray.h *********/
  6054. #endif
  6055. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6056. #endif
  6057. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6058. #endif
  6059. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6060. #endif
  6061. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6062. /********* Start of inlined file: juce_PropertySet.h *********/
  6063. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6064. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6065. /********* Start of inlined file: juce_StringPairArray.h *********/
  6066. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6067. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6068. /**
  6069. A container for holding a set of strings which are keyed by another string.
  6070. @see StringArray
  6071. */
  6072. class JUCE_API StringPairArray
  6073. {
  6074. public:
  6075. /** Creates an empty array */
  6076. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6077. /** Creates a copy of another array */
  6078. StringPairArray (const StringPairArray& other) throw();
  6079. /** Destructor. */
  6080. ~StringPairArray() throw();
  6081. /** Copies the contents of another string array into this one */
  6082. const StringPairArray& operator= (const StringPairArray& other) throw();
  6083. /** Compares two arrays.
  6084. Comparisons are case-sensitive.
  6085. @returns true only if the other array contains exactly the same strings with the same keys
  6086. */
  6087. bool operator== (const StringPairArray& other) const throw();
  6088. /** Compares two arrays.
  6089. Comparisons are case-sensitive.
  6090. @returns false if the other array contains exactly the same strings with the same keys
  6091. */
  6092. bool operator!= (const StringPairArray& other) const throw();
  6093. /** Finds the value corresponding to a key string.
  6094. If no such key is found, this will just return an empty string. To check whether
  6095. a given key actually exists (because it might actually be paired with an empty string), use
  6096. the getAllKeys() method to obtain a list.
  6097. Obviously the reference returned shouldn't be stored for later use, as the
  6098. string it refers to may disappear when the array changes.
  6099. @see getValue
  6100. */
  6101. const String& operator[] (const String& key) const throw();
  6102. /** Finds the value corresponding to a key string.
  6103. If no such key is found, this will just return the value provided as a default.
  6104. @see operator[]
  6105. */
  6106. const String getValue (const String& key, const String& defaultReturnValue) const;
  6107. /** Returns a list of all keys in the array. */
  6108. const StringArray& getAllKeys() const throw() { return keys; }
  6109. /** Returns a list of all values in the array. */
  6110. const StringArray& getAllValues() const throw() { return values; }
  6111. /** Returns the number of strings in the array */
  6112. inline int size() const throw() { return keys.size(); };
  6113. /** Adds or amends a key/value pair.
  6114. If a value already exists with this key, its value will be overwritten,
  6115. otherwise the key/value pair will be added to the array.
  6116. */
  6117. void set (const String& key,
  6118. const String& value) throw();
  6119. /** Adds the items from another array to this one.
  6120. This is equivalent to using set() to add each of the pairs from the other array.
  6121. */
  6122. void addArray (const StringPairArray& other);
  6123. /** Removes all elements from the array. */
  6124. void clear() throw();
  6125. /** Removes a string from the array based on its key.
  6126. If the key isn't found, nothing will happen.
  6127. */
  6128. void remove (const String& key) throw();
  6129. /** Removes a string from the array based on its index.
  6130. If the index is out-of-range, no action will be taken.
  6131. */
  6132. void remove (const int index) throw();
  6133. /** Reduces the amount of storage being used by the array.
  6134. Arrays typically allocate slightly more storage than they need, and after
  6135. removing elements, they may have quite a lot of unused space allocated.
  6136. This method will reduce the amount of allocated storage to a minimum.
  6137. */
  6138. void minimiseStorageOverheads() throw();
  6139. juce_UseDebuggingNewOperator
  6140. private:
  6141. StringArray keys, values;
  6142. bool ignoreCase;
  6143. };
  6144. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6145. /********* End of inlined file: juce_StringPairArray.h *********/
  6146. /********* Start of inlined file: juce_XmlElement.h *********/
  6147. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6148. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6149. /********* Start of inlined file: juce_OutputStream.h *********/
  6150. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6151. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6152. /********* Start of inlined file: juce_InputStream.h *********/
  6153. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6154. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6155. /** The base class for streams that read data.
  6156. Input and output streams are used throughout the library - subclasses can override
  6157. some or all of the virtual functions to implement their behaviour.
  6158. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6159. */
  6160. class JUCE_API InputStream
  6161. {
  6162. public:
  6163. /** Destructor. */
  6164. virtual ~InputStream() {}
  6165. /** Returns the total number of bytes available for reading in this stream.
  6166. Note that this is the number of bytes available from the start of the
  6167. stream, not from the current position.
  6168. If the size of the stream isn't actually known, this may return -1.
  6169. */
  6170. virtual int64 getTotalLength() = 0;
  6171. /** Returns true if the stream has no more data to read. */
  6172. virtual bool isExhausted() = 0;
  6173. /** Reads a set of bytes from the stream into a memory buffer.
  6174. This is the only read method that subclasses actually need to implement, as the
  6175. InputStream base class implements the other read methods in terms of this one (although
  6176. it's often more efficient for subclasses to implement them directly).
  6177. @param destBuffer the destination buffer for the data
  6178. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6179. memory block passed in is big enough to contain this
  6180. many bytes.
  6181. @returns the actual number of bytes that were read, which may be less than
  6182. maxBytesToRead if the stream is exhausted before it gets that far
  6183. */
  6184. virtual int read (void* destBuffer,
  6185. int maxBytesToRead) = 0;
  6186. /** Reads a byte from the stream.
  6187. If the stream is exhausted, this will return zero.
  6188. @see OutputStream::writeByte
  6189. */
  6190. virtual char readByte();
  6191. /** Reads a boolean from the stream.
  6192. The bool is encoded as a single byte - 1 for true, 0 for false.
  6193. If the stream is exhausted, this will return false.
  6194. @see OutputStream::writeBool
  6195. */
  6196. virtual bool readBool();
  6197. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6198. If the next two bytes read are byte1 and byte2, this returns
  6199. (byte1 | (byte2 << 8)).
  6200. If the stream is exhausted partway through reading the bytes, this will return zero.
  6201. @see OutputStream::writeShort, readShortBigEndian
  6202. */
  6203. virtual short readShort();
  6204. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6205. If the next two bytes read are byte1 and byte2, this returns
  6206. (byte2 | (byte1 << 8)).
  6207. If the stream is exhausted partway through reading the bytes, this will return zero.
  6208. @see OutputStream::writeShortBigEndian, readShort
  6209. */
  6210. virtual short readShortBigEndian();
  6211. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6212. If the next four bytes are byte1 to byte4, this returns
  6213. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6214. If the stream is exhausted partway through reading the bytes, this will return zero.
  6215. @see OutputStream::writeInt, readIntBigEndian
  6216. */
  6217. virtual int readInt();
  6218. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6219. If the next four bytes are byte1 to byte4, this returns
  6220. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6221. If the stream is exhausted partway through reading the bytes, this will return zero.
  6222. @see OutputStream::writeIntBigEndian, readInt
  6223. */
  6224. virtual int readIntBigEndian();
  6225. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6226. If the next eight bytes are byte1 to byte8, this returns
  6227. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6228. If the stream is exhausted partway through reading the bytes, this will return zero.
  6229. @see OutputStream::writeInt64, readInt64BigEndian
  6230. */
  6231. virtual int64 readInt64();
  6232. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6233. If the next eight bytes are byte1 to byte8, this returns
  6234. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6235. If the stream is exhausted partway through reading the bytes, this will return zero.
  6236. @see OutputStream::writeInt64BigEndian, readInt64
  6237. */
  6238. virtual int64 readInt64BigEndian();
  6239. /** Reads four bytes as a 32-bit floating point value.
  6240. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6241. If the stream is exhausted partway through reading the bytes, this will return zero.
  6242. @see OutputStream::writeFloat, readDouble
  6243. */
  6244. virtual float readFloat();
  6245. /** Reads four bytes as a 32-bit floating point value.
  6246. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6247. If the stream is exhausted partway through reading the bytes, this will return zero.
  6248. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6249. */
  6250. virtual float readFloatBigEndian();
  6251. /** Reads eight bytes as a 64-bit floating point value.
  6252. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6253. If the stream is exhausted partway through reading the bytes, this will return zero.
  6254. @see OutputStream::writeDouble, readFloat
  6255. */
  6256. virtual double readDouble();
  6257. /** Reads eight bytes as a 64-bit floating point value.
  6258. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6259. If the stream is exhausted partway through reading the bytes, this will return zero.
  6260. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6261. */
  6262. virtual double readDoubleBigEndian();
  6263. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6264. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6265. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6266. @see OutputStream::writeCompressedInt()
  6267. */
  6268. virtual int readCompressedInt();
  6269. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6270. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6271. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6272. After this call, the stream's position will be left pointing to the character
  6273. following the line-feed, but the linefeeds aren't included in the string that
  6274. is returned.
  6275. */
  6276. virtual const String readNextLine();
  6277. /** Reads a zero-terminated string from the stream.
  6278. This will read characters from the stream until it hits a zero character or
  6279. end-of-stream.
  6280. @see OutputStream::writeString, readEntireStreamAsString
  6281. */
  6282. virtual const String readString();
  6283. /** Tries to read the whole stream and turn it into a string.
  6284. This will read from the stream's current position until the end-of-stream, and
  6285. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6286. */
  6287. virtual const String readEntireStreamAsString();
  6288. /** Reads from the stream and appends the data to a MemoryBlock.
  6289. @param destBlock the block to append the data onto
  6290. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6291. of bytes that will be read - if it's negative, data
  6292. will be read until the stream is exhausted.
  6293. @returns the number of bytes that were added to the memory block
  6294. */
  6295. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6296. int maxNumBytesToRead = -1);
  6297. /** Returns the offset of the next byte that will be read from the stream.
  6298. @see setPosition
  6299. */
  6300. virtual int64 getPosition() = 0;
  6301. /** Tries to move the current read position of the stream.
  6302. The position is an absolute number of bytes from the stream's start.
  6303. Some streams might not be able to do this, in which case they should do
  6304. nothing and return false. Others might be able to manage it by resetting
  6305. themselves and skipping to the correct position, although this is
  6306. obviously a bit slow.
  6307. @returns true if the stream manages to reposition itself correctly
  6308. @see getPosition
  6309. */
  6310. virtual bool setPosition (int64 newPosition) = 0;
  6311. /** Reads and discards a number of bytes from the stream.
  6312. Some input streams might implement this efficiently, but the base
  6313. class will just keep reading data until the requisite number of bytes
  6314. have been done.
  6315. */
  6316. virtual void skipNextBytes (int64 numBytesToSkip);
  6317. juce_UseDebuggingNewOperator
  6318. protected:
  6319. InputStream() throw() {}
  6320. };
  6321. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6322. /********* End of inlined file: juce_InputStream.h *********/
  6323. /**
  6324. The base class for streams that write data to some kind of destination.
  6325. Input and output streams are used throughout the library - subclasses can override
  6326. some or all of the virtual functions to implement their behaviour.
  6327. @see InputStream, MemoryOutputStream, FileOutputStream
  6328. */
  6329. class JUCE_API OutputStream
  6330. {
  6331. public:
  6332. /** Destructor.
  6333. Some subclasses might want to do things like call flush() during their
  6334. destructors.
  6335. */
  6336. virtual ~OutputStream();
  6337. /** If the stream is using a buffer, this will ensure it gets written
  6338. out to the destination. */
  6339. virtual void flush() = 0;
  6340. /** Tries to move the stream's output position.
  6341. Not all streams will be able to seek to a new position - this will return
  6342. false if it fails to work.
  6343. @see getPosition
  6344. */
  6345. virtual bool setPosition (int64 newPosition) = 0;
  6346. /** Returns the stream's current position.
  6347. @see setPosition
  6348. */
  6349. virtual int64 getPosition() = 0;
  6350. /** Writes a block of data to the stream.
  6351. When creating a subclass of OutputStream, this is the only write method
  6352. that needs to be overloaded - the base class has methods for writing other
  6353. types of data which use this to do the work.
  6354. @returns false if the write operation fails for some reason
  6355. */
  6356. virtual bool write (const void* dataToWrite,
  6357. int howManyBytes) = 0;
  6358. /** Writes a single byte to the stream.
  6359. @see InputStream::readByte
  6360. */
  6361. virtual void writeByte (char byte);
  6362. /** Writes a boolean to the stream.
  6363. This is encoded as a byte - either 1 or 0.
  6364. @see InputStream::readBool
  6365. */
  6366. virtual void writeBool (bool boolValue);
  6367. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6368. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6369. @see InputStream::readShort
  6370. */
  6371. virtual void writeShort (short value);
  6372. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6373. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6374. @see InputStream::readShortBigEndian
  6375. */
  6376. virtual void writeShortBigEndian (short value);
  6377. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6378. @see InputStream::readInt
  6379. */
  6380. virtual void writeInt (int value);
  6381. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6382. @see InputStream::readIntBigEndian
  6383. */
  6384. virtual void writeIntBigEndian (int value);
  6385. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6386. @see InputStream::readInt64
  6387. */
  6388. virtual void writeInt64 (int64 value);
  6389. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6390. @see InputStream::readInt64BigEndian
  6391. */
  6392. virtual void writeInt64BigEndian (int64 value);
  6393. /** Writes a 32-bit floating point value to the stream.
  6394. The binary 32-bit encoding of the float is written as a little-endian int.
  6395. @see InputStream::readFloat
  6396. */
  6397. virtual void writeFloat (float value);
  6398. /** Writes a 32-bit floating point value to the stream.
  6399. The binary 32-bit encoding of the float is written as a big-endian int.
  6400. @see InputStream::readFloatBigEndian
  6401. */
  6402. virtual void writeFloatBigEndian (float value);
  6403. /** Writes a 64-bit floating point value to the stream.
  6404. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6405. @see InputStream::readDouble
  6406. */
  6407. virtual void writeDouble (double value);
  6408. /** Writes a 64-bit floating point value to the stream.
  6409. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6410. @see InputStream::readDoubleBigEndian
  6411. */
  6412. virtual void writeDoubleBigEndian (double value);
  6413. /** Writes a condensed encoding of a 32-bit integer.
  6414. If you're storing a lot of integers which are unlikely to have very large values,
  6415. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6416. under 0xffff only 3 bytes, etc.
  6417. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6418. @see InputStream::readCompressedInt
  6419. */
  6420. virtual void writeCompressedInt (int value);
  6421. /** Stores a string in the stream.
  6422. This isn't the method to use if you're trying to append text to the end of a
  6423. text-file! It's intended for storing a string for later retrieval
  6424. by InputStream::readString.
  6425. For appending text to a file, instead use writeText, printf, or operator<<
  6426. @see InputStream::readString, writeText, printf, operator<<
  6427. */
  6428. virtual void writeString (const String& text);
  6429. /** Writes a string of text to the stream.
  6430. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6431. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6432. should only be done at the start of a file).
  6433. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6434. */
  6435. virtual void writeText (const String& text,
  6436. const bool asUnicode,
  6437. const bool writeUnicodeHeaderBytes);
  6438. /** Writes a string of text to the stream.
  6439. @see writeText
  6440. */
  6441. virtual void printf (const char* format, ...);
  6442. /** Reads data from an input stream and writes it to this stream.
  6443. @param source the stream to read from
  6444. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6445. less than zero, it will keep reading until the input
  6446. is exhausted)
  6447. */
  6448. virtual int writeFromInputStream (InputStream& source,
  6449. int maxNumBytesToWrite);
  6450. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6451. virtual OutputStream& operator<< (const int number);
  6452. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6453. virtual OutputStream& operator<< (const double number);
  6454. /** Writes a character to the stream. */
  6455. virtual OutputStream& operator<< (const char character);
  6456. /** Writes a null-terminated string to the stream. */
  6457. virtual OutputStream& operator<< (const char* const text);
  6458. /** Writes a null-terminated unicode text string to the stream, converting it
  6459. to 8-bit characters in the default system encoding. */
  6460. virtual OutputStream& operator<< (const juce_wchar* const text);
  6461. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6462. virtual OutputStream& operator<< (const String& text);
  6463. juce_UseDebuggingNewOperator
  6464. protected:
  6465. OutputStream() throw();
  6466. };
  6467. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6468. /********* End of inlined file: juce_OutputStream.h *********/
  6469. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6470. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6471. will be the name of a pointer to each child element.
  6472. E.g. @code
  6473. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6474. forEachXmlChildElement (*myParentXml, child)
  6475. {
  6476. if (child->hasTagName ("FOO"))
  6477. doSomethingWithXmlElement (child);
  6478. }
  6479. @endcode
  6480. @see forEachXmlChildElementWithTagName
  6481. */
  6482. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6483. \
  6484. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6485. childElementVariableName != 0; \
  6486. childElementVariableName = childElementVariableName->getNextElement())
  6487. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6488. which have a specified tag.
  6489. This does the same job as the forEachXmlChildElement macro, but only for those
  6490. elements that have a particular tag name.
  6491. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6492. will be the name of a pointer to each child element. The requiredTagName is the
  6493. tag name to match.
  6494. E.g. @code
  6495. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6496. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6497. {
  6498. // the child object is now guaranteed to be a <MYTAG> element..
  6499. doSomethingWithMYTAGElement (child);
  6500. }
  6501. @endcode
  6502. @see forEachXmlChildElement
  6503. */
  6504. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6505. \
  6506. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6507. childElementVariableName != 0; \
  6508. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6509. /** Used to build a tree of elements representing an XML document.
  6510. An XML document can be parsed into a tree of XmlElements, each of which
  6511. represents an XML tag structure, and which may itself contain other
  6512. nested elements.
  6513. An XmlElement can also be converted back into a text document, and has
  6514. lots of useful methods for manipulating its attributes and sub-elements,
  6515. so XmlElements can actually be used as a handy general-purpose data
  6516. structure.
  6517. Here's an example of parsing some elements: @code
  6518. // check we're looking at the right kind of document..
  6519. if (myElement->hasTagName ("ANIMALS"))
  6520. {
  6521. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6522. forEachXmlChildElement (*myElement, e)
  6523. {
  6524. if (e->hasTagName ("GIRAFFE"))
  6525. {
  6526. // found a giraffe, so use some of its attributes..
  6527. String giraffeName = e->getStringAttribute ("name");
  6528. int giraffeAge = e->getIntAttribute ("age");
  6529. bool isFriendly = e->getBoolAttribute ("friendly");
  6530. }
  6531. }
  6532. }
  6533. @endcode
  6534. And here's an example of how to create an XML document from scratch: @code
  6535. // create an outer node called "ANIMALS"
  6536. XmlElement animalsList ("ANIMALS");
  6537. for (int i = 0; i < numAnimals; ++i)
  6538. {
  6539. // create an inner element..
  6540. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6541. giraffe->setAttribute ("name", "nigel");
  6542. giraffe->setAttribute ("age", 10);
  6543. giraffe->setAttribute ("friendly", true);
  6544. // ..and add our new element to the parent node
  6545. animalsList.addChildElement (giraffe);
  6546. }
  6547. // now we can turn the whole thing into a text document..
  6548. String myXmlDoc = animalsList.createDocument (String::empty);
  6549. @endcode
  6550. @see XmlDocument
  6551. */
  6552. class JUCE_API XmlElement
  6553. {
  6554. public:
  6555. /** Creates an XmlElement with this tag name. */
  6556. XmlElement (const String& tagName) throw();
  6557. /** Creates a (deep) copy of another element. */
  6558. XmlElement (const XmlElement& other) throw();
  6559. /** Creates a (deep) copy of another element. */
  6560. const XmlElement& operator= (const XmlElement& other) throw();
  6561. /** Deleting an XmlElement will also delete all its child elements. */
  6562. ~XmlElement() throw();
  6563. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6564. The elements are only considered equivalent if they contain the same attiributes
  6565. with the same values, and have the same sub-nodes.
  6566. @param other the other element to compare to
  6567. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6568. same attributes in a different order will be
  6569. considered the same; if false, the attributes must
  6570. be in the same order as well
  6571. */
  6572. bool isEquivalentTo (const XmlElement* const other,
  6573. const bool ignoreOrderOfAttributes) const throw();
  6574. /** Returns an XML text document that represents this element.
  6575. The string returned can be parsed to recreate the same XmlElement that
  6576. was used to create it.
  6577. @param dtdToUse the DTD to add to the document
  6578. @param allOnOneLine if true, this means that the document will not contain any
  6579. linefeeds, so it'll be smaller but not very easy to read.
  6580. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6581. document
  6582. @param encodingType the character encoding format string to put into the xml
  6583. header
  6584. @param lineWrapLength the line length that will be used before items get placed on
  6585. a new line. This isn't an absolute maximum length, it just
  6586. determines how lists of attributes get broken up
  6587. @see writeToFile
  6588. */
  6589. const String createDocument (const String& dtdToUse,
  6590. const bool allOnOneLine = false,
  6591. const bool includeXmlHeader = true,
  6592. const tchar* const encodingType = JUCE_T("UTF-8"),
  6593. const int lineWrapLength = 60) const throw();
  6594. /** Writes the element to a file as an XML document.
  6595. To improve safety in case something goes wrong while writing the file, this
  6596. will actually write the document to a new temporary file in the same
  6597. directory as the destination file, and if this succeeds, it will rename this
  6598. new file as the destination file (overwriting any existing file that was there).
  6599. @param destinationFile the file to write to. If this already exists, it will be
  6600. overwritten.
  6601. @param dtdToUse the DTD to add to the document
  6602. @param encodingType the character encoding format string to put into the xml
  6603. header
  6604. @param lineWrapLength the line length that will be used before items get placed on
  6605. a new line. This isn't an absolute maximum length, it just
  6606. determines how lists of attributes get broken up
  6607. @returns true if the file is written successfully; false if something goes wrong
  6608. in the process
  6609. @see createDocument
  6610. */
  6611. bool writeToFile (const File& destinationFile,
  6612. const String& dtdToUse,
  6613. const tchar* const encodingType = JUCE_T("UTF-8"),
  6614. const int lineWrapLength = 60) const throw();
  6615. /** Returns this element's tag type name.
  6616. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6617. "MOOSE".
  6618. @see hasTagName
  6619. */
  6620. inline const String& getTagName() const throw() { return tagName; }
  6621. /** Tests whether this element has a particular tag name.
  6622. @param possibleTagName the tag name you're comparing it with
  6623. @see getTagName
  6624. */
  6625. bool hasTagName (const tchar* const possibleTagName) const throw();
  6626. /** Returns the number of XML attributes this element contains.
  6627. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6628. return 2.
  6629. */
  6630. int getNumAttributes() const throw();
  6631. /** Returns the name of one of the elements attributes.
  6632. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6633. getAttributeName(1) would return "antlers".
  6634. @see getAttributeValue, getStringAttribute
  6635. */
  6636. const String& getAttributeName (const int attributeIndex) const throw();
  6637. /** Returns the value of one of the elements attributes.
  6638. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6639. getAttributeName(1) would return "2".
  6640. @see getAttributeName, getStringAttribute
  6641. */
  6642. const String& getAttributeValue (const int attributeIndex) const throw();
  6643. // Attribute-handling methods..
  6644. /** Checks whether the element contains an attribute with a certain name. */
  6645. bool hasAttribute (const tchar* const attributeName) const throw();
  6646. /** Returns the value of a named attribute.
  6647. @param attributeName the name of the attribute to look up
  6648. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6649. with this name
  6650. */
  6651. const String getStringAttribute (const tchar* const attributeName,
  6652. const tchar* const defaultReturnValue = 0) const throw();
  6653. /** Compares the value of a named attribute with a value passed-in.
  6654. @param attributeName the name of the attribute to look up
  6655. @param stringToCompareAgainst the value to compare it with
  6656. @param ignoreCase whether the comparison should be case-insensitive
  6657. @returns true if the value of the attribute is the same as the string passed-in;
  6658. false if it's different (or if no such attribute exists)
  6659. */
  6660. bool compareAttribute (const tchar* const attributeName,
  6661. const tchar* const stringToCompareAgainst,
  6662. const bool ignoreCase = false) const throw();
  6663. /** Returns the value of a named attribute as an integer.
  6664. This will try to find the attribute and convert it to an integer (using
  6665. the String::getIntValue() method).
  6666. @param attributeName the name of the attribute to look up
  6667. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6668. with this name
  6669. @see setAttribute (const tchar* const, int)
  6670. */
  6671. int getIntAttribute (const tchar* const attributeName,
  6672. const int defaultReturnValue = 0) const throw();
  6673. /** Returns the value of a named attribute as floating-point.
  6674. This will try to find the attribute and convert it to an integer (using
  6675. the String::getDoubleValue() method).
  6676. @param attributeName the name of the attribute to look up
  6677. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6678. with this name
  6679. @see setAttribute (const tchar* const, double)
  6680. */
  6681. double getDoubleAttribute (const tchar* const attributeName,
  6682. const double defaultReturnValue = 0.0) const throw();
  6683. /** Returns the value of a named attribute as a boolean.
  6684. This will try to find the attribute and interpret it as a boolean. To do this,
  6685. it'll return true if the value is "1", "true", "y", etc, or false for other
  6686. values.
  6687. @param attributeName the name of the attribute to look up
  6688. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6689. with this name
  6690. */
  6691. bool getBoolAttribute (const tchar* const attributeName,
  6692. const bool defaultReturnValue = false) const throw();
  6693. /** Adds a named attribute to the element.
  6694. If the element already contains an attribute with this name, it's value will
  6695. be updated to the new value. If there's no such attribute yet, a new one will
  6696. be added.
  6697. Note that there are other setAttribute() methods that take integers,
  6698. doubles, etc. to make it easy to store numbers.
  6699. @param attributeName the name of the attribute to set
  6700. @param newValue the value to set it to
  6701. @see removeAttribute
  6702. */
  6703. void setAttribute (const tchar* const attributeName,
  6704. const String& newValue) throw();
  6705. /** Adds a named attribute to the element.
  6706. If the element already contains an attribute with this name, it's value will
  6707. be updated to the new value. If there's no such attribute yet, a new one will
  6708. be added.
  6709. Note that there are other setAttribute() methods that take integers,
  6710. doubles, etc. to make it easy to store numbers.
  6711. @param attributeName the name of the attribute to set
  6712. @param newValue the value to set it to
  6713. */
  6714. void setAttribute (const tchar* const attributeName,
  6715. const tchar* const newValue) throw();
  6716. /** Adds a named attribute to the element, setting it to an integer value.
  6717. If the element already contains an attribute with this name, it's value will
  6718. be updated to the new value. If there's no such attribute yet, a new one will
  6719. be added.
  6720. Note that there are other setAttribute() methods that take integers,
  6721. doubles, etc. to make it easy to store numbers.
  6722. @param attributeName the name of the attribute to set
  6723. @param newValue the value to set it to
  6724. */
  6725. void setAttribute (const tchar* const attributeName,
  6726. const int newValue) throw();
  6727. /** Adds a named attribute to the element, setting it to a floating-point value.
  6728. If the element already contains an attribute with this name, it's value will
  6729. be updated to the new value. If there's no such attribute yet, a new one will
  6730. be added.
  6731. Note that there are other setAttribute() methods that take integers,
  6732. doubles, etc. to make it easy to store numbers.
  6733. @param attributeName the name of the attribute to set
  6734. @param newValue the value to set it to
  6735. */
  6736. void setAttribute (const tchar* const attributeName,
  6737. const double newValue) throw();
  6738. /** Removes a named attribute from the element.
  6739. @param attributeName the name of the attribute to remove
  6740. @see removeAllAttributes
  6741. */
  6742. void removeAttribute (const tchar* const attributeName) throw();
  6743. /** Removes all attributes from this element.
  6744. */
  6745. void removeAllAttributes() throw();
  6746. // Child element methods..
  6747. /** Returns the first of this element's sub-elements.
  6748. see getNextElement() for an example of how to iterate the sub-elements.
  6749. @see forEachXmlChildElement
  6750. */
  6751. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6752. /** Returns the next of this element's siblings.
  6753. This can be used for iterating an element's sub-elements, e.g.
  6754. @code
  6755. XmlElement* child = myXmlDocument->getFirstChildElement();
  6756. while (child != 0)
  6757. {
  6758. ...do stuff with this child..
  6759. child = child->getNextElement();
  6760. }
  6761. @endcode
  6762. Note that when iterating the child elements, some of them might be
  6763. text elements as well as XML tags - use isTextElement() to work this
  6764. out.
  6765. Also, it's much easier and neater to use this method indirectly via the
  6766. forEachXmlChildElement macro.
  6767. @returns the sibling element that follows this one, or zero if this is the last
  6768. element in its parent
  6769. @see getNextElement, isTextElement, forEachXmlChildElement
  6770. */
  6771. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6772. /** Returns the next of this element's siblings which has the specified tag
  6773. name.
  6774. This is like getNextElement(), but will scan through the list until it
  6775. finds an element with the given tag name.
  6776. @see getNextElement, forEachXmlChildElementWithTagName
  6777. */
  6778. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6779. /** Returns the number of sub-elements in this element.
  6780. @see getChildElement
  6781. */
  6782. int getNumChildElements() const throw();
  6783. /** Returns the sub-element at a certain index.
  6784. It's not very efficient to iterate the sub-elements by index - see
  6785. getNextElement() for an example of how best to iterate.
  6786. @returns the n'th child of this element, or 0 if the index is out-of-range
  6787. @see getNextElement, isTextElement, getChildByName
  6788. */
  6789. XmlElement* getChildElement (const int index) const throw();
  6790. /** Returns the first sub-element with a given tag-name.
  6791. @param tagNameToLookFor the tag name of the element you want to find
  6792. @returns the first element with this tag name, or 0 if none is found
  6793. @see getNextElement, isTextElement, getChildElement
  6794. */
  6795. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6796. /** Appends an element to this element's list of children.
  6797. Child elements are deleted automatically when their parent is deleted, so
  6798. make sure the object that you pass in will not be deleted by anything else,
  6799. and make sure it's not already the child of another element.
  6800. @see getFirstChildElement, getNextElement, getNumChildElements,
  6801. getChildElement, removeChildElement
  6802. */
  6803. void addChildElement (XmlElement* const newChildElement) throw();
  6804. /** Inserts an element into this element's list of children.
  6805. Child elements are deleted automatically when their parent is deleted, so
  6806. make sure the object that you pass in will not be deleted by anything else,
  6807. and make sure it's not already the child of another element.
  6808. @param newChildNode the element to add
  6809. @param indexToInsertAt the index at which to insert the new element - if this is
  6810. below zero, it will be added to the end of the list
  6811. @see addChildElement, insertChildElement
  6812. */
  6813. void insertChildElement (XmlElement* const newChildNode,
  6814. int indexToInsertAt) throw();
  6815. /** Replaces one of this element's children with another node.
  6816. If the current element passed-in isn't actually a child of this element,
  6817. this will return false and the new one won't be added. Otherwise, the
  6818. existing element will be deleted, replaced with the new one, and it
  6819. will return true.
  6820. */
  6821. bool replaceChildElement (XmlElement* const currentChildElement,
  6822. XmlElement* const newChildNode) throw();
  6823. /** Removes a child element.
  6824. @param childToRemove the child to look for and remove
  6825. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6826. just remove it
  6827. */
  6828. void removeChildElement (XmlElement* const childToRemove,
  6829. const bool shouldDeleteTheChild) throw();
  6830. /** Deletes all the child elements in the element.
  6831. @see removeChildElement, deleteAllChildElementsWithTagName
  6832. */
  6833. void deleteAllChildElements() throw();
  6834. /** Deletes all the child elements with a given tag name.
  6835. @see removeChildElement
  6836. */
  6837. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6838. /** Returns true if the given element is a child of this one. */
  6839. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6840. /** Recursively searches all sub-elements to find one that contains the specified
  6841. child element.
  6842. */
  6843. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6844. /** Sorts the child elements using a comparator.
  6845. This will use a comparator object to sort the elements into order. The object
  6846. passed must have a method of the form:
  6847. @code
  6848. int compareElements (const XmlElement* first, const XmlElement* second);
  6849. @endcode
  6850. ..and this method must return:
  6851. - a value of < 0 if the first comes before the second
  6852. - a value of 0 if the two objects are equivalent
  6853. - a value of > 0 if the second comes before the first
  6854. To improve performance, the compareElements() method can be declared as static or const.
  6855. @param comparator the comparator to use for comparing elements.
  6856. @param retainOrderOfEquivalentItems if this is true, then items
  6857. which the comparator says are equivalent will be
  6858. kept in the order in which they currently appear
  6859. in the array. This is slower to perform, but may
  6860. be important in some cases. If it's false, a faster
  6861. algorithm is used, but equivalent elements may be
  6862. rearranged.
  6863. */
  6864. template <class ElementComparator>
  6865. void sortChildElements (ElementComparator& comparator,
  6866. const bool retainOrderOfEquivalentItems = false) throw()
  6867. {
  6868. const int num = getNumChildElements();
  6869. if (num > 1)
  6870. {
  6871. XmlElement** const elems = getChildElementsAsArray (num);
  6872. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  6873. reorderChildElements (elems, num);
  6874. delete[] elems;
  6875. }
  6876. }
  6877. /** Returns true if this element is a section of text.
  6878. Elements can either be an XML tag element or a secton of text, so this
  6879. is used to find out what kind of element this one is.
  6880. @see getAllText, addTextElement, deleteAllTextElements
  6881. */
  6882. bool isTextElement() const throw();
  6883. /** Returns the text for a text element.
  6884. Note that if you have an element like this:
  6885. @code<xyz>hello</xyz>@endcode
  6886. then calling getText on the "xyz" element won't return "hello", because that is
  6887. actually stored in a special text sub-element inside the xyz element. To get the
  6888. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6889. use getAllSubText() to do this automatically.
  6890. @see isTextElement, getAllSubText, getChildElementAllSubText
  6891. */
  6892. const String getText() const throw();
  6893. /** Sets the text in a text element.
  6894. Note that this is only a valid call if this element is a text element. If it's
  6895. not, then no action will be performed.
  6896. */
  6897. void setText (const String& newText) throw();
  6898. /** Returns all the text from this element's child nodes.
  6899. This iterates all the child elements and when it finds text elements,
  6900. it concatenates their text into a big string which it returns.
  6901. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6902. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6903. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6904. */
  6905. const String getAllSubText() const throw();
  6906. /** Returns all the sub-text of a named child element.
  6907. If there is a child element with the given tag name, this will return
  6908. all of its sub-text (by calling getAllSubText() on it). If there is
  6909. no such child element, this will return the default string passed-in.
  6910. @see getAllSubText
  6911. */
  6912. const String getChildElementAllSubText (const tchar* const childTagName,
  6913. const String& defaultReturnValue) const throw();
  6914. /** Appends a section of text to this element.
  6915. @see isTextElement, getText, getAllSubText
  6916. */
  6917. void addTextElement (const String& text) throw();
  6918. /** Removes all the text elements from this element.
  6919. @see isTextElement, getText, getAllSubText, addTextElement
  6920. */
  6921. void deleteAllTextElements() throw();
  6922. /** Creates a text element that can be added to a parent element.
  6923. */
  6924. static XmlElement* createTextElement (const String& text) throw();
  6925. juce_UseDebuggingNewOperator
  6926. private:
  6927. friend class XmlDocument;
  6928. String tagName;
  6929. XmlElement* firstChildElement;
  6930. XmlElement* nextElement;
  6931. struct XmlAttributeNode
  6932. {
  6933. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6934. XmlAttributeNode (const String& name, const String& value) throw();
  6935. String name, value;
  6936. XmlAttributeNode* next;
  6937. };
  6938. XmlAttributeNode* attributes;
  6939. XmlElement (int) throw(); // for internal use
  6940. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6941. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6942. void writeElementAsText (OutputStream& out,
  6943. const int indentationLevel,
  6944. const int lineWrapLength) const throw();
  6945. XmlElement** getChildElementsAsArray (const int) const throw();
  6946. void reorderChildElements (XmlElement** const, const int) throw();
  6947. };
  6948. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6949. /********* End of inlined file: juce_XmlElement.h *********/
  6950. /**
  6951. A set of named property values, which can be strings, integers, floating point, etc.
  6952. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6953. to load and save types other than strings.
  6954. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6955. messages and saves/loads the list from a file.
  6956. */
  6957. class JUCE_API PropertySet
  6958. {
  6959. public:
  6960. /** Creates an empty PropertySet.
  6961. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6962. case-insensitive way
  6963. */
  6964. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6965. /** Creates a copy of another PropertySet.
  6966. */
  6967. PropertySet (const PropertySet& other) throw();
  6968. /** Copies another PropertySet over this one.
  6969. */
  6970. const PropertySet& operator= (const PropertySet& other) throw();
  6971. /** Destructor. */
  6972. virtual ~PropertySet();
  6973. /** Returns one of the properties as a string.
  6974. If the value isn't found in this set, then this will look for it in a fallback
  6975. property set (if you've specified one with the setFallbackPropertySet() method),
  6976. and if it can't find one there, it'll return the default value passed-in.
  6977. @param keyName the name of the property to retrieve
  6978. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6979. */
  6980. const String getValue (const String& keyName,
  6981. const String& defaultReturnValue = String::empty) const throw();
  6982. /** Returns one of the properties as an integer.
  6983. If the value isn't found in this set, then this will look for it in a fallback
  6984. property set (if you've specified one with the setFallbackPropertySet() method),
  6985. and if it can't find one there, it'll return the default value passed-in.
  6986. @param keyName the name of the property to retrieve
  6987. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6988. */
  6989. int getIntValue (const String& keyName,
  6990. const int defaultReturnValue = 0) const throw();
  6991. /** Returns one of the properties as an double.
  6992. If the value isn't found in this set, then this will look for it in a fallback
  6993. property set (if you've specified one with the setFallbackPropertySet() method),
  6994. and if it can't find one there, it'll return the default value passed-in.
  6995. @param keyName the name of the property to retrieve
  6996. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6997. */
  6998. double getDoubleValue (const String& keyName,
  6999. const double defaultReturnValue = 0.0) const throw();
  7000. /** Returns one of the properties as an boolean.
  7001. The result will be true if the string found for this key name can be parsed as a non-zero
  7002. integer.
  7003. If the value isn't found in this set, then this will look for it in a fallback
  7004. property set (if you've specified one with the setFallbackPropertySet() method),
  7005. and if it can't find one there, it'll return the default value passed-in.
  7006. @param keyName the name of the property to retrieve
  7007. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7008. */
  7009. bool getBoolValue (const String& keyName,
  7010. const bool defaultReturnValue = false) const throw();
  7011. /** Returns one of the properties as an XML element.
  7012. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7013. key isn't found, or if the entry contains an string that isn't valid XML.
  7014. If the value isn't found in this set, then this will look for it in a fallback
  7015. property set (if you've specified one with the setFallbackPropertySet() method),
  7016. and if it can't find one there, it'll return the default value passed-in.
  7017. @param keyName the name of the property to retrieve
  7018. */
  7019. XmlElement* getXmlValue (const String& keyName) const;
  7020. /** Sets a named property as a string.
  7021. @param keyName the name of the property to set. (This mustn't be an empty string)
  7022. @param value the new value to set it to
  7023. */
  7024. void setValue (const String& keyName, const String& value) throw();
  7025. /** Sets a named property as a string.
  7026. @param keyName the name of the property to set. (This mustn't be an empty string)
  7027. @param value the new value to set it to
  7028. */
  7029. void setValue (const String& keyName, const tchar* const value) throw();
  7030. /** Sets a named property to an integer.
  7031. @param keyName the name of the property to set. (This mustn't be an empty string)
  7032. @param value the new value to set it to
  7033. */
  7034. void setValue (const String& keyName, const int value) throw();
  7035. /** Sets a named property to a double.
  7036. @param keyName the name of the property to set. (This mustn't be an empty string)
  7037. @param value the new value to set it to
  7038. */
  7039. void setValue (const String& keyName, const double value) throw();
  7040. /** Sets a named property to a boolean.
  7041. @param keyName the name of the property to set. (This mustn't be an empty string)
  7042. @param value the new value to set it to
  7043. */
  7044. void setValue (const String& keyName, const bool value) throw();
  7045. /** Sets a named property to an XML element.
  7046. @param keyName the name of the property to set. (This mustn't be an empty string)
  7047. @param xml the new element to set it to. If this is zero, the value will be set to
  7048. an empty string
  7049. @see getXmlValue
  7050. */
  7051. void setValue (const String& keyName, const XmlElement* const xml);
  7052. /** Deletes a property.
  7053. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7054. */
  7055. void removeValue (const String& keyName) throw();
  7056. /** Returns true if the properies include the given key. */
  7057. bool containsKey (const String& keyName) const throw();
  7058. /** Removes all values. */
  7059. void clear();
  7060. /** Returns the keys/value pair array containing all the properties. */
  7061. StringPairArray& getAllProperties() throw() { return properties; }
  7062. /** Returns the lock used when reading or writing to this set */
  7063. const CriticalSection& getLock() const throw() { return lock; }
  7064. /** Returns an XML element which encapsulates all the items in this property set.
  7065. The string parameter is the tag name that should be used for the node.
  7066. @see restoreFromXml
  7067. */
  7068. XmlElement* createXml (const String& nodeName) const throw();
  7069. /** Reloads a set of properties that were previously stored as XML.
  7070. The node passed in must have been created by the createXml() method.
  7071. @see createXml
  7072. */
  7073. void restoreFromXml (const XmlElement& xml) throw();
  7074. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7075. set in this one.
  7076. If you set this up to be a pointer to a second property set, then whenever one
  7077. of the getValue() methods fails to find an entry in this set, it will look up that
  7078. value in the fallback set, and if it finds it, it will return that.
  7079. Make sure that you don't delete the fallback set while it's still being used by
  7080. another set! To remove the fallback set, just call this method with a null pointer.
  7081. @see getFallbackPropertySet
  7082. */
  7083. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7084. /** Returns the fallback property set.
  7085. @see setFallbackPropertySet
  7086. */
  7087. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7088. juce_UseDebuggingNewOperator
  7089. protected:
  7090. /** Subclasses can override this to be told when one of the properies has been changed.
  7091. */
  7092. virtual void propertyChanged();
  7093. private:
  7094. StringPairArray properties;
  7095. PropertySet* fallbackProperties;
  7096. CriticalSection lock;
  7097. bool ignoreCaseOfKeys;
  7098. };
  7099. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7100. /********* End of inlined file: juce_PropertySet.h *********/
  7101. #endif
  7102. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7103. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7104. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7105. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7106. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7107. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7108. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7109. /**
  7110. Adds reference-counting to an object.
  7111. To add reference-counting to a class, derive it from this class, and
  7112. use the ReferenceCountedObjectPtr class to point to it.
  7113. e.g. @code
  7114. class MyClass : public ReferenceCountedObject
  7115. {
  7116. void foo();
  7117. // This is a neat way of declaring a typedef for a pointer class,
  7118. // rather than typing out the full templated name each time..
  7119. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7120. };
  7121. MyClass::Ptr p = new MyClass();
  7122. MyClass::Ptr p2 = p;
  7123. p = 0;
  7124. p2->foo();
  7125. @endcode
  7126. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7127. careful not to delete the object manually.
  7128. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7129. */
  7130. class JUCE_API ReferenceCountedObject
  7131. {
  7132. public:
  7133. /** Increments the object's reference count.
  7134. This is done automatically by the smart pointer, but is public just
  7135. in case it's needed for nefarious purposes.
  7136. */
  7137. inline void incReferenceCount() throw()
  7138. {
  7139. atomicIncrement (refCounts);
  7140. jassert (refCounts > 0);
  7141. }
  7142. /** Decreases the object's reference count.
  7143. If the count gets to zero, the object will be deleted.
  7144. */
  7145. inline void decReferenceCount() throw()
  7146. {
  7147. jassert (refCounts > 0);
  7148. if (atomicDecrementAndReturn (refCounts) == 0)
  7149. delete this;
  7150. }
  7151. /** Returns the object's current reference count. */
  7152. inline int getReferenceCount() const throw()
  7153. {
  7154. return refCounts;
  7155. }
  7156. protected:
  7157. /** Creates the reference-counted object (with an initial ref count of zero). */
  7158. ReferenceCountedObject()
  7159. : refCounts (0)
  7160. {
  7161. }
  7162. /** Destructor. */
  7163. virtual ~ReferenceCountedObject()
  7164. {
  7165. // it's dangerous to delete an object that's still referenced by something else!
  7166. jassert (refCounts == 0);
  7167. }
  7168. private:
  7169. int refCounts;
  7170. };
  7171. /**
  7172. Used to point to an object of type ReferenceCountedObject.
  7173. It's wise to use a typedef instead of typing out the templated name
  7174. each time - e.g.
  7175. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7176. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7177. */
  7178. template <class ReferenceCountedObjectClass>
  7179. class ReferenceCountedObjectPtr
  7180. {
  7181. public:
  7182. /** Creates a pointer to a null object. */
  7183. inline ReferenceCountedObjectPtr() throw()
  7184. : referencedObject (0)
  7185. {
  7186. }
  7187. /** Creates a pointer to an object.
  7188. This will increment the object's reference-count if it is non-null.
  7189. */
  7190. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7191. : referencedObject (refCountedObject)
  7192. {
  7193. if (refCountedObject != 0)
  7194. refCountedObject->incReferenceCount();
  7195. }
  7196. /** Copies another pointer.
  7197. This will increment the object's reference-count (if it is non-null).
  7198. */
  7199. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7200. : referencedObject (other.referencedObject)
  7201. {
  7202. if (referencedObject != 0)
  7203. referencedObject->incReferenceCount();
  7204. }
  7205. /** Changes this pointer to point at a different object.
  7206. The reference count of the old object is decremented, and it might be
  7207. deleted if it hits zero. The new object's count is incremented.
  7208. */
  7209. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7210. {
  7211. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7212. if (newObject != referencedObject)
  7213. {
  7214. if (newObject != 0)
  7215. newObject->incReferenceCount();
  7216. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7217. referencedObject = newObject;
  7218. if (oldObject != 0)
  7219. oldObject->decReferenceCount();
  7220. }
  7221. return *this;
  7222. }
  7223. /** Changes this pointer to point at a different object.
  7224. The reference count of the old object is decremented, and it might be
  7225. deleted if it hits zero. The new object's count is incremented.
  7226. */
  7227. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7228. {
  7229. if (referencedObject != newObject)
  7230. {
  7231. if (newObject != 0)
  7232. newObject->incReferenceCount();
  7233. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7234. referencedObject = newObject;
  7235. if (oldObject != 0)
  7236. oldObject->decReferenceCount();
  7237. }
  7238. return *this;
  7239. }
  7240. /** Destructor.
  7241. This will decrement the object's reference-count, and may delete it if it
  7242. gets to zero.
  7243. */
  7244. inline ~ReferenceCountedObjectPtr()
  7245. {
  7246. if (referencedObject != 0)
  7247. referencedObject->decReferenceCount();
  7248. }
  7249. /** Returns the object that this pointer references.
  7250. The pointer returned may be zero, of course.
  7251. */
  7252. inline operator ReferenceCountedObjectClass*() const throw()
  7253. {
  7254. return referencedObject;
  7255. }
  7256. /** Returns true if this pointer refers to the given object. */
  7257. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7258. {
  7259. return referencedObject == object;
  7260. }
  7261. /** Returns true if this pointer doesn't refer to the given object. */
  7262. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7263. {
  7264. return referencedObject != object;
  7265. }
  7266. // the -> operator is called on the referenced object
  7267. inline ReferenceCountedObjectClass* operator->() const throw()
  7268. {
  7269. return referencedObject;
  7270. }
  7271. private:
  7272. ReferenceCountedObjectClass* referencedObject;
  7273. };
  7274. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7275. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7276. /**
  7277. Holds a list of objects derived from ReferenceCountedObject.
  7278. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7279. and takes care of incrementing and decrementing their ref counts when they
  7280. are added and removed from the array.
  7281. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7282. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7283. @see Array, OwnedArray, StringArray
  7284. */
  7285. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7286. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7287. {
  7288. public:
  7289. /** Creates an empty array.
  7290. @param granularity this is the size of increment by which the internal storage
  7291. used by the array will grow. Only change it from the default if you know the
  7292. array is going to be very big and needs to be able to grow efficiently.
  7293. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7294. */
  7295. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7296. : ArrayAllocationBase <ObjectClass*> (granularity),
  7297. numUsed (0)
  7298. {
  7299. }
  7300. /** Creates a copy of another array */
  7301. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7302. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  7303. numUsed (other.numUsed)
  7304. {
  7305. other.lockArray();
  7306. this->setAllocatedSize (numUsed);
  7307. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7308. for (int i = numUsed; --i >= 0;)
  7309. if (this->elements[i] != 0)
  7310. this->elements[i]->incReferenceCount();
  7311. other.unlockArray();
  7312. }
  7313. /** Copies another array into this one.
  7314. Any existing objects in this array will first be released.
  7315. */
  7316. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7317. {
  7318. if (this != &other)
  7319. {
  7320. other.lockArray();
  7321. lock.enter();
  7322. clear();
  7323. this->granularity = other.granularity;
  7324. this->ensureAllocatedSize (other.numUsed);
  7325. numUsed = other.numUsed;
  7326. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7327. minimiseStorageOverheads();
  7328. for (int i = numUsed; --i >= 0;)
  7329. if (this->elements[i] != 0)
  7330. this->elements[i]->incReferenceCount();
  7331. lock.exit();
  7332. other.unlockArray();
  7333. }
  7334. return *this;
  7335. }
  7336. /** Destructor.
  7337. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7338. */
  7339. ~ReferenceCountedArray()
  7340. {
  7341. clear();
  7342. }
  7343. /** Removes all objects from the array.
  7344. Any objects in the array that are not referenced from elsewhere will be deleted.
  7345. */
  7346. void clear()
  7347. {
  7348. lock.enter();
  7349. while (numUsed > 0)
  7350. if (this->elements [--numUsed] != 0)
  7351. this->elements [numUsed]->decReferenceCount();
  7352. jassert (numUsed == 0);
  7353. this->setAllocatedSize (0);
  7354. lock.exit();
  7355. }
  7356. /** Returns the current number of objects in the array. */
  7357. inline int size() const throw()
  7358. {
  7359. return numUsed;
  7360. }
  7361. /** Returns a pointer to the object at this index in the array.
  7362. If the index is out-of-range, this will return a null pointer, (and
  7363. it could be null anyway, because it's ok for the array to hold null
  7364. pointers as well as objects).
  7365. @see getUnchecked
  7366. */
  7367. inline ObjectClass* operator[] (const int index) const throw()
  7368. {
  7369. lock.enter();
  7370. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  7371. ? this->elements [index]
  7372. : (ObjectClass*) 0;
  7373. lock.exit();
  7374. return result;
  7375. }
  7376. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7377. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7378. it can be used when you're sure the index if always going to be legal.
  7379. */
  7380. inline ObjectClass* getUnchecked (const int index) const throw()
  7381. {
  7382. lock.enter();
  7383. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7384. ObjectClass* const result = this->elements [index];
  7385. lock.exit();
  7386. return result;
  7387. }
  7388. /** Returns a pointer to the first object in the array.
  7389. This will return a null pointer if the array's empty.
  7390. @see getLast
  7391. */
  7392. inline ObjectClass* getFirst() const throw()
  7393. {
  7394. lock.enter();
  7395. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  7396. : (ObjectClass*) 0;
  7397. lock.exit();
  7398. return result;
  7399. }
  7400. /** Returns a pointer to the last object in the array.
  7401. This will return a null pointer if the array's empty.
  7402. @see getFirst
  7403. */
  7404. inline ObjectClass* getLast() const throw()
  7405. {
  7406. lock.enter();
  7407. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  7408. : (ObjectClass*) 0;
  7409. lock.exit();
  7410. return result;
  7411. }
  7412. /** Finds the index of the first occurrence of an object in the array.
  7413. @param objectToLookFor the object to look for
  7414. @returns the index at which the object was found, or -1 if it's not found
  7415. */
  7416. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7417. {
  7418. int result = -1;
  7419. lock.enter();
  7420. ObjectClass** e = this->elements;
  7421. for (int i = numUsed; --i >= 0;)
  7422. {
  7423. if (objectToLookFor == *e)
  7424. {
  7425. result = (int) (e - this->elements);
  7426. break;
  7427. }
  7428. ++e;
  7429. }
  7430. lock.exit();
  7431. return result;
  7432. }
  7433. /** Returns true if the array contains a specified object.
  7434. @param objectToLookFor the object to look for
  7435. @returns true if the object is in the array
  7436. */
  7437. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7438. {
  7439. lock.enter();
  7440. ObjectClass** e = this->elements;
  7441. for (int i = numUsed; --i >= 0;)
  7442. {
  7443. if (objectToLookFor == *e)
  7444. {
  7445. lock.exit();
  7446. return true;
  7447. }
  7448. ++e;
  7449. }
  7450. lock.exit();
  7451. return false;
  7452. }
  7453. /** Appends a new object to the end of the array.
  7454. This will increase the new object's reference count.
  7455. @param newObject the new object to add to the array
  7456. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7457. */
  7458. void add (ObjectClass* const newObject) throw()
  7459. {
  7460. lock.enter();
  7461. this->ensureAllocatedSize (numUsed + 1);
  7462. this->elements [numUsed++] = newObject;
  7463. if (newObject != 0)
  7464. newObject->incReferenceCount();
  7465. lock.exit();
  7466. }
  7467. /** Inserts a new object into the array at the given index.
  7468. If the index is less than 0 or greater than the size of the array, the
  7469. element will be added to the end of the array.
  7470. Otherwise, it will be inserted into the array, moving all the later elements
  7471. along to make room.
  7472. This will increase the new object's reference count.
  7473. @param indexToInsertAt the index at which the new element should be inserted
  7474. @param newObject the new object to add to the array
  7475. @see add, addSorted, addIfNotAlreadyThere, set
  7476. */
  7477. void insert (int indexToInsertAt,
  7478. ObjectClass* const newObject) throw()
  7479. {
  7480. if (indexToInsertAt >= 0)
  7481. {
  7482. lock.enter();
  7483. if (indexToInsertAt > numUsed)
  7484. indexToInsertAt = numUsed;
  7485. this->ensureAllocatedSize (numUsed + 1);
  7486. ObjectClass** const e = this->elements + indexToInsertAt;
  7487. const int numToMove = numUsed - indexToInsertAt;
  7488. if (numToMove > 0)
  7489. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7490. *e = newObject;
  7491. if (newObject != 0)
  7492. newObject->incReferenceCount();
  7493. ++numUsed;
  7494. lock.exit();
  7495. }
  7496. else
  7497. {
  7498. add (newObject);
  7499. }
  7500. }
  7501. /** Appends a new object at the end of the array as long as the array doesn't
  7502. already contain it.
  7503. If the array already contains a matching object, nothing will be done.
  7504. @param newObject the new object to add to the array
  7505. */
  7506. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7507. {
  7508. lock.enter();
  7509. if (! contains (newObject))
  7510. add (newObject);
  7511. lock.exit();
  7512. }
  7513. /** Replaces an object in the array with a different one.
  7514. If the index is less than zero, this method does nothing.
  7515. If the index is beyond the end of the array, the new object is added to the end of the array.
  7516. The object being added has its reference count increased, and if it's replacing
  7517. another object, then that one has its reference count decreased, and may be deleted.
  7518. @param indexToChange the index whose value you want to change
  7519. @param newObject the new value to set for this index.
  7520. @see add, insert, remove
  7521. */
  7522. void set (const int indexToChange,
  7523. ObjectClass* const newObject)
  7524. {
  7525. if (indexToChange >= 0)
  7526. {
  7527. lock.enter();
  7528. if (newObject != 0)
  7529. newObject->incReferenceCount();
  7530. if (indexToChange < numUsed)
  7531. {
  7532. if (this->elements [indexToChange] != 0)
  7533. this->elements [indexToChange]->decReferenceCount();
  7534. this->elements [indexToChange] = newObject;
  7535. }
  7536. else
  7537. {
  7538. this->ensureAllocatedSize (numUsed + 1);
  7539. this->elements [numUsed++] = newObject;
  7540. }
  7541. lock.exit();
  7542. }
  7543. }
  7544. /** Adds elements from another array to the end of this array.
  7545. @param arrayToAddFrom the array from which to copy the elements
  7546. @param startIndex the first element of the other array to start copying from
  7547. @param numElementsToAdd how many elements to add from the other array. If this
  7548. value is negative or greater than the number of available elements,
  7549. all available elements will be copied.
  7550. @see add
  7551. */
  7552. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7553. int startIndex = 0,
  7554. int numElementsToAdd = -1) throw()
  7555. {
  7556. arrayToAddFrom.lockArray();
  7557. lock.enter();
  7558. if (startIndex < 0)
  7559. {
  7560. jassertfalse
  7561. startIndex = 0;
  7562. }
  7563. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7564. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7565. if (numElementsToAdd > 0)
  7566. {
  7567. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  7568. while (--numElementsToAdd >= 0)
  7569. add (arrayToAddFrom.getUnchecked (startIndex++));
  7570. }
  7571. lock.exit();
  7572. arrayToAddFrom.unlockArray();
  7573. }
  7574. /** Inserts a new object into the array assuming that the array is sorted.
  7575. This will use a comparator to find the position at which the new object
  7576. should go. If the array isn't sorted, the behaviour of this
  7577. method will be unpredictable.
  7578. @param comparator the comparator object to use to compare the elements - see the
  7579. sort() method for details about this object's form
  7580. @param newObject the new object to insert to the array
  7581. @see add, sort
  7582. */
  7583. template <class ElementComparator>
  7584. void addSorted (ElementComparator& comparator,
  7585. ObjectClass* newObject) throw()
  7586. {
  7587. lock.enter();
  7588. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  7589. lock.exit();
  7590. }
  7591. /** Removes an object from the array.
  7592. This will remove the object at a given index and move back all the
  7593. subsequent objects to close the gap.
  7594. If the index passed in is out-of-range, nothing will happen.
  7595. The object that is removed will have its reference count decreased,
  7596. and may be deleted if not referenced from elsewhere.
  7597. @param indexToRemove the index of the element to remove
  7598. @see removeObject, removeRange
  7599. */
  7600. void remove (const int indexToRemove)
  7601. {
  7602. lock.enter();
  7603. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7604. {
  7605. ObjectClass** const e = this->elements + indexToRemove;
  7606. if (*e != 0)
  7607. (*e)->decReferenceCount();
  7608. --numUsed;
  7609. const int numberToShift = numUsed - indexToRemove;
  7610. if (numberToShift > 0)
  7611. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7612. if ((numUsed << 1) < this->numAllocated)
  7613. minimiseStorageOverheads();
  7614. }
  7615. lock.exit();
  7616. }
  7617. /** Removes the first occurrence of a specified object from the array.
  7618. If the item isn't found, no action is taken. If it is found, it is
  7619. removed and has its reference count decreased.
  7620. @param objectToRemove the object to try to remove
  7621. @see remove, removeRange
  7622. */
  7623. void removeObject (ObjectClass* const objectToRemove)
  7624. {
  7625. lock.enter();
  7626. remove (indexOf (objectToRemove));
  7627. lock.exit();
  7628. }
  7629. /** Removes a range of objects from the array.
  7630. This will remove a set of objects, starting from the given index,
  7631. and move any subsequent elements down to close the gap.
  7632. If the range extends beyond the bounds of the array, it will
  7633. be safely clipped to the size of the array.
  7634. The objects that are removed will have their reference counts decreased,
  7635. and may be deleted if not referenced from elsewhere.
  7636. @param startIndex the index of the first object to remove
  7637. @param numberToRemove how many objects should be removed
  7638. @see remove, removeObject
  7639. */
  7640. void removeRange (const int startIndex,
  7641. const int numberToRemove)
  7642. {
  7643. lock.enter();
  7644. const int start = jlimit (0, numUsed, startIndex);
  7645. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7646. if (end > start)
  7647. {
  7648. int i;
  7649. for (i = start; i < end; ++i)
  7650. {
  7651. if (this->elements[i] != 0)
  7652. {
  7653. this->elements[i]->decReferenceCount();
  7654. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7655. }
  7656. }
  7657. const int rangeSize = end - start;
  7658. ObjectClass** e = this->elements + start;
  7659. i = numUsed - end;
  7660. numUsed -= rangeSize;
  7661. while (--i >= 0)
  7662. {
  7663. *e = e [rangeSize];
  7664. ++e;
  7665. }
  7666. if ((numUsed << 1) < this->numAllocated)
  7667. minimiseStorageOverheads();
  7668. }
  7669. lock.exit();
  7670. }
  7671. /** Removes the last n objects from the array.
  7672. The objects that are removed will have their reference counts decreased,
  7673. and may be deleted if not referenced from elsewhere.
  7674. @param howManyToRemove how many objects to remove from the end of the array
  7675. @see remove, removeObject, removeRange
  7676. */
  7677. void removeLast (int howManyToRemove = 1)
  7678. {
  7679. lock.enter();
  7680. if (howManyToRemove > numUsed)
  7681. howManyToRemove = numUsed;
  7682. while (--howManyToRemove >= 0)
  7683. remove (numUsed - 1);
  7684. lock.exit();
  7685. }
  7686. /** Swaps a pair of objects in the array.
  7687. If either of the indexes passed in is out-of-range, nothing will happen,
  7688. otherwise the two objects at these positions will be exchanged.
  7689. */
  7690. void swap (const int index1,
  7691. const int index2) throw()
  7692. {
  7693. lock.enter();
  7694. if (((unsigned int) index1) < (unsigned int) numUsed
  7695. && ((unsigned int) index2) < (unsigned int) numUsed)
  7696. {
  7697. swapVariables (this->elements [index1],
  7698. this->elements [index2]);
  7699. }
  7700. lock.exit();
  7701. }
  7702. /** Moves one of the objects to a different position.
  7703. This will move the object to a specified index, shuffling along
  7704. any intervening elements as required.
  7705. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7706. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7707. @param currentIndex the index of the object to be moved. If this isn't a
  7708. valid index, then nothing will be done
  7709. @param newIndex the index at which you'd like this object to end up. If this
  7710. is less than zero, it will be moved to the end of the array
  7711. */
  7712. void move (const int currentIndex,
  7713. int newIndex) throw()
  7714. {
  7715. if (currentIndex != newIndex)
  7716. {
  7717. lock.enter();
  7718. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7719. {
  7720. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7721. newIndex = numUsed - 1;
  7722. ObjectClass* const value = this->elements [currentIndex];
  7723. if (newIndex > currentIndex)
  7724. {
  7725. memmove (this->elements + currentIndex,
  7726. this->elements + currentIndex + 1,
  7727. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7728. }
  7729. else
  7730. {
  7731. memmove (this->elements + newIndex + 1,
  7732. this->elements + newIndex,
  7733. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7734. }
  7735. this->elements [newIndex] = value;
  7736. }
  7737. lock.exit();
  7738. }
  7739. }
  7740. /** Compares this array to another one.
  7741. @returns true only if the other array contains the same objects in the same order
  7742. */
  7743. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7744. {
  7745. other.lockArray();
  7746. lock.enter();
  7747. bool result = numUsed == other.numUsed;
  7748. if (result)
  7749. {
  7750. for (int i = numUsed; --i >= 0;)
  7751. {
  7752. if (this->elements [i] != other.elements [i])
  7753. {
  7754. result = false;
  7755. break;
  7756. }
  7757. }
  7758. }
  7759. lock.exit();
  7760. other.unlockArray();
  7761. return result;
  7762. }
  7763. /** Compares this array to another one.
  7764. @see operator==
  7765. */
  7766. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7767. {
  7768. return ! operator== (other);
  7769. }
  7770. /** Sorts the elements in the array.
  7771. This will use a comparator object to sort the elements into order. The object
  7772. passed must have a method of the form:
  7773. @code
  7774. int compareElements (ElementType first, ElementType second);
  7775. @endcode
  7776. ..and this method must return:
  7777. - a value of < 0 if the first comes before the second
  7778. - a value of 0 if the two objects are equivalent
  7779. - a value of > 0 if the second comes before the first
  7780. To improve performance, the compareElements() method can be declared as static or const.
  7781. @param comparator the comparator to use for comparing elements.
  7782. @param retainOrderOfEquivalentItems if this is true, then items
  7783. which the comparator says are equivalent will be
  7784. kept in the order in which they currently appear
  7785. in the array. This is slower to perform, but may
  7786. be important in some cases. If it's false, a faster
  7787. algorithm is used, but equivalent elements may be
  7788. rearranged.
  7789. @see sortArray
  7790. */
  7791. template <class ElementComparator>
  7792. void sort (ElementComparator& comparator,
  7793. const bool retainOrderOfEquivalentItems = false) const throw()
  7794. {
  7795. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7796. // avoids getting warning messages about the parameter being unused
  7797. lock.enter();
  7798. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7799. lock.exit();
  7800. }
  7801. /** Reduces the amount of storage being used by the array.
  7802. Arrays typically allocate slightly more storage than they need, and after
  7803. removing elements, they may have quite a lot of unused space allocated.
  7804. This method will reduce the amount of allocated storage to a minimum.
  7805. */
  7806. void minimiseStorageOverheads() throw()
  7807. {
  7808. lock.enter();
  7809. if (numUsed == 0)
  7810. {
  7811. this->setAllocatedSize (0);
  7812. }
  7813. else
  7814. {
  7815. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  7816. if (newAllocation < this->numAllocated)
  7817. this->setAllocatedSize (newAllocation);
  7818. }
  7819. lock.exit();
  7820. }
  7821. /** Locks the array's CriticalSection.
  7822. Of course if the type of section used is a DummyCriticalSection, this won't
  7823. have any effect.
  7824. @see unlockArray
  7825. */
  7826. void lockArray() const throw()
  7827. {
  7828. lock.enter();
  7829. }
  7830. /** Unlocks the array's CriticalSection.
  7831. Of course if the type of section used is a DummyCriticalSection, this won't
  7832. have any effect.
  7833. @see lockArray
  7834. */
  7835. void unlockArray() const throw()
  7836. {
  7837. lock.exit();
  7838. }
  7839. juce_UseDebuggingNewOperator
  7840. private:
  7841. int numUsed;
  7842. TypeOfCriticalSectionToUse lock;
  7843. };
  7844. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7845. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7846. #endif
  7847. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7848. #endif
  7849. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7850. /********* Start of inlined file: juce_SortedSet.h *********/
  7851. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7852. #define __JUCE_SORTEDSET_JUCEHEADER__
  7853. #if JUCE_MSVC
  7854. #pragma warning (push)
  7855. #pragma warning (disable: 4512)
  7856. #endif
  7857. /**
  7858. Holds a set of unique primitive objects, such as ints or doubles.
  7859. A set can only hold one item with a given value, so if for example it's a
  7860. set of integers, attempting to add the same integer twice will do nothing
  7861. the second time.
  7862. Internally, the list of items is kept sorted (which means that whatever
  7863. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7864. to determine the order), and searching the set for known values is very fast
  7865. because it uses a binary-chop method.
  7866. Note that if you're using a class or struct as the element type, it must be
  7867. capable of being copied or moved with a straightforward memcpy, rather than
  7868. needing construction and destruction code.
  7869. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7870. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7871. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7872. */
  7873. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7874. class SortedSet : private ArrayAllocationBase <ElementType>
  7875. {
  7876. public:
  7877. /** Creates an empty set.
  7878. @param granularity this is the size of increment by which the internal storage
  7879. used by the array will grow. Only change it from the default if you know the
  7880. array is going to be very big and needs to be able to grow efficiently.
  7881. @see ArrayAllocationBase
  7882. */
  7883. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7884. : ArrayAllocationBase <ElementType> (granularity),
  7885. numUsed (0)
  7886. {
  7887. }
  7888. /** Creates a copy of another set.
  7889. @param other the set to copy
  7890. */
  7891. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7892. : ArrayAllocationBase <ElementType> (other.granularity)
  7893. {
  7894. other.lockSet();
  7895. numUsed = other.numUsed;
  7896. setAllocatedSize (other.numUsed);
  7897. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7898. other.unlockSet();
  7899. }
  7900. /** Destructor. */
  7901. ~SortedSet() throw()
  7902. {
  7903. }
  7904. /** Copies another set over this one.
  7905. @param other the set to copy
  7906. */
  7907. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7908. {
  7909. if (this != &other)
  7910. {
  7911. other.lockSet();
  7912. lock.enter();
  7913. this->granularity = other.granularity;
  7914. ensureAllocatedSize (other.size());
  7915. numUsed = other.numUsed;
  7916. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7917. minimiseStorageOverheads();
  7918. lock.exit();
  7919. other.unlockSet();
  7920. }
  7921. return *this;
  7922. }
  7923. /** Compares this set to another one.
  7924. Two sets are considered equal if they both contain the same set of
  7925. elements.
  7926. @param other the other set to compare with
  7927. */
  7928. bool operator== (const SortedSet<ElementType>& other) const throw()
  7929. {
  7930. lock.enter();
  7931. if (numUsed != other.numUsed)
  7932. {
  7933. lock.exit();
  7934. return false;
  7935. }
  7936. for (int i = numUsed; --i >= 0;)
  7937. {
  7938. if (this->elements [i] != other.elements [i])
  7939. {
  7940. lock.exit();
  7941. return false;
  7942. }
  7943. }
  7944. lock.exit();
  7945. return true;
  7946. }
  7947. /** Compares this set to another one.
  7948. Two sets are considered equal if they both contain the same set of
  7949. elements.
  7950. @param other the other set to compare with
  7951. */
  7952. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7953. {
  7954. return ! operator== (other);
  7955. }
  7956. /** Removes all elements from the set.
  7957. This will remove all the elements, and free any storage that the set is
  7958. using. To clear it without freeing the storage, use the clearQuick()
  7959. method instead.
  7960. @see clearQuick
  7961. */
  7962. void clear() throw()
  7963. {
  7964. lock.enter();
  7965. this->setAllocatedSize (0);
  7966. numUsed = 0;
  7967. lock.exit();
  7968. }
  7969. /** Removes all elements from the set without freeing the array's allocated storage.
  7970. @see clear
  7971. */
  7972. void clearQuick() throw()
  7973. {
  7974. lock.enter();
  7975. numUsed = 0;
  7976. lock.exit();
  7977. }
  7978. /** Returns the current number of elements in the set.
  7979. */
  7980. inline int size() const throw()
  7981. {
  7982. return numUsed;
  7983. }
  7984. /** Returns one of the elements in the set.
  7985. If the index passed in is beyond the range of valid elements, this
  7986. will return zero.
  7987. If you're certain that the index will always be a valid element, you
  7988. can call getUnchecked() instead, which is faster.
  7989. @param index the index of the element being requested (0 is the first element in the set)
  7990. @see getUnchecked, getFirst, getLast
  7991. */
  7992. inline ElementType operator[] (const int index) const throw()
  7993. {
  7994. lock.enter();
  7995. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  7996. ? this->elements [index]
  7997. : (ElementType) 0;
  7998. lock.exit();
  7999. return result;
  8000. }
  8001. /** Returns one of the elements in the set, without checking the index passed in.
  8002. Unlike the operator[] method, this will try to return an element without
  8003. checking that the index is within the bounds of the set, so should only
  8004. be used when you're confident that it will always be a valid index.
  8005. @param index the index of the element being requested (0 is the first element in the set)
  8006. @see operator[], getFirst, getLast
  8007. */
  8008. inline ElementType getUnchecked (const int index) const throw()
  8009. {
  8010. lock.enter();
  8011. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8012. const ElementType result = this->elements [index];
  8013. lock.exit();
  8014. return result;
  8015. }
  8016. /** Returns the first element in the set, or 0 if the set is empty.
  8017. @see operator[], getUnchecked, getLast
  8018. */
  8019. inline ElementType getFirst() const throw()
  8020. {
  8021. lock.enter();
  8022. const ElementType result = (numUsed > 0) ? this->elements [0]
  8023. : (ElementType) 0;
  8024. lock.exit();
  8025. return result;
  8026. }
  8027. /** Returns the last element in the set, or 0 if the set is empty.
  8028. @see operator[], getUnchecked, getFirst
  8029. */
  8030. inline ElementType getLast() const throw()
  8031. {
  8032. lock.enter();
  8033. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8034. : (ElementType) 0;
  8035. lock.exit();
  8036. return result;
  8037. }
  8038. /** Finds the index of the first element which matches the value passed in.
  8039. This will search the set for the given object, and return the index
  8040. of its first occurrence. If the object isn't found, the method will return -1.
  8041. @param elementToLookFor the value or object to look for
  8042. @returns the index of the object, or -1 if it's not found
  8043. */
  8044. int indexOf (const ElementType elementToLookFor) const throw()
  8045. {
  8046. lock.enter();
  8047. int start = 0;
  8048. int end = numUsed;
  8049. for (;;)
  8050. {
  8051. if (start >= end)
  8052. {
  8053. lock.exit();
  8054. return -1;
  8055. }
  8056. else if (elementToLookFor == this->elements [start])
  8057. {
  8058. lock.exit();
  8059. return start;
  8060. }
  8061. else
  8062. {
  8063. const int halfway = (start + end) >> 1;
  8064. if (halfway == start)
  8065. {
  8066. lock.exit();
  8067. return -1;
  8068. }
  8069. else if (elementToLookFor >= this->elements [halfway])
  8070. start = halfway;
  8071. else
  8072. end = halfway;
  8073. }
  8074. }
  8075. }
  8076. /** Returns true if the set contains at least one occurrence of an object.
  8077. @param elementToLookFor the value or object to look for
  8078. @returns true if the item is found
  8079. */
  8080. bool contains (const ElementType elementToLookFor) const throw()
  8081. {
  8082. lock.enter();
  8083. int start = 0;
  8084. int end = numUsed;
  8085. for (;;)
  8086. {
  8087. if (start >= end)
  8088. {
  8089. lock.exit();
  8090. return false;
  8091. }
  8092. else if (elementToLookFor == this->elements [start])
  8093. {
  8094. lock.exit();
  8095. return true;
  8096. }
  8097. else
  8098. {
  8099. const int halfway = (start + end) >> 1;
  8100. if (halfway == start)
  8101. {
  8102. lock.exit();
  8103. return false;
  8104. }
  8105. else if (elementToLookFor >= this->elements [halfway])
  8106. start = halfway;
  8107. else
  8108. end = halfway;
  8109. }
  8110. }
  8111. }
  8112. /** Adds a new element to the set, (as long as it's not already in there).
  8113. @param newElement the new object to add to the set
  8114. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8115. */
  8116. void add (const ElementType newElement) throw()
  8117. {
  8118. lock.enter();
  8119. int start = 0;
  8120. int end = numUsed;
  8121. for (;;)
  8122. {
  8123. if (start >= end)
  8124. {
  8125. jassert (start <= end);
  8126. insertInternal (start, newElement);
  8127. break;
  8128. }
  8129. else if (newElement == this->elements [start])
  8130. {
  8131. break;
  8132. }
  8133. else
  8134. {
  8135. const int halfway = (start + end) >> 1;
  8136. if (halfway == start)
  8137. {
  8138. if (newElement >= this->elements [halfway])
  8139. insertInternal (start + 1, newElement);
  8140. else
  8141. insertInternal (start, newElement);
  8142. break;
  8143. }
  8144. else if (newElement >= this->elements [halfway])
  8145. start = halfway;
  8146. else
  8147. end = halfway;
  8148. }
  8149. }
  8150. lock.exit();
  8151. }
  8152. /** Adds elements from an array to this set.
  8153. @param elementsToAdd the array of elements to add
  8154. @param numElementsToAdd how many elements are in this other array
  8155. @see add
  8156. */
  8157. void addArray (const ElementType* elementsToAdd,
  8158. int numElementsToAdd) throw()
  8159. {
  8160. lock.enter();
  8161. while (--numElementsToAdd >= 0)
  8162. add (*elementsToAdd++);
  8163. lock.exit();
  8164. }
  8165. /** Adds elements from another set to this one.
  8166. @param setToAddFrom the set from which to copy the elements
  8167. @param startIndex the first element of the other set to start copying from
  8168. @param numElementsToAdd how many elements to add from the other set. If this
  8169. value is negative or greater than the number of available elements,
  8170. all available elements will be copied.
  8171. @see add
  8172. */
  8173. template <class OtherSetType>
  8174. void addSet (const OtherSetType& setToAddFrom,
  8175. int startIndex = 0,
  8176. int numElementsToAdd = -1) throw()
  8177. {
  8178. setToAddFrom.lockSet();
  8179. lock.enter();
  8180. jassert (this != &setToAddFrom);
  8181. if (this != &setToAddFrom)
  8182. {
  8183. if (startIndex < 0)
  8184. {
  8185. jassertfalse
  8186. startIndex = 0;
  8187. }
  8188. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8189. numElementsToAdd = setToAddFrom.size() - startIndex;
  8190. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8191. }
  8192. lock.exit();
  8193. setToAddFrom.unlockSet();
  8194. }
  8195. /** Removes an element from the set.
  8196. This will remove the element at a given index.
  8197. If the index passed in is out-of-range, nothing will happen.
  8198. @param indexToRemove the index of the element to remove
  8199. @returns the element that has been removed
  8200. @see removeValue, removeRange
  8201. */
  8202. ElementType remove (const int indexToRemove) throw()
  8203. {
  8204. lock.enter();
  8205. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8206. {
  8207. --numUsed;
  8208. ElementType* const e = this->elements + indexToRemove;
  8209. ElementType const removed = *e;
  8210. const int numberToShift = numUsed - indexToRemove;
  8211. if (numberToShift > 0)
  8212. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8213. if ((numUsed << 1) < this->numAllocated)
  8214. minimiseStorageOverheads();
  8215. lock.exit();
  8216. return removed;
  8217. }
  8218. else
  8219. {
  8220. lock.exit();
  8221. return 0;
  8222. }
  8223. }
  8224. /** Removes an item from the set.
  8225. This will remove the given element from the set, if it's there.
  8226. @param valueToRemove the object to try to remove
  8227. @see remove, removeRange
  8228. */
  8229. void removeValue (const ElementType valueToRemove) throw()
  8230. {
  8231. lock.enter();
  8232. remove (indexOf (valueToRemove));
  8233. lock.exit();
  8234. }
  8235. /** Removes any elements which are also in another set.
  8236. @param otherSet the other set in which to look for elements to remove
  8237. @see removeValuesNotIn, remove, removeValue, removeRange
  8238. */
  8239. template <class OtherSetType>
  8240. void removeValuesIn (const OtherSetType& otherSet) throw()
  8241. {
  8242. otherSet.lockSet();
  8243. lock.enter();
  8244. if (this == &otherSet)
  8245. {
  8246. clear();
  8247. }
  8248. else
  8249. {
  8250. if (otherSet.size() > 0)
  8251. {
  8252. for (int i = numUsed; --i >= 0;)
  8253. if (otherSet.contains (this->elements [i]))
  8254. remove (i);
  8255. }
  8256. }
  8257. lock.exit();
  8258. otherSet.unlockSet();
  8259. }
  8260. /** Removes any elements which are not found in another set.
  8261. Only elements which occur in this other set will be retained.
  8262. @param otherSet the set in which to look for elements NOT to remove
  8263. @see removeValuesIn, remove, removeValue, removeRange
  8264. */
  8265. template <class OtherSetType>
  8266. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8267. {
  8268. otherSet.lockSet();
  8269. lock.enter();
  8270. if (this != &otherSet)
  8271. {
  8272. if (otherSet.size() <= 0)
  8273. {
  8274. clear();
  8275. }
  8276. else
  8277. {
  8278. for (int i = numUsed; --i >= 0;)
  8279. if (! otherSet.contains (this->elements [i]))
  8280. remove (i);
  8281. }
  8282. }
  8283. lock.exit();
  8284. otherSet.lockSet();
  8285. }
  8286. /** Reduces the amount of storage being used by the set.
  8287. Sets typically allocate slightly more storage than they need, and after
  8288. removing elements, they may have quite a lot of unused space allocated.
  8289. This method will reduce the amount of allocated storage to a minimum.
  8290. */
  8291. void minimiseStorageOverheads() throw()
  8292. {
  8293. lock.enter();
  8294. if (numUsed == 0)
  8295. {
  8296. this->setAllocatedSize (0);
  8297. }
  8298. else
  8299. {
  8300. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8301. if (newAllocation < this->numAllocated)
  8302. this->setAllocatedSize (newAllocation);
  8303. }
  8304. lock.exit();
  8305. }
  8306. /** Locks the set's CriticalSection.
  8307. Of course if the type of section used is a DummyCriticalSection, this won't
  8308. have any effect.
  8309. @see unlockSet
  8310. */
  8311. void lockSet() const throw()
  8312. {
  8313. lock.enter();
  8314. }
  8315. /** Unlocks the set's CriticalSection.
  8316. Of course if the type of section used is a DummyCriticalSection, this won't
  8317. have any effect.
  8318. @see lockSet
  8319. */
  8320. void unlockSet() const throw()
  8321. {
  8322. lock.exit();
  8323. }
  8324. juce_UseDebuggingNewOperator
  8325. private:
  8326. int numUsed;
  8327. TypeOfCriticalSectionToUse lock;
  8328. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8329. {
  8330. this->ensureAllocatedSize (numUsed + 1);
  8331. ElementType* const insertPos = this->elements + indexToInsertAt;
  8332. const int numberToMove = numUsed - indexToInsertAt;
  8333. if (numberToMove > 0)
  8334. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8335. *insertPos = newElement;
  8336. ++numUsed;
  8337. }
  8338. };
  8339. #if JUCE_MSVC
  8340. #pragma warning (pop)
  8341. #endif
  8342. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8343. /********* End of inlined file: juce_SortedSet.h *********/
  8344. #endif
  8345. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8346. /********* Start of inlined file: juce_SparseSet.h *********/
  8347. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8348. #define __JUCE_SPARSESET_JUCEHEADER__
  8349. /**
  8350. Holds a set of primitive values, storing them as a set of ranges.
  8351. This container acts like a simple BitArray, but can efficiently hold large
  8352. continguous ranges of values. It's quite a specialised class, mostly useful
  8353. for things like keeping the set of selected rows in a listbox.
  8354. The type used as a template paramter must be an integer type, such as int, short,
  8355. int64, etc.
  8356. */
  8357. template <class Type>
  8358. class SparseSet
  8359. {
  8360. public:
  8361. /** Creates a new empty set. */
  8362. SparseSet() throw()
  8363. {
  8364. }
  8365. /** Creates a copy of another SparseSet. */
  8366. SparseSet (const SparseSet<Type>& other) throw()
  8367. : values (other.values)
  8368. {
  8369. }
  8370. /** Destructor. */
  8371. ~SparseSet() throw()
  8372. {
  8373. }
  8374. /** Clears the set. */
  8375. void clear() throw()
  8376. {
  8377. values.clear();
  8378. }
  8379. /** Checks whether the set is empty.
  8380. This is much quicker than using (size() == 0).
  8381. */
  8382. bool isEmpty() const throw()
  8383. {
  8384. return values.size() == 0;
  8385. }
  8386. /** Returns the number of values in the set.
  8387. Because of the way the data is stored, this method can take longer if there
  8388. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8389. are any items.
  8390. */
  8391. Type size() const throw()
  8392. {
  8393. Type num = 0;
  8394. for (int i = 0; i < values.size(); i += 2)
  8395. num += values[i + 1] - values[i];
  8396. return num;
  8397. }
  8398. /** Returns one of the values in the set.
  8399. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8400. @returns the value at this index, or 0 if it's out-of-range
  8401. */
  8402. Type operator[] (int index) const throw()
  8403. {
  8404. for (int i = 0; i < values.size(); i += 2)
  8405. {
  8406. const Type s = values.getUnchecked(i);
  8407. const Type e = values.getUnchecked(i + 1);
  8408. if (index < e - s)
  8409. return s + index;
  8410. index -= e - s;
  8411. }
  8412. return (Type) 0;
  8413. }
  8414. /** Checks whether a particular value is in the set. */
  8415. bool contains (const Type valueToLookFor) const throw()
  8416. {
  8417. bool on = false;
  8418. for (int i = 0; i < values.size(); ++i)
  8419. {
  8420. if (values.getUnchecked(i) > valueToLookFor)
  8421. return on;
  8422. on = ! on;
  8423. }
  8424. return false;
  8425. }
  8426. /** Returns the number of contiguous blocks of values.
  8427. @see getRange
  8428. */
  8429. int getNumRanges() const throw()
  8430. {
  8431. return values.size() >> 1;
  8432. }
  8433. /** Returns one of the contiguous ranges of values stored.
  8434. @param rangeIndex the index of the range to look up, between 0
  8435. and (getNumRanges() - 1)
  8436. @param startValue on return, the value at the start of the range
  8437. @param numValues on return, the number of values in the range
  8438. @see getTotalRange
  8439. */
  8440. bool getRange (const int rangeIndex,
  8441. Type& startValue,
  8442. Type& numValues) const throw()
  8443. {
  8444. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8445. {
  8446. startValue = values [rangeIndex << 1];
  8447. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8448. return true;
  8449. }
  8450. return false;
  8451. }
  8452. /** Returns the lowest and highest values in the set.
  8453. @see getRange
  8454. */
  8455. bool getTotalRange (Type& lowestValue,
  8456. Type& highestValue) const throw()
  8457. {
  8458. if (values.size() > 0)
  8459. {
  8460. lowestValue = values.getUnchecked (0);
  8461. highestValue = values.getUnchecked (values.size() - 1);
  8462. return true;
  8463. }
  8464. return false;
  8465. }
  8466. /** Adds a range of contiguous values to the set.
  8467. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8468. @param firstValue the start of the range of values to add
  8469. @param numValuesToAdd how many values to add
  8470. */
  8471. void addRange (const Type firstValue,
  8472. const Type numValuesToAdd) throw()
  8473. {
  8474. jassert (numValuesToAdd >= 0);
  8475. if (numValuesToAdd > 0)
  8476. {
  8477. removeRange (firstValue, numValuesToAdd);
  8478. IntegerElementComparator<Type> sorter;
  8479. values.addSorted (sorter, firstValue);
  8480. values.addSorted (sorter, firstValue + numValuesToAdd);
  8481. simplify();
  8482. }
  8483. }
  8484. /** Removes a range of values from the set.
  8485. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8486. @param firstValue the start of the range of values to remove
  8487. @param numValuesToRemove how many values to remove
  8488. */
  8489. void removeRange (const Type firstValue,
  8490. const Type numValuesToRemove) throw()
  8491. {
  8492. jassert (numValuesToRemove >= 0);
  8493. if (numValuesToRemove > 0
  8494. && firstValue < values.getLast())
  8495. {
  8496. const bool onAtStart = contains (firstValue - 1);
  8497. Type lastValue = firstValue + numValuesToRemove;
  8498. if (lastValue < firstValue) // possible if the signed arithmetic wraps around
  8499. lastValue = values.getLast();
  8500. const bool onAtEnd = contains (lastValue);
  8501. for (int i = values.size(); --i >= 0;)
  8502. {
  8503. if (values.getUnchecked(i) >= firstValue
  8504. && values.getUnchecked(i) <= lastValue)
  8505. {
  8506. values.remove (i);
  8507. }
  8508. }
  8509. IntegerElementComparator<Type> sorter;
  8510. if (onAtStart)
  8511. values.addSorted (sorter, firstValue);
  8512. if (onAtEnd)
  8513. values.addSorted (sorter, lastValue);
  8514. simplify();
  8515. }
  8516. }
  8517. /** Does an XOR of the values in a given range. */
  8518. void invertRange (const Type firstValue,
  8519. const Type numValues)
  8520. {
  8521. SparseSet newItems;
  8522. newItems.addRange (firstValue, numValues);
  8523. int i;
  8524. for (i = getNumRanges(); --i >= 0;)
  8525. {
  8526. const int start = values [i << 1];
  8527. const int end = values [(i << 1) + 1];
  8528. newItems.removeRange (start, end);
  8529. }
  8530. removeRange (firstValue, numValues);
  8531. for (i = newItems.getNumRanges(); --i >= 0;)
  8532. {
  8533. const int start = newItems.values [i << 1];
  8534. const int end = newItems.values [(i << 1) + 1];
  8535. addRange (start, end);
  8536. }
  8537. }
  8538. /** Checks whether any part of a given range overlaps any part of this one. */
  8539. bool overlapsRange (const Type firstValue,
  8540. const Type numValues) throw()
  8541. {
  8542. jassert (numValues >= 0);
  8543. if (numValues > 0)
  8544. {
  8545. for (int i = getNumRanges(); --i >= 0;)
  8546. {
  8547. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8548. return false;
  8549. if (firstValue + numValues > values.getUnchecked (i << 1))
  8550. return true;
  8551. }
  8552. }
  8553. return false;
  8554. }
  8555. /** Checks whether the whole of a given range is contained within this one. */
  8556. bool containsRange (const Type firstValue,
  8557. const Type numValues) throw()
  8558. {
  8559. jassert (numValues >= 0);
  8560. if (numValues > 0)
  8561. {
  8562. for (int i = getNumRanges(); --i >= 0;)
  8563. {
  8564. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8565. return false;
  8566. if (firstValue >= values.getUnchecked (i << 1)
  8567. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8568. return true;
  8569. }
  8570. }
  8571. return false;
  8572. }
  8573. bool operator== (const SparseSet<Type>& other) throw()
  8574. {
  8575. return values == other.values;
  8576. }
  8577. bool operator!= (const SparseSet<Type>& other) throw()
  8578. {
  8579. return values != other.values;
  8580. }
  8581. juce_UseDebuggingNewOperator
  8582. private:
  8583. // alternating start/end values of ranges of values that are present.
  8584. Array<Type> values;
  8585. void simplify() throw()
  8586. {
  8587. jassert ((values.size() & 1) == 0);
  8588. for (int i = values.size(); --i > 0;)
  8589. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8590. values.removeRange (i - 1, 2);
  8591. }
  8592. };
  8593. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8594. /********* End of inlined file: juce_SparseSet.h *********/
  8595. #endif
  8596. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  8597. #endif
  8598. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  8599. #endif
  8600. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  8601. #endif
  8602. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8603. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  8604. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8605. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8606. /**
  8607. Searches through a the files in a directory, returning each file that is found.
  8608. A DirectoryIterator will search through a directory and its subdirectories using
  8609. a wildcard filepattern match.
  8610. If you may be finding a large number of files, this is better than
  8611. using File::findChildFiles() because it doesn't block while it finds them
  8612. all, and this is more memory-efficient.
  8613. It can also guess how far it's got using a wildly inaccurate algorithm.
  8614. */
  8615. class JUCE_API DirectoryIterator
  8616. {
  8617. public:
  8618. /** Creates a DirectoryIterator for a given directory.
  8619. After creating one of these, call its next() method to get the
  8620. first file - e.g. @code
  8621. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  8622. while (iter.next())
  8623. {
  8624. File theFileItFound (iter.getFile());
  8625. ... etc
  8626. }
  8627. @endcode
  8628. @param directory the directory to search in
  8629. @param isRecursive whether all the subdirectories should also be searched
  8630. @param wildCard the file pattern to match
  8631. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  8632. whether to look for files, directories, or both.
  8633. */
  8634. DirectoryIterator (const File& directory,
  8635. bool isRecursive,
  8636. const String& wildCard = JUCE_T("*"),
  8637. const int whatToLookFor = File::findFiles) throw();
  8638. /** Destructor. */
  8639. ~DirectoryIterator() throw();
  8640. /** Call this to move the iterator along to the next file.
  8641. @returns true if a file was found (you can then use getFile() to see what it was) - or
  8642. false if there are no more matching files.
  8643. */
  8644. bool next() throw();
  8645. /** Returns the file that the iterator is currently pointing at.
  8646. The result of this call is only valid after a call to next() has returned true.
  8647. */
  8648. const File getFile() const throw();
  8649. /** Returns a guess of how far through the search the iterator has got.
  8650. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  8651. very accurate.
  8652. */
  8653. float getEstimatedProgress() const throw();
  8654. juce_UseDebuggingNewOperator
  8655. private:
  8656. OwnedArray <File> filesFound;
  8657. OwnedArray <File> dirsFound;
  8658. String wildCard;
  8659. int index;
  8660. const int whatToLookFor;
  8661. DirectoryIterator* subIterator;
  8662. DirectoryIterator (const DirectoryIterator&);
  8663. const DirectoryIterator& operator= (const DirectoryIterator&);
  8664. };
  8665. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8666. /********* End of inlined file: juce_DirectoryIterator.h *********/
  8667. #endif
  8668. #ifndef __JUCE_FILE_JUCEHEADER__
  8669. #endif
  8670. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8671. /********* Start of inlined file: juce_FileInputStream.h *********/
  8672. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8673. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8674. /**
  8675. An input stream that reads from a local file.
  8676. @see InputStream, FileOutputStream, File::createInputStream
  8677. */
  8678. class JUCE_API FileInputStream : public InputStream
  8679. {
  8680. public:
  8681. /** Creates a FileInputStream.
  8682. @param fileToRead the file to read from - if the file can't be accessed for some
  8683. reason, then the stream will just contain no data
  8684. */
  8685. FileInputStream (const File& fileToRead);
  8686. /** Destructor. */
  8687. ~FileInputStream();
  8688. const File& getFile() const throw() { return file; }
  8689. int64 getTotalLength();
  8690. int read (void* destBuffer, int maxBytesToRead);
  8691. bool isExhausted();
  8692. int64 getPosition();
  8693. bool setPosition (int64 pos);
  8694. juce_UseDebuggingNewOperator
  8695. private:
  8696. File file;
  8697. void* fileHandle;
  8698. int64 currentPosition, totalSize;
  8699. bool needToSeek;
  8700. };
  8701. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8702. /********* End of inlined file: juce_FileInputStream.h *********/
  8703. #endif
  8704. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8705. /********* Start of inlined file: juce_FileOutputStream.h *********/
  8706. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8707. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8708. /**
  8709. An output stream that writes into a local file.
  8710. @see OutputStream, FileInputStream, File::createOutputStream
  8711. */
  8712. class JUCE_API FileOutputStream : public OutputStream
  8713. {
  8714. public:
  8715. /** Creates a FileOutputStream.
  8716. If the file doesn't exist, it will first be created. If the file can't be
  8717. created or opened, the failedToOpen() method will return
  8718. true.
  8719. If the file already exists when opened, the stream's write-postion will
  8720. be set to the end of the file. To overwrite an existing file,
  8721. use File::deleteFile() before opening the stream, or use setPosition(0)
  8722. after it's opened (although this won't truncate the file).
  8723. It's better to use File::createOutputStream() to create one of these, rather
  8724. than using the class directly.
  8725. */
  8726. FileOutputStream (const File& fileToWriteTo,
  8727. const int bufferSizeToUse = 16384);
  8728. /** Destructor. */
  8729. ~FileOutputStream();
  8730. /** Returns the file that this stream is writing to.
  8731. */
  8732. const File& getFile() const throw() { return file; }
  8733. /** Returns true if the stream couldn't be opened for some reason.
  8734. */
  8735. bool failedToOpen() const throw() { return fileHandle == 0; }
  8736. void flush();
  8737. int64 getPosition();
  8738. bool setPosition (int64 pos);
  8739. bool write (const void* data, int numBytes);
  8740. juce_UseDebuggingNewOperator
  8741. private:
  8742. File file;
  8743. void* fileHandle;
  8744. int64 currentPosition;
  8745. int bufferSize, bytesInBuffer;
  8746. char* buffer;
  8747. };
  8748. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8749. /********* End of inlined file: juce_FileOutputStream.h *********/
  8750. #endif
  8751. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8752. /********* Start of inlined file: juce_FileSearchPath.h *********/
  8753. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8754. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  8755. /**
  8756. Encapsulates a set of folders that make up a search path.
  8757. @see File
  8758. */
  8759. class JUCE_API FileSearchPath
  8760. {
  8761. public:
  8762. /** Creates an empty search path. */
  8763. FileSearchPath();
  8764. /** Creates a search path from a string of pathnames.
  8765. The path can be semicolon- or comma-separated, e.g.
  8766. "/foo/bar;/foo/moose;/fish/moose"
  8767. The separate folders are tokenised and added to the search path.
  8768. */
  8769. FileSearchPath (const String& path);
  8770. /** Creates a copy of another search path. */
  8771. FileSearchPath (const FileSearchPath& other);
  8772. /** Destructor. */
  8773. ~FileSearchPath();
  8774. /** Uses a string containing a list of pathnames to re-initialise this list.
  8775. This search path is cleared and the semicolon- or comma-separated folders
  8776. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  8777. */
  8778. const FileSearchPath& operator= (const String& path);
  8779. /** Returns the number of folders in this search path.
  8780. @see operator[]
  8781. */
  8782. int getNumPaths() const;
  8783. /** Returns one of the folders in this search path.
  8784. The file returned isn't guaranteed to actually be a valid directory.
  8785. @see getNumPaths
  8786. */
  8787. const File operator[] (const int index) const;
  8788. /** Returns the search path as a semicolon-separated list of directories. */
  8789. const String toString() const;
  8790. /** Adds a new directory to the search path.
  8791. The new directory is added to the end of the list if the insertIndex parameter is
  8792. less than zero, otherwise it is inserted at the given index.
  8793. */
  8794. void add (const File& directoryToAdd,
  8795. const int insertIndex = -1);
  8796. /** Adds a new directory to the search path if it's not already in there. */
  8797. void addIfNotAlreadyThere (const File& directoryToAdd);
  8798. /** Removes a directory from the search path. */
  8799. void remove (const int indexToRemove);
  8800. /** Merges another search path into this one.
  8801. This will remove any duplicate directories.
  8802. */
  8803. void addPath (const FileSearchPath& other);
  8804. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  8805. If the search is intended to be recursive, there's no point having nested folders in the search
  8806. path, because they'll just get searched twice and you'll get duplicate results.
  8807. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  8808. */
  8809. void removeRedundantPaths();
  8810. /** Removes any directories that don't actually exist. */
  8811. void removeNonExistentPaths();
  8812. /** Searches the path for a wildcard.
  8813. This will search all the directories in the search path in order, adding any
  8814. matching files to the results array.
  8815. @param results an array to append the results to
  8816. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  8817. return files, directories, or both.
  8818. @param searchRecursively whether to recursively search the subdirectories too
  8819. @param wildCardPattern a pattern to match against the filenames
  8820. @returns the number of files added to the array
  8821. @see File::findChildFiles
  8822. */
  8823. int findChildFiles (OwnedArray<File>& results,
  8824. const int whatToLookFor,
  8825. const bool searchRecursively,
  8826. const String& wildCardPattern = JUCE_T("*")) const;
  8827. /** Finds out whether a file is inside one of the path's directories.
  8828. This will return true if the specified file is a child of one of the
  8829. directories specified by this path. Note that this doesn't actually do any
  8830. searching or check that the files exist - it just looks at the pathnames
  8831. to work out whether the file would be inside a directory.
  8832. @param fileToCheck the file to look for
  8833. @param checkRecursively if true, then this will return true if the file is inside a
  8834. subfolder of one of the path's directories (at any depth). If false
  8835. it will only return true if the file is actually a direct child
  8836. of one of the directories.
  8837. @see File::isAChildOf
  8838. */
  8839. bool isFileInPath (const File& fileToCheck,
  8840. const bool checkRecursively) const;
  8841. juce_UseDebuggingNewOperator
  8842. private:
  8843. StringArray directories;
  8844. void init (const String& path);
  8845. };
  8846. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  8847. /********* End of inlined file: juce_FileSearchPath.h *********/
  8848. #endif
  8849. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8850. /********* Start of inlined file: juce_NamedPipe.h *********/
  8851. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8852. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  8853. /**
  8854. A cross-process pipe that can have data written to and read from it.
  8855. Two or more processes can use these for inter-process communication.
  8856. @see InterprocessConnection
  8857. */
  8858. class JUCE_API NamedPipe
  8859. {
  8860. public:
  8861. /** Creates a NamedPipe. */
  8862. NamedPipe();
  8863. /** Destructor. */
  8864. ~NamedPipe();
  8865. /** Tries to open a pipe that already exists.
  8866. Returns true if it succeeds.
  8867. */
  8868. bool openExisting (const String& pipeName);
  8869. /** Tries to create a new pipe.
  8870. Returns true if it succeeds.
  8871. */
  8872. bool createNewPipe (const String& pipeName);
  8873. /** Closes the pipe, if it's open. */
  8874. void close();
  8875. /** True if the pipe is currently open. */
  8876. bool isOpen() const throw();
  8877. /** Returns the last name that was used to try to open this pipe. */
  8878. const String getName() const throw();
  8879. /** Reads data from the pipe.
  8880. This will block until another thread has written enough data into the pipe to fill
  8881. the number of bytes specified, or until another thread calls the cancelPendingReads()
  8882. method.
  8883. If the operation fails, it returns -1, otherwise, it will return the number of
  8884. bytes read.
  8885. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  8886. this is a maximum timeout for reading from the pipe.
  8887. */
  8888. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  8889. /** Writes some data to the pipe.
  8890. If the operation fails, it returns -1, otherwise, it will return the number of
  8891. bytes written.
  8892. */
  8893. int write (const void* sourceBuffer, int numBytesToWrite,
  8894. int timeOutMilliseconds = 2000);
  8895. /** If any threads are currently blocked on a read operation, this tells them to abort.
  8896. */
  8897. void cancelPendingReads();
  8898. juce_UseDebuggingNewOperator
  8899. private:
  8900. void* internal;
  8901. String currentPipeName;
  8902. NamedPipe (const NamedPipe&);
  8903. const NamedPipe& operator= (const NamedPipe&);
  8904. bool openInternal (const String& pipeName, const bool createPipe);
  8905. };
  8906. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  8907. /********* End of inlined file: juce_NamedPipe.h *********/
  8908. #endif
  8909. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8910. /********* Start of inlined file: juce_BlowFish.h *********/
  8911. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8912. #define __JUCE_BLOWFISH_JUCEHEADER__
  8913. /**
  8914. BlowFish encryption class.
  8915. */
  8916. class JUCE_API BlowFish
  8917. {
  8918. public:
  8919. /** Creates an object that can encode/decode based on the specified key.
  8920. The key data can be up to 72 bytes long.
  8921. */
  8922. BlowFish (const uint8* keyData, int keyBytes);
  8923. /** Creates a copy of another blowfish object. */
  8924. BlowFish (const BlowFish& other);
  8925. /** Copies another blowfish object. */
  8926. const BlowFish& operator= (const BlowFish& other);
  8927. /** Destructor. */
  8928. ~BlowFish();
  8929. /** Encrypts a pair of 32-bit integers. */
  8930. void encrypt (uint32& data1, uint32& data2) const;
  8931. /** Decrypts a pair of 32-bit integers. */
  8932. void decrypt (uint32& data1, uint32& data2) const;
  8933. juce_UseDebuggingNewOperator
  8934. private:
  8935. uint32 p[18];
  8936. uint32* s[4];
  8937. uint32 F (uint32 x) const;
  8938. };
  8939. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  8940. /********* End of inlined file: juce_BlowFish.h *********/
  8941. #endif
  8942. #ifndef __JUCE_MD5_JUCEHEADER__
  8943. /********* Start of inlined file: juce_MD5.h *********/
  8944. #ifndef __JUCE_MD5_JUCEHEADER__
  8945. #define __JUCE_MD5_JUCEHEADER__
  8946. /**
  8947. MD5 checksum class.
  8948. Create one of these with a block of source data or a string, and it calculates the
  8949. MD5 checksum of that data.
  8950. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  8951. */
  8952. class JUCE_API MD5
  8953. {
  8954. public:
  8955. /** Creates a null MD5 object. */
  8956. MD5();
  8957. /** Creates a copy of another MD5. */
  8958. MD5 (const MD5& other);
  8959. /** Copies another MD5. */
  8960. const MD5& operator= (const MD5& other);
  8961. /** Creates a checksum for a block of binary data. */
  8962. MD5 (const MemoryBlock& data);
  8963. /** Creates a checksum for a block of binary data. */
  8964. MD5 (const char* data, const int numBytes);
  8965. /** Creates a checksum for a string. */
  8966. MD5 (const String& text);
  8967. /** Creates a checksum for the input from a stream.
  8968. This will read up to the given number of bytes from the stream, and produce the
  8969. checksum of that. If the number of bytes to read is negative, it'll read
  8970. until the stream is exhausted.
  8971. */
  8972. MD5 (InputStream& input, int numBytesToRead = -1);
  8973. /** Creates a checksum for a file. */
  8974. MD5 (const File& file);
  8975. /** Destructor. */
  8976. ~MD5();
  8977. /** Returns the checksum as a 16-byte block of data. */
  8978. const MemoryBlock getRawChecksumData() const;
  8979. /** Returns the checksum as a 32-digit hex string. */
  8980. const String toHexString() const;
  8981. /** Compares this to another MD5. */
  8982. bool operator== (const MD5& other) const;
  8983. /** Compares this to another MD5. */
  8984. bool operator!= (const MD5& other) const;
  8985. juce_UseDebuggingNewOperator
  8986. private:
  8987. uint8 result [16];
  8988. struct ProcessContext
  8989. {
  8990. uint8 buffer [64];
  8991. uint32 state [4];
  8992. uint32 count [2];
  8993. ProcessContext();
  8994. void processBlock (const uint8* const data, int dataSize);
  8995. void transform (const uint8* const buffer);
  8996. void finish (uint8* const result);
  8997. };
  8998. void processStream (InputStream& input, int numBytesToRead);
  8999. };
  9000. #endif // __JUCE_MD5_JUCEHEADER__
  9001. /********* End of inlined file: juce_MD5.h *********/
  9002. #endif
  9003. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9004. /********* Start of inlined file: juce_Primes.h *********/
  9005. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9006. #define __JUCE_PRIMES_JUCEHEADER__
  9007. /**
  9008. Prime number creation class.
  9009. This class contains static methods for generating and testing prime numbers.
  9010. @see BitArray
  9011. */
  9012. class JUCE_API Primes
  9013. {
  9014. public:
  9015. /** Creates a random prime number with a given bit-length.
  9016. The certainty parameter specifies how many iterations to use when testing
  9017. for primality. A safe value might be anything over about 20-30.
  9018. */
  9019. static const BitArray createProbablePrime (int bitLength,
  9020. int certainty) throw();
  9021. /** Tests a number to see if it's prime.
  9022. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9023. whether the number is prime.
  9024. The certainty parameter specifies how many iterations to use when testing - a
  9025. safe value might be anything over about 20-30.
  9026. */
  9027. static bool isProbablyPrime (const BitArray& number,
  9028. int certainty) throw();
  9029. };
  9030. #endif // __JUCE_PRIMES_JUCEHEADER__
  9031. /********* End of inlined file: juce_Primes.h *********/
  9032. #endif
  9033. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9034. /********* Start of inlined file: juce_RSAKey.h *********/
  9035. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9036. #define __JUCE_RSAKEY_JUCEHEADER__
  9037. /**
  9038. RSA public/private key-pair encryption class.
  9039. An object of this type makes up one half of a public/private RSA key pair. Use the
  9040. createKeyPair() method to create a matching pair for encoding/decoding.
  9041. */
  9042. class JUCE_API RSAKey
  9043. {
  9044. public:
  9045. /** Creates a null key object.
  9046. Initialise a pair of objects for use with the createKeyPair() method.
  9047. */
  9048. RSAKey() throw();
  9049. /** Loads a key from an encoded string representation.
  9050. This reloads a key from a string created by the toString() method.
  9051. */
  9052. RSAKey (const String& stringRepresentation) throw();
  9053. /** Destructor. */
  9054. ~RSAKey() throw();
  9055. /** Turns the key into a string representation.
  9056. This can be reloaded using the constructor that takes a string.
  9057. */
  9058. const String toString() const throw();
  9059. /** Encodes or decodes a value.
  9060. Call this on the public key object to encode some data, then use the matching
  9061. private key object to decode it.
  9062. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9063. */
  9064. bool applyToValue (BitArray& value) const throw();
  9065. /** Creates a public/private key-pair.
  9066. Each key will perform one-way encryption that can only be reversed by
  9067. using the other key.
  9068. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9069. sizes are more secure, but this method will take longer to execute.
  9070. */
  9071. static void createKeyPair (RSAKey& publicKey,
  9072. RSAKey& privateKey,
  9073. const int numBits) throw();
  9074. juce_UseDebuggingNewOperator
  9075. protected:
  9076. BitArray part1, part2;
  9077. };
  9078. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9079. /********* End of inlined file: juce_RSAKey.h *********/
  9080. #endif
  9081. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9082. /********* Start of inlined file: juce_Socket.h *********/
  9083. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9084. #define __JUCE_SOCKET_JUCEHEADER__
  9085. /**
  9086. A wrapper for a streaming (TCP) socket.
  9087. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9088. sockets, you could also try the InterprocessConnection class.
  9089. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9090. */
  9091. class JUCE_API StreamingSocket
  9092. {
  9093. public:
  9094. /** Creates an uninitialised socket.
  9095. To connect it, use the connect() method, after which you can read() or write()
  9096. to it.
  9097. To wait for other sockets to connect to this one, the createListener() method
  9098. enters "listener" mode, and can be used to spawn new sockets for each connection
  9099. that comes along.
  9100. */
  9101. StreamingSocket();
  9102. /** Destructor. */
  9103. ~StreamingSocket();
  9104. /** Binds the socket to the specified local port.
  9105. @returns true on success; false may indicate that another socket is already bound
  9106. on the same port
  9107. */
  9108. bool bindToPort (const int localPortNumber);
  9109. /** Tries to connect the socket to hostname:port.
  9110. If timeOutMillisecs is 0, then this method will block until the operating system
  9111. rejects the connection (which could take a long time).
  9112. @returns true if it succeeds.
  9113. @see isConnected
  9114. */
  9115. bool connect (const String& remoteHostname,
  9116. const int remotePortNumber,
  9117. const int timeOutMillisecs = 3000);
  9118. /** True if the socket is currently connected. */
  9119. bool isConnected() const throw() { return connected; }
  9120. /** Closes the connection. */
  9121. void close();
  9122. /** Returns the name of the currently connected host. */
  9123. const String& getHostName() const throw() { return hostName; }
  9124. /** Returns the port number that's currently open. */
  9125. int getPort() const throw() { return portNumber; }
  9126. /** True if the socket is connected to this machine rather than over the network. */
  9127. bool isLocal() const throw();
  9128. /** Waits until the socket is ready for reading or writing.
  9129. If readyForReading is true, it will wait until the socket is ready for
  9130. reading; if false, it will wait until it's ready for writing.
  9131. If the timeout is < 0, it will wait forever, or else will give up after
  9132. the specified time.
  9133. If the socket is ready on return, this returns 1. If it times-out before
  9134. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9135. */
  9136. int waitUntilReady (const bool readyForReading,
  9137. const int timeoutMsecs) const;
  9138. /** Reads bytes from the socket (blocking).
  9139. Note that this method will block unless you have checked the socket is ready
  9140. for reading before calling it (see the waitUntilReady() method).
  9141. @returns the number of bytes read, or -1 if there was an error.
  9142. */
  9143. int read (void* destBuffer, const int maxBytesToRead);
  9144. /** Writes bytes to the socket from a buffer.
  9145. Note that this method will block unless you have checked the socket is ready
  9146. for writing before calling it (see the waitUntilReady() method).
  9147. @returns the number of bytes written, or -1 if there was an error.
  9148. */
  9149. int write (const void* sourceBuffer, const int numBytesToWrite);
  9150. /** Puts this socket into "listener" mode.
  9151. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9152. which will spawn new sockets for each new connection, so that these can
  9153. be handled in parallel by other threads.
  9154. This returns true if it manages to open the socket successfully.
  9155. @see waitForNextConnection
  9156. */
  9157. bool createListener (const int portNumber);
  9158. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9159. socket.
  9160. The object that gets returned will be owned by the caller.
  9161. This method can only be called after using createListener().
  9162. @see createListener
  9163. */
  9164. StreamingSocket* waitForNextConnection() const;
  9165. juce_UseDebuggingNewOperator
  9166. private:
  9167. String hostName;
  9168. int volatile portNumber, handle;
  9169. bool connected, isListener;
  9170. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9171. StreamingSocket (const StreamingSocket&);
  9172. const StreamingSocket& operator= (const StreamingSocket&);
  9173. };
  9174. /**
  9175. A wrapper for a datagram (UDP) socket.
  9176. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9177. sockets, you could also try the InterprocessConnection class.
  9178. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9179. */
  9180. class JUCE_API DatagramSocket
  9181. {
  9182. public:
  9183. /**
  9184. Creates an (uninitialised) datagram socket.
  9185. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9186. the port number is assigned by the operating system.
  9187. To use the socket for sending, call the connect() method. This will not immediately
  9188. make a connection, but will save the destination you've provided. After this, you can
  9189. call read() or write().
  9190. To wait for other sockets to connect to this one, call waitForNextConnection().
  9191. */
  9192. DatagramSocket (const int localPortNumber);
  9193. /** Destructor. */
  9194. ~DatagramSocket();
  9195. /** Binds the socket to the specified local port.
  9196. @returns true on success; false may indicate that another socket is already bound
  9197. on the same port
  9198. */
  9199. bool bindToPort (const int localPortNumber);
  9200. /** Tries to connect the socket to hostname:port.
  9201. If timeOutMillisecs is 0, then this method will block until the operating system
  9202. rejects the connection (which could take a long time).
  9203. @returns true if it succeeds.
  9204. @see isConnected
  9205. */
  9206. bool connect (const String& remoteHostname,
  9207. const int remotePortNumber,
  9208. const int timeOutMillisecs = 3000);
  9209. /** True if the socket is currently connected. */
  9210. bool isConnected() const throw() { return connected; }
  9211. /** Closes the connection. */
  9212. void close();
  9213. /** Returns the name of the currently connected host. */
  9214. const String& getHostName() const throw() { return hostName; }
  9215. /** Returns the port number that's currently open. */
  9216. int getPort() const throw() { return portNumber; }
  9217. /** True if the socket is connected to this machine rather than over the network. */
  9218. bool isLocal() const throw();
  9219. /** Waits until the socket is ready for reading or writing.
  9220. If readyForReading is true, it will wait until the socket is ready for
  9221. reading; if false, it will wait until it's ready for writing.
  9222. If the timeout is < 0, it will wait forever, or else will give up after
  9223. the specified time.
  9224. If the socket is ready on return, this returns 1. If it times-out before
  9225. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9226. */
  9227. int waitUntilReady (const bool readyForReading,
  9228. const int timeoutMsecs) const;
  9229. /** Reads bytes from the socket (blocking).
  9230. Note that this method will block unless you have checked the socket is ready
  9231. for reading before calling it (see the waitUntilReady() method).
  9232. @returns the number of bytes read, or -1 if there was an error.
  9233. */
  9234. int read (void* destBuffer, const int maxBytesToRead);
  9235. /** Writes bytes to the socket from a buffer.
  9236. Note that this method will block unless you have checked the socket is ready
  9237. for writing before calling it (see the waitUntilReady() method).
  9238. @returns the number of bytes written, or -1 if there was an error.
  9239. */
  9240. int write (const void* sourceBuffer, const int numBytesToWrite);
  9241. /** This waits for incoming data to be sent, and returns a socket that can be used
  9242. to read it.
  9243. The object that gets returned is owned by the caller, and can't be used for
  9244. sending, but can be used to read the data.
  9245. */
  9246. DatagramSocket* waitForNextConnection() const;
  9247. juce_UseDebuggingNewOperator
  9248. private:
  9249. String hostName;
  9250. int volatile portNumber, handle;
  9251. bool connected;
  9252. void* serverAddress;
  9253. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9254. DatagramSocket (const DatagramSocket&);
  9255. const DatagramSocket& operator= (const DatagramSocket&);
  9256. };
  9257. #endif // __JUCE_SOCKET_JUCEHEADER__
  9258. /********* End of inlined file: juce_Socket.h *********/
  9259. #endif
  9260. #ifndef __JUCE_URL_JUCEHEADER__
  9261. /********* Start of inlined file: juce_URL.h *********/
  9262. #ifndef __JUCE_URL_JUCEHEADER__
  9263. #define __JUCE_URL_JUCEHEADER__
  9264. /**
  9265. Represents a URL and has a bunch of useful functions to manipulate it.
  9266. This class can be used to launch URLs in browsers, and also to create
  9267. InputStreams that can read from remote http or ftp sources.
  9268. */
  9269. class JUCE_API URL
  9270. {
  9271. public:
  9272. /** Creates an empty URL. */
  9273. URL() throw();
  9274. /** Creates a URL from a string. */
  9275. URL (const String& url);
  9276. /** Creates a copy of another URL. */
  9277. URL (const URL& other);
  9278. /** Destructor. */
  9279. ~URL() throw();
  9280. /** Copies this URL from another one. */
  9281. const URL& operator= (const URL& other);
  9282. /** Returns a string version of the URL.
  9283. If includeGetParameters is true and any parameters have been set with the
  9284. withParameter() method, then the string will have these appended on the
  9285. end and url-encoded.
  9286. */
  9287. const String toString (const bool includeGetParameters) const;
  9288. /** True if it seems to be valid. */
  9289. bool isWellFormed() const;
  9290. /** Returns a copy of this URL, with a GET parameter added to the end.
  9291. Any control characters in the value will be encoded.
  9292. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  9293. would produce a new url whose toString(true) method would return
  9294. "www.fish.com?amount=some+fish".
  9295. */
  9296. const URL withParameter (const String& parameterName,
  9297. const String& parameterValue) const;
  9298. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  9299. When performing a POST where one of your parameters is a binary file, this
  9300. lets you specify the file.
  9301. Note that the filename is stored, but the file itself won't actually be read
  9302. until this URL is later used to create a network input stream.
  9303. */
  9304. const URL withFileToUpload (const String& parameterName,
  9305. const File& fileToUpload,
  9306. const String& mimeType) const;
  9307. /** Returns a set of all the parameters encoded into the url.
  9308. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  9309. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  9310. The values returned will have been cleaned up to remove any escape characters.
  9311. @see getNamedParameter, withParameter
  9312. */
  9313. const StringPairArray& getParameters() const throw();
  9314. /** Returns the set of files that should be uploaded as part of a POST operation.
  9315. This is the set of files that were added to the URL with the withFileToUpload()
  9316. method.
  9317. */
  9318. const StringPairArray& getFilesToUpload() const throw();
  9319. /** Returns the set of mime types associated with each of the upload files.
  9320. */
  9321. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  9322. /** Tries to launch the system's default browser to open the URL.
  9323. Returns true if this seems to have worked.
  9324. */
  9325. bool launchInDefaultBrowser() const;
  9326. /** Takes a guess as to whether a string might be a valid website address.
  9327. This isn't foolproof!
  9328. */
  9329. static bool isProbablyAWebsiteURL (const String& possibleURL);
  9330. /** Takes a guess as to whether a string might be a valid email address.
  9331. This isn't foolproof!
  9332. */
  9333. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  9334. /** This callback function can be used by the createInputStream() method.
  9335. It allows your app to receive progress updates during a lengthy POST operation. If you
  9336. want to continue the operation, this should return true, or false to abort.
  9337. */
  9338. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  9339. /** Attempts to open a stream that can read from this URL.
  9340. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  9341. the paramters, otherwise it'll encode them into the
  9342. URL and do a 'GET'.
  9343. @param progressCallback if this is non-zero, it lets you supply a callback function
  9344. to keep track of the operation's progress. This can be useful
  9345. for lengthy POST operations, so that you can provide user feedback.
  9346. @param progressCallbackContext if a callback is specified, this value will be passed to
  9347. the function
  9348. @param extraHeaders if not empty, this string is appended onto the headers that
  9349. are used for the request. It must therefore be a valid set of HTML
  9350. header directives, separated by newlines.
  9351. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  9352. a negative number, it will be infinite. Otherwise it specifies a
  9353. time in milliseconds.
  9354. */
  9355. InputStream* createInputStream (const bool usePostCommand,
  9356. OpenStreamProgressCallback* const progressCallback = 0,
  9357. void* const progressCallbackContext = 0,
  9358. const String& extraHeaders = String::empty,
  9359. const int connectionTimeOutMs = 0) const;
  9360. /** Tries to download the entire contents of this URL into a binary data block.
  9361. If it succeeds, this will return true and append the data it read onto the end
  9362. of the memory block.
  9363. @param destData the memory block to append the new data to
  9364. @param usePostCommand whether to use a POST command to get the data (uses
  9365. a GET command if this is false)
  9366. @see readEntireTextStream, readEntireXmlStream
  9367. */
  9368. bool readEntireBinaryStream (MemoryBlock& destData,
  9369. const bool usePostCommand = false) const;
  9370. /** Tries to download the entire contents of this URL as a string.
  9371. If it fails, this will return an empty string, otherwise it will return the
  9372. contents of the downloaded file. If you need to distinguish between a read
  9373. operation that fails and one that returns an empty string, you'll need to use
  9374. a different method, such as readEntireBinaryStream().
  9375. @param usePostCommand whether to use a POST command to get the data (uses
  9376. a GET command if this is false)
  9377. @see readEntireBinaryStream, readEntireXmlStream
  9378. */
  9379. const String readEntireTextStream (const bool usePostCommand = false) const;
  9380. /** Tries to download the entire contents of this URL and parse it as XML.
  9381. If it fails, or if the text that it reads can't be parsed as XML, this will
  9382. return 0.
  9383. When it returns a valid XmlElement object, the caller is responsibile for deleting
  9384. this object when no longer needed.
  9385. @param usePostCommand whether to use a POST command to get the data (uses
  9386. a GET command if this is false)
  9387. @see readEntireBinaryStream, readEntireTextStream
  9388. */
  9389. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  9390. /** Adds escape sequences to a string to encode any characters that aren't
  9391. legal in a URL.
  9392. E.g. any spaces will be replaced with "%20".
  9393. This is the opposite of removeEscapeChars().
  9394. If isParameter is true, it means that the string is going to be used
  9395. as a parameter, so it also encodes '$' and ',' (which would otherwise
  9396. be legal in a URL.
  9397. @see removeEscapeChars
  9398. */
  9399. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  9400. const bool isParameter);
  9401. /** Replaces any escape character sequences in a string with their original
  9402. character codes.
  9403. E.g. any instances of "%20" will be replaced by a space.
  9404. This is the opposite of addEscapeChars().
  9405. @see addEscapeChars
  9406. */
  9407. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  9408. juce_UseDebuggingNewOperator
  9409. private:
  9410. String url;
  9411. StringPairArray parameters, filesToUpload, mimeTypes;
  9412. };
  9413. #endif // __JUCE_URL_JUCEHEADER__
  9414. /********* End of inlined file: juce_URL.h *********/
  9415. #endif
  9416. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9417. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9418. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9419. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9420. /** Wraps another input stream, and reads from it using an intermediate buffer
  9421. If you're using an input stream such as a file input stream, and making lots of
  9422. small read accesses to it, it's probably sensible to wrap it in one of these,
  9423. so that the source stream gets accessed in larger chunk sizes, meaning less
  9424. work for the underlying stream.
  9425. */
  9426. class JUCE_API BufferedInputStream : public InputStream
  9427. {
  9428. public:
  9429. /** Creates a BufferedInputStream from an input source.
  9430. @param sourceStream the source stream to read from
  9431. @param bufferSize the size of reservoir to use to buffer the source
  9432. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9433. deleted by this object when it is itself deleted.
  9434. */
  9435. BufferedInputStream (InputStream* const sourceStream,
  9436. const int bufferSize,
  9437. const bool deleteSourceWhenDestroyed) throw();
  9438. /** Destructor.
  9439. This may also delete the source stream, if that option was chosen when the
  9440. buffered stream was created.
  9441. */
  9442. ~BufferedInputStream() throw();
  9443. int64 getTotalLength();
  9444. int64 getPosition();
  9445. bool setPosition (int64 newPosition);
  9446. int read (void* destBuffer, int maxBytesToRead);
  9447. const String readString();
  9448. bool isExhausted();
  9449. juce_UseDebuggingNewOperator
  9450. private:
  9451. InputStream* const source;
  9452. const bool deleteSourceWhenDestroyed;
  9453. int bufferSize;
  9454. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9455. char* buffer;
  9456. void ensureBuffered();
  9457. BufferedInputStream (const BufferedInputStream&);
  9458. const BufferedInputStream& operator= (const BufferedInputStream&);
  9459. };
  9460. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9461. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9462. #endif
  9463. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9464. /********* Start of inlined file: juce_FileInputSource.h *********/
  9465. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9466. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9467. /********* Start of inlined file: juce_InputSource.h *********/
  9468. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9469. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9470. /**
  9471. A lightweight object that can create a stream to read some kind of resource.
  9472. This may be used to refer to a file, or some other kind of source, allowing a
  9473. caller to create an input stream that can read from it when required.
  9474. @see FileInputSource
  9475. */
  9476. class JUCE_API InputSource
  9477. {
  9478. public:
  9479. InputSource() throw() {}
  9480. /** Destructor. */
  9481. virtual ~InputSource() {}
  9482. /** Returns a new InputStream to read this item.
  9483. @returns an inputstream that the caller will delete, or 0 if
  9484. the filename isn't found.
  9485. */
  9486. virtual InputStream* createInputStream() = 0;
  9487. /** Returns a new InputStream to read an item, relative.
  9488. @param relatedItemPath the relative pathname of the resource that is required
  9489. @returns an inputstream that the caller will delete, or 0 if
  9490. the item isn't found.
  9491. */
  9492. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9493. /** Returns a hash code that uniquely represents this item.
  9494. */
  9495. virtual int64 hashCode() const = 0;
  9496. juce_UseDebuggingNewOperator
  9497. };
  9498. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9499. /********* End of inlined file: juce_InputSource.h *********/
  9500. /**
  9501. A type of InputSource that represents a normal file.
  9502. @see InputSource
  9503. */
  9504. class JUCE_API FileInputSource : public InputSource
  9505. {
  9506. public:
  9507. FileInputSource (const File& file) throw();
  9508. ~FileInputSource();
  9509. InputStream* createInputStream();
  9510. InputStream* createInputStreamFor (const String& relatedItemPath);
  9511. int64 hashCode() const;
  9512. juce_UseDebuggingNewOperator
  9513. private:
  9514. const File file;
  9515. FileInputSource (const FileInputSource&);
  9516. const FileInputSource& operator= (const FileInputSource&);
  9517. };
  9518. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9519. /********* End of inlined file: juce_FileInputSource.h *********/
  9520. #endif
  9521. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9522. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9523. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9524. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9525. /**
  9526. A stream which uses zlib to compress the data written into it.
  9527. @see GZIPDecompressorInputStream
  9528. */
  9529. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9530. {
  9531. public:
  9532. /** Creates a compression stream.
  9533. @param destStream the stream into which the compressed data should
  9534. be written
  9535. @param compressionLevel how much to compress the data, between 1 and 9, where
  9536. 1 is the fastest/lowest compression, and 9 is the
  9537. slowest/highest compression. Any value outside this range
  9538. indicates that a default compression level should be used.
  9539. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9540. this stream is destroyed
  9541. @param noWrap this is used internally by the ZipFile class
  9542. and should be ignored by user applications
  9543. */
  9544. GZIPCompressorOutputStream (OutputStream* const destStream,
  9545. int compressionLevel = 0,
  9546. const bool deleteDestStreamWhenDestroyed = false,
  9547. const bool noWrap = false);
  9548. /** Destructor. */
  9549. ~GZIPCompressorOutputStream();
  9550. void flush();
  9551. int64 getPosition();
  9552. bool setPosition (int64 newPosition);
  9553. bool write (const void* destBuffer, int howMany);
  9554. juce_UseDebuggingNewOperator
  9555. private:
  9556. OutputStream* const destStream;
  9557. const bool deleteDestStream;
  9558. uint8* buffer;
  9559. void* helper;
  9560. bool doNextBlock();
  9561. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9562. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9563. };
  9564. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9565. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9566. #endif
  9567. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9568. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9569. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9570. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9571. /**
  9572. This stream will decompress a source-stream using zlib.
  9573. Tip: if you're reading lots of small items from one of these streams, you
  9574. can increase the performance enormously by passing it through a
  9575. BufferedInputStream, so that it has to read larger blocks less often.
  9576. @see GZIPCompressorOutputStream
  9577. */
  9578. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9579. {
  9580. public:
  9581. /** Creates a decompressor stream.
  9582. @param sourceStream the stream to read from
  9583. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9584. when this object is destroyed
  9585. @param noWrap this is used internally by the ZipFile class
  9586. and should be ignored by user applications
  9587. @param uncompressedStreamLength if the creator knows the length that the
  9588. uncompressed stream will be, then it can supply this
  9589. value, which will be returned by getTotalLength()
  9590. */
  9591. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9592. const bool deleteSourceWhenDestroyed,
  9593. const bool noWrap = false,
  9594. const int64 uncompressedStreamLength = -1);
  9595. /** Destructor. */
  9596. ~GZIPDecompressorInputStream();
  9597. int64 getPosition();
  9598. bool setPosition (int64 pos);
  9599. int64 getTotalLength();
  9600. bool isExhausted();
  9601. int read (void* destBuffer, int maxBytesToRead);
  9602. juce_UseDebuggingNewOperator
  9603. private:
  9604. InputStream* const sourceStream;
  9605. const int64 uncompressedStreamLength;
  9606. const bool deleteSourceWhenDestroyed, noWrap;
  9607. bool isEof;
  9608. int activeBufferSize;
  9609. int64 originalSourcePos, currentPos;
  9610. uint8* buffer;
  9611. void* helper;
  9612. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9613. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9614. };
  9615. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9616. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9617. #endif
  9618. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9619. #endif
  9620. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9621. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9622. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9623. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9624. /**
  9625. Allows a block of data and to be accessed as a stream.
  9626. This can either be used to refer to a shared block of memory, or can make its
  9627. own internal copy of the data when the MemoryInputStream is created.
  9628. */
  9629. class JUCE_API MemoryInputStream : public InputStream
  9630. {
  9631. public:
  9632. /** Creates a MemoryInputStream.
  9633. @param sourceData the block of data to use as the stream's source
  9634. @param sourceDataSize the number of bytes in the source data block
  9635. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9636. the source data, so this data shouldn't be changed
  9637. for the lifetime of the stream; if this parameter is
  9638. true, the stream will make its own copy of the
  9639. data and use that.
  9640. */
  9641. MemoryInputStream (const void* const sourceData,
  9642. const int sourceDataSize,
  9643. const bool keepInternalCopyOfData) throw();
  9644. /** Destructor. */
  9645. ~MemoryInputStream() throw();
  9646. int64 getPosition();
  9647. bool setPosition (int64 pos);
  9648. int64 getTotalLength();
  9649. bool isExhausted();
  9650. int read (void* destBuffer, int maxBytesToRead);
  9651. juce_UseDebuggingNewOperator
  9652. private:
  9653. const char* data;
  9654. int dataSize, position;
  9655. MemoryBlock internalCopy;
  9656. };
  9657. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9658. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9659. #endif
  9660. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9661. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9662. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9663. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9664. /** Writes data to an internal memory buffer, which grows as required.
  9665. The data that was written into the stream can then be accessed later as
  9666. a contiguous block of memory.
  9667. */
  9668. class JUCE_API MemoryOutputStream : public OutputStream
  9669. {
  9670. public:
  9671. /** Creates a memory stream ready for writing into.
  9672. @param initialSize the intial amount of space to allocate for writing into
  9673. @param granularity the increments by which the internal storage will be increased
  9674. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9675. place that the data gets stored. If it's zero, the stream
  9676. will allocate its own storage internally, which you can
  9677. access using getData() and getDataSize()
  9678. */
  9679. MemoryOutputStream (const int initialSize = 256,
  9680. const int granularity = 256,
  9681. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9682. /** Destructor.
  9683. This will free any data that was written to it.
  9684. */
  9685. ~MemoryOutputStream() throw();
  9686. /** Returns a pointer to the data that has been written to the stream.
  9687. @see getDataSize
  9688. */
  9689. const char* getData() throw();
  9690. /** Returns the number of bytes of data that have been written to the stream.
  9691. @see getData
  9692. */
  9693. int getDataSize() const throw();
  9694. /** Resets the stream, clearing any data that has been written to it so far. */
  9695. void reset() throw();
  9696. void flush();
  9697. bool write (const void* buffer, int howMany);
  9698. int64 getPosition();
  9699. bool setPosition (int64 newPosition);
  9700. juce_UseDebuggingNewOperator
  9701. private:
  9702. MemoryBlock* data;
  9703. int position, size, blockSize;
  9704. bool ownsMemoryBlock;
  9705. };
  9706. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9707. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9708. #endif
  9709. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9710. /********* Start of inlined file: juce_SubregionStream.h *********/
  9711. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9712. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9713. /** Wraps another input stream, and reads from a specific part of it.
  9714. This lets you take a subsection of a stream and present it as an entire
  9715. stream in its own right.
  9716. */
  9717. class JUCE_API SubregionStream : public InputStream
  9718. {
  9719. public:
  9720. /** Creates a SubregionStream from an input source.
  9721. @param sourceStream the source stream to read from
  9722. @param startPositionInSourceStream this is the position in the source stream that
  9723. corresponds to position 0 in this stream
  9724. @param lengthOfSourceStream this specifies the maximum number of bytes
  9725. from the source stream that will be passed through
  9726. by this stream. When the position of this stream
  9727. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9728. If the length passed in here is greater than the length
  9729. of the source stream (as returned by getTotalLength()),
  9730. then the smaller value will be used.
  9731. Passing a negative value for this parameter means it
  9732. will keep reading until the source's end-of-stream.
  9733. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9734. deleted by this object when it is itself deleted.
  9735. */
  9736. SubregionStream (InputStream* const sourceStream,
  9737. const int64 startPositionInSourceStream,
  9738. const int64 lengthOfSourceStream,
  9739. const bool deleteSourceWhenDestroyed) throw();
  9740. /** Destructor.
  9741. This may also delete the source stream, if that option was chosen when the
  9742. buffered stream was created.
  9743. */
  9744. ~SubregionStream() throw();
  9745. int64 getTotalLength();
  9746. int64 getPosition();
  9747. bool setPosition (int64 newPosition);
  9748. int read (void* destBuffer, int maxBytesToRead);
  9749. bool isExhausted();
  9750. juce_UseDebuggingNewOperator
  9751. private:
  9752. InputStream* const source;
  9753. const bool deleteSourceWhenDestroyed;
  9754. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9755. SubregionStream (const SubregionStream&);
  9756. const SubregionStream& operator= (const SubregionStream&);
  9757. };
  9758. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9759. /********* End of inlined file: juce_SubregionStream.h *********/
  9760. #endif
  9761. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9762. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9763. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9764. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9765. /** A timer for measuring performance of code and dumping the results to a file.
  9766. e.g. @code
  9767. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9768. for (;;)
  9769. {
  9770. pc.start();
  9771. doSomethingFishy();
  9772. pc.stop();
  9773. }
  9774. @endcode
  9775. In this example, the time of each period between calling start/stop will be
  9776. measured and averaged over 50 runs, and the results printed to a file
  9777. every 50 times round the loop.
  9778. */
  9779. class JUCE_API PerformanceCounter
  9780. {
  9781. public:
  9782. /** Creates a PerformanceCounter object.
  9783. @param counterName the name used when printing out the statistics
  9784. @param runsPerPrintout the number of start/stop iterations before calling
  9785. printStatistics()
  9786. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9787. the results are just written to the debugger output
  9788. */
  9789. PerformanceCounter (const String& counterName,
  9790. int runsPerPrintout = 100,
  9791. const File& loggingFile = File::nonexistent);
  9792. /** Destructor. */
  9793. ~PerformanceCounter();
  9794. /** Starts timing.
  9795. @see stop
  9796. */
  9797. void start();
  9798. /** Stops timing and prints out the results.
  9799. The number of iterations before doing a printout of the
  9800. results is set in the constructor.
  9801. @see start
  9802. */
  9803. void stop();
  9804. /** Dumps the current metrics to the debugger output and to a file.
  9805. As well as using Logger::outputDebugString to print the results,
  9806. this will write then to the file specified in the constructor (if
  9807. this was valid).
  9808. */
  9809. void printStatistics();
  9810. juce_UseDebuggingNewOperator
  9811. private:
  9812. String name;
  9813. int numRuns, runsPerPrint;
  9814. double totalTime;
  9815. int64 started;
  9816. File outputFile;
  9817. };
  9818. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9819. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9820. #endif
  9821. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9822. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9823. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9824. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9825. /**
  9826. A collection of miscellaneous platform-specific utilities.
  9827. */
  9828. class JUCE_API PlatformUtilities
  9829. {
  9830. public:
  9831. /** Plays the operating system's default alert 'beep' sound. */
  9832. static void beep();
  9833. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9834. const String& emailSubject,
  9835. const String& bodyText,
  9836. const StringArray& filesToAttach);
  9837. #if JUCE_MAC || DOXYGEN
  9838. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9839. static const String cfStringToJuceString (CFStringRef cfString);
  9840. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9841. static CFStringRef juceStringToCFString (const String& s);
  9842. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9843. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9844. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9845. static const String makePathFromFSRef (FSRef* file);
  9846. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9847. their precomposed equivalents.
  9848. */
  9849. static const String convertToPrecomposedUnicode (const String& s);
  9850. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9851. static OSType getTypeOfFile (const String& filename);
  9852. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9853. static bool isBundle (const String& filename);
  9854. #endif
  9855. #if JUCE_WIN32 || DOXYGEN
  9856. // Some registry helper functions:
  9857. /** WIN32 ONLY - Returns a string from the registry.
  9858. The path is a string for the entire path of a value in the registry,
  9859. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9860. */
  9861. static const String getRegistryValue (const String& regValuePath,
  9862. const String& defaultValue = String::empty);
  9863. /** WIN32 ONLY - Sets a registry value as a string.
  9864. This will take care of creating any groups needed to get to the given
  9865. registry value.
  9866. */
  9867. static void setRegistryValue (const String& regValuePath,
  9868. const String& value);
  9869. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9870. static bool registryValueExists (const String& regValuePath);
  9871. /** WIN32 ONLY - Deletes a registry value. */
  9872. static void deleteRegistryValue (const String& regValuePath);
  9873. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9874. static void deleteRegistryKey (const String& regKeyPath);
  9875. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9876. In a normal Juce application this will be set to the module handle
  9877. of the application executable.
  9878. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9879. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9880. to set the correct module handle in your DllMain() function, because
  9881. the win32 system relies on the correct instance handle when opening windows.
  9882. */
  9883. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9884. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9885. @see getCurrentModuleInstanceHandle()
  9886. */
  9887. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  9888. /** WIN32 ONLY - Gets the command-line params as a string.
  9889. This is needed to avoid unicode problems with the argc type params.
  9890. */
  9891. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  9892. #endif
  9893. /** Clears the floating point unit's flags.
  9894. Only has an effect under win32, currently.
  9895. */
  9896. static void fpuReset();
  9897. #if JUCE_LINUX || JUCE_WIN32
  9898. /** Loads a dynamically-linked library into the process's address space.
  9899. @param pathOrFilename the platform-dependent name and search path
  9900. @returns a handle which can be used by getProcedureEntryPoint(), or
  9901. zero if it fails.
  9902. @see freeDynamicLibrary, getProcedureEntryPoint
  9903. */
  9904. static void* loadDynamicLibrary (const String& pathOrFilename);
  9905. /** Frees a dynamically-linked library.
  9906. @param libraryHandle a handle created by loadDynamicLibrary
  9907. @see loadDynamicLibrary, getProcedureEntryPoint
  9908. */
  9909. static void freeDynamicLibrary (void* libraryHandle);
  9910. /** Finds a procedure call in a dynamically-linked library.
  9911. @param libraryHandle a library handle returned by loadDynamicLibrary
  9912. @param procedureName the name of the procedure call to try to load
  9913. @returns a pointer to the function if found, or 0 if it fails
  9914. @see loadDynamicLibrary
  9915. */
  9916. static void* getProcedureEntryPoint (void* libraryHandle,
  9917. const String& procedureName);
  9918. #endif
  9919. #if JUCE_LINUX || DOXYGEN
  9920. #endif
  9921. };
  9922. #if JUCE_MAC
  9923. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  9924. using RAII.
  9925. */
  9926. class ScopedAutoReleasePool
  9927. {
  9928. public:
  9929. ScopedAutoReleasePool();
  9930. ~ScopedAutoReleasePool();
  9931. private:
  9932. void* pool;
  9933. };
  9934. /**
  9935. A wrapper class for picking up events from an Apple IR remote control device.
  9936. To use it, just create a subclass of this class, implementing the buttonPressed()
  9937. callback, then call start() and stop() to start or stop receiving events.
  9938. */
  9939. class JUCE_API AppleRemoteDevice
  9940. {
  9941. public:
  9942. AppleRemoteDevice();
  9943. virtual ~AppleRemoteDevice();
  9944. /** The set of buttons that may be pressed.
  9945. @see buttonPressed
  9946. */
  9947. enum ButtonType
  9948. {
  9949. menuButton = 0, /**< The menu button (if it's held for a short time). */
  9950. playButton, /**< The play button. */
  9951. plusButton, /**< The plus or volume-up button. */
  9952. minusButton, /**< The minus or volume-down button. */
  9953. rightButton, /**< The right button (if it's held for a short time). */
  9954. leftButton, /**< The left button (if it's held for a short time). */
  9955. rightButton_Long, /**< The right button (if it's held for a long time). */
  9956. leftButton_Long, /**< The menu button (if it's held for a long time). */
  9957. menuButton_Long, /**< The menu button (if it's held for a long time). */
  9958. playButtonSleepMode,
  9959. switched
  9960. };
  9961. /** Override this method to receive the callback about a button press.
  9962. The callback will happen on the application's message thread.
  9963. Some buttons trigger matching up and down events, in which the isDown parameter
  9964. will be true and then false. Others only send a single event when the
  9965. button is pressed.
  9966. */
  9967. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  9968. /** Starts the device running and responding to events.
  9969. Returns true if it managed to open the device.
  9970. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  9971. and will not be available to any other part of the system. If
  9972. false, it will be shared with other apps.
  9973. @see stop
  9974. */
  9975. bool start (const bool inExclusiveMode) throw();
  9976. /** Stops the device running.
  9977. @see start
  9978. */
  9979. void stop() throw();
  9980. /** Returns true if the device has been started successfully.
  9981. */
  9982. bool isActive() const throw();
  9983. /** Returns the ID number of the remote, if it has sent one.
  9984. */
  9985. int getRemoteId() const throw() { return remoteId; }
  9986. juce_UseDebuggingNewOperator
  9987. /** @internal */
  9988. void handleCallbackInternal();
  9989. private:
  9990. void* device;
  9991. void* queue;
  9992. int remoteId;
  9993. bool open (const bool openInExclusiveMode) throw();
  9994. };
  9995. #endif
  9996. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9997. /********* End of inlined file: juce_PlatformUtilities.h *********/
  9998. #endif
  9999. #ifndef __JUCE_UUID_JUCEHEADER__
  10000. /********* Start of inlined file: juce_Uuid.h *********/
  10001. #ifndef __JUCE_UUID_JUCEHEADER__
  10002. #define __JUCE_UUID_JUCEHEADER__
  10003. /**
  10004. A universally unique 128-bit identifier.
  10005. This class generates very random unique numbers based on the system time
  10006. and MAC addresses if any are available. It's extremely unlikely that two identical
  10007. UUIDs would ever be created by chance.
  10008. The class includes methods for saving the ID as a string or as raw binary data.
  10009. */
  10010. class JUCE_API Uuid
  10011. {
  10012. public:
  10013. /** Creates a new unique ID. */
  10014. Uuid();
  10015. /** Destructor. */
  10016. ~Uuid() throw();
  10017. /** Creates a copy of another UUID. */
  10018. Uuid (const Uuid& other);
  10019. /** Copies another UUID. */
  10020. Uuid& operator= (const Uuid& other);
  10021. /** Returns true if the ID is zero. */
  10022. bool isNull() const throw();
  10023. /** Compares two UUIDs. */
  10024. bool operator== (const Uuid& other) const;
  10025. /** Compares two UUIDs. */
  10026. bool operator!= (const Uuid& other) const;
  10027. /** Returns a stringified version of this UUID.
  10028. A Uuid object can later be reconstructed from this string using operator= or
  10029. the constructor that takes a string parameter.
  10030. @returns a 32 character hex string.
  10031. */
  10032. const String toString() const;
  10033. /** Creates an ID from an encoded string version.
  10034. @see toString
  10035. */
  10036. Uuid (const String& uuidString);
  10037. /** Copies from a stringified UUID.
  10038. The string passed in should be one that was created with the toString() method.
  10039. */
  10040. Uuid& operator= (const String& uuidString);
  10041. /** Returns a pointer to the internal binary representation of the ID.
  10042. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10043. the constructor or operator= method that takes an array of uint8s.
  10044. */
  10045. const uint8* getRawData() const throw() { return value.asBytes; }
  10046. /** Creates a UUID from a 16-byte array.
  10047. @see getRawData
  10048. */
  10049. Uuid (const uint8* const rawData);
  10050. /** Sets this UUID from 16-bytes of raw data. */
  10051. Uuid& operator= (const uint8* const rawData);
  10052. juce_UseDebuggingNewOperator
  10053. private:
  10054. union
  10055. {
  10056. uint8 asBytes [16];
  10057. int asInt[4];
  10058. int64 asInt64[2];
  10059. } value;
  10060. };
  10061. #endif // __JUCE_UUID_JUCEHEADER__
  10062. /********* End of inlined file: juce_Uuid.h *********/
  10063. #endif
  10064. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10065. /********* Start of inlined file: juce_ZipFile.h *********/
  10066. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10067. #define __JUCE_ZIPFILE_JUCEHEADER__
  10068. /**
  10069. Decodes a ZIP file from a stream.
  10070. This can enumerate the items in a ZIP file and can create suitable stream objects
  10071. to read each one.
  10072. */
  10073. class JUCE_API ZipFile
  10074. {
  10075. public:
  10076. /** Creates a ZipFile for a given stream.
  10077. @param inputStream the stream to read from
  10078. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10079. will be deleted when this ZipFile object is deleted
  10080. */
  10081. ZipFile (InputStream* const inputStream,
  10082. const bool deleteStreamWhenDestroyed) throw();
  10083. /** Creates a ZipFile based for a file. */
  10084. ZipFile (const File& file);
  10085. /** Creates a ZipFile for an input source.
  10086. The inputSource object will be owned by the zip file, which will delete
  10087. it later when not needed.
  10088. */
  10089. ZipFile (InputSource* const inputSource);
  10090. /** Destructor. */
  10091. ~ZipFile() throw();
  10092. /**
  10093. Contains information about one of the entries in a ZipFile.
  10094. @see ZipFile::getEntry
  10095. */
  10096. struct ZipEntry
  10097. {
  10098. /** The name of the file, which may also include a partial pathname. */
  10099. String filename;
  10100. /** The file's original size. */
  10101. unsigned int uncompressedSize;
  10102. /** The last time the file was modified. */
  10103. Time fileTime;
  10104. };
  10105. /** Returns the number of items in the zip file. */
  10106. int getNumEntries() const throw();
  10107. /** Returns a structure that describes one of the entries in the zip file.
  10108. This may return zero if the index is out of range.
  10109. @see ZipFile::ZipEntry
  10110. */
  10111. const ZipEntry* getEntry (const int index) const throw();
  10112. /** Returns the index of the first entry with a given filename.
  10113. This uses a case-sensitive comparison to look for a filename in the
  10114. list of entries. It might return -1 if no match is found.
  10115. @see ZipFile::ZipEntry
  10116. */
  10117. int getIndexOfFileName (const String& fileName) const throw();
  10118. /** Returns a structure that describes one of the entries in the zip file.
  10119. This uses a case-sensitive comparison to look for a filename in the
  10120. list of entries. It might return 0 if no match is found.
  10121. @see ZipFile::ZipEntry
  10122. */
  10123. const ZipEntry* getEntry (const String& fileName) const throw();
  10124. /** Sorts the list of entries, based on the filename.
  10125. */
  10126. void sortEntriesByFilename();
  10127. /** Creates a stream that can read from one of the zip file's entries.
  10128. The stream that is returned must be deleted by the caller (and
  10129. zero might be returned if a stream can't be opened for some reason).
  10130. The stream must not be used after the ZipFile object that created
  10131. has been deleted.
  10132. */
  10133. InputStream* createStreamForEntry (const int index);
  10134. /** Uncompresses all of the files in the zip file.
  10135. This will expand all the entires into a target directory. The relative
  10136. paths of the entries are used.
  10137. @param targetDirectory the root folder to uncompress to
  10138. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10139. */
  10140. void uncompressTo (const File& targetDirectory,
  10141. const bool shouldOverwriteFiles = true);
  10142. juce_UseDebuggingNewOperator
  10143. private:
  10144. VoidArray entries;
  10145. friend class ZipInputStream;
  10146. CriticalSection lock;
  10147. InputStream* inputStream;
  10148. InputSource* inputSource;
  10149. bool deleteStreamWhenDestroyed;
  10150. int numEntries, centralRecStart;
  10151. #ifdef JUCE_DEBUG
  10152. int numOpenStreams;
  10153. #endif
  10154. void init();
  10155. int findEndOfZipEntryTable (InputStream* in);
  10156. ZipFile (const ZipFile&);
  10157. const ZipFile& operator= (const ZipFile&);
  10158. };
  10159. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10160. /********* End of inlined file: juce_ZipFile.h *********/
  10161. #endif
  10162. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10163. #endif
  10164. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10165. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10166. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10167. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10168. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10169. string into a localised version using the LocalisedStrings class.
  10170. @see LocalisedStrings
  10171. */
  10172. #define TRANS(stringLiteral) \
  10173. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10174. /**
  10175. Used to convert strings to localised foreign-language versions.
  10176. This is basically a look-up table of strings and their translated equivalents.
  10177. It can be loaded from a text file, so that you can supply a set of localised
  10178. versions of strings that you use in your app.
  10179. To use it in your code, simply call the translate() method on each string that
  10180. might have foreign versions, and if none is found, the method will just return
  10181. the original string.
  10182. The translation file should start with some lines specifying a description of
  10183. the language it contains, and also a list of ISO country codes where it might
  10184. be appropriate to use the file. After that, each line of the file should contain
  10185. a pair of quoted strings with an '=' sign.
  10186. E.g. for a french translation, the file might be:
  10187. @code
  10188. language: French
  10189. countries: fr be mc ch lu
  10190. "hello" = "bonjour"
  10191. "goodbye" = "au revoir"
  10192. @endcode
  10193. If the strings need to contain a quote character, they can use '\"' instead, and
  10194. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10195. (you can use this to add comments).
  10196. Note that this is a singleton class, so don't create or destroy the object directly.
  10197. There's also a TRANS(text) macro defined to make it easy to use the this.
  10198. E.g. @code
  10199. printSomething (TRANS("hello"));
  10200. @endcode
  10201. This macro is used in the Juce classes themselves, so your application has a chance to
  10202. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10203. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10204. code).
  10205. */
  10206. class JUCE_API LocalisedStrings
  10207. {
  10208. public:
  10209. /** Creates a set of translations from the text of a translation file.
  10210. When you create one of these, you can call setCurrentMappings() to make it
  10211. the set of mappings that the system's using.
  10212. */
  10213. LocalisedStrings (const String& fileContents) throw();
  10214. /** Creates a set of translations from a 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 File& fileToLoad) throw();
  10219. /** Destructor. */
  10220. ~LocalisedStrings() throw();
  10221. /** Selects the current set of mappings to be used by the system.
  10222. The object you pass in will be automatically deleted when no longer needed, so
  10223. don't keep a pointer to it. You can also pass in zero to remove the current
  10224. mappings.
  10225. See also the TRANS() macro, which uses the current set to do its translation.
  10226. @see translateWithCurrentMappings
  10227. */
  10228. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10229. /** Returns the currently selected set of mappings.
  10230. This is the object that was last passed to setCurrentMappings(). It may
  10231. be 0 if none has been created.
  10232. */
  10233. static LocalisedStrings* getCurrentMappings() throw();
  10234. /** Tries to translate a string using the currently selected set of mappings.
  10235. If no mapping has been set, or if the mapping doesn't contain a translation
  10236. for the string, this will just return the original string.
  10237. See also the TRANS() macro, which uses this method to do its translation.
  10238. @see setCurrentMappings, getCurrentMappings
  10239. */
  10240. static const String translateWithCurrentMappings (const String& text) throw();
  10241. /** Tries to translate a string using the currently selected set of mappings.
  10242. If no mapping has been set, or if the mapping doesn't contain a translation
  10243. for the string, this will just return the original string.
  10244. See also the TRANS() macro, which uses this method to do its translation.
  10245. @see setCurrentMappings, getCurrentMappings
  10246. */
  10247. static const String translateWithCurrentMappings (const char* text) throw();
  10248. /** Attempts to look up a string and return its localised version.
  10249. If the string isn't found in the list, the original string will be returned.
  10250. */
  10251. const String translate (const String& text) const throw();
  10252. /** Returns the name of the language specified in the translation file.
  10253. This is specified in the file using a line starting with "language:", e.g.
  10254. @code
  10255. language: german
  10256. @endcode
  10257. */
  10258. const String getLanguageName() const throw() { return languageName; }
  10259. /** Returns the list of suitable country codes listed in the translation file.
  10260. These is specified in the file using a line starting with "countries:", e.g.
  10261. @code
  10262. countries: fr be mc ch lu
  10263. @endcode
  10264. The country codes are supposed to be 2-character ISO complient codes.
  10265. */
  10266. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10267. juce_UseDebuggingNewOperator
  10268. private:
  10269. String languageName;
  10270. StringArray countryCodes;
  10271. StringPairArray translations;
  10272. void loadFromText (const String& fileContents) throw();
  10273. };
  10274. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10275. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10276. #endif
  10277. #ifndef __JUCE_STRING_JUCEHEADER__
  10278. #endif
  10279. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10280. #endif
  10281. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10282. #endif
  10283. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10284. /********* Start of inlined file: juce_XmlDocument.h *********/
  10285. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10286. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10287. /**
  10288. Parses a text-based XML document and creates an XmlElement object from it.
  10289. The parser will parse DTDs to load external entities but won't
  10290. check the document for validity against the DTD.
  10291. e.g.
  10292. @code
  10293. XmlDocument myDocument (File ("myfile.xml"));
  10294. XmlElement* mainElement = myDocument.getDocumentElement();
  10295. if (mainElement == 0)
  10296. {
  10297. String error = myDocument.getLastParseError();
  10298. }
  10299. else
  10300. {
  10301. ..use the element
  10302. }
  10303. @endcode
  10304. @see XmlElement
  10305. */
  10306. class JUCE_API XmlDocument
  10307. {
  10308. public:
  10309. /** Creates an XmlDocument from the xml text.
  10310. The text doesn't actually get parsed until the getDocumentElement() method is
  10311. called.
  10312. */
  10313. XmlDocument (const String& documentText) throw();
  10314. /** Creates an XmlDocument from a file.
  10315. The text doesn't actually get parsed until the getDocumentElement() method is
  10316. called.
  10317. */
  10318. XmlDocument (const File& file);
  10319. /** Destructor. */
  10320. ~XmlDocument() throw();
  10321. /** Creates an XmlElement object to represent the main document node.
  10322. This method will do the actual parsing of the text, and if there's a
  10323. parse error, it may returns 0 (and you can find out the error using
  10324. the getLastParseError() method).
  10325. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10326. first section of the file, and will only
  10327. return the outer document element - this
  10328. allows quick checking of large files to
  10329. see if they contain the correct type of
  10330. tag, without having to parse the entire file
  10331. @returns a new XmlElement which the caller will need to delete, or null if
  10332. there was an error.
  10333. @see getLastParseError
  10334. */
  10335. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10336. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10337. @returns the error, or an empty string if there was no error.
  10338. */
  10339. const String& getLastParseError() const throw();
  10340. /** Sets an input source object to use for parsing documents that reference external entities.
  10341. If the document has been created from a file, this probably won't be needed, but
  10342. if you're parsing some text and there might be a DTD that references external
  10343. files, you may need to create a custom input source that can retrieve the
  10344. other files it needs.
  10345. The object that is passed-in will be deleted automatically when no longer needed.
  10346. @see InputSource
  10347. */
  10348. void setInputSource (InputSource* const newSource) throw();
  10349. juce_UseDebuggingNewOperator
  10350. private:
  10351. String originalText;
  10352. const tchar* input;
  10353. bool outOfData, errorOccurred;
  10354. bool identifierLookupTable [128];
  10355. String lastError, dtdText;
  10356. StringArray tokenisedDTD;
  10357. bool needToLoadDTD;
  10358. InputSource* inputSource;
  10359. void setLastError (const String& desc, const bool carryOn) throw();
  10360. void skipHeader() throw();
  10361. void skipNextWhiteSpace() throw();
  10362. tchar readNextChar() throw();
  10363. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10364. void readChildElements (XmlElement* parent) throw();
  10365. int findNextTokenLength() throw();
  10366. void readQuotedString (String& result) throw();
  10367. void readEntity (String& result) throw();
  10368. const String getFileContents (const String& filename) const;
  10369. const String expandEntity (const String& entity);
  10370. const String expandExternalEntity (const String& entity);
  10371. const String getParameterEntity (const String& entity);
  10372. };
  10373. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10374. /********* End of inlined file: juce_XmlDocument.h *********/
  10375. #endif
  10376. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10377. #endif
  10378. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10379. #endif
  10380. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10381. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10382. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10383. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10384. /**
  10385. Acts as a critical section which processes can use to block each other.
  10386. @see CriticalSection
  10387. */
  10388. class JUCE_API InterProcessLock
  10389. {
  10390. public:
  10391. /** Creates a lock object.
  10392. @param name a name that processes will use to identify this lock object
  10393. */
  10394. InterProcessLock (const String& name) throw();
  10395. /** Destructor.
  10396. This will also release the lock if it's currently held by this process.
  10397. */
  10398. ~InterProcessLock() throw();
  10399. /** Attempts to lock the critical section.
  10400. @param timeOutMillisecs how many milliseconds to wait if the lock
  10401. is already held by another process - a value of
  10402. 0 will return immediately, negative values will wait
  10403. forever
  10404. @returns true if the lock could be gained within the timeout period, or
  10405. false if the timeout expired.
  10406. */
  10407. bool enter (int timeOutMillisecs = -1) throw();
  10408. /** Releases the lock if it's currently held by this process.
  10409. */
  10410. void exit() throw();
  10411. juce_UseDebuggingNewOperator
  10412. private:
  10413. void* internal;
  10414. String name;
  10415. int reentrancyLevel;
  10416. InterProcessLock (const InterProcessLock&);
  10417. const InterProcessLock& operator= (const InterProcessLock&);
  10418. };
  10419. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10420. /********* End of inlined file: juce_InterProcessLock.h *********/
  10421. #endif
  10422. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10423. /********* Start of inlined file: juce_Process.h *********/
  10424. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10425. #define __JUCE_PROCESS_JUCEHEADER__
  10426. /** Represents the current executable's process.
  10427. This contains methods for controlling the current application at the
  10428. process-level.
  10429. @see Thread, JUCEApplication
  10430. */
  10431. class JUCE_API Process
  10432. {
  10433. public:
  10434. enum ProcessPriority
  10435. {
  10436. LowPriority = 0,
  10437. NormalPriority = 1,
  10438. HighPriority = 2,
  10439. RealtimePriority = 3
  10440. };
  10441. /** Changes the current process's priority.
  10442. @param priority the process priority, where
  10443. 0=low, 1=normal, 2=high, 3=realtime
  10444. */
  10445. static void setPriority (const ProcessPriority priority);
  10446. /** Kills the current process immediately.
  10447. This is an emergency process terminator that kills the application
  10448. immediately - it's intended only for use only when something goes
  10449. horribly wrong.
  10450. @see JUCEApplication::quit
  10451. */
  10452. static void terminate();
  10453. /** Returns true if this application process is the one that the user is
  10454. currently using.
  10455. */
  10456. static bool isForegroundProcess() throw();
  10457. /** Raises the current process's privilege level.
  10458. Does nothing if this isn't supported by the current OS, or if process
  10459. privilege level is fixed.
  10460. */
  10461. static void raisePrivilege();
  10462. /** Lowers the current process's privilege level.
  10463. Does nothing if this isn't supported by the current OS, or if process
  10464. privilege level is fixed.
  10465. */
  10466. static void lowerPrivilege();
  10467. /** Returns true if this process is being hosted by a debugger.
  10468. */
  10469. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10470. };
  10471. #endif // __JUCE_PROCESS_JUCEHEADER__
  10472. /********* End of inlined file: juce_Process.h *********/
  10473. #endif
  10474. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10475. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10476. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10477. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10478. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10479. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10480. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10481. /**
  10482. Allows threads to wait for events triggered by other threads.
  10483. A thread can call wait() on a WaitableObject, and this will suspend the
  10484. calling thread until another thread wakes it up by calling the signal()
  10485. method.
  10486. */
  10487. class JUCE_API WaitableEvent
  10488. {
  10489. public:
  10490. /** Creates a WaitableEvent object. */
  10491. WaitableEvent() throw();
  10492. /** Destructor.
  10493. If other threads are waiting on this object when it gets deleted, this
  10494. can cause nasty errors, so be careful!
  10495. */
  10496. ~WaitableEvent() throw();
  10497. /** Suspends the calling thread until the event has been signalled.
  10498. This will wait until the object's signal() method is called by another thread,
  10499. or until the timeout expires.
  10500. After the event has been signalled, this method will return true and reset
  10501. the event.
  10502. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10503. value will cause it to wait forever.
  10504. @returns true if the object has been signalled, false if the timeout expires first.
  10505. @see signal, reset
  10506. */
  10507. bool wait (const int timeOutMilliseconds = -1) const throw();
  10508. /** Wakes up any threads that are currently waiting on this object.
  10509. If signal() is called when nothing is waiting, the next thread to call wait()
  10510. will return immediately and reset the signal.
  10511. @see wait, reset
  10512. */
  10513. void signal() const throw();
  10514. /** Resets the event to an unsignalled state.
  10515. If it's not already signalled, this does nothing.
  10516. */
  10517. void reset() const throw();
  10518. juce_UseDebuggingNewOperator
  10519. private:
  10520. void* internal;
  10521. WaitableEvent (const WaitableEvent&);
  10522. const WaitableEvent& operator= (const WaitableEvent&);
  10523. };
  10524. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10525. /********* End of inlined file: juce_WaitableEvent.h *********/
  10526. /**
  10527. A critical section that allows multiple simultaneous readers.
  10528. Features of this type of lock are:
  10529. - Multiple readers can hold the lock at the same time, but only one writer
  10530. can hold it at once.
  10531. - Writers trying to gain the lock will be blocked until all readers and writers
  10532. have released it
  10533. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  10534. blocked until the writer has obtained and released it
  10535. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  10536. there are no other readers
  10537. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  10538. - Recursive locking is supported.
  10539. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  10540. */
  10541. class JUCE_API ReadWriteLock
  10542. {
  10543. public:
  10544. /**
  10545. Creates a ReadWriteLock object.
  10546. */
  10547. ReadWriteLock() throw();
  10548. /** Destructor.
  10549. If the object is deleted whilst locked, any subsequent behaviour
  10550. is unpredictable.
  10551. */
  10552. ~ReadWriteLock() throw();
  10553. /** Locks this object for reading.
  10554. Multiple threads can simulaneously lock the object for reading, but if another
  10555. thread has it locked for writing, then this will block until it releases the
  10556. lock.
  10557. @see exitRead, ScopedReadLock
  10558. */
  10559. void enterRead() const throw();
  10560. /** Releases the read-lock.
  10561. If the caller thread hasn't got the lock, this can have unpredictable results.
  10562. If the enterRead() method has been called multiple times by the thread, each
  10563. call must be matched by a call to exitRead() before other threads will be allowed
  10564. to take over the lock.
  10565. @see enterRead, ScopedReadLock
  10566. */
  10567. void exitRead() const throw();
  10568. /** Locks this object for writing.
  10569. This will block until any other threads that have it locked for reading or
  10570. writing have released their lock.
  10571. @see exitWrite, ScopedWriteLock
  10572. */
  10573. void enterWrite() const throw();
  10574. /** Tries to lock this object for writing.
  10575. This is like enterWrite(), but doesn't block - it returns true if it manages
  10576. to obtain the lock.
  10577. @see enterWrite
  10578. */
  10579. bool tryEnterWrite() const throw();
  10580. /** Releases the write-lock.
  10581. If the caller thread hasn't got the lock, this can have unpredictable results.
  10582. If the enterWrite() method has been called multiple times by the thread, each
  10583. call must be matched by a call to exit() before other threads will be allowed
  10584. to take over the lock.
  10585. @see enterWrite, ScopedWriteLock
  10586. */
  10587. void exitWrite() const throw();
  10588. juce_UseDebuggingNewOperator
  10589. private:
  10590. CriticalSection accessLock;
  10591. WaitableEvent waitEvent;
  10592. mutable int numWaitingWriters, numWriters;
  10593. mutable int64 writerThreadId;
  10594. mutable Array <int64> readerThreads;
  10595. ReadWriteLock (const ReadWriteLock&);
  10596. const ReadWriteLock& operator= (const ReadWriteLock&);
  10597. };
  10598. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  10599. /********* End of inlined file: juce_ReadWriteLock.h *********/
  10600. #endif
  10601. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  10602. #endif
  10603. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10604. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  10605. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10606. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10607. /**
  10608. Automatically locks and unlocks a ReadWriteLock object.
  10609. Use one of these as a local variable to control access to a ReadWriteLock.
  10610. e.g. @code
  10611. ReadWriteLock myLock;
  10612. for (;;)
  10613. {
  10614. const ScopedReadLock myScopedLock (myLock);
  10615. // myLock is now locked
  10616. ...do some stuff...
  10617. // myLock gets unlocked here.
  10618. }
  10619. @endcode
  10620. @see ReadWriteLock, ScopedWriteLock
  10621. */
  10622. class JUCE_API ScopedReadLock
  10623. {
  10624. public:
  10625. /** Creates a ScopedReadLock.
  10626. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  10627. when the ScopedReadLock object is deleted, the ReadWriteLock will
  10628. be unlocked.
  10629. Make sure this object is created and deleted by the same thread,
  10630. otherwise there are no guarantees what will happen! Best just to use it
  10631. as a local stack object, rather than creating one with the new() operator.
  10632. */
  10633. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  10634. /** Destructor.
  10635. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  10636. Make sure this object is created and deleted by the same thread,
  10637. otherwise there are no guarantees what will happen!
  10638. */
  10639. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  10640. private:
  10641. const ReadWriteLock& lock_;
  10642. ScopedReadLock (const ScopedReadLock&);
  10643. const ScopedReadLock& operator= (const ScopedReadLock&);
  10644. };
  10645. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10646. /********* End of inlined file: juce_ScopedReadLock.h *********/
  10647. #endif
  10648. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10649. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  10650. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10651. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10652. /**
  10653. Automatically tries to lock and unlock a CriticalSection object.
  10654. Use one of these as a local variable to control access to a CriticalSection.
  10655. e.g. @code
  10656. CriticalSection myCriticalSection;
  10657. for (;;)
  10658. {
  10659. const ScopedTryLock myScopedTryLock (myCriticalSection);
  10660. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  10661. // should test this with the isLocked() method before doing your thread-unsafe
  10662. // action..
  10663. if (myScopedTryLock.isLocked())
  10664. {
  10665. ...do some stuff...
  10666. }
  10667. else
  10668. {
  10669. ..our attempt at locking failed because another thread had already locked it..
  10670. }
  10671. // myCriticalSection gets unlocked here (if it was locked)
  10672. }
  10673. @endcode
  10674. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  10675. */
  10676. class JUCE_API ScopedTryLock
  10677. {
  10678. public:
  10679. /** Creates a ScopedTryLock.
  10680. As soon as it is created, this will try to lock the CriticalSection, and
  10681. when the ScopedTryLock object is deleted, the CriticalSection will
  10682. be unlocked if the lock was successful.
  10683. Make sure this object is created and deleted by the same thread,
  10684. otherwise there are no guarantees what will happen! Best just to use it
  10685. as a local stack object, rather than creating one with the new() operator.
  10686. */
  10687. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  10688. /** Destructor.
  10689. The CriticalSection will be unlocked (if locked) when the destructor is called.
  10690. Make sure this object is created and deleted by the same thread,
  10691. otherwise there are no guarantees what will happen!
  10692. */
  10693. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  10694. /** Lock state
  10695. @return True if the CriticalSection is locked.
  10696. */
  10697. bool isLocked() const throw() { return lockWasSuccessful; }
  10698. private:
  10699. const CriticalSection& lock_;
  10700. const bool lockWasSuccessful;
  10701. ScopedTryLock (const ScopedTryLock&);
  10702. const ScopedTryLock& operator= (const ScopedTryLock&);
  10703. };
  10704. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10705. /********* End of inlined file: juce_ScopedTryLock.h *********/
  10706. #endif
  10707. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10708. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  10709. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10710. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10711. /**
  10712. Automatically locks and unlocks a ReadWriteLock object.
  10713. Use one of these as a local variable to control access to a ReadWriteLock.
  10714. e.g. @code
  10715. ReadWriteLock myLock;
  10716. for (;;)
  10717. {
  10718. const ScopedWriteLock myScopedLock (myLock);
  10719. // myLock is now locked
  10720. ...do some stuff...
  10721. // myLock gets unlocked here.
  10722. }
  10723. @endcode
  10724. @see ReadWriteLock, ScopedReadLock
  10725. */
  10726. class JUCE_API ScopedWriteLock
  10727. {
  10728. public:
  10729. /** Creates a ScopedWriteLock.
  10730. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  10731. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  10732. be unlocked.
  10733. Make sure this object is created and deleted by the same thread,
  10734. otherwise there are no guarantees what will happen! Best just to use it
  10735. as a local stack object, rather than creating one with the new() operator.
  10736. */
  10737. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  10738. /** Destructor.
  10739. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  10740. Make sure this object is created and deleted by the same thread,
  10741. otherwise there are no guarantees what will happen!
  10742. */
  10743. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  10744. private:
  10745. const ReadWriteLock& lock_;
  10746. ScopedWriteLock (const ScopedWriteLock&);
  10747. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  10748. };
  10749. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10750. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  10751. #endif
  10752. #ifndef __JUCE_THREAD_JUCEHEADER__
  10753. /********* Start of inlined file: juce_Thread.h *********/
  10754. #ifndef __JUCE_THREAD_JUCEHEADER__
  10755. #define __JUCE_THREAD_JUCEHEADER__
  10756. /**
  10757. Encapsulates a thread.
  10758. Subclasses derive from Thread and implement the run() method, in which they
  10759. do their business. The thread can then be started with the startThread() method
  10760. and controlled with various other methods.
  10761. This class also contains some thread-related static methods, such
  10762. as sleep(), yield(), getCurrentThreadId() etc.
  10763. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10764. MessageManagerLock
  10765. */
  10766. class JUCE_API Thread
  10767. {
  10768. public:
  10769. /**
  10770. Creates a thread.
  10771. When first created, the thread is not running. Use the startThread()
  10772. method to start it.
  10773. */
  10774. Thread (const String& threadName);
  10775. /** Destructor.
  10776. Deleting a Thread object that is running will only give the thread a
  10777. brief opportunity to stop itself cleanly, so it's recommended that you
  10778. should always call stopThread() with a decent timeout before deleting,
  10779. to avoid the thread being forcibly killed (which is a Bad Thing).
  10780. */
  10781. virtual ~Thread();
  10782. /** Must be implemented to perform the thread's actual code.
  10783. Remember that the thread must regularly check the threadShouldExit()
  10784. method whilst running, and if this returns true it should return from
  10785. the run() method as soon as possible to avoid being forcibly killed.
  10786. @see threadShouldExit, startThread
  10787. */
  10788. virtual void run() = 0;
  10789. // Thread control functions..
  10790. /** Starts the thread running.
  10791. This will start the thread's run() method.
  10792. (if it's already started, startThread() won't do anything).
  10793. @see stopThread
  10794. */
  10795. void startThread() throw();
  10796. /** Starts the thread with a given priority.
  10797. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10798. If the thread is already running, its priority will be changed.
  10799. @see startThread, setPriority
  10800. */
  10801. void startThread (const int priority) throw();
  10802. /** Attempts to stop the thread running.
  10803. This method will cause the threadShouldExit() method to return true
  10804. and call notify() in case the thread is currently waiting.
  10805. Hopefully the thread will then respond to this by exiting cleanly, and
  10806. the stopThread method will wait for a given time-period for this to
  10807. happen.
  10808. If the thread is stuck and fails to respond after the time-out, it gets
  10809. forcibly killed, which is a very bad thing to happen, as it could still
  10810. be holding locks, etc. which are needed by other parts of your program.
  10811. @param timeOutMilliseconds The number of milliseconds to wait for the
  10812. thread to finish before killing it by force. A negative
  10813. value in here will wait forever.
  10814. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10815. */
  10816. void stopThread (const int timeOutMilliseconds) throw();
  10817. /** Returns true if the thread is currently active */
  10818. bool isThreadRunning() const throw();
  10819. /** Sets a flag to tell the thread it should stop.
  10820. Calling this means that the threadShouldExit() method will then return true.
  10821. The thread should be regularly checking this to see whether it should exit.
  10822. @see threadShouldExit
  10823. @see waitForThreadToExit
  10824. */
  10825. void signalThreadShouldExit() throw();
  10826. /** Checks whether the thread has been told to stop running.
  10827. Threads need to check this regularly, and if it returns true, they should
  10828. return from their run() method at the first possible opportunity.
  10829. @see signalThreadShouldExit
  10830. */
  10831. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10832. /** Waits for the thread to stop.
  10833. This will waits until isThreadRunning() is false or until a timeout expires.
  10834. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10835. is less than zero, it will wait forever.
  10836. @returns true if the thread exits, or false if the timeout expires first.
  10837. */
  10838. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10839. /** Changes the thread's priority.
  10840. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10841. of 5 is normal.
  10842. */
  10843. void setPriority (const int priority) throw();
  10844. /** Changes the priority of the caller thread.
  10845. Similar to setPriority(), but this static method acts on the caller thread.
  10846. @see setPriority
  10847. */
  10848. static void setCurrentThreadPriority (const int priority) throw();
  10849. /** Sets the affinity mask for the thread.
  10850. This will only have an effect next time the thread is started - i.e. if the
  10851. thread is already running when called, it'll have no effect.
  10852. @see setCurrentThreadAffinityMask
  10853. */
  10854. void setAffinityMask (const uint32 affinityMask) throw();
  10855. /** Changes the affinity mask for the caller thread.
  10856. This will change the affinity mask for the thread that calls this static method.
  10857. @see setAffinityMask
  10858. */
  10859. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10860. // this can be called from any thread that needs to pause..
  10861. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10862. /** Yields the calling thread's current time-slot. */
  10863. static void JUCE_CALLTYPE yield() throw();
  10864. /** Makes the thread wait for a notification.
  10865. This puts the thread to sleep until either the timeout period expires, or
  10866. another thread calls the notify() method to wake it up.
  10867. @returns true if the event has been signalled, false if the timeout expires.
  10868. */
  10869. bool wait (const int timeOutMilliseconds) const throw();
  10870. /** Wakes up the thread.
  10871. If the thread has called the wait() method, this will wake it up.
  10872. @see wait
  10873. */
  10874. void notify() const throw();
  10875. /** Returns an id that identifies the caller thread.
  10876. To find the ID of a particular thread object, use getThreadId().
  10877. @returns a unique identifier that identifies the calling thread.
  10878. @see getThreadId
  10879. */
  10880. static int64 getCurrentThreadId() throw();
  10881. /** Finds the thread object that is currently running.
  10882. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10883. object associated with them, so this will return 0.
  10884. */
  10885. static Thread* getCurrentThread() throw();
  10886. /** Returns the ID of this thread.
  10887. That means the ID of this thread object - not of the thread that's calling the method.
  10888. This can change when the thread is started and stopped, and will be invalid if the
  10889. thread's not actually running.
  10890. @see getCurrentThreadId
  10891. */
  10892. int64 getThreadId() const throw();
  10893. /** Returns the name of the thread.
  10894. This is the name that gets set in the constructor.
  10895. */
  10896. const String getThreadName() const throw() { return threadName_; }
  10897. /** Returns the number of currently-running threads.
  10898. @returns the number of Thread objects known to be currently running.
  10899. @see stopAllThreads
  10900. */
  10901. static int getNumRunningThreads() throw();
  10902. /** Tries to stop all currently-running threads.
  10903. This will attempt to stop all the threads known to be running at the moment.
  10904. */
  10905. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10906. juce_UseDebuggingNewOperator
  10907. private:
  10908. const String threadName_;
  10909. void* volatile threadHandle_;
  10910. CriticalSection startStopLock;
  10911. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10912. int threadPriority_;
  10913. int64 threadId_;
  10914. uint32 affinityMask_;
  10915. bool volatile threadShouldExit_;
  10916. friend void JUCE_API juce_threadEntryPoint (void*);
  10917. static void threadEntryPoint (Thread* thread) throw();
  10918. Thread (const Thread&);
  10919. const Thread& operator= (const Thread&);
  10920. };
  10921. #endif // __JUCE_THREAD_JUCEHEADER__
  10922. /********* End of inlined file: juce_Thread.h *********/
  10923. #endif
  10924. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10925. /********* Start of inlined file: juce_ThreadPool.h *********/
  10926. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10927. #define __JUCE_THREADPOOL_JUCEHEADER__
  10928. class ThreadPool;
  10929. class ThreadPoolThread;
  10930. /**
  10931. A task that is executed by a ThreadPool object.
  10932. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  10933. its threads.
  10934. The runJob() method needs to be implemented to do the task, and if the code that
  10935. does the work takes a significant time to run, it must keep checking the shouldExit()
  10936. method to see if something is trying to interrupt the job. If shouldExit() returns
  10937. true, the runJob() method must return immediately.
  10938. @see ThreadPool, Thread
  10939. */
  10940. class JUCE_API ThreadPoolJob
  10941. {
  10942. public:
  10943. /** Creates a thread pool job object.
  10944. After creating your job, add it to a thread pool with ThreadPool::addJob().
  10945. */
  10946. ThreadPoolJob (const String& name);
  10947. /** Destructor. */
  10948. virtual ~ThreadPoolJob();
  10949. /** Returns the name of this job.
  10950. @see setJobName
  10951. */
  10952. const String getJobName() const;
  10953. /** Changes the job's name.
  10954. @see getJobName
  10955. */
  10956. void setJobName (const String& newName);
  10957. /** These are the values that can be returned by the runJob() method.
  10958. */
  10959. enum JobStatus
  10960. {
  10961. jobHasFinished = 0, /**< indicates that the job has finished and can be
  10962. removed from the pool. */
  10963. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  10964. should be automatically deleted by the pool. */
  10965. jobNeedsRunningAgain /**< indicates that the job would like to be called
  10966. again when a thread is free. */
  10967. };
  10968. /** Peforms the actual work that this job needs to do.
  10969. Your subclass must implement this method, in which is does its work.
  10970. If the code in this method takes a significant time to run, it must repeatedly check
  10971. the shouldExit() method to see if something is trying to interrupt the job.
  10972. If shouldExit() ever returns true, the runJob() method must return immediately.
  10973. If this method returns jobHasFinished, then the job will be removed from the pool
  10974. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  10975. pool and will get a chance to run again as soon as a thread is free.
  10976. @see shouldExit()
  10977. */
  10978. virtual JobStatus runJob() = 0;
  10979. /** Returns true if this job is currently running its runJob() method. */
  10980. bool isRunning() const throw() { return isActive; }
  10981. /** Returns true if something is trying to interrupt this job and make it stop.
  10982. Your runJob() method must call this whenever it gets a chance, and if it ever
  10983. returns true, the runJob() method must return immediately.
  10984. @see signalJobShouldExit()
  10985. */
  10986. bool shouldExit() const throw() { return shouldStop; }
  10987. /** Calling this will cause the shouldExit() method to return true, and the job
  10988. should (if it's been implemented correctly) stop as soon as possible.
  10989. @see shouldExit()
  10990. */
  10991. void signalJobShouldExit();
  10992. juce_UseDebuggingNewOperator
  10993. private:
  10994. friend class ThreadPool;
  10995. friend class ThreadPoolThread;
  10996. String jobName;
  10997. ThreadPool* pool;
  10998. bool shouldStop, isActive, shouldBeDeleted;
  10999. };
  11000. /**
  11001. A set of threads that will run a list of jobs.
  11002. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11003. will be called by the next pooled thread that becomes free.
  11004. @see ThreadPoolJob, Thread
  11005. */
  11006. class JUCE_API ThreadPool
  11007. {
  11008. public:
  11009. /** Creates a thread pool.
  11010. Once you've created a pool, you can give it some things to do with the addJob()
  11011. method.
  11012. @param numberOfThreads the maximum number of actual threads to run.
  11013. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11014. until there are some jobs to run. If false, then
  11015. all the threads will be fired-up immediately so that
  11016. they're ready for action
  11017. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11018. inactive for this length of time, they will automatically
  11019. be stopped until more jobs come along and they're needed
  11020. */
  11021. ThreadPool (const int numberOfThreads,
  11022. const bool startThreadsOnlyWhenNeeded = true,
  11023. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11024. /** Destructor.
  11025. This will attempt to remove all the jobs before deleting, but if you want to
  11026. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11027. the pool.
  11028. */
  11029. ~ThreadPool();
  11030. /** Adds a job to the queue.
  11031. Once a job has been added, then the next time a thread is free, it will run
  11032. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11033. runJob() method, the pool will either remove the job from the pool or add it to
  11034. the back of the queue to be run again.
  11035. */
  11036. void addJob (ThreadPoolJob* const job);
  11037. /** Tries to remove a job from the pool.
  11038. If the job isn't yet running, this will simply remove it. If it is running, it
  11039. will wait for it to finish.
  11040. If the timeout period expires before the job finishes running, then the job will be
  11041. left in the pool and this will return false. It returns true if the job is sucessfully
  11042. stopped and removed.
  11043. @param job the job to remove
  11044. @param interruptIfRunning if true, then if the job is currently busy, its
  11045. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11046. to interrupt it. If false, then if the job will be allowed to run
  11047. until it stops normally (or the timeout expires)
  11048. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11049. before giving up and returning false
  11050. */
  11051. bool removeJob (ThreadPoolJob* const job,
  11052. const bool interruptIfRunning,
  11053. const int timeOutMilliseconds);
  11054. /** Tries clear all jobs from the pool.
  11055. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11056. methods called to try to interrupt them
  11057. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11058. before giving up and returning false
  11059. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11060. expires while waiting for them to stop
  11061. */
  11062. bool removeAllJobs (const bool interruptRunningJobs,
  11063. const int timeOutMilliseconds);
  11064. /** Returns the number of jobs currently running or queued.
  11065. */
  11066. int getNumJobs() const throw();
  11067. /** Returns one of the jobs in the queue.
  11068. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11069. around in the list, and this method may return 0 if the index is currently out-of-range.
  11070. */
  11071. ThreadPoolJob* getJob (const int index) const;
  11072. /** Returns true if the given job is currently queued or running.
  11073. @see isJobRunning()
  11074. */
  11075. bool contains (const ThreadPoolJob* const job) const throw();
  11076. /** Returns true if the given job is currently being run by a thread.
  11077. */
  11078. bool isJobRunning (const ThreadPoolJob* const job) const;
  11079. /** Waits until a job has finished running and has been removed from the pool.
  11080. This will wait until the job is no longer in the pool - i.e. until its
  11081. runJob() method returns ThreadPoolJob::jobHasFinished.
  11082. If the timeout period expires before the job finishes, this will return false;
  11083. it returns true if the job has finished successfully.
  11084. */
  11085. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11086. const int timeOutMilliseconds) const;
  11087. /** Returns a list of the names of all the jobs currently running or queued.
  11088. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11089. */
  11090. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  11091. /** Changes the priority of all the threads.
  11092. This will call Thread::setPriority() for each thread in the pool.
  11093. */
  11094. void setThreadPriorities (const int newPriority);
  11095. juce_UseDebuggingNewOperator
  11096. private:
  11097. const int numThreads, threadStopTimeout;
  11098. int priority;
  11099. Thread** threads;
  11100. VoidArray jobs;
  11101. CriticalSection lock;
  11102. uint32 lastJobEndTime;
  11103. friend class ThreadPoolThread;
  11104. bool runNextJob();
  11105. ThreadPool (const ThreadPool&);
  11106. const ThreadPool& operator= (const ThreadPool&);
  11107. };
  11108. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11109. /********* End of inlined file: juce_ThreadPool.h *********/
  11110. #endif
  11111. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11112. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11113. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11114. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11115. /**
  11116. Used by the TimeSliceThread class.
  11117. To register your class with a TimeSliceThread, derive from this class and
  11118. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11119. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11120. deleting your client!
  11121. @see TimeSliceThread
  11122. */
  11123. class JUCE_API TimeSliceClient
  11124. {
  11125. public:
  11126. /** Destructor. */
  11127. virtual ~TimeSliceClient() {}
  11128. /** Called back by a TimeSliceThread.
  11129. When you register this class with it, a TimeSliceThread will repeatedly call
  11130. this method.
  11131. The implementation of this method should use its time-slice to do something that's
  11132. quick - never block for longer than absolutely necessary.
  11133. @returns Your method should return true if it needs more time, or false if it's
  11134. not too busy and doesn't need calling back urgently. If all the thread's
  11135. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11136. up to half a second in between callbacks. You can force the TimeSliceThread
  11137. to wake up and poll again immediately by calling its notify() method.
  11138. */
  11139. virtual bool useTimeSlice() = 0;
  11140. };
  11141. /**
  11142. A thread that keeps a list of clients, and calls each one in turn, giving them
  11143. all a chance to run some sort of short task.
  11144. @see TimeSliceClient, Thread
  11145. */
  11146. class JUCE_API TimeSliceThread : public Thread
  11147. {
  11148. public:
  11149. /**
  11150. Creates a TimeSliceThread.
  11151. When first created, the thread is not running. Use the startThread()
  11152. method to start it.
  11153. */
  11154. TimeSliceThread (const String& threadName);
  11155. /** Destructor.
  11156. Deleting a Thread object that is running will only give the thread a
  11157. brief opportunity to stop itself cleanly, so it's recommended that you
  11158. should always call stopThread() with a decent timeout before deleting,
  11159. to avoid the thread being forcibly killed (which is a Bad Thing).
  11160. */
  11161. ~TimeSliceThread();
  11162. /** Adds a client to the list.
  11163. The client's callbacks will start immediately (possibly before the method
  11164. has returned).
  11165. */
  11166. void addTimeSliceClient (TimeSliceClient* const client);
  11167. /** Removes a client from the list.
  11168. This method will make sure that all callbacks to the client have completely
  11169. finished before the method returns.
  11170. */
  11171. void removeTimeSliceClient (TimeSliceClient* const client);
  11172. /** Returns the number of registered clients. */
  11173. int getNumClients() const throw();
  11174. /** Returns one of the registered clients. */
  11175. TimeSliceClient* getClient (const int index) const throw();
  11176. /** @internal */
  11177. void run();
  11178. juce_UseDebuggingNewOperator
  11179. private:
  11180. CriticalSection callbackLock, listLock;
  11181. Array <TimeSliceClient*> clients;
  11182. int index;
  11183. TimeSliceClient* clientBeingCalled;
  11184. bool clientsChanged;
  11185. TimeSliceThread (const TimeSliceThread&);
  11186. const TimeSliceThread& operator= (const TimeSliceThread&);
  11187. };
  11188. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11189. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11190. #endif
  11191. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11192. #endif
  11193. #endif
  11194. /********* End of inlined file: juce_core_includes.h *********/
  11195. // if you're compiling a command-line app, you might want to just include the core headers,
  11196. // so you can set this macro before including juce.h
  11197. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11198. /********* Start of inlined file: juce_app_includes.h *********/
  11199. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11200. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11201. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11202. /********* Start of inlined file: juce_Application.h *********/
  11203. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11204. #define __JUCE_APPLICATION_JUCEHEADER__
  11205. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11206. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11207. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11208. /********* Start of inlined file: juce_Component.h *********/
  11209. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11210. #define __JUCE_COMPONENT_JUCEHEADER__
  11211. /********* Start of inlined file: juce_MouseCursor.h *********/
  11212. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11213. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11214. class Image;
  11215. class RefCountedMouseCursor;
  11216. class ComponentPeer;
  11217. class Component;
  11218. /**
  11219. Represents a mouse cursor image.
  11220. This object can either be used to represent one of the standard mouse
  11221. cursor shapes, or a custom one generated from an image.
  11222. */
  11223. class JUCE_API MouseCursor
  11224. {
  11225. public:
  11226. /** The set of available standard mouse cursors. */
  11227. enum StandardCursorType
  11228. {
  11229. NoCursor = 0, /**< An invisible cursor. */
  11230. NormalCursor, /**< The stardard arrow cursor. */
  11231. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11232. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11233. CrosshairCursor, /**< A pair of crosshairs. */
  11234. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11235. that you're dragging a copy of something. */
  11236. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11237. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11238. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11239. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11240. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11241. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11242. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11243. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11244. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11245. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11246. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11247. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11248. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11249. };
  11250. /** Creates the standard arrow cursor. */
  11251. MouseCursor() throw();
  11252. /** Creates one of the standard mouse cursor */
  11253. MouseCursor (const StandardCursorType type) throw();
  11254. /** Creates a custom cursor from an image.
  11255. @param image the image to use for the cursor - if this is bigger than the
  11256. system can manage, it might get scaled down first, and might
  11257. also have to be turned to black-and-white if it can't do colour
  11258. cursors.
  11259. @param hotSpotX the x position of the cursor's hotspot within the image
  11260. @param hotSpotY the y position of the cursor's hotspot within the image
  11261. */
  11262. MouseCursor (Image& image,
  11263. const int hotSpotX,
  11264. const int hotSpotY) throw();
  11265. /** Creates a copy of another cursor object. */
  11266. MouseCursor (const MouseCursor& other) throw();
  11267. /** Copies this cursor from another object. */
  11268. const MouseCursor& operator= (const MouseCursor& other) throw();
  11269. /** Destructor. */
  11270. ~MouseCursor() throw();
  11271. /** Checks whether two mouse cursors are the same.
  11272. For custom cursors, two cursors created from the same image won't be
  11273. recognised as the same, only MouseCursor objects that have been
  11274. copied from the same object.
  11275. */
  11276. bool operator== (const MouseCursor& other) const throw();
  11277. /** Checks whether two mouse cursors are the same.
  11278. For custom cursors, two cursors created from the same image won't be
  11279. recognised as the same, only MouseCursor objects that have been
  11280. copied from the same object.
  11281. */
  11282. bool operator!= (const MouseCursor& other) const throw();
  11283. /** Makes the system show its default 'busy' cursor.
  11284. This will turn the system cursor to an hourglass or spinning beachball
  11285. until the next time the mouse is moved, or hideWaitCursor() is called.
  11286. This is handy if the message loop is about to block for a couple of
  11287. seconds while busy and you want to give the user feedback about this.
  11288. @see MessageManager::setTimeBeforeShowingWaitCursor
  11289. */
  11290. static void showWaitCursor() throw();
  11291. /** If showWaitCursor has been called, this will return the mouse to its
  11292. normal state.
  11293. This will look at what component is under the mouse, and update the
  11294. cursor to be the correct one for that component.
  11295. @see showWaitCursor
  11296. */
  11297. static void hideWaitCursor() throw();
  11298. juce_UseDebuggingNewOperator
  11299. private:
  11300. RefCountedMouseCursor* cursorHandle;
  11301. friend class Component;
  11302. void showInWindow (ComponentPeer* window) const throw();
  11303. void showInAllWindows() const throw();
  11304. void* getHandle() const throw();
  11305. };
  11306. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11307. /********* End of inlined file: juce_MouseCursor.h *********/
  11308. /********* Start of inlined file: juce_MouseListener.h *********/
  11309. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11310. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11311. /********* Start of inlined file: juce_MouseEvent.h *********/
  11312. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11313. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11314. class Component;
  11315. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11316. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11317. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11318. /**
  11319. Represents the state of the mouse buttons and modifier keys.
  11320. This is used both by mouse events and by KeyPress objects to describe
  11321. the state of keys such as shift, control, alt, etc.
  11322. @see KeyPress, MouseEvent::mods
  11323. */
  11324. class JUCE_API ModifierKeys
  11325. {
  11326. public:
  11327. /** Creates a ModifierKeys object from a raw set of flags.
  11328. @param flags to represent the keys that are down
  11329. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11330. rightButtonModifier, commandModifier, popupMenuClickModifier
  11331. */
  11332. ModifierKeys (const int flags = 0) throw();
  11333. /** Creates a copy of another object. */
  11334. ModifierKeys (const ModifierKeys& other) throw();
  11335. /** Copies this object from another one. */
  11336. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11337. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11338. This is a platform-agnostic way of checking for the operating system's
  11339. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11340. Windows/Linux, it's actually checking for the CTRL key.
  11341. */
  11342. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11343. /** Checks whether the user is trying to launch a pop-up menu.
  11344. This checks for platform-specific modifiers that might indicate that the user
  11345. is following the operating system's normal method of showing a pop-up menu.
  11346. So on Windows/Linux, this method is really testing for a right-click.
  11347. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11348. */
  11349. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11350. /** Checks whether the flag is set for the left mouse-button. */
  11351. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11352. /** Checks whether the flag is set for the right mouse-button.
  11353. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11354. this is platform-independent (and makes your code more explanatory too).
  11355. */
  11356. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11357. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11358. /** Tests for any of the mouse-button flags. */
  11359. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11360. /** Tests for any of the modifier key flags. */
  11361. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11362. /** Checks whether the shift key's flag is set. */
  11363. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11364. /** Checks whether the CTRL key's flag is set.
  11365. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11366. popup-menu modifiers.
  11367. @see isCommandDown, isPopupMenu
  11368. */
  11369. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11370. /** Checks whether the shift key's flag is set. */
  11371. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11372. /** Flags that represent the different keys. */
  11373. enum Flags
  11374. {
  11375. /** Shift key flag. */
  11376. shiftModifier = 1,
  11377. /** CTRL key flag. */
  11378. ctrlModifier = 2,
  11379. /** ALT key flag. */
  11380. altModifier = 4,
  11381. /** Left mouse button flag. */
  11382. leftButtonModifier = 16,
  11383. /** Right mouse button flag. */
  11384. rightButtonModifier = 32,
  11385. /** Middle mouse button flag. */
  11386. middleButtonModifier = 64,
  11387. #if JUCE_MAC
  11388. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11389. commandModifier = 8,
  11390. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11391. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11392. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11393. #else
  11394. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11395. commandModifier = ctrlModifier,
  11396. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11397. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11398. popupMenuClickModifier = rightButtonModifier,
  11399. #endif
  11400. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11401. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11402. /** Represents a combination of all the mouse buttons at once. */
  11403. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11404. };
  11405. /** Returns the raw flags for direct testing. */
  11406. inline int getRawFlags() const throw() { return flags; }
  11407. /** Tests a combination of flags and returns true if any of them are set. */
  11408. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11409. /** Creates a ModifierKeys object to represent the last-known state of the
  11410. keyboard and mouse buttons.
  11411. @see getCurrentModifiersRealtime
  11412. */
  11413. static const ModifierKeys getCurrentModifiers() throw();
  11414. /** Creates a ModifierKeys object to represent the current state of the
  11415. keyboard and mouse buttons.
  11416. This isn't often needed and isn't recommended, but will actively check all the
  11417. mouse and key states rather than just returning their last-known state like
  11418. getCurrentModifiers() does.
  11419. This is only needed in special circumstances for up-to-date modifier information
  11420. at times when the app's event loop isn't running normally.
  11421. */
  11422. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11423. private:
  11424. int flags;
  11425. static int currentModifierFlags;
  11426. friend class ComponentPeer;
  11427. static void updateCurrentModifiers() throw();
  11428. };
  11429. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11430. /********* End of inlined file: juce_ModifierKeys.h *********/
  11431. /**
  11432. Contains position and status information about a mouse event.
  11433. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11434. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11435. */
  11436. class JUCE_API MouseEvent
  11437. {
  11438. public:
  11439. /** Creates a MouseEvent.
  11440. Normally an application will never need to use this.
  11441. @param x the x position of the mouse, relative to the component that is passed-in
  11442. @param y the y position of the mouse, relative to the component that is passed-in
  11443. @param modifiers the key modifiers at the time of the event
  11444. @param originator the component that the mouse event applies to
  11445. @param eventTime the time the event happened
  11446. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11447. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11448. the same as the current mouse-x position.
  11449. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11450. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11451. the same as the current mouse-y position.
  11452. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11453. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11454. the same as the current mouse-event time.
  11455. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11456. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11457. */
  11458. MouseEvent (const int x, const int y,
  11459. const ModifierKeys& modifiers,
  11460. Component* const originator,
  11461. const Time& eventTime,
  11462. const int mouseDownX,
  11463. const int mouseDownY,
  11464. const Time& mouseDownTime,
  11465. const int numberOfClicks,
  11466. const bool mouseWasDragged) throw();
  11467. /** Destructor. */
  11468. ~MouseEvent() throw();
  11469. /** The x-position of the mouse when the event occurred.
  11470. This value is relative to the top-left of the component to which the
  11471. event applies (as indicated by the MouseEvent::eventComponent field).
  11472. */
  11473. int x;
  11474. /** The y-position of the mouse when the event occurred.
  11475. This value is relative to the top-left of the component to which the
  11476. event applies (as indicated by the MouseEvent::eventComponent field).
  11477. */
  11478. int y;
  11479. /** The key modifiers associated with the event.
  11480. This will let you find out which mouse buttons were down, as well as which
  11481. modifier keys were held down.
  11482. When used for mouse-up events, this will indicate the state of the mouse buttons
  11483. just before they were released, so that you can tell which button they let go of.
  11484. */
  11485. ModifierKeys mods;
  11486. /** The component that this event applies to.
  11487. This is usually the component that the mouse was over at the time, but for mouse-drag
  11488. events the mouse could actually be over a different component and the events are
  11489. still sent to the component that the button was originally pressed on.
  11490. The x and y member variables are relative to this component's position.
  11491. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11492. component, this pointer will be updated, but originalComponent remains unchanged.
  11493. @see originalComponent
  11494. */
  11495. Component* eventComponent;
  11496. /** The component that the event first occurred on.
  11497. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11498. component, this value remains unchanged to indicate the first component that received it.
  11499. @see eventComponent
  11500. */
  11501. Component* originalComponent;
  11502. /** The time that this mouse-event occurred.
  11503. */
  11504. Time eventTime;
  11505. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11506. The co-ordinate is relative to the component specified in MouseEvent::component.
  11507. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11508. */
  11509. int getMouseDownX() const throw();
  11510. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11511. The co-ordinate is relative to the component specified in MouseEvent::component.
  11512. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11513. */
  11514. int getMouseDownY() const throw();
  11515. /** Returns the straight-line distance between where the mouse is now and where it
  11516. was the last time the button was pressed.
  11517. This is quite handy for things like deciding whether the user has moved far enough
  11518. for it to be considered a drag operation.
  11519. @see getDistanceFromDragStartX
  11520. */
  11521. int getDistanceFromDragStart() const throw();
  11522. /** Returns the difference between the mouse's current x postion and where it was
  11523. when the button was last pressed.
  11524. @see getDistanceFromDragStart
  11525. */
  11526. int getDistanceFromDragStartX() const throw();
  11527. /** Returns the difference between the mouse's current y postion and where it was
  11528. when the button was last pressed.
  11529. @see getDistanceFromDragStart
  11530. */
  11531. int getDistanceFromDragStartY() const throw();
  11532. /** Returns true if the mouse has just been clicked.
  11533. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11534. the user has dragged the mouse more than a few pixels from the place where the
  11535. mouse-down occurred.
  11536. Once they have dragged it far enough for this method to return false, it will continue
  11537. to return false until the mouse-up, even if they move the mouse back to the same
  11538. position where they originally pressed it. This means that it's very handy for
  11539. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11540. callback to ignore any small movements they might make while clicking.
  11541. @returns true if the mouse wasn't dragged by more than a few pixels between
  11542. the last time the button was pressed and released.
  11543. */
  11544. bool mouseWasClicked() const throw();
  11545. /** For a click event, the number of times the mouse was clicked in succession.
  11546. So for example a double-click event will return 2, a triple-click 3, etc.
  11547. */
  11548. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11549. /** Returns the time that the mouse button has been held down for.
  11550. If called from a mouseDrag or mouseUp callback, this will return the
  11551. number of milliseconds since the corresponding mouseDown event occurred.
  11552. If called in other contexts, e.g. a mouseMove, then the returned value
  11553. may be 0 or an undefined value.
  11554. */
  11555. int getLengthOfMousePress() const throw();
  11556. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11557. The co-ordinates are relative to the top-left of the main monitor.
  11558. @see getMouseDownScreenX, Desktop::getMousePosition
  11559. */
  11560. int getScreenX() const throw();
  11561. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11562. The co-ordinates are relative to the top-left of the main monitor.
  11563. @see getMouseDownScreenY, Desktop::getMousePosition
  11564. */
  11565. int getScreenY() const throw();
  11566. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11567. The co-ordinates are relative to the top-left of the main monitor.
  11568. @see getScreenX, Desktop::getMousePosition
  11569. */
  11570. int getMouseDownScreenX() const throw();
  11571. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11572. The co-ordinates are relative to the top-left of the main monitor.
  11573. @see getScreenY, Desktop::getMousePosition
  11574. */
  11575. int getMouseDownScreenY() const throw();
  11576. /** Creates a version of this event that is relative to a different component.
  11577. The x and y positions of the event that is returned will have been
  11578. adjusted to be relative to the new component.
  11579. */
  11580. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11581. /** Changes the application-wide setting for the double-click time limit.
  11582. This is the maximum length of time between mouse-clicks for it to be
  11583. considered a double-click. It's used by the Component class.
  11584. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11585. */
  11586. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11587. /** Returns the application-wide setting for the double-click time limit.
  11588. This is the maximum length of time between mouse-clicks for it to be
  11589. considered a double-click. It's used by the Component class.
  11590. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11591. */
  11592. static int getDoubleClickTimeout() throw();
  11593. juce_UseDebuggingNewOperator
  11594. private:
  11595. int mouseDownX, mouseDownY;
  11596. Time mouseDownTime;
  11597. int numberOfClicks;
  11598. bool wasMovedSinceMouseDown;
  11599. };
  11600. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11601. /********* End of inlined file: juce_MouseEvent.h *********/
  11602. /**
  11603. A MouseListener can be registered with a component to receive callbacks
  11604. about mouse events that happen to that component.
  11605. @see Component::addMouseListener, Component::removeMouseListener
  11606. */
  11607. class JUCE_API MouseListener
  11608. {
  11609. public:
  11610. /** Destructor. */
  11611. virtual ~MouseListener() {}
  11612. /** Called when the mouse moves inside a component.
  11613. If the mouse button isn't pressed and the mouse moves over a component,
  11614. this will be called to let the component react to this.
  11615. A component will always get a mouseEnter callback before a mouseMove.
  11616. @param e details about the position and status of the mouse event, including
  11617. the source component in which it occurred
  11618. @see mouseEnter, mouseExit, mouseDrag, contains
  11619. */
  11620. virtual void mouseMove (const MouseEvent& e);
  11621. /** Called when the mouse first enters a component.
  11622. If the mouse button isn't pressed and the mouse moves into a component,
  11623. this will be called to let the component react to this.
  11624. When the mouse button is pressed and held down while being moved in
  11625. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11626. mouseDrag messages are sent to the component that the mouse was originally
  11627. clicked on, until the button is released.
  11628. @param e details about the position and status of the mouse event, including
  11629. the source component in which it occurred
  11630. @see mouseExit, mouseDrag, mouseMove, contains
  11631. */
  11632. virtual void mouseEnter (const MouseEvent& e);
  11633. /** Called when the mouse moves out of a component.
  11634. This will be called when the mouse moves off the edge of this
  11635. component.
  11636. If the mouse button was pressed, and it was then dragged off the
  11637. edge of the component and released, then this callback will happen
  11638. when the button is released, after the mouseUp callback.
  11639. @param e details about the position and status of the mouse event, including
  11640. the source component in which it occurred
  11641. @see mouseEnter, mouseDrag, mouseMove, contains
  11642. */
  11643. virtual void mouseExit (const MouseEvent& e);
  11644. /** Called when a mouse button is pressed.
  11645. The MouseEvent object passed in contains lots of methods for finding out
  11646. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11647. were held down at the time.
  11648. Once a button is held down, the mouseDrag method will be called when the
  11649. mouse moves, until the button is released.
  11650. @param e details about the position and status of the mouse event, including
  11651. the source component in which it occurred
  11652. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11653. */
  11654. virtual void mouseDown (const MouseEvent& e);
  11655. /** Called when the mouse is moved while a button is held down.
  11656. When a mouse button is pressed inside a component, that component
  11657. receives mouseDrag callbacks each time the mouse moves, even if the
  11658. mouse strays outside the component's bounds.
  11659. @param e details about the position and status of the mouse event, including
  11660. the source component in which it occurred
  11661. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11662. */
  11663. virtual void mouseDrag (const MouseEvent& e);
  11664. /** Called when a mouse button is released.
  11665. A mouseUp callback is sent to the component in which a button was pressed
  11666. even if the mouse is actually over a different component when the
  11667. button is released.
  11668. The MouseEvent object passed in contains lots of methods for finding out
  11669. which buttons were down just before they were released.
  11670. @param e details about the position and status of the mouse event, including
  11671. the source component in which it occurred
  11672. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11673. */
  11674. virtual void mouseUp (const MouseEvent& e);
  11675. /** Called when a mouse button has been double-clicked on a component.
  11676. The MouseEvent object passed in contains lots of methods for finding out
  11677. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11678. were held down at the time.
  11679. @param e details about the position and status of the mouse event, including
  11680. the source component in which it occurred
  11681. @see mouseDown, mouseUp
  11682. */
  11683. virtual void mouseDoubleClick (const MouseEvent& e);
  11684. /** Called when the mouse-wheel is moved.
  11685. This callback is sent to the component that the mouse is over when the
  11686. wheel is moved.
  11687. If not overridden, the component will forward this message to its parent, so
  11688. that parent components can collect mouse-wheel messages that happen to
  11689. child components which aren't interested in them.
  11690. @param e details about the position and status of the mouse event, including
  11691. the source component in which it occurred
  11692. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11693. value means the wheel has been pushed to the right, negative means it
  11694. was pushed to the left
  11695. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11696. value means the wheel has been pushed upwards, negative means it
  11697. was pushed downwards
  11698. */
  11699. virtual void mouseWheelMove (const MouseEvent& e,
  11700. float wheelIncrementX,
  11701. float wheelIncrementY);
  11702. private:
  11703. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11704. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11705. // if that happens, update your code to use the new one above.
  11706. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11707. };
  11708. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11709. /********* End of inlined file: juce_MouseListener.h *********/
  11710. /********* Start of inlined file: juce_ComponentListener.h *********/
  11711. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11712. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11713. class Component;
  11714. /**
  11715. Gets informed about changes to a component's hierarchy or position.
  11716. To monitor a component for changes, register a subclass of ComponentListener
  11717. with the component using Component::addComponentListener().
  11718. Be sure to deregister listeners before you delete them!
  11719. @see Component::addComponentListener, Component::removeComponentListener
  11720. */
  11721. class JUCE_API ComponentListener
  11722. {
  11723. public:
  11724. /** Destructor. */
  11725. virtual ~ComponentListener() {}
  11726. /** Called when the component's position or size changes.
  11727. @param component the component that was moved or resized
  11728. @param wasMoved true if the component's top-left corner has just moved
  11729. @param wasResized true if the component's width or height has just changed
  11730. @see Component::setBounds, Component::resized, Component::moved
  11731. */
  11732. virtual void componentMovedOrResized (Component& component,
  11733. bool wasMoved,
  11734. bool wasResized);
  11735. /** Called when the component is brought to the top of the z-order.
  11736. @param component the component that was moved
  11737. @see Component::toFront, Component::broughtToFront
  11738. */
  11739. virtual void componentBroughtToFront (Component& component);
  11740. /** Called when the component is made visible or invisible.
  11741. @param component the component that changed
  11742. @see Component::setVisible
  11743. */
  11744. virtual void componentVisibilityChanged (Component& component);
  11745. /** Called when the component has children added or removed.
  11746. @param component the component whose children were changed
  11747. @see Component::childrenChanged, Component::addChildComponent,
  11748. Component::removeChildComponent
  11749. */
  11750. virtual void componentChildrenChanged (Component& component);
  11751. /** Called to indicate that the component's parents have changed.
  11752. When a component is added or removed from its parent, all of its children
  11753. will produce this notification (recursively - so all children of its
  11754. children will also be called as well).
  11755. @param component the component that this listener is registered with
  11756. @see Component::parentHierarchyChanged
  11757. */
  11758. virtual void componentParentHierarchyChanged (Component& component);
  11759. /** Called when the component's name is changed.
  11760. @see Component::setName, Component::getName
  11761. */
  11762. virtual void componentNameChanged (Component& component);
  11763. };
  11764. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11765. /********* End of inlined file: juce_ComponentListener.h *********/
  11766. /********* Start of inlined file: juce_KeyListener.h *********/
  11767. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11768. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11769. /********* Start of inlined file: juce_KeyPress.h *********/
  11770. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11771. #define __JUCE_KEYPRESS_JUCEHEADER__
  11772. /**
  11773. Represents a key press, including any modifier keys that are needed.
  11774. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11775. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11776. */
  11777. class JUCE_API KeyPress
  11778. {
  11779. public:
  11780. /** Creates an (invalid) KeyPress.
  11781. @see isValid
  11782. */
  11783. KeyPress() throw();
  11784. /** Creates a KeyPress for a key and some modifiers.
  11785. e.g.
  11786. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11787. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11788. @param keyCode a code that represents the key - this value must be
  11789. one of special constants listed in this class, or an
  11790. 8-bit character code such as a letter (case is ignored),
  11791. digit or a simple key like "," or ".". Note that this
  11792. isn't the same as the textCharacter parameter, so for example
  11793. a keyCode of 'a' and a shift-key modifier should have a
  11794. textCharacter value of 'A'.
  11795. @param modifiers the modifiers to associate with the keystroke
  11796. @param textCharacter the character that would be printed if someone typed
  11797. this keypress into a text editor. This value may be
  11798. null if the keypress is a non-printing character
  11799. @see getKeyCode, isKeyCode, getModifiers
  11800. */
  11801. KeyPress (const int keyCode,
  11802. const ModifierKeys& modifiers,
  11803. const juce_wchar textCharacter) throw();
  11804. /** Creates a keypress with a keyCode but no modifiers or text character.
  11805. */
  11806. KeyPress (const int keyCode) throw();
  11807. /** Creates a copy of another KeyPress. */
  11808. KeyPress (const KeyPress& other) throw();
  11809. /** Copies this KeyPress from another one. */
  11810. const KeyPress& operator= (const KeyPress& other) throw();
  11811. /** Compares two KeyPress objects. */
  11812. bool operator== (const KeyPress& other) const throw();
  11813. /** Compares two KeyPress objects. */
  11814. bool operator!= (const KeyPress& other) const throw();
  11815. /** Returns true if this is a valid KeyPress.
  11816. A null keypress can be created by the default constructor, in case it's
  11817. needed.
  11818. */
  11819. bool isValid() const throw() { return keyCode != 0; }
  11820. /** Returns the key code itself.
  11821. This will either be one of the special constants defined in this class,
  11822. or an 8-bit character code.
  11823. */
  11824. int getKeyCode() const throw() { return keyCode; }
  11825. /** Returns the key modifiers.
  11826. @see ModifierKeys
  11827. */
  11828. const ModifierKeys getModifiers() const throw() { return mods; }
  11829. /** Returns the character that is associated with this keypress.
  11830. This is the character that you'd expect to see printed if you press this
  11831. keypress in a text editor or similar component.
  11832. */
  11833. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11834. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11835. the modifiers.
  11836. The values for key codes can either be one of the special constants defined in
  11837. this class, or an 8-bit character code.
  11838. @see getKeyCode
  11839. */
  11840. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11841. /** Converts a textual key description to a KeyPress.
  11842. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11843. This isn't designed to cope with any kind of input, but should be given the
  11844. strings that are created by the getTextDescription() method.
  11845. If the string can't be parsed, the object returned will be invalid.
  11846. @see getTextDescription
  11847. */
  11848. static const KeyPress createFromDescription (const String& textVersion) throw();
  11849. /** Creates a textual description of the key combination.
  11850. e.g. "CTRL + C" or "DELETE".
  11851. To store a keypress in a file, use this method, along with createFromDescription()
  11852. to retrieve it later.
  11853. */
  11854. const String getTextDescription() const throw();
  11855. /** Checks whether the user is currently holding down the keys that make up this
  11856. KeyPress.
  11857. Note that this will return false if any extra modifier keys are
  11858. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11859. then it will be false.
  11860. */
  11861. bool isCurrentlyDown() const throw();
  11862. /** Checks whether a particular key is held down, irrespective of modifiers.
  11863. The values for key codes can either be one of the special constants defined in
  11864. this class, or an 8-bit character code.
  11865. */
  11866. static bool isKeyCurrentlyDown (int keyCode) throw();
  11867. // Key codes
  11868. //
  11869. // Note that the actual values of these are platform-specific and may change
  11870. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  11871. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  11872. //
  11873. static const int spaceKey; /**< key-code for the space bar */
  11874. static const int escapeKey; /**< key-code for the escape key */
  11875. static const int returnKey; /**< key-code for the return key*/
  11876. static const int tabKey; /**< key-code for the tab key*/
  11877. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  11878. static const int backspaceKey; /**< key-code for the backspace key */
  11879. static const int insertKey; /**< key-code for the insert key */
  11880. static const int upKey; /**< key-code for the cursor-up key */
  11881. static const int downKey; /**< key-code for the cursor-down key */
  11882. static const int leftKey; /**< key-code for the cursor-left key */
  11883. static const int rightKey; /**< key-code for the cursor-right key */
  11884. static const int pageUpKey; /**< key-code for the page-up key */
  11885. static const int pageDownKey; /**< key-code for the page-down key */
  11886. static const int homeKey; /**< key-code for the home key */
  11887. static const int endKey; /**< key-code for the end key */
  11888. static const int F1Key; /**< key-code for the F1 key */
  11889. static const int F2Key; /**< key-code for the F2 key */
  11890. static const int F3Key; /**< key-code for the F3 key */
  11891. static const int F4Key; /**< key-code for the F4 key */
  11892. static const int F5Key; /**< key-code for the F5 key */
  11893. static const int F6Key; /**< key-code for the F6 key */
  11894. static const int F7Key; /**< key-code for the F7 key */
  11895. static const int F8Key; /**< key-code for the F8 key */
  11896. static const int F9Key; /**< key-code for the F9 key */
  11897. static const int F10Key; /**< key-code for the F10 key */
  11898. static const int F11Key; /**< key-code for the F11 key */
  11899. static const int F12Key; /**< key-code for the F12 key */
  11900. static const int F13Key; /**< key-code for the F13 key */
  11901. static const int F14Key; /**< key-code for the F14 key */
  11902. static const int F15Key; /**< key-code for the F15 key */
  11903. static const int F16Key; /**< key-code for the F16 key */
  11904. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  11905. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  11906. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  11907. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  11908. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  11909. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  11910. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  11911. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  11912. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  11913. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  11914. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  11915. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  11916. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  11917. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  11918. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  11919. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  11920. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  11921. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  11922. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  11923. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  11924. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  11925. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  11926. juce_UseDebuggingNewOperator
  11927. private:
  11928. int keyCode;
  11929. ModifierKeys mods;
  11930. juce_wchar textCharacter;
  11931. };
  11932. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  11933. /********* End of inlined file: juce_KeyPress.h *********/
  11934. class Component;
  11935. /**
  11936. Receives callbacks when keys are pressed.
  11937. You can add a key listener to a component to be informed when that component
  11938. gets key events. See the Component::addListener method for more details.
  11939. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  11940. */
  11941. class JUCE_API KeyListener
  11942. {
  11943. public:
  11944. /** Destructor. */
  11945. virtual ~KeyListener() {}
  11946. /** Called to indicate that a key has been pressed.
  11947. If your implementation returns true, then the key event is considered to have
  11948. been consumed, and will not be passed on to any other components. If it returns
  11949. false, then the key will be passed to other components that might want to use it.
  11950. @param key the keystroke, including modifier keys
  11951. @param originatingComponent the component that received the key event
  11952. @see keyStateChanged, Component::keyPressed
  11953. */
  11954. virtual bool keyPressed (const KeyPress& key,
  11955. Component* originatingComponent) = 0;
  11956. /** Called when any key is pressed or released.
  11957. When this is called, classes that might be interested in
  11958. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  11959. check whether their key has changed.
  11960. If your implementation returns true, then the key event is considered to have
  11961. been consumed, and will not be passed on to any other components. If it returns
  11962. false, then the key will be passed to other components that might want to use it.
  11963. @param originatingComponent the component that received the key event
  11964. @see KeyPress, Component::keyStateChanged
  11965. */
  11966. virtual bool keyStateChanged (Component* originatingComponent);
  11967. };
  11968. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  11969. /********* End of inlined file: juce_KeyListener.h *********/
  11970. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  11971. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  11972. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  11973. class Component;
  11974. /**
  11975. Controls the order in which focus moves between components.
  11976. The default algorithm used by this class to work out the order of traversal
  11977. is as follows:
  11978. - if two components both have an explicit focus order specified, then the
  11979. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  11980. method).
  11981. - any component with an explicit focus order greater than 0 comes before ones
  11982. that don't have an order specified.
  11983. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  11984. order.
  11985. If you need traversal in a more customised way, you can create a subclass
  11986. of KeyboardFocusTraverser that uses your own algorithm, and use
  11987. Component::createFocusTraverser() to create it.
  11988. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  11989. */
  11990. class JUCE_API KeyboardFocusTraverser
  11991. {
  11992. public:
  11993. KeyboardFocusTraverser();
  11994. /** Destructor. */
  11995. virtual ~KeyboardFocusTraverser();
  11996. /** Returns the component that should be given focus after the specified one
  11997. when moving "forwards".
  11998. The default implementation will return the next component which is to the
  11999. right of or below this one.
  12000. This may return 0 if there's no suitable candidate.
  12001. */
  12002. virtual Component* getNextComponent (Component* current);
  12003. /** Returns the component that should be given focus after the specified one
  12004. when moving "backwards".
  12005. The default implementation will return the next component which is to the
  12006. left of or above this one.
  12007. This may return 0 if there's no suitable candidate.
  12008. */
  12009. virtual Component* getPreviousComponent (Component* current);
  12010. /** Returns the component that should receive focus be default within the given
  12011. parent component.
  12012. The default implementation will just return the foremost child component that
  12013. wants focus.
  12014. This may return 0 if there's no suitable candidate.
  12015. */
  12016. virtual Component* getDefaultComponent (Component* parentComponent);
  12017. };
  12018. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12019. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12020. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12021. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12022. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12023. /********* Start of inlined file: juce_Graphics.h *********/
  12024. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12025. #define __JUCE_GRAPHICS_JUCEHEADER__
  12026. /********* Start of inlined file: juce_Font.h *********/
  12027. #ifndef __JUCE_FONT_JUCEHEADER__
  12028. #define __JUCE_FONT_JUCEHEADER__
  12029. /********* Start of inlined file: juce_Typeface.h *********/
  12030. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12031. #define __JUCE_TYPEFACE_JUCEHEADER__
  12032. /********* Start of inlined file: juce_Path.h *********/
  12033. #ifndef __JUCE_PATH_JUCEHEADER__
  12034. #define __JUCE_PATH_JUCEHEADER__
  12035. /********* Start of inlined file: juce_AffineTransform.h *********/
  12036. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12037. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12038. /**
  12039. Represents a 2D affine-transformation matrix.
  12040. An affine transformation is a transformation such as a rotation, scale, shear,
  12041. resize or translation.
  12042. These are used for various 2D transformation tasks, e.g. with Path objects.
  12043. @see Path, Point, Line
  12044. */
  12045. class JUCE_API AffineTransform
  12046. {
  12047. public:
  12048. /** Creates an identity transform. */
  12049. AffineTransform() throw();
  12050. /** Creates a copy of another transform. */
  12051. AffineTransform (const AffineTransform& other) throw();
  12052. /** Creates a transform from a set of raw matrix values.
  12053. The resulting matrix is:
  12054. (mat00 mat01 mat02)
  12055. (mat10 mat11 mat12)
  12056. ( 0 0 1 )
  12057. */
  12058. AffineTransform (const float mat00, const float mat01, const float mat02,
  12059. const float mat10, const float mat11, const float mat12) throw();
  12060. /** Copies from another AffineTransform object */
  12061. const AffineTransform& operator= (const AffineTransform& other) throw();
  12062. /** Compares two transforms. */
  12063. bool operator== (const AffineTransform& other) const throw();
  12064. /** Compares two transforms. */
  12065. bool operator!= (const AffineTransform& other) const throw();
  12066. /** A ready-to-use identity transform, which you can use to append other
  12067. transformations to.
  12068. e.g. @code
  12069. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12070. .scaled (2.0f);
  12071. @endcode
  12072. */
  12073. static const AffineTransform identity;
  12074. /** Transforms a 2D co-ordinate using this matrix. */
  12075. void transformPoint (float& x,
  12076. float& y) const throw();
  12077. /** Transforms a 2D co-ordinate using this matrix. */
  12078. void transformPoint (double& x,
  12079. double& y) const throw();
  12080. /** Returns a new transform which is the same as this one followed by a translation. */
  12081. const AffineTransform translated (const float deltaX,
  12082. const float deltaY) const throw();
  12083. /** Returns a new transform which is a translation. */
  12084. static const AffineTransform translation (const float deltaX,
  12085. const float deltaY) throw();
  12086. /** Returns a transform which is the same as this one followed by a rotation.
  12087. The rotation is specified by a number of radians to rotate clockwise, centred around
  12088. the origin (0, 0).
  12089. */
  12090. const AffineTransform rotated (const float angleInRadians) const throw();
  12091. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12092. The rotation is specified by a number of radians to rotate clockwise, centred around
  12093. the co-ordinates passed in.
  12094. */
  12095. const AffineTransform rotated (const float angleInRadians,
  12096. const float pivotX,
  12097. const float pivotY) const throw();
  12098. /** Returns a new transform which is a rotation about (0, 0). */
  12099. static const AffineTransform rotation (const float angleInRadians) throw();
  12100. /** Returns a new transform which is a rotation about a given point. */
  12101. static const AffineTransform rotation (const float angleInRadians,
  12102. const float pivotX,
  12103. const float pivotY) throw();
  12104. /** Returns a transform which is the same as this one followed by a re-scaling.
  12105. The scaling is centred around the origin (0, 0).
  12106. */
  12107. const AffineTransform scaled (const float factorX,
  12108. const float factorY) const throw();
  12109. /** Returns a new transform which is a re-scale about the origin. */
  12110. static const AffineTransform scale (const float factorX,
  12111. const float factorY) throw();
  12112. /** Returns a transform which is the same as this one followed by a shear.
  12113. The shear is centred around the origin (0, 0).
  12114. */
  12115. const AffineTransform sheared (const float shearX,
  12116. const float shearY) const throw();
  12117. /** Returns a matrix which is the inverse operation of this one.
  12118. Some matrices don't have an inverse - in this case, the method will just return
  12119. an identity transform.
  12120. */
  12121. const AffineTransform inverted() const throw();
  12122. /** Returns the result of concatenating another transformation after this one. */
  12123. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12124. /** Returns true if this transform has no effect on points. */
  12125. bool isIdentity() const throw();
  12126. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12127. bool isSingularity() const throw();
  12128. juce_UseDebuggingNewOperator
  12129. /* The transform matrix is:
  12130. (mat00 mat01 mat02)
  12131. (mat10 mat11 mat12)
  12132. ( 0 0 1 )
  12133. */
  12134. float mat00, mat01, mat02;
  12135. float mat10, mat11, mat12;
  12136. private:
  12137. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12138. const float mat10, const float mat11, const float mat12) const throw();
  12139. };
  12140. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12141. /********* End of inlined file: juce_AffineTransform.h *********/
  12142. /********* Start of inlined file: juce_Point.h *********/
  12143. #ifndef __JUCE_POINT_JUCEHEADER__
  12144. #define __JUCE_POINT_JUCEHEADER__
  12145. /**
  12146. A pair of (x, y) co-ordinates.
  12147. Uses 32-bit floating point accuracy.
  12148. @see Line, Path, AffineTransform
  12149. */
  12150. class JUCE_API Point
  12151. {
  12152. public:
  12153. /** Creates a point with co-ordinates (0, 0). */
  12154. Point() throw();
  12155. /** Creates a copy of another point. */
  12156. Point (const Point& other) throw();
  12157. /** Creates a point from an (x, y) position. */
  12158. Point (const float x, const float y) throw();
  12159. /** Copies this point from another one.
  12160. @see setXY
  12161. */
  12162. const Point& operator= (const Point& other) throw();
  12163. /** Destructor. */
  12164. ~Point() throw();
  12165. /** Returns the point's x co-ordinate. */
  12166. inline float getX() const throw() { return x; }
  12167. /** Returns the point's y co-ordinate. */
  12168. inline float getY() const throw() { return y; }
  12169. /** Changes the point's x and y co-ordinates. */
  12170. void setXY (const float x,
  12171. const float y) throw();
  12172. /** Uses a transform to change the point's co-ordinates.
  12173. @see AffineTransform::transformPoint
  12174. */
  12175. void applyTransform (const AffineTransform& transform) throw();
  12176. juce_UseDebuggingNewOperator
  12177. private:
  12178. float x, y;
  12179. };
  12180. #endif // __JUCE_POINT_JUCEHEADER__
  12181. /********* End of inlined file: juce_Point.h *********/
  12182. /********* Start of inlined file: juce_Justification.h *********/
  12183. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12184. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12185. /**
  12186. Represents a type of justification to be used when positioning graphical items.
  12187. e.g. it indicates whether something should be placed top-left, top-right,
  12188. centred, etc.
  12189. It is used in various places wherever this kind of information is needed.
  12190. */
  12191. class JUCE_API Justification
  12192. {
  12193. public:
  12194. /** Creates a Justification object using a combination of flags. */
  12195. inline Justification (const int flags_) throw() : flags (flags_) {}
  12196. /** Creates a copy of another Justification object. */
  12197. Justification (const Justification& other) throw();
  12198. /** Copies another Justification object. */
  12199. const Justification& operator= (const Justification& other) throw();
  12200. /** Returns the raw flags that are set for this Justification object. */
  12201. inline int getFlags() const throw() { return flags; }
  12202. /** Tests a set of flags for this object.
  12203. @returns true if any of the flags passed in are set on this object.
  12204. */
  12205. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12206. /** Returns just the flags from this object that deal with vertical layout. */
  12207. int getOnlyVerticalFlags() const throw();
  12208. /** Returns just the flags from this object that deal with horizontal layout. */
  12209. int getOnlyHorizontalFlags() const throw();
  12210. /** Adjusts the position of a rectangle to fit it into a space.
  12211. The (x, y) position of the rectangle will be updated to position it inside the
  12212. given space according to the justification flags.
  12213. */
  12214. void applyToRectangle (int& x, int& y,
  12215. const int w, const int h,
  12216. const int spaceX, const int spaceY,
  12217. const int spaceW, const int spaceH) const throw();
  12218. /** Flag values that can be combined and used in the constructor. */
  12219. enum
  12220. {
  12221. /** Indicates that the item should be aligned against the left edge of the available space. */
  12222. left = 1,
  12223. /** Indicates that the item should be aligned against the right edge of the available space. */
  12224. right = 2,
  12225. /** Indicates that the item should be placed in the centre between the left and right
  12226. sides of the available space. */
  12227. horizontallyCentred = 4,
  12228. /** Indicates that the item should be aligned against the top edge of the available space. */
  12229. top = 8,
  12230. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12231. bottom = 16,
  12232. /** Indicates that the item should be placed in the centre between the top and bottom
  12233. sides of the available space. */
  12234. verticallyCentred = 32,
  12235. /** Indicates that lines of text should be spread out to fill the maximum width
  12236. available, so that both margins are aligned vertically.
  12237. */
  12238. horizontallyJustified = 64,
  12239. /** Indicates that the item should be centred vertically and horizontally.
  12240. This is equivalent to (horizontallyCentred | verticallyCentred)
  12241. */
  12242. centred = 36,
  12243. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12244. This is equivalent to (left | verticallyCentred)
  12245. */
  12246. centredLeft = 33,
  12247. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12248. This is equivalent to (right | verticallyCentred)
  12249. */
  12250. centredRight = 34,
  12251. /** Indicates that the item should be centred horizontally and placed at the top.
  12252. This is equivalent to (horizontallyCentred | top)
  12253. */
  12254. centredTop = 12,
  12255. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12256. This is equivalent to (horizontallyCentred | bottom)
  12257. */
  12258. centredBottom = 20,
  12259. /** Indicates that the item should be placed in the top-left corner.
  12260. This is equivalent to (left | top)
  12261. */
  12262. topLeft = 9,
  12263. /** Indicates that the item should be placed in the top-right corner.
  12264. This is equivalent to (right | top)
  12265. */
  12266. topRight = 10,
  12267. /** Indicates that the item should be placed in the bottom-left corner.
  12268. This is equivalent to (left | bottom)
  12269. */
  12270. bottomLeft = 17,
  12271. /** Indicates that the item should be placed in the bottom-left corner.
  12272. This is equivalent to (right | bottom)
  12273. */
  12274. bottomRight = 18
  12275. };
  12276. private:
  12277. int flags;
  12278. };
  12279. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12280. /********* End of inlined file: juce_Justification.h *********/
  12281. /**
  12282. A path is a sequence of lines and curves that may either form a closed shape
  12283. or be open-ended.
  12284. To use a path, you can create an empty one, then add lines and curves to it
  12285. to create shapes, then it can be rendered by a Graphics context or used
  12286. for geometric operations.
  12287. e.g. @code
  12288. Path myPath;
  12289. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12290. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12291. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12292. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12293. // add an ellipse as well, which will form a second sub-path within the path..
  12294. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12295. // double the width of the whole thing..
  12296. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12297. // and draw it to a graphics context with a 5-pixel thick outline.
  12298. g.strokePath (myPath, PathStrokeType (5.0f));
  12299. @endcode
  12300. A path object can actually contain multiple sub-paths, which may themselves
  12301. be open or closed.
  12302. @see PathFlatteningIterator, PathStrokeType, Graphics
  12303. */
  12304. class JUCE_API Path : private ArrayAllocationBase <float>
  12305. {
  12306. public:
  12307. /** Creates an empty path. */
  12308. Path() throw();
  12309. /** Creates a copy of another path. */
  12310. Path (const Path& other) throw();
  12311. /** Destructor. */
  12312. ~Path() throw();
  12313. /** Copies this path from another one. */
  12314. const Path& operator= (const Path& other) throw();
  12315. /** Returns true if the path doesn't contain any lines or curves. */
  12316. bool isEmpty() const throw();
  12317. /** Returns the smallest rectangle that contains all points within the path.
  12318. */
  12319. void getBounds (float& x, float& y,
  12320. float& w, float& h) const throw();
  12321. /** Returns the smallest rectangle that contains all points within the path
  12322. after it's been transformed with the given tranasform matrix.
  12323. */
  12324. void getBoundsTransformed (const AffineTransform& transform,
  12325. float& x, float& y,
  12326. float& w, float& h) const throw();
  12327. /** Checks whether a point lies within the path.
  12328. This is only relevent for closed paths (see closeSubPath()), and
  12329. may produce false results if used on a path which has open sub-paths.
  12330. The path's winding rule is taken into account by this method.
  12331. @see closeSubPath, setUsingNonZeroWinding
  12332. */
  12333. bool contains (const float x,
  12334. const float y) const throw();
  12335. /** Checks whether a line crosses the path.
  12336. This will return positive if the line crosses any of the paths constituent
  12337. lines or curves. It doesn't take into account whether the line is inside
  12338. or outside the path, or whether the path is open or closed.
  12339. */
  12340. bool intersectsLine (const float x1, const float y1,
  12341. const float x2, const float y2) throw();
  12342. /** Removes all lines and curves, resetting the path completely. */
  12343. void clear() throw();
  12344. /** Begins a new subpath with a given starting position.
  12345. This will move the path's current position to the co-ordinates passed in and
  12346. make it ready to draw lines or curves starting from this position.
  12347. After adding whatever lines and curves are needed, you can either
  12348. close the current sub-path using closeSubPath() or call startNewSubPath()
  12349. to move to a new sub-path, leaving the old one open-ended.
  12350. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12351. */
  12352. void startNewSubPath (const float startX,
  12353. const float startY) throw();
  12354. /** Closes a the current sub-path with a line back to its start-point.
  12355. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12356. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12357. to join the final point back to the start.
  12358. This ensures that closes shapes are recognised as such, and this is
  12359. important for tasks like drawing strokes, which needs to know whether to
  12360. draw end-caps or not.
  12361. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12362. */
  12363. void closeSubPath() throw();
  12364. /** Adds a line from the shape's last position to a new end-point.
  12365. This will connect the end-point of the last line or curve that was added
  12366. to a new point, using a straight line.
  12367. See the class description for an example of how to add lines and curves to a path.
  12368. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12369. */
  12370. void lineTo (const float endX,
  12371. const float endY) throw();
  12372. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12373. This will connect the end-point of the last line or curve that was added
  12374. to a new point, using a quadratic spline with one control-point.
  12375. See the class description for an example of how to add lines and curves to a path.
  12376. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12377. */
  12378. void quadraticTo (const float controlPointX,
  12379. const float controlPointY,
  12380. const float endPointX,
  12381. const float endPointY) throw();
  12382. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12383. This will connect the end-point of the last line or curve that was added
  12384. to a new point, using a cubic spline with two control-points.
  12385. See the class description for an example of how to add lines and curves to a path.
  12386. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12387. */
  12388. void cubicTo (const float controlPoint1X,
  12389. const float controlPoint1Y,
  12390. const float controlPoint2X,
  12391. const float controlPoint2Y,
  12392. const float endPointX,
  12393. const float endPointY) throw();
  12394. /** Returns the last point that was added to the path by one of the drawing methods.
  12395. */
  12396. const Point getCurrentPosition() const;
  12397. /** Adds a rectangle to the path.
  12398. The rectangle is added as a new sub-path. (Any currently open paths will be
  12399. left open).
  12400. @see addRoundedRectangle, addTriangle
  12401. */
  12402. void addRectangle (const float x, const float y,
  12403. const float w, const float h) throw();
  12404. /** Adds a rectangle with rounded corners to the path.
  12405. The rectangle is added as a new sub-path. (Any currently open paths will be
  12406. left open).
  12407. @see addRectangle, addTriangle
  12408. */
  12409. void addRoundedRectangle (const float x, const float y,
  12410. const float w, const float h,
  12411. float cornerSize) throw();
  12412. /** Adds a rectangle with rounded corners to the path.
  12413. The rectangle is added as a new sub-path. (Any currently open paths will be
  12414. left open).
  12415. @see addRectangle, addTriangle
  12416. */
  12417. void addRoundedRectangle (const float x, const float y,
  12418. const float w, const float h,
  12419. float cornerSizeX,
  12420. float cornerSizeY) throw();
  12421. /** Adds a triangle to the path.
  12422. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12423. left open).
  12424. Note that whether the vertices are specified in clockwise or anticlockwise
  12425. order will affect how the triangle is filled when it overlaps other
  12426. shapes (the winding order setting will affect this of course).
  12427. */
  12428. void addTriangle (const float x1, const float y1,
  12429. const float x2, const float y2,
  12430. const float x3, const float y3) throw();
  12431. /** Adds a quadrilateral to the path.
  12432. The quad is added as a new closed sub-path. (Any currently open paths will be
  12433. left open).
  12434. Note that whether the vertices are specified in clockwise or anticlockwise
  12435. order will affect how the quad is filled when it overlaps other
  12436. shapes (the winding order setting will affect this of course).
  12437. */
  12438. void addQuadrilateral (const float x1, const float y1,
  12439. const float x2, const float y2,
  12440. const float x3, const float y3,
  12441. const float x4, const float y4) throw();
  12442. /** Adds an ellipse to the path.
  12443. The shape is added as a new sub-path. (Any currently open paths will be
  12444. left open).
  12445. @see addArc
  12446. */
  12447. void addEllipse (const float x, const float y,
  12448. const float width, const float height) throw();
  12449. /** Adds an elliptical arc to the current path.
  12450. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12451. or anti-clockwise according to whether the end angle is greater than the start. This means
  12452. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12453. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12454. @param y the top edge of the rectangle in which the elliptical outline fits
  12455. @param width the width of the rectangle in which the elliptical outline fits
  12456. @param height the height of the rectangle in which the elliptical outline fits
  12457. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12458. top-centre of the ellipse)
  12459. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12460. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12461. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12462. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12463. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12464. it will be added to the current sub-path, continuing from the current postition
  12465. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12466. */
  12467. void addArc (const float x, const float y,
  12468. const float width, const float height,
  12469. const float fromRadians,
  12470. const float toRadians,
  12471. const bool startAsNewSubPath = false) throw();
  12472. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12473. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12474. or anti-clockwise according to whether the end angle is greater than the start. This means
  12475. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12476. @param centreX the centre x of the ellipse
  12477. @param centreY the centre y of the ellipse
  12478. @param radiusX the horizontal radius of the ellipse
  12479. @param radiusY the vertical radius of the ellipse
  12480. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12481. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12482. top-centre of the ellipse)
  12483. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12484. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12485. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12486. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12487. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12488. it will be added to the current sub-path, continuing from the current postition
  12489. @see addArc, arcTo
  12490. */
  12491. void addCentredArc (const float centreX, const float centreY,
  12492. const float radiusX, const float radiusY,
  12493. const float rotationOfEllipse,
  12494. const float fromRadians,
  12495. const float toRadians,
  12496. const bool startAsNewSubPath = false) throw();
  12497. /** Adds a "pie-chart" shape to the path.
  12498. The shape is added as a new sub-path. (Any currently open paths will be
  12499. left open).
  12500. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12501. or anti-clockwise according to whether the end angle is greater than the start. This means
  12502. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12503. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12504. @param y the top edge of the rectangle in which the elliptical outline fits
  12505. @param width the width of the rectangle in which the elliptical outline fits
  12506. @param height the height of the rectangle in which the elliptical outline fits
  12507. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12508. top-centre of the ellipse)
  12509. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12510. top-centre of the ellipse)
  12511. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12512. ellipse at its centre, where this value indicates the inner ellipse's size with
  12513. respect to the outer one.
  12514. @see addArc
  12515. */
  12516. void addPieSegment (const float x, const float y,
  12517. const float width, const float height,
  12518. const float fromRadians,
  12519. const float toRadians,
  12520. const float innerCircleProportionalSize);
  12521. /** Adds a line with a specified thickness.
  12522. The line is added as a new closed sub-path. (Any currently open paths will be
  12523. left open).
  12524. @see addArrow
  12525. */
  12526. void addLineSegment (const float startX, const float startY,
  12527. const float endX, const float endY,
  12528. float lineThickness) throw();
  12529. /** Adds a line with an arrowhead on the end.
  12530. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12531. left open).
  12532. */
  12533. void addArrow (const float startX, const float startY,
  12534. const float endX, const float endY,
  12535. float lineThickness,
  12536. float arrowheadWidth,
  12537. float arrowheadLength) throw();
  12538. /** Adds a star shape to the path.
  12539. */
  12540. void addStar (const float centreX,
  12541. const float centreY,
  12542. const int numberOfPoints,
  12543. const float innerRadius,
  12544. const float outerRadius,
  12545. const float startAngle = 0.0f);
  12546. /** Adds a speech-bubble shape to the path.
  12547. @param bodyX the left of the main body area of the bubble
  12548. @param bodyY the top of the main body area of the bubble
  12549. @param bodyW the width of the main body area of the bubble
  12550. @param bodyH the height of the main body area of the bubble
  12551. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12552. @param arrowTipX the x position that the tip of the arrow should connect to
  12553. @param arrowTipY the y position that the tip of the arrow should connect to
  12554. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12555. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12556. arrow's base should be - this is a proportional distance between 0 and 1.0
  12557. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12558. */
  12559. void addBubble (float bodyX, float bodyY,
  12560. float bodyW, float bodyH,
  12561. float cornerSize,
  12562. float arrowTipX,
  12563. float arrowTipY,
  12564. int whichSide,
  12565. float arrowPositionAlongEdgeProportional,
  12566. float arrowWidth);
  12567. /** Adds another path to this one.
  12568. The new path is added as a new sub-path. (Any currently open paths in this
  12569. path will be left open).
  12570. @param pathToAppend the path to add
  12571. */
  12572. void addPath (const Path& pathToAppend) throw();
  12573. /** Adds another path to this one, transforming it on the way in.
  12574. The new path is added as a new sub-path, its points being transformed by the given
  12575. matrix before being added.
  12576. @param pathToAppend the path to add
  12577. @param transformToApply an optional transform to apply to the incoming vertices
  12578. */
  12579. void addPath (const Path& pathToAppend,
  12580. const AffineTransform& transformToApply) throw();
  12581. /** Swaps the contents of this path with another one.
  12582. The internal data of the two paths is swapped over, so this is much faster than
  12583. copying it to a temp variable and back.
  12584. */
  12585. void swapWithPath (Path& other);
  12586. /** Applies a 2D transform to all the vertices in the path.
  12587. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12588. */
  12589. void applyTransform (const AffineTransform& transform) throw();
  12590. /** Rescales this path to make it fit neatly into a given space.
  12591. This is effectively a quick way of calling
  12592. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12593. @param x the x position of the rectangle to fit the path inside
  12594. @param y the y position of the rectangle to fit the path inside
  12595. @param width the width of the rectangle to fit the path inside
  12596. @param height the height of the rectangle to fit the path inside
  12597. @param preserveProportions if true, it will fit the path into the space without altering its
  12598. horizontal/vertical scale ratio; if false, it will distort the
  12599. path to fill the specified ratio both horizontally and vertically
  12600. @see applyTransform, getTransformToScaleToFit
  12601. */
  12602. void scaleToFit (const float x, const float y,
  12603. const float width, const float height,
  12604. const bool preserveProportions) throw();
  12605. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12606. @param x the x position of the rectangle to fit the path inside
  12607. @param y the y position of the rectangle to fit the path inside
  12608. @param width the width of the rectangle to fit the path inside
  12609. @param height the height of the rectangle to fit the path inside
  12610. @param preserveProportions if true, it will fit the path into the space without altering its
  12611. horizontal/vertical scale ratio; if false, it will distort the
  12612. path to fill the specified ratio both horizontally and vertically
  12613. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12614. than the available rectangle, so this describes how it should be
  12615. positioned within the space.
  12616. @returns an appropriate transformation
  12617. @see applyTransform, scaleToFit
  12618. */
  12619. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12620. const float width, const float height,
  12621. const bool preserveProportions,
  12622. const Justification& justificationType = Justification::centred) const throw();
  12623. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12624. Wherever two lines meet at an angle, this will replace the corner with a curve
  12625. of the given radius.
  12626. */
  12627. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12628. /** Changes the winding-rule to be used when filling the path.
  12629. If set to true (which is the default), then the path uses a non-zero-winding rule
  12630. to determine which points are inside the path. If set to false, it uses an
  12631. alternate-winding rule.
  12632. The winding-rule comes into play when areas of the shape overlap other
  12633. areas, and determines whether the overlapping regions are considered to be
  12634. inside or outside.
  12635. Changing this value just sets a flag - it doesn't affect the contents of the
  12636. path.
  12637. @see isUsingNonZeroWinding
  12638. */
  12639. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12640. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12641. The default for a new path is true.
  12642. @see setUsingNonZeroWinding
  12643. */
  12644. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12645. /** Iterates the lines and curves that a path contains.
  12646. @see Path, PathFlatteningIterator
  12647. */
  12648. class JUCE_API Iterator
  12649. {
  12650. public:
  12651. Iterator (const Path& path);
  12652. ~Iterator();
  12653. /** Moves onto the next element in the path.
  12654. If this returns false, there are no more elements. If it returns true,
  12655. the elementType variable will be set to the type of the current element,
  12656. and some of the x and y variables will be filled in with values.
  12657. */
  12658. bool next();
  12659. enum PathElementType
  12660. {
  12661. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12662. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12663. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12664. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12665. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12666. };
  12667. PathElementType elementType;
  12668. float x1, y1, x2, y2, x3, y3;
  12669. private:
  12670. const Path& path;
  12671. int index;
  12672. Iterator (const Iterator&);
  12673. const Iterator& operator= (const Iterator&);
  12674. };
  12675. /** Loads a stored path from a data stream.
  12676. The data in the stream must have been written using writePathToStream().
  12677. Note that this will append the stored path to whatever is currently in
  12678. this path, so you might need to call clear() beforehand.
  12679. @see loadPathFromData, writePathToStream
  12680. */
  12681. void loadPathFromStream (InputStream& source);
  12682. /** Loads a stored path from a block of data.
  12683. This is similar to loadPathFromStream(), but just reads from a block
  12684. of data. Useful if you're including stored shapes in your code as a
  12685. block of static data.
  12686. @see loadPathFromStream, writePathToStream
  12687. */
  12688. void loadPathFromData (const unsigned char* const data,
  12689. const int numberOfBytes) throw();
  12690. /** Stores the path by writing it out to a stream.
  12691. After writing out a path, you can reload it using loadPathFromStream().
  12692. @see loadPathFromStream, loadPathFromData
  12693. */
  12694. void writePathToStream (OutputStream& destination) const;
  12695. /** Creates a string containing a textual representation of this path.
  12696. @see restoreFromString
  12697. */
  12698. const String toString() const;
  12699. /** Restores this path from a string that was created with the toString() method.
  12700. @see toString()
  12701. */
  12702. void restoreFromString (const String& stringVersion);
  12703. juce_UseDebuggingNewOperator
  12704. private:
  12705. friend class PathFlatteningIterator;
  12706. friend class Path::Iterator;
  12707. int numElements;
  12708. float pathXMin, pathXMax, pathYMin, pathYMax;
  12709. bool useNonZeroWinding;
  12710. static const float lineMarker;
  12711. static const float moveMarker;
  12712. static const float quadMarker;
  12713. static const float cubicMarker;
  12714. static const float closeSubPathMarker;
  12715. };
  12716. #endif // __JUCE_PATH_JUCEHEADER__
  12717. /********* End of inlined file: juce_Path.h *********/
  12718. class Font;
  12719. class Typeface;
  12720. /**
  12721. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12722. @see Typeface, PositionedGlyph, GlyphArrangement
  12723. */
  12724. class JUCE_API TypefaceGlyphInfo
  12725. {
  12726. public:
  12727. /** Returns the path that describes the glyph's outline.
  12728. This is normalised to a height of 1.0, and its origin is the
  12729. left-hand edge of the glyph's baseline.
  12730. */
  12731. const Path& getPath() const throw() { return path; }
  12732. /** Returns the unicode character that this glyph represents. */
  12733. juce_wchar getCharacter() const throw() { return character; }
  12734. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12735. /** Returns the distance to leave between this and a following character.
  12736. The value returned is expressed as a proportion of the font's height.
  12737. */
  12738. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12739. /** Returns the typeface that this glyph belongs to. */
  12740. Typeface* getTypeface() const throw() { return typeface; }
  12741. private:
  12742. friend class Typeface;
  12743. struct KerningPair
  12744. {
  12745. juce_wchar character2;
  12746. float kerningAmount;
  12747. };
  12748. const juce_wchar character;
  12749. const Path path;
  12750. float width;
  12751. MemoryBlock kerningPairs;
  12752. Typeface* const typeface;
  12753. TypefaceGlyphInfo (const juce_wchar character,
  12754. const Path& shape,
  12755. const float horizontalSeparation,
  12756. Typeface* const typeface) throw();
  12757. ~TypefaceGlyphInfo() throw();
  12758. KerningPair& getKerningPair (const int index) const throw();
  12759. int getNumKerningPairs() const throw();
  12760. void addKerningPair (const juce_wchar subsequentCharacter,
  12761. const float extraKerningAmount) throw();
  12762. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12763. };
  12764. /**
  12765. Represents a size-independent system font.
  12766. A Font object represents a particular Typeface along with a specific size,
  12767. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12768. of the shapes of the glyphs and their properties.
  12769. */
  12770. class JUCE_API Typeface : public ReferenceCountedObject
  12771. {
  12772. public:
  12773. /** Tries to load a named system font and to initialise all the glyphs
  12774. appropriately from it.
  12775. @param faceName the name of the typeface, e.g. "Times"
  12776. @param bold whether to try to find a bold version of the font (may not always be available)
  12777. @param italic whether to try to find an italicised version of the font (may not always be available)
  12778. */
  12779. Typeface (const String& faceName,
  12780. const bool bold,
  12781. const bool italic);
  12782. /** Creates a copy of another typeface */
  12783. Typeface (const Typeface& other);
  12784. /** Destructor. */
  12785. ~Typeface();
  12786. /** Copies another typeface over this one. */
  12787. const Typeface& operator= (const Typeface& other) throw();
  12788. /** Returns a unique ID for the typeface.
  12789. This is based on the name and style, so can be used to compare two Typeface objects.
  12790. */
  12791. int hashCode() const throw() { return hash; }
  12792. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12793. const String& getName() const throw() { return typefaceName; }
  12794. /** Returns the font's ascent as a proportion of its height. */
  12795. float getAscent() const throw() { return ascent; }
  12796. /** Returns true if the font is flagged as being bold. */
  12797. bool isBold() const throw() { return bold; }
  12798. /** Returns true if the typeface's 'italic' flag is set. */
  12799. bool isItalic() const throw() { return italic; }
  12800. /** Finds the Path that describes the outline shape of a character.
  12801. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12802. height of the font).
  12803. This may return 0 if the typeface has no characters, but if the character
  12804. that is asked for is not found, it will first try to return a default
  12805. character instead.
  12806. */
  12807. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12808. /** Tries to find the information describing a glyph for this character.
  12809. If there isn't a glyph specifically for the character it will return
  12810. a default glyph instead; if the typeface is empty, it may return a null
  12811. pointer.
  12812. */
  12813. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12814. /** Deletes all the glyphs and kerning data fom the typeface. */
  12815. void clear() throw();
  12816. /** Adds a glyph to the typeface.
  12817. This is typically only called by the platform-specific code that generates
  12818. the typeface from a system font.
  12819. */
  12820. void addGlyph (const juce_wchar character,
  12821. const Path& path,
  12822. const float horizontalSpacing) throw();
  12823. /** Adds a kerning distance to the typeface.
  12824. The extra amount passed in is expressed as a proportion of the font's
  12825. height, normalised to 1.0.
  12826. This is typically only called by the platform-specific code that generates
  12827. the typeface from a system font.
  12828. */
  12829. void addKerningPair (const juce_wchar firstChar,
  12830. const juce_wchar secondChar,
  12831. const float extraAmount) throw();
  12832. /** Sets the typeface's name.
  12833. This is typically only called by the platform-specific code that generates
  12834. the typeface from a system font. Calling this method won't actually affect
  12835. the underlying font being used.
  12836. */
  12837. void setName (const String& name) throw();
  12838. /** Sets the font's ascent value, as a proportion of the font height.
  12839. This is typically only called by the platform-specific code that generates
  12840. the typeface from a system font.
  12841. */
  12842. void setAscent (const float newAscent) throw();
  12843. /** Sets the typeface's 'bold' flag.
  12844. This is typically only called by the platform-specific code that generates
  12845. the typeface from a system font.
  12846. */
  12847. void setBold (const bool shouldBeBold) throw();
  12848. /** Sets the typeface's 'italic' flag.
  12849. This is typically only called by the platform-specific code that generates
  12850. the typeface from a system font.
  12851. */
  12852. void setItalic (const bool shouldBeItalic) throw();
  12853. /** Changes the character index to use as the default character.
  12854. This is the character that gets returned for characters which don't have a
  12855. glyph set for them.
  12856. */
  12857. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12858. /** Creates a typeface from data created using Typeface::serialise().
  12859. This will attempt to load a compressed typeface that was created using
  12860. the Typeface::serialise() method. This is handy if you want to store
  12861. a typeface in your application as a binary blob, and use it without
  12862. having to actually install it on the computer.
  12863. @see Typeface::serialise()
  12864. */
  12865. Typeface (InputStream& serialisedTypefaceStream);
  12866. /** Writes the typeface to a stream (using a proprietary format).
  12867. This lets you save a typeface and reload it using the
  12868. Typeface::Typeface (InputStream&) constructor. The data's saved in
  12869. a compressed format.
  12870. @see Typeface::Typeface (InputStream&)
  12871. */
  12872. void serialise (OutputStream& outputStream);
  12873. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  12874. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  12875. juce_UseDebuggingNewOperator
  12876. private:
  12877. VoidArray glyphs;
  12878. short lookupTable [128];
  12879. String typefaceName;
  12880. int hash;
  12881. float ascent; // as a proportion of the height
  12882. bool bold, italic, isFullyPopulated;
  12883. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  12884. Typeface() throw();
  12885. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  12886. friend class Font;
  12887. friend class TypefaceCache;
  12888. friend class FontGlyphAlphaMap;
  12889. static const Ptr getTypefaceFor (const Font& font) throw();
  12890. // this is a platform-dependent method that will look for the given typeface
  12891. // and set up its kerning tables, etc. accordingly.
  12892. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  12893. // to the typeface immediately, rather than having to add them later on-demand.
  12894. void initialiseTypefaceCharacteristics (const String& fontName,
  12895. bool bold, bool italic,
  12896. bool addAllGlyphsToFont) throw();
  12897. // platform-specific routine to look up and add a glyph to this typeface
  12898. bool findAndAddSystemGlyph (juce_wchar character) throw();
  12899. void updateHashCode() throw();
  12900. };
  12901. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  12902. /********* End of inlined file: juce_Typeface.h *********/
  12903. /**
  12904. Represents a particular font, including its size, style, etc.
  12905. Apart from the typeface to be used, a Font object also dictates whether
  12906. the font is bold, italic, underlined, how big it is, and its kerning and
  12907. horizontal scale factor.
  12908. @see Typeface
  12909. */
  12910. class JUCE_API Font
  12911. {
  12912. public:
  12913. /** A combination of these values is used by the constructor to specify the
  12914. style of font to use.
  12915. */
  12916. enum FontStyleFlags
  12917. {
  12918. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  12919. bold = 1, /**< boldens the font. @see setStyleFlags */
  12920. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  12921. underlined = 4 /**< underlines the font. @see setStyleFlags */
  12922. };
  12923. /** Creates a sans-serif font in a given size.
  12924. @param fontHeight the height in pixels (can be fractional)
  12925. @param styleFlags the style to use - this can be a combination of the
  12926. Font::bold, Font::italic and Font::underlined, or
  12927. just Font::plain for the normal style.
  12928. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12929. */
  12930. Font (const float fontHeight,
  12931. const int styleFlags = plain) throw();
  12932. /** Creates a font with a given typeface and parameters.
  12933. @param typefaceName the name of the typeface to use
  12934. @param fontHeight the height in pixels (can be fractional)
  12935. @param styleFlags the style to use - this can be a combination of the
  12936. Font::bold, Font::italic and Font::underlined, or
  12937. just Font::plain for the normal style.
  12938. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12939. */
  12940. Font (const String& typefaceName,
  12941. const float fontHeight,
  12942. const int styleFlags) throw();
  12943. /** Creates a copy of another Font object. */
  12944. Font (const Font& other) throw();
  12945. /** Creates a font based on a typeface.
  12946. The font object stores its own internal copy of the typeface, so you can safely
  12947. delete the one passed in after calling this.
  12948. */
  12949. Font (const Typeface& typeface) throw();
  12950. /** Creates a basic sans-serif font at a default height.
  12951. You should use one of the other constructors for creating a font that you're planning
  12952. on drawing with - this constructor is here to help initialise objects before changing
  12953. the font's settings later.
  12954. */
  12955. Font() throw();
  12956. /** Copies this font from another one. */
  12957. const Font& operator= (const Font& other) throw();
  12958. bool operator== (const Font& other) const throw();
  12959. bool operator!= (const Font& other) const throw();
  12960. /** Destructor. */
  12961. ~Font() throw();
  12962. /** Changes the name of the typeface family.
  12963. e.g. "Arial", "Courier", etc.
  12964. If a suitable font isn't found on the machine, it'll just use a default instead.
  12965. */
  12966. void setTypefaceName (const String& faceName) throw();
  12967. /** Returns the name of the typeface family that this font uses.
  12968. e.g. "Arial", "Courier", etc.
  12969. */
  12970. const String& getTypefaceName() const throw() { return typefaceName; }
  12971. /** Returns a platform-specific font family that is recommended for sans-serif fonts.
  12972. This is the typeface that will be used when a font is created without
  12973. specifying another name.
  12974. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  12975. setDefaultSansSerifFontName
  12976. */
  12977. static const String getDefaultSansSerifFontName() throw();
  12978. /** Returns a platform-specific font family that is recommended for serif fonts.
  12979. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  12980. */
  12981. static const String getDefaultSerifFontName() throw();
  12982. /** Returns a platform-specific font family that is recommended for monospaced fonts.
  12983. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  12984. */
  12985. static const String getDefaultMonospacedFontName() throw();
  12986. /** Changes the default sans-serif typeface family name.
  12987. This changes the value that is returned by getDefaultSansSerifFontName(), so
  12988. changing this will change the default system font used.
  12989. @see getDefaultSansSerifFontName
  12990. */
  12991. static void setDefaultSansSerifFontName (const String& name) throw();
  12992. /** Returns the total height of this font.
  12993. This is the maximum height, from the top of the ascent to the bottom of the
  12994. descenders.
  12995. @see setHeight, setHeightWithoutChangingWidth, getAscent
  12996. */
  12997. float getHeight() const throw() { return height; }
  12998. /** Changes the font's height.
  12999. @see getHeight, setHeightWithoutChangingWidth
  13000. */
  13001. void setHeight (float newHeight) throw();
  13002. /** Changes the font's height without changing its width.
  13003. This alters the horizontal scale to compensate for the change in height.
  13004. */
  13005. void setHeightWithoutChangingWidth (float newHeight) throw();
  13006. /** Returns the height of the font above its baseline.
  13007. This is the maximum height from the baseline to the top.
  13008. @see getHeight, getDescent
  13009. */
  13010. float getAscent() const throw();
  13011. /** Returns the amount that the font descends below its baseline.
  13012. This is calculated as (getHeight() - getAscent()).
  13013. @see getAscent, getHeight
  13014. */
  13015. float getDescent() const throw();
  13016. /** Returns the font's style flags.
  13017. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13018. enum, to describe whether the font is bold, italic, etc.
  13019. @see FontStyleFlags
  13020. */
  13021. int getStyleFlags() const throw() { return styleFlags; }
  13022. /** Changes the font's style.
  13023. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13024. enum, to set the font's properties
  13025. @see FontStyleFlags
  13026. */
  13027. void setStyleFlags (const int newFlags) throw();
  13028. /** Makes the font bold or non-bold. */
  13029. void setBold (const bool shouldBeBold) throw();
  13030. /** Returns true if the font is bold. */
  13031. bool isBold() const throw();
  13032. /** Makes the font italic or non-italic. */
  13033. void setItalic (const bool shouldBeItalic) throw();
  13034. /** Returns true if the font is italic. */
  13035. bool isItalic() const throw();
  13036. /** Makes the font underlined or non-underlined. */
  13037. void setUnderline (const bool shouldBeUnderlined) throw();
  13038. /** Returns true if the font is underlined. */
  13039. bool isUnderlined() const throw();
  13040. /** Changes the font's horizontal scale factor.
  13041. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13042. narrower, greater than 1.0 will be stretched out.
  13043. */
  13044. void setHorizontalScale (const float scaleFactor) throw();
  13045. /** Returns the font's horizontal scale.
  13046. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13047. than 1.0 will be stretched out.
  13048. @see setHorizontalScale
  13049. */
  13050. float getHorizontalScale() const throw() { return horizontalScale; }
  13051. /** Changes the font's kerning.
  13052. @param extraKerning a multiple of the font's height that will be added
  13053. to space between the characters. So a value of zero is
  13054. normal spacing, positive values spread the letters out,
  13055. negative values make them closer together.
  13056. */
  13057. void setExtraKerningFactor (const float extraKerning) throw();
  13058. /** Returns the font's kerning.
  13059. This is the extra space added between adjacent characters, as a proportion
  13060. of the font's height.
  13061. A value of zero is normal spacing, positive values will spread the letters
  13062. out more, and negative values make them closer together.
  13063. */
  13064. float getExtraKerningFactor() const throw() { return kerning; }
  13065. /** Changes all the font's characteristics with one call. */
  13066. void setSizeAndStyle (const float newHeight,
  13067. const int newStyleFlags,
  13068. const float newHorizontalScale,
  13069. const float newKerningAmount) throw();
  13070. /** Resets this font's characteristics.
  13071. This is basically like saying "myFont = Font();", because it resets the
  13072. typeface, size, style, etc to a default state. Not very useful to most
  13073. people, its raison d'etre is to help the Graphics class be more efficient.
  13074. */
  13075. void resetToDefaultState() throw();
  13076. /** Returns the total width of a string as it would be drawn using this font.
  13077. For a more accurate floating-point result, use getStringWidthFloat().
  13078. */
  13079. int getStringWidth (const String& text) const throw();
  13080. /** Returns the total width of a string as it would be drawn using this font.
  13081. @see getStringWidth
  13082. */
  13083. float getStringWidthFloat (const String& text) const throw();
  13084. /** Returns the typeface used by this font.
  13085. Note that the object returned may go out of scope if this font is deleted
  13086. or has its style changed.
  13087. */
  13088. Typeface* getTypeface() const throw();
  13089. /** Creates an array of Font objects to represent all the fonts on the system.
  13090. If you just need the names of the typefaces, you can also use
  13091. findAllTypefaceNames() instead.
  13092. @param results the array to which new Font objects will be added.
  13093. */
  13094. static void findFonts (OwnedArray<Font>& results) throw();
  13095. /** Returns a list of all the available typeface names.
  13096. The names returned can be passed into setTypefaceName().
  13097. You can use this instead of findFonts() if you only need their names, and not
  13098. font objects.
  13099. */
  13100. static const StringArray findAllTypefaceNames() throw();
  13101. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13102. in the requested typeface.
  13103. */
  13104. static const String getFallbackFontName() throw();
  13105. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13106. available in whatever font you're trying to use.
  13107. */
  13108. static void setFallbackFontName (const String& name) throw();
  13109. juce_UseDebuggingNewOperator
  13110. private:
  13111. friend class FontGlyphAlphaMap;
  13112. friend class TypefaceCache;
  13113. String typefaceName;
  13114. float height, horizontalScale, kerning;
  13115. mutable float ascent;
  13116. int styleFlags;
  13117. mutable Typeface::Ptr typeface;
  13118. // platform-specific calls
  13119. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13120. friend void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  13121. static void initialiseDefaultFontNames() throw();
  13122. };
  13123. #endif // __JUCE_FONT_JUCEHEADER__
  13124. /********* End of inlined file: juce_Font.h *********/
  13125. /********* Start of inlined file: juce_Rectangle.h *********/
  13126. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13127. #define __JUCE_RECTANGLE_JUCEHEADER__
  13128. /**
  13129. A rectangle, specified using integer co-ordinates.
  13130. @see RectangleList, Path, Line, Point
  13131. */
  13132. class JUCE_API Rectangle
  13133. {
  13134. public:
  13135. /** Creates a rectangle of zero size.
  13136. The default co-ordinates will be (0, 0, 0, 0).
  13137. */
  13138. Rectangle() throw();
  13139. /** Creates a copy of another rectangle. */
  13140. Rectangle (const Rectangle& other) throw();
  13141. /** Creates a rectangle with a given position and size. */
  13142. Rectangle (const int x, const int y,
  13143. const int width, const int height) throw();
  13144. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13145. Rectangle (const int width, const int height) throw();
  13146. /** Destructor. */
  13147. ~Rectangle() throw();
  13148. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13149. inline int getX() const throw() { return x; }
  13150. /** Returns the y co-ordinate of the rectangle's top edge. */
  13151. inline int getY() const throw() { return y; }
  13152. /** Returns the width of the rectangle. */
  13153. inline int getWidth() const throw() { return w; }
  13154. /** Returns the height of the rectangle. */
  13155. inline int getHeight() const throw() { return h; }
  13156. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13157. inline int getRight() const throw() { return x + w; }
  13158. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13159. inline int getBottom() const throw() { return y + h; }
  13160. /** Returns the x co-ordinate of the rectangle's centre. */
  13161. inline int getCentreX() const throw() { return x + (w >> 1); }
  13162. /** Returns the y co-ordinate of the rectangle's centre. */
  13163. inline int getCentreY() const throw() { return y + (h >> 1); }
  13164. /** Returns true if the rectangle's width and height are both zero or less */
  13165. bool isEmpty() const throw();
  13166. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13167. void setPosition (const int x, const int y) throw();
  13168. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13169. void setSize (const int w, const int h) throw();
  13170. /** Changes all the rectangle's co-ordinates. */
  13171. void setBounds (const int newX, const int newY,
  13172. const int newWidth, const int newHeight) throw();
  13173. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13174. void translate (const int deltaX,
  13175. const int deltaY) throw();
  13176. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13177. const Rectangle translated (const int deltaX,
  13178. const int deltaY) const throw();
  13179. /** Expands the rectangle by a given amount.
  13180. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13181. @see expanded, reduce, reduced
  13182. */
  13183. void expand (const int deltaX,
  13184. const int deltaY) throw();
  13185. /** Returns a rectangle that is larger than this one by a given amount.
  13186. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13187. @see expand, reduce, reduced
  13188. */
  13189. const Rectangle expanded (const int deltaX,
  13190. const int deltaY) const throw();
  13191. /** Shrinks the rectangle by a given amount.
  13192. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13193. @see reduced, expand, expanded
  13194. */
  13195. void reduce (const int deltaX,
  13196. const int deltaY) throw();
  13197. /** Returns a rectangle that is smaller than this one by a given amount.
  13198. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13199. @see reduce, expand, expanded
  13200. */
  13201. const Rectangle reduced (const int deltaX,
  13202. const int deltaY) const throw();
  13203. /** Returns true if the two rectangles are identical. */
  13204. bool operator== (const Rectangle& other) const throw();
  13205. /** Returns true if the two rectangles are not identical. */
  13206. bool operator!= (const Rectangle& other) const throw();
  13207. /** Returns true if this co-ordinate is inside the rectangle. */
  13208. bool contains (const int x, const int y) const throw();
  13209. /** Returns true if this other rectangle is completely inside this one. */
  13210. bool contains (const Rectangle& other) const throw();
  13211. /** Returns true if any part of another rectangle overlaps this one. */
  13212. bool intersects (const Rectangle& other) const throw();
  13213. /** Returns the region that is the overlap between this and another rectangle.
  13214. If the two rectangles don't overlap, the rectangle returned will be empty.
  13215. */
  13216. const Rectangle getIntersection (const Rectangle& other) const throw();
  13217. /** Clips a rectangle so that it lies only within this one.
  13218. This is a non-static version of intersectRectangles().
  13219. Returns false if the two regions didn't overlap.
  13220. */
  13221. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13222. /** Returns the smallest rectangle that contains both this one and the one
  13223. passed-in.
  13224. */
  13225. const Rectangle getUnion (const Rectangle& other) const throw();
  13226. /** If this rectangle merged with another one results in a simple rectangle, this
  13227. will set this rectangle to the result, and return true.
  13228. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13229. or if they form a complex region.
  13230. */
  13231. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13232. /** If after removing another rectangle from this one the result is a simple rectangle,
  13233. this will set this object's bounds to be the result, and return true.
  13234. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13235. or if removing the other one would form a complex region.
  13236. */
  13237. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13238. /** Static utility to intersect two sets of rectangular co-ordinates.
  13239. Returns false if the two regions didn't overlap.
  13240. @see intersectRectangle
  13241. */
  13242. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13243. int x2, int y2, int w2, int h2) throw();
  13244. /** Creates a string describing this rectangle.
  13245. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13246. Coupled with the fromString() method, this is very handy for things like
  13247. storing rectangles (particularly component positions) in XML attributes.
  13248. @see fromString
  13249. */
  13250. const String toString() const throw();
  13251. /** Parses a string containing a rectangle's details.
  13252. The string should contain 4 integer tokens, in the form "x y width height". They
  13253. can be comma or whitespace separated.
  13254. This method is intended to go with the toString() method, to form an easy way
  13255. of saving/loading rectangles as strings.
  13256. @see toString
  13257. */
  13258. static const Rectangle fromString (const String& stringVersion);
  13259. juce_UseDebuggingNewOperator
  13260. private:
  13261. friend class RectangleList;
  13262. int x, y, w, h;
  13263. };
  13264. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13265. /********* End of inlined file: juce_Rectangle.h *********/
  13266. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13267. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13268. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13269. /**
  13270. Describes a type of stroke used to render a solid outline along a path.
  13271. A PathStrokeType object can be used directly to create the shape of an outline
  13272. around a path, and is used by Graphics::strokePath to specify the type of
  13273. stroke to draw.
  13274. @see Path, Graphics::strokePath
  13275. */
  13276. class JUCE_API PathStrokeType
  13277. {
  13278. public:
  13279. /** The type of shape to use for the corners between two adjacent line segments. */
  13280. enum JointStyle
  13281. {
  13282. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13283. Note that for angles that curve back on themselves, drawing a
  13284. mitre could require extending the point too far away from the
  13285. path, so a mitre limit is imposed and any corners that exceed it
  13286. are drawn as bevelled instead. */
  13287. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13288. beveled /**< Indicates that corners should be drawn with a line flattening their
  13289. outside edge. */
  13290. };
  13291. /** The type shape to use for the ends of lines. */
  13292. enum EndCapStyle
  13293. {
  13294. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13295. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13296. the thickness of the stroke. */
  13297. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13298. };
  13299. /** Creates a stroke type.
  13300. @param strokeThickness the width of the line to use
  13301. @param jointStyle the type of joints to use for corners
  13302. @param endStyle the type of end-caps to use for the ends of open paths.
  13303. */
  13304. PathStrokeType (const float strokeThickness,
  13305. const JointStyle jointStyle = mitered,
  13306. const EndCapStyle endStyle = butt) throw();
  13307. /** Createes a copy of another stroke type. */
  13308. PathStrokeType (const PathStrokeType& other) throw();
  13309. /** Copies another stroke onto this one. */
  13310. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13311. /** Destructor. */
  13312. ~PathStrokeType() throw();
  13313. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13314. @param destPath the resultant stroked outline shape will be copied into this path.
  13315. Note that it's ok for the source and destination Paths to be
  13316. the same object, so you can easily turn a path into a stroked version
  13317. of itself.
  13318. @param sourcePath the path to use as the source
  13319. @param transform an optional transform to apply to the points from the source path
  13320. as they are being used
  13321. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13322. a higher resolution, which improved the quality if you'll later want
  13323. to enlarge the stroked path
  13324. @see createDashedStroke
  13325. */
  13326. void createStrokedPath (Path& destPath,
  13327. const Path& sourcePath,
  13328. const AffineTransform& transform = AffineTransform::identity,
  13329. const float extraAccuracy = 1.0f) const throw();
  13330. /** Applies this stroke type to a path, creating a dashed line.
  13331. This is similar to createStrokedPath, but uses the array passed in to
  13332. break the stroke up into a series of dashes.
  13333. @param destPath the resultant stroked outline shape will be copied into this path.
  13334. Note that it's ok for the source and destination Paths to be
  13335. the same object, so you can easily turn a path into a stroked version
  13336. of itself.
  13337. @param sourcePath the path to use as the source
  13338. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13339. a line of length 2, then skip a length of 3, then add a line of length 4,
  13340. skip 5, and keep repeating this pattern.
  13341. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13342. an even number, otherwise the pattern will get out of step as it
  13343. repeats.
  13344. @param transform an optional transform to apply to the points from the source path
  13345. as they are being used
  13346. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13347. a higher resolution, which improved the quality if you'll later want
  13348. to enlarge the stroked path
  13349. */
  13350. void createDashedStroke (Path& destPath,
  13351. const Path& sourcePath,
  13352. const float* dashLengths,
  13353. int numDashLengths,
  13354. const AffineTransform& transform = AffineTransform::identity,
  13355. const float extraAccuracy = 1.0f) const throw();
  13356. /** Returns the stroke thickness. */
  13357. float getStrokeThickness() const throw() { return thickness; }
  13358. /** Returns the joint style. */
  13359. JointStyle getJointStyle() const throw() { return jointStyle; }
  13360. /** Returns the end-cap style. */
  13361. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13362. juce_UseDebuggingNewOperator
  13363. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13364. bool operator== (const PathStrokeType& other) const throw();
  13365. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13366. bool operator!= (const PathStrokeType& other) const throw();
  13367. private:
  13368. float thickness;
  13369. JointStyle jointStyle;
  13370. EndCapStyle endStyle;
  13371. };
  13372. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13373. /********* End of inlined file: juce_PathStrokeType.h *********/
  13374. /********* Start of inlined file: juce_Line.h *********/
  13375. #ifndef __JUCE_LINE_JUCEHEADER__
  13376. #define __JUCE_LINE_JUCEHEADER__
  13377. /**
  13378. Represents a line, using 32-bit float co-ordinates.
  13379. This class contains a bunch of useful methods for various geometric
  13380. tasks.
  13381. @see Point, Rectangle, Path, Graphics::drawLine
  13382. */
  13383. class JUCE_API Line
  13384. {
  13385. public:
  13386. /** Creates a line, using (0, 0) as its start and end points. */
  13387. Line() throw();
  13388. /** Creates a copy of another line. */
  13389. Line (const Line& other) throw();
  13390. /** Creates a line based on the co-ordinates of its start and end points. */
  13391. Line (const float startX,
  13392. const float startY,
  13393. const float endX,
  13394. const float endY) throw();
  13395. /** Creates a line from its start and end points. */
  13396. Line (const Point& start,
  13397. const Point& end) throw();
  13398. /** Copies a line from another one. */
  13399. const Line& operator= (const Line& other) throw();
  13400. /** Destructor. */
  13401. ~Line() throw();
  13402. /** Returns the x co-ordinate of the line's start point. */
  13403. inline float getStartX() const throw() { return startX; }
  13404. /** Returns the y co-ordinate of the line's start point. */
  13405. inline float getStartY() const throw() { return startY; }
  13406. /** Returns the x co-ordinate of the line's end point. */
  13407. inline float getEndX() const throw() { return endX; }
  13408. /** Returns the y co-ordinate of the line's end point. */
  13409. inline float getEndY() const throw() { return endY; }
  13410. /** Returns the line's start point. */
  13411. const Point getStart() const throw();
  13412. /** Returns the line's end point. */
  13413. const Point getEnd() const throw();
  13414. /** Changes this line's start point */
  13415. void setStart (const float newStartX,
  13416. const float newStartY) throw();
  13417. /** Changes this line's end point */
  13418. void setEnd (const float newEndX,
  13419. const float newEndY) throw();
  13420. /** Changes this line's start point */
  13421. void setStart (const Point& newStart) throw();
  13422. /** Changes this line's end point */
  13423. void setEnd (const Point& newEnd) throw();
  13424. /** Applies an affine transform to the line's start and end points. */
  13425. void applyTransform (const AffineTransform& transform) throw();
  13426. /** Returns the length of the line. */
  13427. float getLength() const throw();
  13428. /** Returns true if the line's start and end x co-ordinates are the same. */
  13429. bool isVertical() const throw();
  13430. /** Returns true if the line's start and end y co-ordinates are the same. */
  13431. bool isHorizontal() const throw();
  13432. /** Returns the line's angle.
  13433. This value is the number of radians clockwise from the 3 o'clock direction,
  13434. where the line's start point is considered to be at the centre.
  13435. */
  13436. float getAngle() const throw();
  13437. /** Compares two lines. */
  13438. bool operator== (const Line& other) const throw();
  13439. /** Compares two lines. */
  13440. bool operator!= (const Line& other) const throw();
  13441. /** Finds the intersection between two lines.
  13442. @param line the other line
  13443. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13444. where they would meet if they were infinitely long)
  13445. the intersection (if the lines intersect). If the lines
  13446. are parallel, this will just be set to the position
  13447. of one of the line's endpoints.
  13448. @param intersectionY the y co-ordinate of the point where the lines meet
  13449. @returns true if the line segments intersect; false if they dont. Even if they
  13450. don't intersect, the intersection co-ordinates returned will still
  13451. be valid
  13452. */
  13453. bool intersects (const Line& line,
  13454. float& intersectionX,
  13455. float& intersectionY) const throw();
  13456. /** Returns the location of the point which is a given distance along this line.
  13457. @param distanceFromStart the distance to move along the line from its
  13458. start point. This value can be negative or longer
  13459. than the line itself
  13460. @see getPointAlongLineProportionally
  13461. */
  13462. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13463. /** Returns a point which is a certain distance along and to the side of this line.
  13464. This effectively moves a given distance along the line, then another distance
  13465. perpendicularly to this, and returns the resulting position.
  13466. @param distanceFromStart the distance to move along the line from its
  13467. start point. This value can be negative or longer
  13468. than the line itself
  13469. @param perpendicularDistance how far to move sideways from the line. If you're
  13470. looking along the line from its start towards its
  13471. end, then a positive value here will move to the
  13472. right, negative value move to the left.
  13473. */
  13474. const Point getPointAlongLine (const float distanceFromStart,
  13475. const float perpendicularDistance) const throw();
  13476. /** Returns the location of the point which is a given distance along this line
  13477. proportional to the line's length.
  13478. @param proportionOfLength the distance to move along the line from its
  13479. start point, in multiples of the line's length.
  13480. So a value of 0.0 will return the line's start point
  13481. and a value of 1.0 will return its end point. (This value
  13482. can be negative or greater than 1.0).
  13483. @see getPointAlongLine
  13484. */
  13485. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13486. /** Returns the smallest distance between this line segment and a given point.
  13487. So if the point is close to the line, this will return the perpendicular
  13488. distance from the line; if the point is a long way beyond one of the line's
  13489. end-point's, it'll return the straight-line distance to the nearest end-point.
  13490. @param x x position of the point to test
  13491. @param y y position of the point to test
  13492. @returns the point's distance from the line
  13493. @see getPositionAlongLineOfNearestPoint
  13494. */
  13495. float getDistanceFromLine (const float x,
  13496. const float y) const throw();
  13497. /** Finds the point on this line which is nearest to a given point, and
  13498. returns its position as a proportional position along the line.
  13499. @param x x position of the point to test
  13500. @param y y position of the point to test
  13501. @returns a value 0 to 1.0 which is the distance along this line from the
  13502. line's start to the point which is nearest to the point passed-in. To
  13503. turn this number into a position, use getPointAlongLineProportionally().
  13504. @see getDistanceFromLine, getPointAlongLineProportionally
  13505. */
  13506. float findNearestPointTo (const float x,
  13507. const float y) const throw();
  13508. /** Returns true if the given point lies above this line.
  13509. The return value is true if the point's y coordinate is less than the y
  13510. coordinate of this line at the given x (assuming the line extends infinitely
  13511. in both directions).
  13512. */
  13513. bool isPointAbove (const float x, const float y) const throw();
  13514. /** Returns a shortened copy of this line.
  13515. This will chop off part of the start of this line by a certain amount, (leaving the
  13516. end-point the same), and return the new line.
  13517. */
  13518. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13519. /** Returns a shortened copy of this line.
  13520. This will chop off part of the end of this line by a certain amount, (leaving the
  13521. start-point the same), and return the new line.
  13522. */
  13523. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13524. /** Cuts off parts of this line to keep the parts that are either inside or
  13525. outside a path.
  13526. Note that this isn't smart enough to cope with situations where the
  13527. line would need to be cut into multiple pieces to correctly clip against
  13528. a re-entrant shape.
  13529. @param path the path to clip against
  13530. @param keepSectionOutsidePath if true, it's the section outside the path
  13531. that will be kept; if false its the section inside
  13532. the path
  13533. @returns true if the line was changed.
  13534. */
  13535. bool clipToPath (const Path& path,
  13536. const bool keepSectionOutsidePath) throw();
  13537. juce_UseDebuggingNewOperator
  13538. private:
  13539. float startX, startY, endX, endY;
  13540. };
  13541. #endif // __JUCE_LINE_JUCEHEADER__
  13542. /********* End of inlined file: juce_Line.h *********/
  13543. /********* Start of inlined file: juce_Colours.h *********/
  13544. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13545. #define __JUCE_COLOURS_JUCEHEADER__
  13546. /********* Start of inlined file: juce_Colour.h *********/
  13547. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13548. #define __JUCE_COLOUR_JUCEHEADER__
  13549. /********* Start of inlined file: juce_PixelFormats.h *********/
  13550. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13551. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13552. #if JUCE_MSVC
  13553. #pragma pack (push, 1)
  13554. #define PACKED
  13555. #elif JUCE_GCC
  13556. #define PACKED __attribute__((packed))
  13557. #else
  13558. #define PACKED
  13559. #endif
  13560. /**
  13561. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13562. operations with it.
  13563. This is used internally by the imaging classes.
  13564. @see PixelRGB
  13565. */
  13566. class JUCE_API PixelARGB
  13567. {
  13568. public:
  13569. /** Creates a pixel without defining its colour. */
  13570. PixelARGB() throw() {}
  13571. ~PixelARGB() throw() {}
  13572. /** Creates a pixel from a 32-bit argb value.
  13573. */
  13574. PixelARGB (const uint32 argb_) throw()
  13575. : argb (argb_)
  13576. {
  13577. }
  13578. forcedinline uint32 getARGB() const throw() { return argb; }
  13579. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13580. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13581. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13582. forcedinline uint8 getRed() const throw() { return components.r; }
  13583. forcedinline uint8 getGreen() const throw() { return components.g; }
  13584. forcedinline uint8 getBlue() const throw() { return components.b; }
  13585. /** Blends another pixel onto this one.
  13586. This takes into account the opacity of the pixel being overlaid, and blends
  13587. it accordingly.
  13588. */
  13589. template <class Pixel>
  13590. forcedinline void blend (const Pixel& src) throw()
  13591. {
  13592. uint32 sargb = src.getARGB();
  13593. const uint32 alpha = 0x100 - (sargb >> 24);
  13594. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13595. sargb += 0xff00ff00 & (getAG() * alpha);
  13596. argb = sargb;
  13597. }
  13598. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13599. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13600. being used, so this can blend semi-transparently from a PixelRGB argument.
  13601. */
  13602. template <class Pixel>
  13603. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13604. {
  13605. ++extraAlpha;
  13606. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13607. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13608. const uint32 alpha = 0x100 - (sargb >> 24);
  13609. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13610. sargb += 0xff00ff00 & (getAG() * alpha);
  13611. argb = sargb;
  13612. }
  13613. /** Blends another pixel with this one, creating a colour that is somewhere
  13614. between the two, as specified by the amount.
  13615. */
  13616. template <class Pixel>
  13617. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13618. {
  13619. uint32 drb = getRB();
  13620. drb += (((src.getRB() - drb) * amount) >> 8);
  13621. drb &= 0x00ff00ff;
  13622. uint32 dag = getAG();
  13623. dag += (((src.getAG() - dag) * amount) >> 8);
  13624. dag &= 0x00ff00ff;
  13625. dag <<= 8;
  13626. dag |= drb;
  13627. argb = dag;
  13628. }
  13629. /** Copies another pixel colour over this one.
  13630. This doesn't blend it - this colour is simply replaced by the other one.
  13631. */
  13632. template <class Pixel>
  13633. forcedinline void set (const Pixel& src) throw()
  13634. {
  13635. argb = src.getARGB();
  13636. }
  13637. /** Replaces the colour's alpha value with another one. */
  13638. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13639. {
  13640. components.a = newAlpha;
  13641. }
  13642. /** Multiplies the colour's alpha value with another one. */
  13643. forcedinline void multiplyAlpha (int multiplier) throw()
  13644. {
  13645. ++multiplier;
  13646. argb = ((multiplier * getAG()) & 0xff00ff00)
  13647. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13648. }
  13649. forcedinline void multiplyAlpha (const float multiplier) throw()
  13650. {
  13651. multiplyAlpha ((int) (multiplier * 256.0f));
  13652. }
  13653. /** Sets the pixel's colour from individual components. */
  13654. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13655. {
  13656. components.b = b;
  13657. components.g = g;
  13658. components.r = r;
  13659. components.a = a;
  13660. }
  13661. /** Premultiplies the pixel's RGB values by its alpha. */
  13662. forcedinline void premultiply() throw()
  13663. {
  13664. const uint32 alpha = components.a;
  13665. if (alpha < 0xff)
  13666. {
  13667. if (alpha == 0)
  13668. {
  13669. components.b = 0;
  13670. components.g = 0;
  13671. components.r = 0;
  13672. }
  13673. else
  13674. {
  13675. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13676. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13677. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13678. }
  13679. }
  13680. }
  13681. /** Unpremultiplies the pixel's RGB values. */
  13682. forcedinline void unpremultiply() throw()
  13683. {
  13684. const uint32 alpha = components.a;
  13685. if (alpha < 0xff)
  13686. {
  13687. if (alpha == 0)
  13688. {
  13689. components.b = 0;
  13690. components.g = 0;
  13691. components.r = 0;
  13692. }
  13693. else
  13694. {
  13695. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13696. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13697. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13698. }
  13699. }
  13700. }
  13701. forcedinline void desaturate() throw()
  13702. {
  13703. if (components.a < 0xff && components.a > 0)
  13704. {
  13705. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13706. components.r = components.g = components.b
  13707. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13708. }
  13709. else
  13710. {
  13711. components.r = components.g = components.b
  13712. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13713. }
  13714. }
  13715. private:
  13716. union
  13717. {
  13718. uint32 argb;
  13719. struct
  13720. {
  13721. #if JUCE_BIG_ENDIAN
  13722. uint8 a : 8, r : 8, g : 8, b : 8;
  13723. #else
  13724. uint8 b, g, r, a;
  13725. #endif
  13726. } PACKED components;
  13727. };
  13728. } PACKED;
  13729. /**
  13730. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13731. This is used internally by the imaging classes.
  13732. @see PixelARGB
  13733. */
  13734. class JUCE_API PixelRGB
  13735. {
  13736. public:
  13737. /** Creates a pixel without defining its colour. */
  13738. PixelRGB() throw() {}
  13739. ~PixelRGB() throw() {}
  13740. /** Creates a pixel from a 32-bit argb value.
  13741. (The argb format is that used by PixelARGB)
  13742. */
  13743. PixelRGB (const uint32 argb) throw()
  13744. {
  13745. r = (uint8) (argb >> 16);
  13746. g = (uint8) (argb >> 8);
  13747. b = (uint8) (argb);
  13748. }
  13749. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13750. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13751. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13752. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13753. forcedinline uint8 getRed() const throw() { return r; }
  13754. forcedinline uint8 getGreen() const throw() { return g; }
  13755. forcedinline uint8 getBlue() const throw() { return b; }
  13756. /** Blends another pixel onto this one.
  13757. This takes into account the opacity of the pixel being overlaid, and blends
  13758. it accordingly.
  13759. */
  13760. forcedinline void blend (const PixelARGB& src) throw()
  13761. {
  13762. uint32 sargb = src.getARGB();
  13763. const uint32 alpha = 0x100 - (sargb >> 24);
  13764. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13765. sargb += 0x0000ff00 & (g * alpha);
  13766. r = (uint8) (sargb >> 16);
  13767. g = (uint8) (sargb >> 8);
  13768. b = (uint8) sargb;
  13769. }
  13770. forcedinline void blend (const PixelRGB& src) throw()
  13771. {
  13772. set (src);
  13773. }
  13774. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13775. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13776. being used, so this can blend semi-transparently from a PixelRGB argument.
  13777. */
  13778. template <class Pixel>
  13779. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13780. {
  13781. ++extraAlpha;
  13782. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13783. const uint32 sag = extraAlpha * src.getAG();
  13784. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13785. const uint32 alpha = 0x100 - (sargb >> 24);
  13786. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13787. sargb += 0x0000ff00 & (g * alpha);
  13788. b = (uint8) sargb;
  13789. g = (uint8) (sargb >> 8);
  13790. r = (uint8) (sargb >> 16);
  13791. }
  13792. /** Blends another pixel with this one, creating a colour that is somewhere
  13793. between the two, as specified by the amount.
  13794. */
  13795. template <class Pixel>
  13796. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13797. {
  13798. uint32 drb = getRB();
  13799. drb += (((src.getRB() - drb) * amount) >> 8);
  13800. uint32 dag = getAG();
  13801. dag += (((src.getAG() - dag) * amount) >> 8);
  13802. b = (uint8) drb;
  13803. g = (uint8) dag;
  13804. r = (uint8) (drb >> 16);
  13805. }
  13806. /** Copies another pixel colour over this one.
  13807. This doesn't blend it - this colour is simply replaced by the other one.
  13808. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13809. is thrown away.
  13810. */
  13811. template <class Pixel>
  13812. forcedinline void set (const Pixel& src) throw()
  13813. {
  13814. b = src.getBlue();
  13815. g = src.getGreen();
  13816. r = src.getRed();
  13817. }
  13818. /** This method is included for compatibility with the PixelARGB class. */
  13819. forcedinline void setAlpha (const uint8) throw() {}
  13820. /** Multiplies the colour's alpha value with another one. */
  13821. forcedinline void multiplyAlpha (int) throw() {}
  13822. /** Sets the pixel's colour from individual components. */
  13823. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  13824. {
  13825. r = r_;
  13826. g = g_;
  13827. b = b_;
  13828. }
  13829. /** Premultiplies the pixel's RGB values by its alpha. */
  13830. forcedinline void premultiply() throw() {}
  13831. /** Unpremultiplies the pixel's RGB values. */
  13832. forcedinline void unpremultiply() throw() {}
  13833. forcedinline void desaturate() throw()
  13834. {
  13835. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  13836. }
  13837. private:
  13838. #if JUCE_MAC
  13839. uint8 r, g, b;
  13840. #else
  13841. uint8 b, g, r;
  13842. #endif
  13843. } PACKED;
  13844. #if JUCE_MSVC
  13845. #pragma pack (pop)
  13846. #endif
  13847. #undef PACKED
  13848. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  13849. /********* End of inlined file: juce_PixelFormats.h *********/
  13850. /**
  13851. Represents a colour, also including a transparency value.
  13852. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  13853. */
  13854. class JUCE_API Colour
  13855. {
  13856. public:
  13857. /** Creates a transparent black colour. */
  13858. Colour() throw();
  13859. /** Creates a copy of another Colour object. */
  13860. Colour (const Colour& other) throw();
  13861. /** Creates a colour from a 32-bit ARGB value.
  13862. The format of this number is:
  13863. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13864. All components in the range 0x00 to 0xff.
  13865. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13866. @see getPixelARGB
  13867. */
  13868. explicit Colour (const uint32 argb) throw();
  13869. /** Creates an opaque colour using 8-bit red, green and blue values */
  13870. Colour (const uint8 red,
  13871. const uint8 green,
  13872. const uint8 blue) throw();
  13873. /** Creates an opaque colour using 8-bit red, green and blue values */
  13874. static const Colour fromRGB (const uint8 red,
  13875. const uint8 green,
  13876. const uint8 blue) throw();
  13877. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13878. Colour (const uint8 red,
  13879. const uint8 green,
  13880. const uint8 blue,
  13881. const uint8 alpha) throw();
  13882. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13883. static const Colour fromRGBA (const uint8 red,
  13884. const uint8 green,
  13885. const uint8 blue,
  13886. const uint8 alpha) throw();
  13887. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  13888. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  13889. Values outside the valid range will be clipped.
  13890. */
  13891. Colour (const uint8 red,
  13892. const uint8 green,
  13893. const uint8 blue,
  13894. const float alpha) throw();
  13895. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  13896. static const Colour fromRGBAFloat (const uint8 red,
  13897. const uint8 green,
  13898. const uint8 blue,
  13899. const float alpha) throw();
  13900. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13901. The floating point values must be between 0.0 and 1.0.
  13902. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13903. Values outside the valid range will be clipped.
  13904. */
  13905. Colour (const float hue,
  13906. const float saturation,
  13907. const float brightness,
  13908. const uint8 alpha) throw();
  13909. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  13910. All values must be between 0.0 and 1.0.
  13911. Numbers outside the valid range will be clipped.
  13912. */
  13913. Colour (const float hue,
  13914. const float saturation,
  13915. const float brightness,
  13916. const float alpha) throw();
  13917. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13918. The floating point values must be between 0.0 and 1.0.
  13919. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13920. Values outside the valid range will be clipped.
  13921. */
  13922. static const Colour fromHSV (const float hue,
  13923. const float saturation,
  13924. const float brightness,
  13925. const float alpha) throw();
  13926. /** Destructor. */
  13927. ~Colour() throw();
  13928. /** Copies another Colour object. */
  13929. const Colour& operator= (const Colour& other) throw();
  13930. /** Compares two colours. */
  13931. bool operator== (const Colour& other) const throw();
  13932. /** Compares two colours. */
  13933. bool operator!= (const Colour& other) const throw();
  13934. /** Returns the red component of this colour.
  13935. @returns a value between 0x00 and 0xff.
  13936. */
  13937. uint8 getRed() const throw() { return argb.getRed(); }
  13938. /** Returns the green component of this colour.
  13939. @returns a value between 0x00 and 0xff.
  13940. */
  13941. uint8 getGreen() const throw() { return argb.getGreen(); }
  13942. /** Returns the blue component of this colour.
  13943. @returns a value between 0x00 and 0xff.
  13944. */
  13945. uint8 getBlue() const throw() { return argb.getBlue(); }
  13946. /** Returns the red component of this colour as a floating point value.
  13947. @returns a value between 0.0 and 1.0
  13948. */
  13949. float getFloatRed() const throw();
  13950. /** Returns the green component of this colour as a floating point value.
  13951. @returns a value between 0.0 and 1.0
  13952. */
  13953. float getFloatGreen() const throw();
  13954. /** Returns the blue component of this colour as a floating point value.
  13955. @returns a value between 0.0 and 1.0
  13956. */
  13957. float getFloatBlue() const throw();
  13958. /** Returns a premultiplied ARGB pixel object that represents this colour.
  13959. */
  13960. const PixelARGB getPixelARGB() const throw();
  13961. /** Returns a 32-bit integer that represents this colour.
  13962. The format of this number is:
  13963. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13964. */
  13965. uint32 getARGB() const throw();
  13966. /** Returns the colour's alpha (opacity).
  13967. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  13968. */
  13969. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  13970. /** Returns the colour's alpha (opacity) as a floating point value.
  13971. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  13972. */
  13973. float getFloatAlpha() const throw();
  13974. /** Returns true if this colour is completely opaque.
  13975. Equivalent to (getAlpha() == 0xff).
  13976. */
  13977. bool isOpaque() const throw();
  13978. /** Returns true if this colour is completely transparent.
  13979. Equivalent to (getAlpha() == 0x00).
  13980. */
  13981. bool isTransparent() const throw();
  13982. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  13983. const Colour withAlpha (const uint8 newAlpha) const throw();
  13984. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  13985. const Colour withAlpha (const float newAlpha) const throw();
  13986. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  13987. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  13988. */
  13989. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  13990. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  13991. If the foreground colour is semi-transparent, it is blended onto this colour
  13992. accordingly.
  13993. */
  13994. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  13995. /** Returns the colour's hue component.
  13996. The value returned is in the range 0.0 to 1.0
  13997. */
  13998. float getHue() const throw();
  13999. /** Returns the colour's saturation component.
  14000. The value returned is in the range 0.0 to 1.0
  14001. */
  14002. float getSaturation() const throw();
  14003. /** Returns the colour's brightness component.
  14004. The value returned is in the range 0.0 to 1.0
  14005. */
  14006. float getBrightness() const throw();
  14007. /** Returns the colour's hue, saturation and brightness components all at once.
  14008. The values returned are in the range 0.0 to 1.0
  14009. */
  14010. void getHSB (float& hue,
  14011. float& saturation,
  14012. float& brightness) const throw();
  14013. /** Returns a copy of this colour with a different hue. */
  14014. const Colour withHue (const float newHue) const throw();
  14015. /** Returns a copy of this colour with a different saturation. */
  14016. const Colour withSaturation (const float newSaturation) const throw();
  14017. /** Returns a copy of this colour with a different brightness.
  14018. @see brighter, darker, withMultipliedBrightness
  14019. */
  14020. const Colour withBrightness (const float newBrightness) const throw();
  14021. /** Returns a copy of this colour with it hue rotated.
  14022. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14023. @see brighter, darker, withMultipliedBrightness
  14024. */
  14025. const Colour withRotatedHue (const float amountToRotate) const throw();
  14026. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14027. The new colour's saturation is (this->getSaturation() * multiplier)
  14028. (the result is clipped to legal limits).
  14029. */
  14030. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14031. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14032. The new colour's saturation is (this->getBrightness() * multiplier)
  14033. (the result is clipped to legal limits).
  14034. */
  14035. const Colour withMultipliedBrightness (const float amount) const throw();
  14036. /** Returns a brighter version of this colour.
  14037. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14038. unchanged, and higher values make it brighter
  14039. @see withMultipliedBrightness
  14040. */
  14041. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14042. /** Returns a darker version of this colour.
  14043. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14044. unchanged, and higher values make it darker
  14045. @see withMultipliedBrightness
  14046. */
  14047. const Colour darker (float amountDarker = 0.4f) const throw();
  14048. /** Returns a colour that will be clearly visible against this colour.
  14049. The amount parameter indicates how contrasting the new colour should
  14050. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14051. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14052. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14053. */
  14054. const Colour contrasting (const float amount = 1.0f) const throw();
  14055. /** Returns a colour that contrasts against two colours.
  14056. Looks for a colour that contrasts with both of the colours passed-in.
  14057. Handy for things like choosing a highlight colour in text editors, etc.
  14058. */
  14059. static const Colour contrasting (const Colour& colour1,
  14060. const Colour& colour2) throw();
  14061. /** Returns an opaque shade of grey.
  14062. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14063. */
  14064. static const Colour greyLevel (const float brightness) throw();
  14065. /** Returns a stringified version of this colour.
  14066. The string can be turned back into a colour using the fromString() method.
  14067. */
  14068. const String toString() const throw();
  14069. /** Reads the colour from a string that was created with toString().
  14070. */
  14071. static const Colour fromString (const String& encodedColourString);
  14072. juce_UseDebuggingNewOperator
  14073. private:
  14074. PixelARGB argb;
  14075. };
  14076. #endif // __JUCE_COLOUR_JUCEHEADER__
  14077. /********* End of inlined file: juce_Colour.h *********/
  14078. /**
  14079. Contains a set of predefined named colours (mostly standard HTML colours)
  14080. @see Colour, Colours::greyLevel
  14081. */
  14082. class Colours
  14083. {
  14084. public:
  14085. static JUCE_API const Colour
  14086. transparentBlack, /**< ARGB = 0x00000000 */
  14087. transparentWhite, /**< ARGB = 0x00ffffff */
  14088. black, /**< ARGB = 0xff000000 */
  14089. white, /**< ARGB = 0xffffffff */
  14090. blue, /**< ARGB = 0xff0000ff */
  14091. grey, /**< ARGB = 0xff808080 */
  14092. green, /**< ARGB = 0xff008000 */
  14093. red, /**< ARGB = 0xffff0000 */
  14094. yellow, /**< ARGB = 0xffffff00 */
  14095. aliceblue, antiquewhite, aqua, aquamarine,
  14096. azure, beige, bisque, blanchedalmond,
  14097. blueviolet, brown, burlywood, cadetblue,
  14098. chartreuse, chocolate, coral, cornflowerblue,
  14099. cornsilk, crimson, cyan, darkblue,
  14100. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14101. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14102. darkorchid, darkred, darksalmon, darkseagreen,
  14103. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14104. deeppink, deepskyblue, dimgrey, dodgerblue,
  14105. firebrick, floralwhite, forestgreen, fuchsia,
  14106. gainsboro, gold, goldenrod, greenyellow,
  14107. honeydew, hotpink, indianred, indigo,
  14108. ivory, khaki, lavender, lavenderblush,
  14109. lemonchiffon, lightblue, lightcoral, lightcyan,
  14110. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14111. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14112. lightsteelblue, lightyellow, lime, limegreen,
  14113. linen, magenta, maroon, mediumaquamarine,
  14114. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14115. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14116. midnightblue, mintcream, mistyrose, navajowhite,
  14117. navy, oldlace, olive, olivedrab,
  14118. orange, orangered, orchid, palegoldenrod,
  14119. palegreen, paleturquoise, palevioletred, papayawhip,
  14120. peachpuff, peru, pink, plum,
  14121. powderblue, purple, rosybrown, royalblue,
  14122. saddlebrown, salmon, sandybrown, seagreen,
  14123. seashell, sienna, silver, skyblue,
  14124. slateblue, slategrey, snow, springgreen,
  14125. steelblue, tan, teal, thistle,
  14126. tomato, turquoise, violet, wheat,
  14127. whitesmoke, yellowgreen;
  14128. /** Attempts to look up a string in the list of known colour names, and return
  14129. the appropriate colour.
  14130. A non-case-sensitive search is made of the list of predefined colours, and
  14131. if a match is found, that colour is returned. If no match is found, the
  14132. colour passed in as the defaultColour parameter is returned.
  14133. */
  14134. static JUCE_API const Colour findColourForName (const String& colourName,
  14135. const Colour& defaultColour);
  14136. private:
  14137. // this isn't a class you should ever instantiate - it's just here for the
  14138. // static values in it.
  14139. Colours();
  14140. };
  14141. #endif // __JUCE_COLOURS_JUCEHEADER__
  14142. /********* End of inlined file: juce_Colours.h *********/
  14143. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14144. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14145. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14146. /********* Start of inlined file: juce_Brush.h *********/
  14147. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14148. #define __JUCE_BRUSH_JUCEHEADER__
  14149. class Path;
  14150. class AffineTransform;
  14151. class LowLevelGraphicsContext;
  14152. class Image;
  14153. class Graphics;
  14154. /**
  14155. A brush is used to fill areas with colours, patterns, or images.
  14156. The Graphics class has an idea of a current brush which it uses to render
  14157. shapes, rectangles, lines, text, etc.
  14158. This is the base class - there are subclasses for useful types of fill pattern,
  14159. and applications can define their own brushes too.
  14160. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14161. */
  14162. class JUCE_API Brush
  14163. {
  14164. protected:
  14165. /** Creates a Brush.
  14166. (Nothing much happens in the base class).
  14167. */
  14168. Brush() throw();
  14169. public:
  14170. /** Destructor. */
  14171. virtual ~Brush() throw();
  14172. /** Creates a copy of whatever class of Brush this is. */
  14173. virtual Brush* createCopy() const throw() = 0;
  14174. /** Does whatever is relevent to transform the geometry of this brush. */
  14175. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14176. /** Does whatever is relevent to change the opacity of this brush. */
  14177. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14178. /** Must return true if this brush won't draw any pixels. */
  14179. virtual bool isInvisible() const throw() = 0;
  14180. virtual void paintPath (LowLevelGraphicsContext& context,
  14181. const Path& path, const AffineTransform& transform) throw() = 0;
  14182. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14183. int x, int y, int w, int h) throw() = 0;
  14184. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14185. const Image& alphaChannelImage, int imageX, int imageY,
  14186. int x, int y, int w, int h) throw() = 0;
  14187. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14188. int x, float y1, float y2) throw();
  14189. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14190. int y, float x1, float x2) throw();
  14191. virtual void paintLine (LowLevelGraphicsContext& context,
  14192. float x1, float y1, float x2, float y2) throw();
  14193. private:
  14194. Brush (const Brush&);
  14195. const Brush& operator= (const Brush&);
  14196. };
  14197. #endif // __JUCE_BRUSH_JUCEHEADER__
  14198. /********* End of inlined file: juce_Brush.h *********/
  14199. /**
  14200. A Brush that fills its area with a solid (or semi-transparent) colour.
  14201. An application won't normally need to use this class directly, as drawing
  14202. with solid colours is taken care of automatically by the Graphics class
  14203. (it actually uses one of these brushes internally when you set the colour
  14204. with the Graphics::setColour() method).
  14205. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14206. */
  14207. class JUCE_API SolidColourBrush : public Brush
  14208. {
  14209. public:
  14210. /** Creates a SolidColourBrush to draw with the given colour.
  14211. The colour can be changed later with the setColour() method.
  14212. */
  14213. SolidColourBrush (const Colour& colour) throw();
  14214. /** Creates a SolidColourBrush set to black.
  14215. The colour can be changed later with the setColour() method.
  14216. */
  14217. SolidColourBrush() throw();
  14218. /** Destructor. */
  14219. ~SolidColourBrush() throw();
  14220. /** Returns the colour currently being used. */
  14221. const Colour& getColour() const throw() { return colour; }
  14222. /** Sets the colour to use for drawing. */
  14223. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14224. Brush* createCopy() const throw();
  14225. void applyTransform (const AffineTransform& transform) throw();
  14226. bool isInvisible() const throw();
  14227. void multiplyOpacity (const float multiple) throw();
  14228. void paintPath (LowLevelGraphicsContext& context,
  14229. const Path& path, const AffineTransform& transform) throw();
  14230. void paintRectangle (LowLevelGraphicsContext& context,
  14231. int x, int y, int w, int h) throw();
  14232. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14233. const Image& alphaChannelImage, int imageX, int imageY,
  14234. int x, int y, int w, int h) throw();
  14235. void paintVerticalLine (LowLevelGraphicsContext& context,
  14236. int x, float y1, float y2) throw();
  14237. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14238. int y, float x1, float x2) throw();
  14239. void paintLine (LowLevelGraphicsContext& context,
  14240. float x1, float y1, float x2, float y2) throw();
  14241. juce_UseDebuggingNewOperator
  14242. private:
  14243. Colour colour;
  14244. SolidColourBrush (const SolidColourBrush&);
  14245. const SolidColourBrush& operator= (const SolidColourBrush&);
  14246. };
  14247. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14248. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14249. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14250. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14251. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14252. /**
  14253. Defines the method used to postion some kind of rectangular object within
  14254. a rectangular viewport.
  14255. Although similar to Justification, this is more specific, and has some extra
  14256. options.
  14257. */
  14258. class JUCE_API RectanglePlacement
  14259. {
  14260. public:
  14261. /** Creates a RectanglePlacement object using a combination of flags. */
  14262. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14263. /** Creates a copy of another Justification object. */
  14264. RectanglePlacement (const RectanglePlacement& other) throw();
  14265. /** Copies another Justification object. */
  14266. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14267. /** Flag values that can be combined and used in the constructor. */
  14268. enum
  14269. {
  14270. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14271. xLeft = 1,
  14272. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14273. xRight = 2,
  14274. /** Indicates that the source should be placed in the centre between the left and right
  14275. sides of the available space. */
  14276. xMid = 4,
  14277. /** Indicates that the source's top edge should be aligned with the top edge of the
  14278. destination rectangle. */
  14279. yTop = 8,
  14280. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14281. destination rectangle. */
  14282. yBottom = 16,
  14283. /** Indicates that the source should be placed in the centre between the top and bottom
  14284. sides of the available space. */
  14285. yMid = 32,
  14286. /** If this flag is set, then the source rectangle will be resized to completely fill
  14287. the destination rectangle, and all other flags are ignored.
  14288. */
  14289. stretchToFit = 64,
  14290. /** If this flag is set, then the source rectangle will be resized so that it is the
  14291. minimum size to completely fill the destination rectangle. This means that some
  14292. of the source rectangle may fall outside the destination.
  14293. If this flag is not set, the source will be given the maximum size at which none
  14294. of it falls outside the destination rectangle.
  14295. */
  14296. fillDestination = 128,
  14297. /** Indicates that the source rectangle can be reduced in size if required, but should
  14298. never be made larger than its original size.
  14299. */
  14300. onlyReduceInSize = 256,
  14301. /** Indicates that the source rectangle can be enlarged if required, but should
  14302. never be made smaller than its original size.
  14303. */
  14304. onlyIncreaseInSize = 512,
  14305. /** Indicates that the source rectangle's size should be left unchanged.
  14306. */
  14307. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14308. /** A shorthand value that is equivalent to (xMid | yMid). */
  14309. centred = 4 + 32
  14310. };
  14311. /** Returns the raw flags that are set for this object. */
  14312. inline int getFlags() const throw() { return flags; }
  14313. /** Tests a set of flags for this object.
  14314. @returns true if any of the flags passed in are set on this object.
  14315. */
  14316. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14317. /** Adjusts the position and size of a rectangle to fit it into a space.
  14318. The source rectangle co-ordinates will be adjusted so that they fit into
  14319. the destination rectangle based on this object's flags.
  14320. */
  14321. void applyTo (double& sourceX,
  14322. double& sourceY,
  14323. double& sourceW,
  14324. double& sourceH,
  14325. const double destinationX,
  14326. const double destinationY,
  14327. const double destinationW,
  14328. const double destinationH) const throw();
  14329. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14330. into the destination rectangle using the current flags.
  14331. */
  14332. const AffineTransform getTransformToFit (float sourceX,
  14333. float sourceY,
  14334. float sourceW,
  14335. float sourceH,
  14336. const float destinationX,
  14337. const float destinationY,
  14338. const float destinationW,
  14339. const float destinationH) const throw();
  14340. private:
  14341. int flags;
  14342. };
  14343. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14344. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14345. class LowLevelGraphicsContext;
  14346. class Image;
  14347. class RectangleList;
  14348. /**
  14349. A graphics context, used for drawing a component or image.
  14350. When a Component needs painting, a Graphics context is passed to its
  14351. Component::paint() method, and this you then call methods within this
  14352. object to actually draw the component's content.
  14353. A Graphics can also be created from an image, to allow drawing directly onto
  14354. that image.
  14355. @see Component::paint
  14356. */
  14357. class JUCE_API Graphics
  14358. {
  14359. public:
  14360. /** Creates a Graphics object to draw directly onto the given image.
  14361. The graphics object that is created will be set up to draw onto the image,
  14362. with the context's clipping area being the entire size of the image, and its
  14363. origin being the image's origin. To draw into a subsection of an image, use the
  14364. reduceClipRegion() and setOrigin() methods.
  14365. Obviously you shouldn't delete the image before this context is deleted.
  14366. */
  14367. Graphics (Image& imageToDrawOnto) throw();
  14368. /** Destructor. */
  14369. ~Graphics() throw();
  14370. /** Changes the current drawing colour.
  14371. This sets the colour that will now be used for drawing operations - it also
  14372. sets the opacity to that of the colour passed-in.
  14373. If a brush is being used when this method is called, the brush will be deselected,
  14374. and any subsequent drawing will be done with a solid colour brush instead.
  14375. @see setOpacity, setBrush, getColour
  14376. */
  14377. void setColour (const Colour& newColour) throw();
  14378. /** Returns the colour that's currently being used.
  14379. This will return the last colour set by setColour(), even if the colour's not
  14380. currently being used for drawing because a brush has been selected instead.
  14381. @see setColour
  14382. */
  14383. const Colour& getCurrentColour() const throw();
  14384. /** Changes the opacity to use with the current colour.
  14385. If a solid colour is being used for drawing, this changes its opacity (and this
  14386. will be reflected by calls to the getColour() method).
  14387. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14388. */
  14389. void setOpacity (const float newOpacity) throw();
  14390. /** Changes the current brush to use for drawing.
  14391. If a null pointer is passed in, the context will revert to using a solid
  14392. colour for drawing (using the last colour set by setColour()).
  14393. If a brush is passed in, a copy of it will be used for subsequent drawing
  14394. operations until setColour() or setBrush() is called.
  14395. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14396. */
  14397. void setBrush (const Brush* const newBrush) throw();
  14398. /** Changes the font to use for subsequent text-drawing functions.
  14399. Note there's also a setFont (float, int) method to quickly change the size and
  14400. style of the current font.
  14401. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14402. */
  14403. void setFont (const Font& newFont) throw();
  14404. /** Changes the size and style of the currently-selected font.
  14405. This is a convenient shortcut that changes the context's current font to a
  14406. different size or style. The typeface won't be changed.
  14407. @see Font
  14408. */
  14409. void setFont (const float newFontHeight,
  14410. const int fontStyleFlags = Font::plain) throw();
  14411. /** Returns the font that's currently being used for text operations.
  14412. @see setFont
  14413. */
  14414. const Font& getCurrentFont() const throw();
  14415. /** Draws a one-line text string.
  14416. This will use the current colour (or brush) to fill the text. The font is the last
  14417. one specified by setFont().
  14418. @param text the string to draw
  14419. @param startX the position to draw the left-hand edge of the text
  14420. @param baselineY the position of the text's baseline
  14421. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14422. */
  14423. void drawSingleLineText (const String& text,
  14424. const int startX,
  14425. const int baselineY) const throw();
  14426. /** Draws text across multiple lines.
  14427. This will break the text onto a new line where there's a new-line or
  14428. carriage-return character, or at a word-boundary when the text becomes wider
  14429. than the size specified by the maximumLineWidth parameter.
  14430. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14431. */
  14432. void drawMultiLineText (const String& text,
  14433. const int startX,
  14434. const int baselineY,
  14435. const int maximumLineWidth) const throw();
  14436. /** Renders a string of text as a vector path.
  14437. This allows a string to be transformed with an arbitrary AffineTransform and
  14438. rendered using the current colour/brush. It's much slower than the normal text methods
  14439. but more accurate.
  14440. @see setFont
  14441. */
  14442. void drawTextAsPath (const String& text,
  14443. const AffineTransform& transform) const throw();
  14444. /** Draws a line of text within a specified rectangle.
  14445. The text will be positioned within the rectangle based on the justification
  14446. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14447. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14448. flag is true).
  14449. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14450. */
  14451. void drawText (const String& text,
  14452. const int x,
  14453. const int y,
  14454. const int width,
  14455. const int height,
  14456. const Justification& justificationType,
  14457. const bool useEllipsesIfTooBig) const throw();
  14458. /** Tries to draw a text string inside a given space.
  14459. This does its best to make the given text readable within the specified rectangle,
  14460. so it useful for labelling things.
  14461. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14462. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14463. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14464. it's been truncated.
  14465. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14466. both horizontally and vertically.
  14467. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14468. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14469. can set this value to 1.0f.
  14470. @see GlyphArrangement::addFittedText
  14471. */
  14472. void drawFittedText (const String& text,
  14473. const int x,
  14474. const int y,
  14475. const int width,
  14476. const int height,
  14477. const Justification& justificationFlags,
  14478. const int maximumNumberOfLines,
  14479. const float minimumHorizontalScale = 0.7f) const throw();
  14480. /** Fills the context's entire clip region with the current colour or brush.
  14481. (See also the fillAll (const Colour&) method which is a quick way of filling
  14482. it with a given colour).
  14483. */
  14484. void fillAll() const throw();
  14485. /** Fills the context's entire clip region with a given colour.
  14486. This leaves the context's current colour and brush unchanged, it just
  14487. uses the specified colour temporarily.
  14488. */
  14489. void fillAll (const Colour& colourToUse) const throw();
  14490. /** Fills a rectangle with the current colour or brush.
  14491. @see drawRect, fillRoundedRectangle
  14492. */
  14493. void fillRect (int x,
  14494. int y,
  14495. int width,
  14496. int height) const throw();
  14497. /** Fills a rectangle with the current colour or brush. */
  14498. void fillRect (const Rectangle& rectangle) const throw();
  14499. /** Fills a rectangle with the current colour or brush.
  14500. This uses sub-pixel positioning so is slower than the fillRect method which
  14501. takes integer co-ordinates.
  14502. */
  14503. void fillRect (const float x,
  14504. const float y,
  14505. const float width,
  14506. const float height) const throw();
  14507. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14508. @see drawRoundedRectangle, Path::addRoundedRectangle
  14509. */
  14510. void fillRoundedRectangle (const float x,
  14511. const float y,
  14512. const float width,
  14513. const float height,
  14514. const float cornerSize) const throw();
  14515. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14516. @see drawRoundedRectangle, Path::addRoundedRectangle
  14517. */
  14518. void fillRoundedRectangle (const Rectangle& rectangle,
  14519. const float cornerSize) const throw();
  14520. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14521. */
  14522. void fillCheckerBoard (int x, int y,
  14523. int width, int height,
  14524. const int checkWidth,
  14525. const int checkHeight,
  14526. const Colour& colour1,
  14527. const Colour& colour2) const throw();
  14528. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14529. The lines are drawn inside the given rectangle, and greater line thicknesses
  14530. extend inwards.
  14531. @see fillRect
  14532. */
  14533. void drawRect (const int x,
  14534. const int y,
  14535. const int width,
  14536. const int height,
  14537. const int lineThickness = 1) const throw();
  14538. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14539. The lines are drawn inside the given rectangle, and greater line thicknesses
  14540. extend inwards.
  14541. @see fillRect
  14542. */
  14543. void drawRect (const float x,
  14544. const float y,
  14545. const float width,
  14546. const float height,
  14547. const float lineThickness = 1.0f) const throw();
  14548. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14549. The lines are drawn inside the given rectangle, and greater line thicknesses
  14550. extend inwards.
  14551. @see fillRect
  14552. */
  14553. void drawRect (const Rectangle& rectangle,
  14554. const int lineThickness = 1) const throw();
  14555. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14556. @see fillRoundedRectangle, Path::addRoundedRectangle
  14557. */
  14558. void drawRoundedRectangle (const float x,
  14559. const float y,
  14560. const float width,
  14561. const float height,
  14562. const float cornerSize,
  14563. const float lineThickness) const throw();
  14564. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14565. @see fillRoundedRectangle, Path::addRoundedRectangle
  14566. */
  14567. void drawRoundedRectangle (const Rectangle& rectangle,
  14568. const float cornerSize,
  14569. const float lineThickness) const throw();
  14570. /** Draws a 3D raised (or indented) bevel using two colours.
  14571. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14572. extend inwards.
  14573. The top-left colour is used for the top- and left-hand edges of the
  14574. bevel; the bottom-right colour is used for the bottom- and right-hand
  14575. edges.
  14576. */
  14577. void drawBevel (const int x,
  14578. const int y,
  14579. const int width,
  14580. const int height,
  14581. const int bevelThickness,
  14582. const Colour& topLeftColour = Colours::white,
  14583. const Colour& bottomRightColour = Colours::black,
  14584. const bool useGradient = true) const throw();
  14585. /** Draws a pixel using the current colour or brush.
  14586. */
  14587. void setPixel (int x, int y) const throw();
  14588. /** Fills an ellipse with the current colour or brush.
  14589. The ellipse is drawn to fit inside the given rectangle.
  14590. @see drawEllipse, Path::addEllipse
  14591. */
  14592. void fillEllipse (const float x,
  14593. const float y,
  14594. const float width,
  14595. const float height) const throw();
  14596. /** Draws an elliptical stroke using the current colour or brush.
  14597. @see fillEllipse, Path::addEllipse
  14598. */
  14599. void drawEllipse (const float x,
  14600. const float y,
  14601. const float width,
  14602. const float height,
  14603. const float lineThickness) const throw();
  14604. /** Draws a line between two points.
  14605. The line is 1 pixel wide and drawn with the current colour or brush.
  14606. */
  14607. void drawLine (float startX,
  14608. float startY,
  14609. float endX,
  14610. float endY) const throw();
  14611. /** Draws a line between two points with a given thickness.
  14612. @see Path::addLineSegment
  14613. */
  14614. void drawLine (const float startX,
  14615. const float startY,
  14616. const float endX,
  14617. const float endY,
  14618. const float lineThickness) const throw();
  14619. /** Draws a line between two points.
  14620. The line is 1 pixel wide and drawn with the current colour or brush.
  14621. */
  14622. void drawLine (const Line& line) const throw();
  14623. /** Draws a line between two points with a given thickness.
  14624. @see Path::addLineSegment
  14625. */
  14626. void drawLine (const Line& line,
  14627. const float lineThickness) const throw();
  14628. /** Draws a dashed line using a custom set of dash-lengths.
  14629. @param startX the line's start x co-ordinate
  14630. @param startY the line's start y co-ordinate
  14631. @param endX the line's end x co-ordinate
  14632. @param endY the line's end y co-ordinate
  14633. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14634. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14635. draw 6 pixels, skip 7 pixels, and then repeat.
  14636. @param numDashLengths the number of elements in the array (this must be an even number).
  14637. @param lineThickness the thickness of the line to draw
  14638. @see PathStrokeType::createDashedStroke
  14639. */
  14640. void drawDashedLine (const float startX,
  14641. const float startY,
  14642. const float endX,
  14643. const float endY,
  14644. const float* const dashLengths,
  14645. const int numDashLengths,
  14646. const float lineThickness = 1.0f) const throw();
  14647. /** Draws a vertical line of pixels at a given x position.
  14648. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14649. positions, and these will be anti-aliased if necessary.
  14650. */
  14651. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14652. /** Draws a horizontal line of pixels at a given y position.
  14653. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14654. positions, and these will be anti-aliased if necessary.
  14655. */
  14656. void drawHorizontalLine (const int y, float left, float right) const throw();
  14657. /** Fills a path using the currently selected colour or brush.
  14658. */
  14659. void fillPath (const Path& path,
  14660. const AffineTransform& transform = AffineTransform::identity) const throw();
  14661. /** Draws a path's outline using the currently selected colour or brush.
  14662. */
  14663. void strokePath (const Path& path,
  14664. const PathStrokeType& strokeType,
  14665. const AffineTransform& transform = AffineTransform::identity) const throw();
  14666. /** Draws a line with an arrowhead.
  14667. @param startX the line's start x co-ordinate
  14668. @param startY the line's start y co-ordinate
  14669. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14670. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14671. @param lineThickness the thickness of the line
  14672. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14673. @param arrowheadLength the length of the arrow head (along the length of the line)
  14674. */
  14675. void drawArrow (const float startX,
  14676. const float startY,
  14677. const float endX,
  14678. const float endY,
  14679. const float lineThickness,
  14680. const float arrowheadWidth,
  14681. const float arrowheadLength) const throw();
  14682. /** Types of rendering quality that can be specified when drawing images.
  14683. @see blendImage, Graphics::setImageResamplingQuality
  14684. */
  14685. enum ResamplingQuality
  14686. {
  14687. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14688. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14689. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14690. };
  14691. /** Changes the quality that will be used when resampling images.
  14692. By default a Graphics object will be set to mediumRenderingQuality.
  14693. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14694. */
  14695. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14696. /** Draws an image.
  14697. This will draw the whole of an image, positioning its top-left corner at the
  14698. given co-ordinates, and keeping its size the same. This is the simplest image
  14699. drawing method - the others give more control over the scaling and clipping
  14700. of the images.
  14701. Images are composited using the context's current opacity, so if you
  14702. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14703. (or setColour() with an opaque colour) before drawing images.
  14704. */
  14705. void drawImageAt (const Image* const imageToDraw,
  14706. const int topLeftX,
  14707. const int topLeftY,
  14708. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14709. /** Draws part of an image, rescaling it to fit in a given target region.
  14710. The specified area of the source image is rescaled and drawn to fill the
  14711. specifed destination rectangle.
  14712. Images are composited using the context's current opacity, so if you
  14713. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14714. (or setColour() with an opaque colour) before drawing images.
  14715. @param imageToDraw the image to overlay
  14716. @param destX the left of the destination rectangle
  14717. @param destY the top of the destination rectangle
  14718. @param destWidth the width of the destination rectangle
  14719. @param destHeight the height of the destination rectangle
  14720. @param sourceX the left of the rectangle to copy from the source image
  14721. @param sourceY the top of the rectangle to copy from the source image
  14722. @param sourceWidth the width of the rectangle to copy from the source image
  14723. @param sourceHeight the height of the rectangle to copy from the source image
  14724. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14725. the source image's alpha channel is used as a mask with
  14726. which to fill the destination using the current colour
  14727. or brush. (If the source is has no alpha channel, then
  14728. it will just fill the target with a solid rectangle)
  14729. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14730. */
  14731. void drawImage (const Image* const imageToDraw,
  14732. int destX,
  14733. int destY,
  14734. int destWidth,
  14735. int destHeight,
  14736. int sourceX,
  14737. int sourceY,
  14738. int sourceWidth,
  14739. int sourceHeight,
  14740. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14741. /** Draws part of an image, having applied an affine transform to it.
  14742. This lets you throw the image around in some wacky ways, rotate it, shear,
  14743. scale it, etc.
  14744. A clipping subregion is specified within the source image and no pixels
  14745. outside this region will be used.
  14746. Images are composited using the context's current opacity, so if you
  14747. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14748. (or setColour() with an opaque colour) before drawing images.
  14749. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14750. are ignored and it is filled with the current brush, masked by its alpha channel.
  14751. @see setImageResamplingQuality, drawImage
  14752. */
  14753. void drawImageTransformed (const Image* const imageToDraw,
  14754. int sourceClipX,
  14755. int sourceClipY,
  14756. int sourceClipWidth,
  14757. int sourceClipHeight,
  14758. const AffineTransform& transform,
  14759. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14760. /** Draws an image to fit within a designated rectangle.
  14761. If the image is too big or too small for the space, it will be rescaled
  14762. to fit as nicely as it can do without affecting its aspect ratio. It will
  14763. then be placed within the target rectangle according to the justification flags
  14764. specified.
  14765. @param imageToDraw the source image to draw
  14766. @param destX top-left of the target rectangle to fit it into
  14767. @param destY top-left of the target rectangle to fit it into
  14768. @param destWidth size of the target rectangle to fit the image into
  14769. @param destHeight size of the target rectangle to fit the image into
  14770. @param placementWithinTarget this specifies how the image should be positioned
  14771. within the target rectangle - see the RectanglePlacement
  14772. class for more details about this.
  14773. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14774. alpha channel will be used as a mask with which to
  14775. draw with the current brush or colour. This is
  14776. similar to fillAlphaMap(), and see also drawImage()
  14777. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14778. */
  14779. void drawImageWithin (const Image* const imageToDraw,
  14780. const int destX,
  14781. const int destY,
  14782. const int destWidth,
  14783. const int destHeight,
  14784. const RectanglePlacement& placementWithinTarget,
  14785. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14786. /** Returns the position of the bounding box for the current clipping region.
  14787. @see getClipRegion, clipRegionIntersects
  14788. */
  14789. const Rectangle getClipBounds() const throw();
  14790. /** Checks whether a rectangle overlaps the context's clipping region.
  14791. If this returns false, no part of the given area can be drawn onto, so this
  14792. method can be used to optimise a component's paint() method, by letting it
  14793. avoid drawing complex objects that aren't within the region being repainted.
  14794. */
  14795. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14796. /** Intersects the current clipping region with another region.
  14797. @returns true if the resulting clipping region is non-zero in size
  14798. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14799. */
  14800. bool reduceClipRegion (const int x, const int y,
  14801. const int width, const int height) throw();
  14802. /** Intersects the current clipping region with a rectangle list region.
  14803. @returns true if the resulting clipping region is non-zero in size
  14804. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14805. */
  14806. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14807. /** Excludes a rectangle to stop it being drawn into. */
  14808. void excludeClipRegion (const int x, const int y,
  14809. const int width, const int height) throw();
  14810. /** Returns true if no drawing can be done because the clip region is zero. */
  14811. bool isClipEmpty() const throw();
  14812. /** Saves the current graphics state on an internal stack.
  14813. To restore the state, use restoreState().
  14814. */
  14815. void saveState() throw();
  14816. /** Restores a graphics state that was previously saved with saveState().
  14817. */
  14818. void restoreState() throw();
  14819. /** Moves the position of the context's origin.
  14820. This changes the position that the context considers to be (0, 0) to
  14821. the specified position.
  14822. So if you call setOrigin (100, 100), then the position that was previously
  14823. referred to as (100, 100) will subsequently be considered to be (0, 0).
  14824. @see reduceClipRegion
  14825. */
  14826. void setOrigin (const int newOriginX,
  14827. const int newOriginY) throw();
  14828. /** Resets the current colour, brush, and font to default settings. */
  14829. void resetToDefaultState() throw();
  14830. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  14831. bool isVectorDevice() const throw();
  14832. juce_UseDebuggingNewOperator
  14833. /** Create a graphics that uses a given low-level renderer.
  14834. For internal use only.
  14835. NB. The context will NOT be deleted by this object when it is deleted.
  14836. */
  14837. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  14838. /** @internal */
  14839. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  14840. private:
  14841. LowLevelGraphicsContext* const context;
  14842. const bool ownsContext;
  14843. struct GraphicsState
  14844. {
  14845. GraphicsState() throw();
  14846. GraphicsState (const GraphicsState&) throw();
  14847. ~GraphicsState() throw();
  14848. Colour colour;
  14849. Brush* brush;
  14850. Font font;
  14851. ResamplingQuality quality;
  14852. };
  14853. GraphicsState* state;
  14854. OwnedArray <GraphicsState> stateStack;
  14855. bool saveStatePending;
  14856. void saveStateIfPending() throw();
  14857. const Graphics& operator= (const Graphics& other);
  14858. Graphics (const Graphics&);
  14859. };
  14860. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  14861. /********* End of inlined file: juce_Graphics.h *********/
  14862. /**
  14863. A graphical effect filter that can be applied to components.
  14864. An ImageEffectFilter can be applied to the image that a component
  14865. paints before it hits the screen.
  14866. This is used for adding effects like shadows, blurs, etc.
  14867. @see Component::setComponentEffect
  14868. */
  14869. class JUCE_API ImageEffectFilter
  14870. {
  14871. public:
  14872. /** Overridden to render the effect.
  14873. The implementation of this method must use the image that is passed in
  14874. as its source, and should render its output to the graphics context passed in.
  14875. @param sourceImage the image that the source component has just rendered with
  14876. its paint() method. The image may or may not have an alpha
  14877. channel, depending on whether the component is opaque.
  14878. @param destContext the graphics context to use to draw the resultant image.
  14879. */
  14880. virtual void applyEffect (Image& sourceImage,
  14881. Graphics& destContext) = 0;
  14882. /** Destructor. */
  14883. virtual ~ImageEffectFilter() {}
  14884. };
  14885. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  14886. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  14887. /********* Start of inlined file: juce_RectangleList.h *********/
  14888. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  14889. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  14890. /**
  14891. Maintains a set of rectangles as a complex region.
  14892. This class allows a set of rectangles to be treated as a solid shape, and can
  14893. add and remove rectangular sections of it, and simplify overlapping or
  14894. adjacent rectangles.
  14895. @see Rectangle
  14896. */
  14897. class JUCE_API RectangleList
  14898. {
  14899. public:
  14900. /** Creates an empty RectangleList */
  14901. RectangleList() throw();
  14902. /** Creates a copy of another list */
  14903. RectangleList (const RectangleList& other) throw();
  14904. /** Creates a list containing just one rectangle. */
  14905. RectangleList (const Rectangle& rect) throw();
  14906. /** Copies this list from another one. */
  14907. const RectangleList& operator= (const RectangleList& other) throw();
  14908. /** Destructor. */
  14909. ~RectangleList() throw();
  14910. /** Returns true if the region is empty. */
  14911. bool isEmpty() const throw();
  14912. /** Returns the number of rectangles in the list. */
  14913. int getNumRectangles() const throw() { return rects.size(); }
  14914. /** Returns one of the rectangles at a particular index.
  14915. @returns the rectangle at the index, or an empty rectangle if the
  14916. index is out-of-range.
  14917. */
  14918. const Rectangle getRectangle (const int index) const throw();
  14919. /** Removes all rectangles to leave an empty region. */
  14920. void clear() throw();
  14921. /** Merges a new rectangle into the list.
  14922. The rectangle being added will first be clipped to remove any parts of it
  14923. that overlap existing rectangles in the list.
  14924. */
  14925. void add (const int x, const int y,
  14926. const int w, const int h) throw();
  14927. /** Merges a new rectangle into the list.
  14928. The rectangle being added will first be clipped to remove any parts of it
  14929. that overlap existing rectangles in the list, and adjacent rectangles will be
  14930. merged into it.
  14931. */
  14932. void add (const Rectangle& rect) throw();
  14933. /** Dumbly adds a rectangle to the list without checking for overlaps.
  14934. This simply adds the rectangle to the end, it doesn't merge it or remove
  14935. any overlapping bits.
  14936. */
  14937. void addWithoutMerging (const Rectangle& rect) throw();
  14938. /** Merges another rectangle list into this one.
  14939. Any overlaps between the two lists will be clipped, so that the result is
  14940. the union of both lists.
  14941. */
  14942. void add (const RectangleList& other) throw();
  14943. /** Removes a rectangular region from the list.
  14944. Any rectangles in the list which overlap this will be clipped and subdivided
  14945. if necessary.
  14946. */
  14947. void subtract (const Rectangle& rect) throw();
  14948. /** Removes all areas in another RectangleList from this one.
  14949. Any rectangles in the list which overlap this will be clipped and subdivided
  14950. if necessary.
  14951. */
  14952. void subtract (const RectangleList& otherList) throw();
  14953. /** Removes any areas of the region that lie outside a given rectangle.
  14954. Any rectangles in the list which overlap this will be clipped and subdivided
  14955. if necessary.
  14956. Returns true if the resulting region is not empty, false if it is empty.
  14957. @see getIntersectionWith
  14958. */
  14959. bool clipTo (const Rectangle& rect) throw();
  14960. /** Removes any areas of the region that lie outside a given rectangle list.
  14961. Any rectangles in this object which overlap the specified list will be clipped
  14962. and subdivided if necessary.
  14963. Returns true if the resulting region is not empty, false if it is empty.
  14964. @see getIntersectionWith
  14965. */
  14966. bool clipTo (const RectangleList& other) throw();
  14967. /** Creates a region which is the result of clipping this one to a given rectangle.
  14968. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  14969. resulting region into the list whose reference is passed-in.
  14970. Returns true if the resulting region is not empty, false if it is empty.
  14971. @see clipTo
  14972. */
  14973. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  14974. /** Swaps the contents of this and another list.
  14975. This swaps their internal pointers, so is hugely faster than using copy-by-value
  14976. to swap them.
  14977. */
  14978. void swapWith (RectangleList& otherList) throw();
  14979. /** Checks whether the region contains a given point.
  14980. @returns true if the point lies within one of the rectangles in the list
  14981. */
  14982. bool containsPoint (const int x, const int y) const throw();
  14983. /** Checks whether the region contains the whole of a given rectangle.
  14984. @returns true all parts of the rectangle passed in lie within the region
  14985. defined by this object
  14986. @see intersectsRectangle, containsPoint
  14987. */
  14988. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  14989. /** Checks whether the region contains any part of a given rectangle.
  14990. @returns true if any part of the rectangle passed in lies within the region
  14991. defined by this object
  14992. @see containsRectangle
  14993. */
  14994. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  14995. /** Checks whether this region intersects any part of another one.
  14996. @see intersectsRectangle
  14997. */
  14998. bool intersects (const RectangleList& other) const throw();
  14999. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15000. const Rectangle getBounds() const throw();
  15001. /** Optimises the list into a minimum number of constituent rectangles.
  15002. This will try to combine any adjacent rectangles into larger ones where
  15003. possible, to simplify lists that might have been fragmented by repeated
  15004. add/subtract calls.
  15005. */
  15006. void consolidate() throw();
  15007. /** Adds an x and y value to all the co-ordinates. */
  15008. void offsetAll (const int dx, const int dy) throw();
  15009. /** Creates a Path object to represent this region. */
  15010. const Path toPath() const throw();
  15011. /** An iterator for accessing all the rectangles in a RectangleList. */
  15012. class Iterator
  15013. {
  15014. public:
  15015. Iterator (const RectangleList& list) throw();
  15016. ~Iterator() throw();
  15017. /** Advances to the next rectangle, and returns true if it's not finished.
  15018. Call this before using getRectangle() to find the rectangle that was returned.
  15019. */
  15020. bool next() throw();
  15021. /** Returns the current rectangle. */
  15022. const Rectangle* getRectangle() const throw() { return current; }
  15023. juce_UseDebuggingNewOperator
  15024. private:
  15025. const Rectangle* current;
  15026. const RectangleList& owner;
  15027. int index;
  15028. Iterator (const Iterator&);
  15029. const Iterator& operator= (const Iterator&);
  15030. };
  15031. juce_UseDebuggingNewOperator
  15032. private:
  15033. friend class Iterator;
  15034. Array <Rectangle> rects;
  15035. };
  15036. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15037. /********* End of inlined file: juce_RectangleList.h *********/
  15038. /********* Start of inlined file: juce_BorderSize.h *********/
  15039. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15040. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15041. /**
  15042. Specifies a set of gaps to be left around the sides of a rectangle.
  15043. This is basically the size of the spaces at the top, bottom, left and right of
  15044. a rectangle. It's used by various component classes to specify borders.
  15045. @see Rectangle
  15046. */
  15047. class JUCE_API BorderSize
  15048. {
  15049. public:
  15050. /** Creates a null border.
  15051. All sizes are left as 0.
  15052. */
  15053. BorderSize() throw();
  15054. /** Creates a copy of another border. */
  15055. BorderSize (const BorderSize& other) throw();
  15056. /** Creates a border with the given gaps. */
  15057. BorderSize (const int topGap,
  15058. const int leftGap,
  15059. const int bottomGap,
  15060. const int rightGap) throw();
  15061. /** Creates a border with the given gap on all sides. */
  15062. BorderSize (const int allGaps) throw();
  15063. /** Destructor. */
  15064. ~BorderSize() throw();
  15065. /** Returns the gap that should be left at the top of the region. */
  15066. int getTop() const throw() { return top; }
  15067. /** Returns the gap that should be left at the top of the region. */
  15068. int getLeft() const throw() { return left; }
  15069. /** Returns the gap that should be left at the top of the region. */
  15070. int getBottom() const throw() { return bottom; }
  15071. /** Returns the gap that should be left at the top of the region. */
  15072. int getRight() const throw() { return right; }
  15073. /** Returns the sum of the top and bottom gaps. */
  15074. int getTopAndBottom() const throw() { return top + bottom; }
  15075. /** Returns the sum of the left and right gaps. */
  15076. int getLeftAndRight() const throw() { return left + right; }
  15077. /** Changes the top gap. */
  15078. void setTop (const int newTopGap) throw();
  15079. /** Changes the left gap. */
  15080. void setLeft (const int newLeftGap) throw();
  15081. /** Changes the bottom gap. */
  15082. void setBottom (const int newBottomGap) throw();
  15083. /** Changes the right gap. */
  15084. void setRight (const int newRightGap) throw();
  15085. /** Returns a rectangle with these borders removed from it. */
  15086. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15087. /** Removes this border from a given rectangle. */
  15088. void subtractFrom (Rectangle& rectangle) const throw();
  15089. /** Returns a rectangle with these borders added around it. */
  15090. const Rectangle addedTo (const Rectangle& original) const throw();
  15091. /** Adds this border around a given rectangle. */
  15092. void addTo (Rectangle& original) const throw();
  15093. bool operator== (const BorderSize& other) const throw();
  15094. bool operator!= (const BorderSize& other) const throw();
  15095. juce_UseDebuggingNewOperator
  15096. private:
  15097. int top, left, bottom, right;
  15098. };
  15099. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15100. /********* End of inlined file: juce_BorderSize.h *********/
  15101. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15102. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15103. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15104. class Component;
  15105. class Graphics;
  15106. /********* Start of inlined file: juce_MessageListener.h *********/
  15107. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15108. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15109. /********* Start of inlined file: juce_Message.h *********/
  15110. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15111. #define __JUCE_MESSAGE_JUCEHEADER__
  15112. class MessageListener;
  15113. class MessageManager;
  15114. /** The base class for objects that can be delivered to a MessageListener.
  15115. The simplest Message object contains a few integer and pointer parameters
  15116. that the user can set, and this is enough for a lot of purposes. For passing more
  15117. complex data, subclasses of Message can also be used.
  15118. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15119. */
  15120. class JUCE_API Message
  15121. {
  15122. public:
  15123. /** Creates an uninitialised message.
  15124. The class's variables will also be left uninitialised.
  15125. */
  15126. Message() throw();
  15127. /** Creates a message object, filling in the member variables.
  15128. The corresponding public member variables will be set from the parameters
  15129. passed in.
  15130. */
  15131. Message (const int intParameter1,
  15132. const int intParameter2,
  15133. const int intParameter3,
  15134. void* const pointerParameter) throw();
  15135. /** Destructor. */
  15136. virtual ~Message() throw();
  15137. // These values can be used for carrying simple data that the application needs to
  15138. // pass around. For more complex messages, just create a subclass.
  15139. int intParameter1; /**< user-defined integer value. */
  15140. int intParameter2; /**< user-defined integer value. */
  15141. int intParameter3; /**< user-defined integer value. */
  15142. void* pointerParameter; /**< user-defined pointer value. */
  15143. juce_UseDebuggingNewOperator
  15144. private:
  15145. friend class MessageListener;
  15146. friend class MessageManager;
  15147. MessageListener* messageRecipient;
  15148. Message (const Message&);
  15149. const Message& operator= (const Message&);
  15150. };
  15151. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15152. /********* End of inlined file: juce_Message.h *********/
  15153. /**
  15154. MessageListener subclasses can post and receive Message objects.
  15155. @see Message, MessageManager, ActionListener, ChangeListener
  15156. */
  15157. class JUCE_API MessageListener
  15158. {
  15159. protected:
  15160. /** Creates a MessageListener. */
  15161. MessageListener() throw();
  15162. public:
  15163. /** Destructor.
  15164. When a MessageListener is deleted, it removes itself from a global list
  15165. of registered listeners, so that the isValidMessageListener() method
  15166. will no longer return true.
  15167. */
  15168. virtual ~MessageListener();
  15169. /** This is the callback method that receives incoming messages.
  15170. This is called by the MessageManager from its dispatch loop.
  15171. @see postMessage
  15172. */
  15173. virtual void handleMessage (const Message& message) = 0;
  15174. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15175. later on.
  15176. This method can be called safely by any thread.
  15177. @param message the message object to send - this will be deleted
  15178. automatically by the message queue, so don't keep any
  15179. references to it after calling this method.
  15180. @see handleMessage
  15181. */
  15182. void postMessage (Message* const message) const throw();
  15183. /** Checks whether this MessageListener has been deleted.
  15184. Although not foolproof, this method is safe to call on dangling or null
  15185. pointers. A list of active MessageListeners is kept internally, so this
  15186. checks whether the object is on this list or not.
  15187. Note that it's possible to get a false-positive here, if an object is
  15188. deleted and another is subsequently created that happens to be at the
  15189. exact same memory location, but I can't think of a good way of avoiding
  15190. this.
  15191. */
  15192. bool isValidMessageListener() const throw();
  15193. };
  15194. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15195. /********* End of inlined file: juce_MessageListener.h *********/
  15196. class ComponentBoundsConstrainer;
  15197. class ComponentDeletionWatcher;
  15198. /**
  15199. The base class for window objects that wrap a component as a real operating
  15200. system object.
  15201. This is an abstract base class - the platform specific code contains default
  15202. implementations of it that create and manage windows.
  15203. @see Component::createNewPeer
  15204. */
  15205. class JUCE_API ComponentPeer : public MessageListener
  15206. {
  15207. public:
  15208. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15209. enum StyleFlags
  15210. {
  15211. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15212. entry on the taskbar (ignored on MacOSX) */
  15213. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15214. tooltip, etc. */
  15215. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15216. through it (may not be possible on some platforms). */
  15217. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15218. title bar and frame\. if not specified, the window will be
  15219. borderless. */
  15220. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15221. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15222. minimise button on it. */
  15223. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15224. maximise button on it. */
  15225. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15226. close button on it. */
  15227. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15228. not be possible on all platforms). */
  15229. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15230. do its own repainting, but only to repaint when the
  15231. performAnyPendingRepaintsNow() method is called. */
  15232. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15233. be used for things like plugin windows, to stop them interfering
  15234. with the host's shortcut keys */
  15235. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15236. };
  15237. /** Creates a peer.
  15238. The component is the one that we intend to represent, and the style flags are
  15239. a combination of the values in the StyleFlags enum
  15240. */
  15241. ComponentPeer (Component* const component,
  15242. const int styleFlags) throw();
  15243. /** Destructor. */
  15244. virtual ~ComponentPeer();
  15245. /** Returns the component being represented by this peer. */
  15246. Component* getComponent() const throw() { return component; }
  15247. /** Returns the set of style flags that were set when the window was created.
  15248. @see Component::addToDesktop
  15249. */
  15250. int getStyleFlags() const throw() { return styleFlags; }
  15251. /** Returns the raw handle to whatever kind of window is being used.
  15252. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15253. but rememeber there's no guarantees what you'll get back.
  15254. */
  15255. virtual void* getNativeHandle() const = 0;
  15256. /** Shows or hides the window. */
  15257. virtual void setVisible (bool shouldBeVisible) = 0;
  15258. /** Changes the title of the window. */
  15259. virtual void setTitle (const String& title) = 0;
  15260. /** Moves the window without changing its size.
  15261. If the native window is contained in another window, then the co-ordinates are
  15262. relative to the parent window's origin, not the screen origin.
  15263. This should result in a callback to handleMovedOrResized().
  15264. */
  15265. virtual void setPosition (int x, int y) = 0;
  15266. /** Resizes the window without changing its position.
  15267. This should result in a callback to handleMovedOrResized().
  15268. */
  15269. virtual void setSize (int w, int h) = 0;
  15270. /** Moves and resizes the window.
  15271. If the native window is contained in another window, then the co-ordinates are
  15272. relative to the parent window's origin, not the screen origin.
  15273. This should result in a callback to handleMovedOrResized().
  15274. */
  15275. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15276. /** Returns the current position and size of the window.
  15277. If the native window is contained in another window, then the co-ordinates are
  15278. relative to the parent window's origin, not the screen origin.
  15279. */
  15280. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15281. /** Returns the x-position of this window, relative to the screen's origin. */
  15282. virtual int getScreenX() const = 0;
  15283. /** Returns the y-position of this window, relative to the screen's origin. */
  15284. virtual int getScreenY() const = 0;
  15285. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15286. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15287. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15288. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15289. /** Minimises the window. */
  15290. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15291. /** True if the window is currently minimised. */
  15292. virtual bool isMinimised() const = 0;
  15293. /** Enable/disable fullscreen mode for the window. */
  15294. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15295. /** True if the window is currently full-screen. */
  15296. virtual bool isFullScreen() const = 0;
  15297. /** Sets the size to restore to if fullscreen mode is turned off. */
  15298. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15299. /** Returns the size to restore to if fullscreen mode is turned off. */
  15300. const Rectangle& getNonFullScreenBounds() const throw();
  15301. /** Attempts to change the icon associated with this window.
  15302. */
  15303. virtual void setIcon (const Image& newIcon) = 0;
  15304. /** Sets a constrainer to use if the peer can resize itself.
  15305. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15306. */
  15307. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15308. /** Returns the current constrainer, if one has been set. */
  15309. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15310. /** Checks if a point is in the window.
  15311. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15312. is false, then this returns false if the point is actually inside a child of this
  15313. window.
  15314. */
  15315. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15316. /** Returns the size of the window frame that's around this window.
  15317. Whether or not the window has a normal window frame depends on the flags
  15318. that were set when the window was created by Component::addToDesktop()
  15319. */
  15320. virtual const BorderSize getFrameSize() const = 0;
  15321. /** This is called when the window's bounds change.
  15322. A peer implementation must call this when the window is moved and resized, so that
  15323. this method can pass the message on to the component.
  15324. */
  15325. void handleMovedOrResized();
  15326. /** This is called if the screen resolution changes.
  15327. A peer implementation must call this if the monitor arrangement changes or the available
  15328. screen size changes.
  15329. */
  15330. void handleScreenSizeChange();
  15331. /** This is called to repaint the component into the given context. */
  15332. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15333. /** Sets this window to either be always-on-top or normal.
  15334. Some kinds of window might not be able to do this, so should return false.
  15335. */
  15336. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15337. /** Brings the window to the top, optionally also giving it focus. */
  15338. virtual void toFront (bool makeActive) = 0;
  15339. /** Moves the window to be just behind another one. */
  15340. virtual void toBehind (ComponentPeer* other) = 0;
  15341. /** Called when the window is brought to the front, either by the OS or by a call
  15342. to toFront().
  15343. */
  15344. void handleBroughtToFront();
  15345. /** True if the window has the keyboard focus. */
  15346. virtual bool isFocused() const = 0;
  15347. /** Tries to give the window keyboard focus. */
  15348. virtual void grabFocus() = 0;
  15349. /** Tells the window that text input may be required at the given position.
  15350. This may cause things like a virtual on-screen keyboard to appear, depending
  15351. on the OS.
  15352. */
  15353. virtual void textInputRequired (int x, int y) = 0;
  15354. /** Called when the window gains keyboard focus. */
  15355. void handleFocusGain();
  15356. /** Called when the window loses keyboard focus. */
  15357. void handleFocusLoss();
  15358. Component* getLastFocusedSubcomponent() const throw();
  15359. /** Called when a key is pressed.
  15360. For keycode info, see the KeyPress class.
  15361. Returns true if the keystroke was used.
  15362. */
  15363. bool handleKeyPress (const int keyCode,
  15364. const juce_wchar textCharacter);
  15365. /** Called whenever a key is pressed or released.
  15366. Returns true if the keystroke was used.
  15367. */
  15368. bool handleKeyUpOrDown();
  15369. /** Called whenever a modifier key is pressed or released. */
  15370. void handleModifierKeysChange();
  15371. /** Invalidates a region of the window to be repainted asynchronously. */
  15372. virtual void repaint (int x, int y, int w, int h) = 0;
  15373. /** This can be called (from the message thread) to cause the immediate redrawing
  15374. of any areas of this window that need repainting.
  15375. You shouldn't ever really need to use this, it's mainly for special purposes
  15376. like supporting audio plugins where the host's event loop is out of our control.
  15377. */
  15378. virtual void performAnyPendingRepaintsNow() = 0;
  15379. void handleMouseEnter (int x, int y, const int64 time);
  15380. void handleMouseMove (int x, int y, const int64 time);
  15381. void handleMouseDown (int x, int y, const int64 time);
  15382. void handleMouseDrag (int x, int y, const int64 time);
  15383. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15384. void handleMouseExit (int x, int y, const int64 time);
  15385. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15386. /** Causes a mouse-move callback to be made asynchronously. */
  15387. void sendFakeMouseMove() throw();
  15388. void handleUserClosingWindow();
  15389. void handleFileDragMove (const StringArray& files, int x, int y);
  15390. void handleFileDragExit (const StringArray& files);
  15391. void handleFileDragDrop (const StringArray& files, int x, int y);
  15392. /** Resets the masking region.
  15393. The subclass should call this every time it's about to call the handlePaint
  15394. method.
  15395. @see addMaskedRegion
  15396. */
  15397. void clearMaskedRegion() throw();
  15398. /** Adds a rectangle to the set of areas not to paint over.
  15399. A component can call this on its peer during its paint() method, to signal
  15400. that the painting code should ignore a given region. The reason
  15401. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15402. The masked region is cleared each time before a paint happens, so a component
  15403. will have to make sure it calls this every time it's painted.
  15404. */
  15405. void addMaskedRegion (int x, int y, int w, int h) throw();
  15406. /** Returns the number of currently-active peers.
  15407. @see getPeer
  15408. */
  15409. static int getNumPeers() throw();
  15410. /** Returns one of the currently-active peers.
  15411. @see getNumPeers
  15412. */
  15413. static ComponentPeer* getPeer (const int index) throw();
  15414. /** Checks if this peer object is valid.
  15415. @see getNumPeers
  15416. */
  15417. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15418. juce_UseDebuggingNewOperator
  15419. protected:
  15420. Component* const component;
  15421. const int styleFlags;
  15422. RectangleList maskedRegion;
  15423. Rectangle lastNonFullscreenBounds;
  15424. uint32 lastPaintTime;
  15425. ComponentBoundsConstrainer* constrainer;
  15426. static void updateCurrentModifiers() throw();
  15427. /** @internal */
  15428. void handleMessage (const Message& message);
  15429. private:
  15430. Component* lastFocusedComponent;
  15431. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15432. Component* lastDragAndDropCompUnderMouse;
  15433. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15434. friend class Component;
  15435. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15436. void setLastDragDropTarget (Component* comp);
  15437. ComponentPeer (const ComponentPeer&);
  15438. const ComponentPeer& operator= (const ComponentPeer&);
  15439. };
  15440. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15441. /********* End of inlined file: juce_ComponentPeer.h *********/
  15442. class LookAndFeel;
  15443. /**
  15444. The base class for all JUCE user-interface objects.
  15445. */
  15446. class JUCE_API Component : public MouseListener,
  15447. protected MessageListener
  15448. {
  15449. public:
  15450. /** Creates a component.
  15451. To get it to actually appear, you'll also need to:
  15452. - Either add it to a parent component or use the addToDesktop() method to
  15453. make it a desktop window
  15454. - Set its size and position to something sensible
  15455. - Use setVisible() to make it visible
  15456. And for it to serve any useful purpose, you'll need to write a
  15457. subclass of Component or use one of the other types of component from
  15458. the library.
  15459. */
  15460. Component() throw();
  15461. /** Destructor.
  15462. Note that when a component is deleted, any child components it might
  15463. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15464. */
  15465. virtual ~Component();
  15466. /** Creates a component, setting its name at the same time.
  15467. @see getName, setName
  15468. */
  15469. Component (const String& componentName) throw();
  15470. /** Returns the name of this component.
  15471. @see setName
  15472. */
  15473. const String& getName() const throw() { return componentName_; }
  15474. /** Sets the name of this component.
  15475. When the name changes, all registered ComponentListeners will receive a
  15476. ComponentListener::componentNameChanged() callback.
  15477. @see getName
  15478. */
  15479. virtual void setName (const String& newName);
  15480. /** Checks whether this Component object has been deleted.
  15481. This will check whether this object is still a valid component, or whether
  15482. it's been deleted.
  15483. It's safe to call this on null or dangling pointers, but note that there is a
  15484. small risk if another new (but different) component has been created at the
  15485. same memory address which this one occupied, this methods can return a
  15486. false positive.
  15487. */
  15488. bool isValidComponent() const throw();
  15489. /** Makes the component visible or invisible.
  15490. This method will show or hide the component.
  15491. Note that components default to being non-visible when first created.
  15492. Also note that visible components won't be seen unless all their parent components
  15493. are also visible.
  15494. This method will call visibilityChanged() and also componentVisibilityChanged()
  15495. for any component listeners that are interested in this component.
  15496. @param shouldBeVisible whether to show or hide the component
  15497. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15498. */
  15499. virtual void setVisible (bool shouldBeVisible);
  15500. /** Tests whether the component is visible or not.
  15501. this doesn't necessarily tell you whether this comp is actually on the screen
  15502. because this depends on whether all the parent components are also visible - use
  15503. isShowing() to find this out.
  15504. @see isShowing, setVisible
  15505. */
  15506. bool isVisible() const throw() { return flags.visibleFlag; }
  15507. /** Called when this component's visiblility changes.
  15508. @see setVisible, isVisible
  15509. */
  15510. virtual void visibilityChanged();
  15511. /** Tests whether this component and all its parents are visible.
  15512. @returns true only if this component and all its parents are visible.
  15513. @see isVisible
  15514. */
  15515. bool isShowing() const throw();
  15516. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15517. To do this, this function will cunningly:
  15518. - take a snapshot of the component as it currently looks
  15519. - call setVisible(false) on the component
  15520. - replace it with a special component that will continue drawing the
  15521. snapshot, animating it and gradually making it more transparent
  15522. - when it's gone, the special component will also be deleted
  15523. As soon as this method returns, the component can be safely removed and deleted
  15524. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15525. component's destructor.
  15526. Passing non-zero x and y values will cause the ghostly component image to
  15527. also whizz off by this distance while fading out. If the scale factor is
  15528. not 1.0, it will also zoom from the component's current size to this new size.
  15529. One thing to be careful about is that the parent component must be able to cope
  15530. with this unknown component type being added to it.
  15531. */
  15532. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15533. const int deltaXToMove = 0,
  15534. const int deltaYToMove = 0,
  15535. const float scaleFactorAtEnd = 1.0f);
  15536. /** Makes this component appear as a window on the desktop.
  15537. Note that before calling this, you should make sure that the component's opacity is
  15538. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15539. system will try to create a special transparent window for it, which will generally take
  15540. a lot more CPU to operate (and might not even be possible on some platforms).
  15541. If the component is inside a parent component at the time this method is called, it
  15542. will be first be removed from that parent. Likewise if a component on the desktop
  15543. is subsequently added to another component, it'll be removed from the desktop.
  15544. @param windowStyleFlags a combination of the flags specified in the
  15545. ComponentPeer::StyleFlags enum, which define the
  15546. window's characteristics.
  15547. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15548. in which the juce component should place itself. On Windows,
  15549. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15550. supported on all platforms, and best left as 0 unless you know
  15551. what you're doing
  15552. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15553. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15554. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15555. */
  15556. virtual void addToDesktop (int windowStyleFlags,
  15557. void* nativeWindowToAttachTo = 0);
  15558. /** If the component is currently showing on the desktop, this will hide it.
  15559. You can also use setVisible() to hide a desktop window temporarily, but
  15560. removeFromDesktop() will free any system resources that are being used up.
  15561. @see addToDesktop, isOnDesktop
  15562. */
  15563. void removeFromDesktop();
  15564. /** Returns true if this component is currently showing on the desktop.
  15565. @see addToDesktop, removeFromDesktop
  15566. */
  15567. bool isOnDesktop() const throw();
  15568. /** Returns the heavyweight window that contains this component.
  15569. If this component is itself on the desktop, this will return the window
  15570. object that it is using. Otherwise, it will return the window of
  15571. its top-level parent component.
  15572. This may return 0 if there isn't a desktop component.
  15573. @see addToDesktop, isOnDesktop
  15574. */
  15575. ComponentPeer* getPeer() const throw();
  15576. /** For components on the desktop, this is called if the system wants to close the window.
  15577. This is a signal that either the user or the system wants the window to close. The
  15578. default implementation of this method will trigger an assertion to warn you that your
  15579. component should do something about it, but you can override this to ignore the event
  15580. if you want.
  15581. */
  15582. virtual void userTriedToCloseWindow();
  15583. /** Called for a desktop component which has just been minimised or un-minimised.
  15584. This will only be called for components on the desktop.
  15585. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15586. */
  15587. virtual void minimisationStateChanged (bool isNowMinimised);
  15588. /** Brings the component to the front of its siblings.
  15589. If some of the component's siblings have had their 'always-on-top' flag set,
  15590. then they will still be kept in front of this one (unless of course this
  15591. one is also 'always-on-top').
  15592. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15593. to the component (see grabKeyboardFocus() for more details)
  15594. @see toBack, toBehind, setAlwaysOnTop
  15595. */
  15596. void toFront (const bool shouldAlsoGainFocus);
  15597. /** Changes this component's z-order to be at the back of all its siblings.
  15598. If the component is set to be 'always-on-top', it will only be moved to the
  15599. back of the other other 'always-on-top' components.
  15600. @see toFront, toBehind, setAlwaysOnTop
  15601. */
  15602. void toBack();
  15603. /** Changes this component's z-order so that it's just behind another component.
  15604. @see toFront, toBack
  15605. */
  15606. void toBehind (Component* const other);
  15607. /** Sets whether the component should always be kept at the front of its siblings.
  15608. @see isAlwaysOnTop
  15609. */
  15610. void setAlwaysOnTop (const bool shouldStayOnTop);
  15611. /** Returns true if this component is set to always stay in front of its siblings.
  15612. @see setAlwaysOnTop
  15613. */
  15614. bool isAlwaysOnTop() const throw();
  15615. /** Returns the x co-ordinate of the component's left edge.
  15616. This is a distance in pixels from the left edge of the component's parent.
  15617. @see getScreenX
  15618. */
  15619. inline int getX() const throw() { return bounds_.getX(); }
  15620. /** Returns the y co-ordinate of the top of this component.
  15621. This is a distance in pixels from the top edge of the component's parent.
  15622. @see getScreenY
  15623. */
  15624. inline int getY() const throw() { return bounds_.getY(); }
  15625. /** Returns the component's width in pixels. */
  15626. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15627. /** Returns the component's height in pixels. */
  15628. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15629. /** Returns the x co-ordinate of the component's right-hand edge.
  15630. This is a distance in pixels from the left edge of the component's parent.
  15631. */
  15632. int getRight() const throw() { return bounds_.getRight(); }
  15633. /** Returns the y co-ordinate of the bottom edge of this component.
  15634. This is a distance in pixels from the top edge of the component's parent.
  15635. */
  15636. int getBottom() const throw() { return bounds_.getBottom(); }
  15637. /** Returns this component's bounding box.
  15638. The rectangle returned is relative to the top-left of the component's parent.
  15639. */
  15640. const Rectangle& getBounds() const throw() { return bounds_; }
  15641. /** Returns the region of this component that's not obscured by other, opaque components.
  15642. The RectangleList that is returned represents the area of this component
  15643. which isn't covered by opaque child components.
  15644. If includeSiblings is true, it will also take into account any siblings
  15645. that may be overlapping the component.
  15646. */
  15647. void getVisibleArea (RectangleList& result,
  15648. const bool includeSiblings) const;
  15649. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15650. @see getX, relativePositionToGlobal
  15651. */
  15652. int getScreenX() const throw();
  15653. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15654. @see getY, relativePositionToGlobal
  15655. */
  15656. int getScreenY() const throw();
  15657. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15658. @see globalPositionToRelative, relativePositionToOtherComponent
  15659. */
  15660. void relativePositionToGlobal (int& x, int& y) const throw();
  15661. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15662. @see relativePositionToGlobal, relativePositionToOtherComponent
  15663. */
  15664. void globalPositionToRelative (int& x, int& y) const throw();
  15665. /** Converts a position relative to this component's top-left into a position
  15666. relative to another component's top-left.
  15667. @see relativePositionToGlobal, globalPositionToRelative
  15668. */
  15669. void relativePositionToOtherComponent (const Component* const targetComponent,
  15670. int& x, int& y) const throw();
  15671. /** Moves the component to a new position.
  15672. Changes the component's top-left position (without changing its size).
  15673. The position is relative to the top-left of the component's parent.
  15674. If the component actually moves, this method will make a synchronous call to moved().
  15675. @see setBounds, ComponentListener::componentMovedOrResized
  15676. */
  15677. void setTopLeftPosition (const int x, const int y);
  15678. /** Moves the component to a new position.
  15679. Changes the position of the component's top-right corner (keeping it the same size).
  15680. The position is relative to the top-left of the component's parent.
  15681. If the component actually moves, this method will make a synchronous call to moved().
  15682. */
  15683. void setTopRightPosition (const int x, const int y);
  15684. /** Changes the size of the component.
  15685. A synchronous call to resized() will be occur if the size actually changes.
  15686. */
  15687. void setSize (const int newWidth, const int newHeight);
  15688. /** Changes the component's position and size.
  15689. The co-ordinates are relative to the top-left of the component's parent, or relative
  15690. to the origin of the screen is the component is on the desktop.
  15691. If this method changes the component's top-left position, it will make a synchronous
  15692. call to moved(). If it changes the size, it will also make a call to resized().
  15693. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15694. */
  15695. void setBounds (int x, int y, int width, int height);
  15696. /** Changes the component's position and size.
  15697. @see setBounds
  15698. */
  15699. void setBounds (const Rectangle& newBounds);
  15700. /** Changes the component's position and size in terms of fractions of its parent's size.
  15701. The values are factors of the parent's size, so for example
  15702. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15703. width and height of the parent, with its top-left position 20% of
  15704. the way across and down the parent.
  15705. */
  15706. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15707. const float proportionalWidth, const float proportionalHeight);
  15708. /** Changes the component's position and size based on the amount of space to leave around it.
  15709. This will position the component within its parent, leaving the specified number of
  15710. pixels around each edge.
  15711. */
  15712. void setBoundsInset (const BorderSize& borders);
  15713. /** Positions the component within a given rectangle, keeping its proportions
  15714. unchanged.
  15715. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15716. rectangle as possible without changing its aspect ratio (the component's
  15717. current size is used to determine its aspect ratio, so a zero-size component
  15718. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15719. too big to fit inside the rectangle.
  15720. It will then be positioned within the rectangle according to the justification flags
  15721. specified.
  15722. */
  15723. void setBoundsToFit (int x, int y, int width, int height,
  15724. const Justification& justification,
  15725. const bool onlyReduceInSize);
  15726. /** Changes the position of the component's centre.
  15727. Leaves the component's size unchanged, but sets the position of its centre
  15728. relative to its parent's top-left.
  15729. */
  15730. void setCentrePosition (const int x, const int y);
  15731. /** Changes the position of the component's centre.
  15732. Leaves the position unchanged, but positions its centre relative to its
  15733. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15734. its parent.
  15735. */
  15736. void setCentreRelative (const float x, const float y);
  15737. /** Changes the component's size and centres it within its parent.
  15738. After changing the size, the component will be moved so that it's
  15739. centred within its parent.
  15740. */
  15741. void centreWithSize (const int width, const int height);
  15742. /** Returns a proportion of the component's width.
  15743. This is a handy equivalent of (getWidth() * proportion).
  15744. */
  15745. int proportionOfWidth (const float proportion) const throw();
  15746. /** Returns a proportion of the component's height.
  15747. This is a handy equivalent of (getHeight() * proportion).
  15748. */
  15749. int proportionOfHeight (const float proportion) const throw();
  15750. /** Returns the width of the component's parent.
  15751. If the component has no parent (i.e. if it's on the desktop), this will return
  15752. the width of the screen.
  15753. */
  15754. int getParentWidth() const throw();
  15755. /** Returns the height of the component's parent.
  15756. If the component has no parent (i.e. if it's on the desktop), this will return
  15757. the height of the screen.
  15758. */
  15759. int getParentHeight() const throw();
  15760. /** Returns the screen co-ordinates of the monitor that contains this component.
  15761. If there's only one monitor, this will return its size - if there are multiple
  15762. monitors, it will return the area of the monitor that contains the component's
  15763. centre.
  15764. */
  15765. const Rectangle getParentMonitorArea() const throw();
  15766. /** Returns the number of child components that this component contains.
  15767. @see getChildComponent, getIndexOfChildComponent
  15768. */
  15769. int getNumChildComponents() const throw();
  15770. /** Returns one of this component's child components, by it index.
  15771. The component with index 0 is at the back of the z-order, the one at the
  15772. front will have index (getNumChildComponents() - 1).
  15773. If the index is out-of-range, this will return a null pointer.
  15774. @see getNumChildComponents, getIndexOfChildComponent
  15775. */
  15776. Component* getChildComponent (const int index) const throw();
  15777. /** Returns the index of this component in the list of child components.
  15778. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15779. values are further towards the front.
  15780. Returns -1 if the component passed-in is not a child of this component.
  15781. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15782. */
  15783. int getIndexOfChildComponent (const Component* const child) const throw();
  15784. /** Adds a child component to this one.
  15785. @param child the new component to add. If the component passed-in is already
  15786. the child of another component, it'll first be removed from that.
  15787. @param zOrder The index in the child-list at which this component should be inserted.
  15788. A value of -1 will insert it in front of the others, 0 is the back.
  15789. @see removeChildComponent, addAndMakeVisible, getChild,
  15790. ComponentListener::componentChildrenChanged
  15791. */
  15792. void addChildComponent (Component* const child,
  15793. int zOrder = -1);
  15794. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15795. Quite a useful function, this is just the same as calling addChildComponent()
  15796. followed by setVisible (true) on the child.
  15797. */
  15798. void addAndMakeVisible (Component* const child,
  15799. int zOrder = -1);
  15800. /** Removes one of this component's child-components.
  15801. If the child passed-in isn't actually a child of this component (either because
  15802. it's invalid or is the child of a different parent), then nothing is done.
  15803. Note that removing a child will not delete it!
  15804. @see addChildComponent, ComponentListener::componentChildrenChanged
  15805. */
  15806. void removeChildComponent (Component* const childToRemove);
  15807. /** Removes one of this component's child-components by index.
  15808. This will return a pointer to the component that was removed, or null if
  15809. the index was out-of-range.
  15810. Note that removing a child will not delete it!
  15811. @see addChildComponent, ComponentListener::componentChildrenChanged
  15812. */
  15813. Component* removeChildComponent (const int childIndexToRemove);
  15814. /** Removes all this component's children.
  15815. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  15816. */
  15817. void removeAllChildren();
  15818. /** Removes all this component's children, and deletes them.
  15819. @see removeAllChildren
  15820. */
  15821. void deleteAllChildren();
  15822. /** Returns the component which this component is inside.
  15823. If this is the highest-level component or hasn't yet been added to
  15824. a parent, this will return null.
  15825. */
  15826. Component* getParentComponent() const throw() { return parentComponent_; }
  15827. /** Searches the parent components for a component of a specified class.
  15828. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  15829. component that can be dynamically cast to a MyComp, or will return 0 if none
  15830. of the parents are suitable.
  15831. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  15832. */
  15833. template <class TargetClass>
  15834. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  15835. {
  15836. (void) dummyParameter;
  15837. Component* p = parentComponent_;
  15838. while (p != 0)
  15839. {
  15840. TargetClass* target = dynamic_cast <TargetClass*> (p);
  15841. if (target != 0)
  15842. return target;
  15843. p = p->parentComponent_;
  15844. }
  15845. return 0;
  15846. }
  15847. /** Returns the highest-level component which contains this one or its parents.
  15848. This will search upwards in the parent-hierarchy from this component, until it
  15849. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  15850. not yet added to a parent), and will return that.
  15851. */
  15852. Component* getTopLevelComponent() const throw();
  15853. /** Checks whether a component is anywhere inside this component or its children.
  15854. This will recursively check through this components children to see if the
  15855. given component is anywhere inside.
  15856. */
  15857. bool isParentOf (const Component* possibleChild) const throw();
  15858. /** Called to indicate that the component's parents have changed.
  15859. When a component is added or removed from its parent, this method will
  15860. be called on all of its children (recursively - so all children of its
  15861. children will also be called as well).
  15862. Subclasses can override this if they need to react to this in some way.
  15863. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  15864. */
  15865. virtual void parentHierarchyChanged();
  15866. /** Subclasses can use this callback to be told when children are added or removed.
  15867. @see parentHierarchyChanged
  15868. */
  15869. virtual void childrenChanged();
  15870. /** Tests whether a given point inside the component.
  15871. Overriding this method allows you to create components which only intercept
  15872. mouse-clicks within a user-defined area.
  15873. This is called to find out whether a particular x, y co-ordinate is
  15874. considered to be inside the component or not, and is used by methods such
  15875. as contains() and getComponentAt() to work out which component
  15876. the mouse is clicked on.
  15877. Components with custom shapes will probably want to override it to perform
  15878. some more complex hit-testing.
  15879. The default implementation of this method returns either true or false,
  15880. depending on the value that was set by calling setInterceptsMouseClicks() (true
  15881. is the default return value).
  15882. Note that the hit-test region is not related to the opacity with which
  15883. areas of a component are painted.
  15884. Applications should never call hitTest() directly - instead use the
  15885. contains() method, because this will also test for occlusion by the
  15886. component's parent.
  15887. Note that for components on the desktop, this method will be ignored, because it's
  15888. not always possible to implement this behaviour on all platforms.
  15889. @param x the x co-ordinate to test, relative to the left hand edge of this
  15890. component. This value is guaranteed to be greater than or equal to
  15891. zero, and less than the component's width
  15892. @param y the y co-ordinate to test, relative to the top edge of this
  15893. component. This value is guaranteed to be greater than or equal to
  15894. zero, and less than the component's height
  15895. @returns true if the click is considered to be inside the component
  15896. @see setInterceptsMouseClicks, contains
  15897. */
  15898. virtual bool hitTest (int x, int y);
  15899. /** Changes the default return value for the hitTest() method.
  15900. Setting this to false is an easy way to make a component pass its mouse-clicks
  15901. through to the components behind it.
  15902. When a component is created, the default setting for this is true.
  15903. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  15904. return false (or true for child components if allowClicksOnChildComponents
  15905. is true)
  15906. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  15907. components can be clicked on as normal but clicks on this component pass
  15908. straight through; if this is false and allowClicksOnThisComponent
  15909. is false, then neither this component nor any child components can
  15910. be clicked on
  15911. @see hitTest, getInterceptsMouseClicks
  15912. */
  15913. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  15914. const bool allowClicksOnChildComponents) throw();
  15915. /** Retrieves the current state of the mouse-click interception flags.
  15916. On return, the two parameters are set to the state used in the last call to
  15917. setInterceptsMouseClicks().
  15918. @see setInterceptsMouseClicks
  15919. */
  15920. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  15921. bool& allowsClicksOnChildComponents) const throw();
  15922. /** Returns true if a given point lies within this component or one of its children.
  15923. Never override this method! Use hitTest to create custom hit regions.
  15924. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15925. @param y the y co-ordinate to test, relative to this component's top edge.
  15926. @returns true if the point is within the component's hit-test area, but only if
  15927. that part of the component isn't clipped by its parent component. Note
  15928. that this won't take into account any overlapping sibling components
  15929. which might be in the way - for that, see reallyContains()
  15930. @see hitTest, reallyContains, getComponentAt
  15931. */
  15932. virtual bool contains (int x, int y);
  15933. /** Returns true if a given point lies in this component, taking any overlapping
  15934. siblings into account.
  15935. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15936. @param y the y co-ordinate to test, relative to this component's top edge.
  15937. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  15938. component, this determines the value that will
  15939. be returned.
  15940. @see contains, getComponentAt
  15941. */
  15942. bool reallyContains (int x, int y,
  15943. const bool returnTrueIfWithinAChild);
  15944. /** Returns the component at a certain point within this one.
  15945. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15946. @param y the y co-ordinate to test, relative to this component's top edge.
  15947. @returns the component that is at this position - which may be 0, this component,
  15948. or one of its children. Note that overlapping siblings that might actually
  15949. be in the way are not taken into account by this method - to account for these,
  15950. instead call getComponentAt on the top-level parent of this component.
  15951. @see hitTest, contains, reallyContains
  15952. */
  15953. Component* getComponentAt (const int x, const int y);
  15954. /** Marks the whole component as needing to be redrawn.
  15955. Calling this will not do any repainting immediately, but will mark the component
  15956. as 'dirty'. At some point in the near future the operating system will send a paint
  15957. message, which will redraw all the dirty regions of all components.
  15958. There's no guarantee about how soon after calling repaint() the redraw will actually
  15959. happen, and other queued events may be delivered before a redraw is done.
  15960. If the setBufferedToImage() method has been used to cause this component
  15961. to use a buffer, the repaint() call will invalidate the component's buffer.
  15962. To redraw just a subsection of the component rather than the whole thing,
  15963. use the repaint (int, int, int, int) method.
  15964. @see paint
  15965. */
  15966. void repaint() throw();
  15967. /** Marks a subsection of this component as needing to be redrawn.
  15968. Calling this will not do any repainting immediately, but will mark the given region
  15969. of the component as 'dirty'. At some point in the near future the operating system
  15970. will send a paint message, which will redraw all the dirty regions of all components.
  15971. There's no guarantee about how soon after calling repaint() the redraw will actually
  15972. happen, and other queued events may be delivered before a redraw is done.
  15973. The region that is passed in will be clipped to keep it within the bounds of this
  15974. component.
  15975. @see repaint()
  15976. */
  15977. void repaint (const int x, const int y,
  15978. const int width, const int height) throw();
  15979. /** Makes the component use an internal buffer to optimise its redrawing.
  15980. Setting this flag to true will cause the component to allocate an
  15981. internal buffer into which it paints itself, so that when asked to
  15982. redraw itself, it can use this buffer rather than actually calling the
  15983. paint() method.
  15984. The buffer is kept until the repaint() method is called directly on
  15985. this component (or until it is resized), when the image is invalidated
  15986. and then redrawn the next time the component is painted.
  15987. Note that only the drawing that happens within the component's paint()
  15988. method is drawn into the buffer, it's child components are not buffered, and
  15989. nor is the paintOverChildren() method.
  15990. @see repaint, paint, createComponentSnapshot
  15991. */
  15992. void setBufferedToImage (const bool shouldBeBuffered) throw();
  15993. /** Generates a snapshot of part of this component.
  15994. This will return a new Image, the size of the rectangle specified,
  15995. containing a snapshot of the specified area of the component and all
  15996. its children.
  15997. The image may or may not have an alpha-channel, depending on whether the
  15998. image is opaque or not.
  15999. If the clipImageToComponentBounds parameter is true and the area is greater than
  16000. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16001. then parts of the component beyond its bounds can be drawn.
  16002. The caller is responsible for deleting the image that is returned.
  16003. @see paintEntireComponent
  16004. */
  16005. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16006. const bool clipImageToComponentBounds = true);
  16007. /** Draws this component and all its subcomponents onto the specified graphics
  16008. context.
  16009. You should very rarely have to use this method, it's simply there in case you need
  16010. to draw a component with a custom graphics context for some reason, e.g. for
  16011. creating a snapshot of the component.
  16012. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16013. on its children in order to render the entire tree.
  16014. The graphics context may be left in an undefined state after this method returns,
  16015. so you may need to reset it if you're going to use it again.
  16016. */
  16017. void paintEntireComponent (Graphics& context);
  16018. /** Adds an effect filter to alter the component's appearance.
  16019. When a component has an effect filter set, then this is applied to the
  16020. results of its paint() method. There are a few preset effects, such as
  16021. a drop-shadow or glow, but they can be user-defined as well.
  16022. The effect that is passed in will not be deleted by the component - the
  16023. caller must take care of deleting it.
  16024. To remove an effect from a component, pass a null pointer in as the parameter.
  16025. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16026. */
  16027. void setComponentEffect (ImageEffectFilter* const newEffect);
  16028. /** Returns the current component effect.
  16029. @see setComponentEffect
  16030. */
  16031. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16032. /** Finds the appropriate look-and-feel to use for this component.
  16033. If the component hasn't had a look-and-feel explicitly set, this will
  16034. return the parent's look-and-feel, or just the default one if there's no
  16035. parent.
  16036. @see setLookAndFeel, lookAndFeelChanged
  16037. */
  16038. LookAndFeel& getLookAndFeel() const throw();
  16039. /** Sets the look and feel to use for this component.
  16040. This will also change the look and feel for any child components that haven't
  16041. had their look set explicitly.
  16042. The object passed in will not be deleted by the component, so it's the caller's
  16043. responsibility to manage it. It may be used at any time until this component
  16044. has been deleted.
  16045. Calling this method will also invoke the sendLookAndFeelChange() method.
  16046. @see getLookAndFeel, lookAndFeelChanged
  16047. */
  16048. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16049. /** Called to let the component react to a change in the look-and-feel setting.
  16050. When the look-and-feel is changed for a component, this will be called in
  16051. all its child components, recursively.
  16052. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16053. an application uses a LookAndFeel class that might have changed internally.
  16054. @see sendLookAndFeelChange, getLookAndFeel
  16055. */
  16056. virtual void lookAndFeelChanged();
  16057. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16058. This will recurse through the children and their children, calling lookAndFeelChanged()
  16059. on them all.
  16060. @see lookAndFeelChanged
  16061. */
  16062. void sendLookAndFeelChange();
  16063. /** Indicates whether any parts of the component might be transparent.
  16064. Components that always paint all of their contents with solid colour and
  16065. thus completely cover any components behind them should use this method
  16066. to tell the repaint system that they are opaque.
  16067. This information is used to optimise drawing, because it means that
  16068. objects underneath opaque windows don't need to be painted.
  16069. By default, components are considered transparent, unless this is used to
  16070. make it otherwise.
  16071. @see isOpaque, getVisibleArea
  16072. */
  16073. void setOpaque (const bool shouldBeOpaque) throw();
  16074. /** Returns true if no parts of this component are transparent.
  16075. @returns the value that was set by setOpaque, (the default being false)
  16076. @see setOpaque
  16077. */
  16078. bool isOpaque() const throw();
  16079. /** Indicates whether the component should be brought to the front when clicked.
  16080. Setting this flag to true will cause the component to be brought to the front
  16081. when the mouse is clicked somewhere inside it or its child components.
  16082. Note that a top-level desktop window might still be brought to the front by the
  16083. operating system when it's clicked, depending on how the OS works.
  16084. By default this is set to false.
  16085. @see setMouseClickGrabsKeyboardFocus
  16086. */
  16087. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16088. /** Indicates whether the component should be brought to the front when clicked-on.
  16089. @see setBroughtToFrontOnMouseClick
  16090. */
  16091. bool isBroughtToFrontOnMouseClick() const throw();
  16092. // Keyboard focus methods
  16093. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16094. By default components aren't actually interested in gaining the
  16095. focus, but this method can be used to turn this on.
  16096. See the grabKeyboardFocus() method for details about the way a component
  16097. is chosen to receive the focus.
  16098. @see grabKeyboardFocus, getWantsKeyboardFocus
  16099. */
  16100. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16101. /** Returns true if the component is interested in getting keyboard focus.
  16102. This returns the flag set by setWantsKeyboardFocus(). The default
  16103. setting is false.
  16104. @see setWantsKeyboardFocus
  16105. */
  16106. bool getWantsKeyboardFocus() const throw();
  16107. /** Chooses whether a click on this component automatically grabs the focus.
  16108. By default this is set to true, but you might want a component which can
  16109. be focused, but where you don't want the user to be able to affect it directly
  16110. by clicking.
  16111. */
  16112. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16113. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16114. See setMouseClickGrabsKeyboardFocus() for more info.
  16115. */
  16116. bool getMouseClickGrabsKeyboardFocus() const throw();
  16117. /** Tries to give keyboard focus to this component.
  16118. When the user clicks on a component or its grabKeyboardFocus()
  16119. method is called, the following procedure is used to work out which
  16120. component should get it:
  16121. - if the component that was clicked on actually wants focus (as indicated
  16122. by calling getWantsKeyboardFocus), it gets it.
  16123. - if the component itself doesn't want focus, it will try to pass it
  16124. on to whichever of its children is the default component, as determined by
  16125. KeyboardFocusTraverser::getDefaultComponent()
  16126. - if none of its children want focus at all, it will pass it up to its
  16127. parent instead, unless it's a top-level component without a parent,
  16128. in which case it just takes the focus itself.
  16129. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16130. getCurrentlyFocusedComponent, focusGained, focusLost,
  16131. keyPressed, keyStateChanged
  16132. */
  16133. void grabKeyboardFocus();
  16134. /** Returns true if this component currently has the keyboard focus.
  16135. @param trueIfChildIsFocused if this is true, then the method returns true if
  16136. either this component or any of its children (recursively)
  16137. have the focus. If false, the method only returns true if
  16138. this component has the focus.
  16139. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16140. focusGained, focusLost
  16141. */
  16142. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16143. /** Returns the component that currently has the keyboard focus.
  16144. @returns the focused component, or null if nothing is focused.
  16145. */
  16146. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16147. /** Tries to move the keyboard focus to one of this component's siblings.
  16148. This will try to move focus to either the next or previous component. (This
  16149. is the method that is used when shifting focus by pressing the tab key).
  16150. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16151. @param moveToNext if true, the focus will move forwards; if false, it will
  16152. move backwards
  16153. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16154. */
  16155. void moveKeyboardFocusToSibling (const bool moveToNext);
  16156. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16157. which focus should be passed from this component.
  16158. The default implementation of this method will return a default
  16159. KeyboardFocusTraverser if this component is a focus container (as determined
  16160. by the setFocusContainer() method). If the component isn't a focus
  16161. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16162. If you overrride this to return a custom KeyboardFocusTraverser, then
  16163. this component and all its sub-components will use the new object to
  16164. make their focusing decisions.
  16165. The method should return a new object, which the caller is required to
  16166. delete when no longer needed.
  16167. */
  16168. virtual KeyboardFocusTraverser* createFocusTraverser();
  16169. /** Returns the focus order of this component, if one has been specified.
  16170. By default components don't have a focus order - in that case, this
  16171. will return 0. Lower numbers indicate that the component will be
  16172. earlier in the focus traversal order.
  16173. To change the order, call setExplicitFocusOrder().
  16174. The focus order may be used by the KeyboardFocusTraverser class as part of
  16175. its algorithm for deciding the order in which components should be traversed.
  16176. See the KeyboardFocusTraverser class for more details on this.
  16177. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16178. */
  16179. int getExplicitFocusOrder() const throw();
  16180. /** Sets the index used in determining the order in which focusable components
  16181. should be traversed.
  16182. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16183. that traversal should use other factors, like the component's position.
  16184. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16185. */
  16186. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16187. /** Indicates whether this component is a parent for components that can have
  16188. their focus traversed.
  16189. This flag is used by the default implementation of the createFocusTraverser()
  16190. method, which uses the flag to find the first parent component (of the currently
  16191. focused one) which wants to be a focus container.
  16192. So using this method to set the flag to 'true' causes this component to
  16193. act as the top level within which focus is passed around.
  16194. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16195. */
  16196. void setFocusContainer (const bool isFocusContainer) throw();
  16197. /** Returns true if this component has been marked as a focus container.
  16198. See setFocusContainer() for more details.
  16199. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16200. */
  16201. bool isFocusContainer() const throw();
  16202. /** Returns true if the component (and all its parents) are enabled.
  16203. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16204. what difference this makes to the component depends on the type. E.g. buttons
  16205. and sliders will choose to draw themselves differently, etc.
  16206. Note that if one of this component's parents is disabled, this will always
  16207. return false, even if this component itself is enabled.
  16208. @see setEnabled, enablementChanged
  16209. */
  16210. bool isEnabled() const throw();
  16211. /** Enables or disables this component.
  16212. Disabling a component will also cause all of its child components to become
  16213. disabled.
  16214. Similarly, enabling a component which is inside a disabled parent
  16215. component won't make any difference until the parent is re-enabled.
  16216. @see isEnabled, enablementChanged
  16217. */
  16218. void setEnabled (const bool shouldBeEnabled);
  16219. /** Callback to indicate that this component has been enabled or disabled.
  16220. This can be triggered by one of the component's parent components
  16221. being enabled or disabled, as well as changes to the component itself.
  16222. The default implementation of this method does nothing; your class may
  16223. wish to repaint itself or something when this happens.
  16224. @see setEnabled, isEnabled
  16225. */
  16226. virtual void enablementChanged();
  16227. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16228. Note that the cursor set by this method can be overridden by the getMouseCursor
  16229. method.
  16230. @see MouseCursor
  16231. */
  16232. void setMouseCursor (const MouseCursor& cursorType) throw();
  16233. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16234. The default implementation will return the cursor that was set by setCursor()
  16235. but can be overridden for more specialised purposes, e.g. returning different
  16236. cursors depending on the mouse position.
  16237. @see MouseCursor
  16238. */
  16239. virtual const MouseCursor getMouseCursor();
  16240. /** Forces the current mouse cursor to be updated.
  16241. If you're overriding the getMouseCursor() method to control which cursor is
  16242. displayed, then this will only be checked each time the user moves the mouse. So
  16243. if you want to force the system to check that the cursor being displayed is
  16244. up-to-date (even if the mouse is just sitting there), call this method.
  16245. This isn't needed if you're only using setMouseCursor().
  16246. */
  16247. void updateMouseCursor() const throw();
  16248. /** Components can override this method to draw their content.
  16249. The paint() method gets called when a region of a component needs redrawing,
  16250. either because the component's repaint() method has been called, or because
  16251. something has happened on the screen that means a section of a window needs
  16252. to be redrawn.
  16253. Any child components will draw themselves over whatever this method draws. If
  16254. you need to paint over the top of your child components, you can also implement
  16255. the paintOverChildren() method to do this.
  16256. If you want to cause a component to redraw itself, this is done asynchronously -
  16257. calling the repaint() method marks a region of the component as "dirty", and the
  16258. paint() method will automatically be called sometime later, by the message thread,
  16259. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16260. you never redraw something synchronously.
  16261. You should never need to call this method directly - to take a snapshot of the
  16262. component you could use createComponentSnapshot() or paintEntireComponent().
  16263. @param g the graphics context that must be used to do the drawing operations.
  16264. @see repaint, paintOverChildren, Graphics
  16265. */
  16266. virtual void paint (Graphics& g);
  16267. /** Components can override this method to draw over the top of their children.
  16268. For most drawing operations, it's better to use the normal paint() method,
  16269. but if you need to overlay something on top of the children, this can be
  16270. used.
  16271. @see paint, Graphics
  16272. */
  16273. virtual void paintOverChildren (Graphics& g);
  16274. /** Called when the mouse moves inside this component.
  16275. If the mouse button isn't pressed and the mouse moves over a component,
  16276. this will be called to let the component react to this.
  16277. A component will always get a mouseEnter callback before a mouseMove.
  16278. @param e details about the position and status of the mouse event
  16279. @see mouseEnter, mouseExit, mouseDrag, contains
  16280. */
  16281. virtual void mouseMove (const MouseEvent& e);
  16282. /** Called when the mouse first enters this component.
  16283. If the mouse button isn't pressed and the mouse moves into a component,
  16284. this will be called to let the component react to this.
  16285. When the mouse button is pressed and held down while being moved in
  16286. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16287. mouseDrag messages are sent to the component that the mouse was originally
  16288. clicked on, until the button is released.
  16289. If you're writing a component that needs to repaint itself when the mouse
  16290. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16291. method.
  16292. @param e details about the position and status of the mouse event
  16293. @see mouseExit, mouseDrag, mouseMove, contains
  16294. */
  16295. virtual void mouseEnter (const MouseEvent& e);
  16296. /** Called when the mouse moves out of this component.
  16297. This will be called when the mouse moves off the edge of this
  16298. component.
  16299. If the mouse button was pressed, and it was then dragged off the
  16300. edge of the component and released, then this callback will happen
  16301. when the button is released, after the mouseUp callback.
  16302. If you're writing a component that needs to repaint itself when the mouse
  16303. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16304. method.
  16305. @param e details about the position and status of the mouse event
  16306. @see mouseEnter, mouseDrag, mouseMove, contains
  16307. */
  16308. virtual void mouseExit (const MouseEvent& e);
  16309. /** Called when a mouse button is pressed while it's over this component.
  16310. The MouseEvent object passed in contains lots of methods for finding out
  16311. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16312. were held down at the time.
  16313. Once a button is held down, the mouseDrag method will be called when the
  16314. mouse moves, until the button is released.
  16315. @param e details about the position and status of the mouse event
  16316. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16317. */
  16318. virtual void mouseDown (const MouseEvent& e);
  16319. /** Called when the mouse is moved while a button is held down.
  16320. When a mouse button is pressed inside a component, that component
  16321. receives mouseDrag callbacks each time the mouse moves, even if the
  16322. mouse strays outside the component's bounds.
  16323. If you want to be able to drag things off the edge of a component
  16324. and have the component scroll when you get to the edges, the
  16325. beginDragAutoRepeat() method might be useful.
  16326. @param e details about the position and status of the mouse event
  16327. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16328. */
  16329. virtual void mouseDrag (const MouseEvent& e);
  16330. /** Called when a mouse button is released.
  16331. A mouseUp callback is sent to the component in which a button was pressed
  16332. even if the mouse is actually over a different component when the
  16333. button is released.
  16334. The MouseEvent object passed in contains lots of methods for finding out
  16335. which buttons were down just before they were released.
  16336. @param e details about the position and status of the mouse event
  16337. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16338. */
  16339. virtual void mouseUp (const MouseEvent& e);
  16340. /** Called when a mouse button has been double-clicked in this component.
  16341. The MouseEvent object passed in contains lots of methods for finding out
  16342. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16343. were held down at the time.
  16344. For altering the time limit used to detect double-clicks,
  16345. see MouseEvent::setDoubleClickTimeout.
  16346. @param e details about the position and status of the mouse event
  16347. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16348. MouseEvent::getDoubleClickTimeout
  16349. */
  16350. virtual void mouseDoubleClick (const MouseEvent& e);
  16351. /** Called when the mouse-wheel is moved.
  16352. This callback is sent to the component that the mouse is over when the
  16353. wheel is moved.
  16354. If not overridden, the component will forward this message to its parent, so
  16355. that parent components can collect mouse-wheel messages that happen to
  16356. child components which aren't interested in them.
  16357. @param e details about the position and status of the mouse event
  16358. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16359. value means the wheel has been pushed to the right, negative means it
  16360. was pushed to the left
  16361. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16362. value means the wheel has been pushed upwards, negative means it
  16363. was pushed downwards
  16364. */
  16365. virtual void mouseWheelMove (const MouseEvent& e,
  16366. float wheelIncrementX,
  16367. float wheelIncrementY);
  16368. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16369. next mouse-drag operation.
  16370. This allows you to make sure that mouseDrag() events sent continuously, even
  16371. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16372. components when the mouse is near an edge.
  16373. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16374. minimum interval between consecutive mouse drag callbacks. The callbacks
  16375. will continue until the mouse is released, and then the interval will be reset,
  16376. so you need to make sure it's called every time you begin a drag event. If it
  16377. is called when the mouse isn't actually being pressed, it will apply to the next
  16378. mouse-drag operation that happens.
  16379. Passing an interval of 0 or less will cancel the auto-repeat.
  16380. @see mouseDrag
  16381. */
  16382. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16383. /** Causes automatic repaints when the mouse enters or exits this component.
  16384. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16385. on the component, it will trigger a repaint.
  16386. This is handy for things like buttons that need to draw themselves differently when
  16387. the mouse moves over them, and it avoids having to override all the different mouse
  16388. callbacks and call repaint().
  16389. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16390. */
  16391. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16392. /** Registers a listener to be told when mouse events occur in this component.
  16393. If you need to get informed about mouse events in a component but can't or
  16394. don't want to override its methods, you can attach any number of listeners
  16395. to the component, and these will get told about the events in addition to
  16396. the component's own callbacks being called.
  16397. Note that a MouseListener can also be attached to more than one component.
  16398. @param newListener the listener to register
  16399. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16400. for events that happen to any child component
  16401. within this component, including deeply-nested
  16402. child components. If false, it will only be
  16403. told about events that this component handles.
  16404. @see MouseListener, removeMouseListener
  16405. */
  16406. void addMouseListener (MouseListener* const newListener,
  16407. const bool wantsEventsForAllNestedChildComponents) throw();
  16408. /** Deregisters a mouse listener.
  16409. @see addMouseListener, MouseListener
  16410. */
  16411. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16412. /** Adds a listener that wants to hear about keypresses that this component receives.
  16413. The listeners that are registered with a component are called by its keyPressed() or
  16414. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16415. If you add an object as a key listener, be careful to remove it when the object
  16416. is deleted, or the component will be left with a dangling pointer.
  16417. @see keyPressed, keyStateChanged, removeKeyListener
  16418. */
  16419. void addKeyListener (KeyListener* const newListener) throw();
  16420. /** Removes a previously-registered key listener.
  16421. @see addKeyListener
  16422. */
  16423. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16424. /** Called when a key is pressed.
  16425. When a key is pressed, the component that has the keyboard focus will have this
  16426. method called. Remember that a component will only be given the focus if its
  16427. setWantsKeyboardFocus() method has been used to enable this.
  16428. If your implementation returns true, the event will be consumed and not passed
  16429. on to any other listeners. If it returns false, the key will be passed to any
  16430. KeyListeners that have been registered with this component. As soon as one of these
  16431. returns true, the process will stop, but if they all return false, the event will
  16432. be passed upwards to this component's parent, and so on.
  16433. The default implementation of this method does nothing and returns false.
  16434. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16435. */
  16436. virtual bool keyPressed (const KeyPress& key);
  16437. /** Called when a key is pressed or released.
  16438. Whenever a key on the keyboard is pressed or released (including modifier keys
  16439. like shift and ctrl), this method will be called on the component that currently
  16440. has the keyboard focus. Remember that a component will only be given the focus if
  16441. its setWantsKeyboardFocus() method has been used to enable this.
  16442. If your implementation returns true, the event will be consumed and not passed
  16443. on to any other listeners. If it returns false, then any KeyListeners that have
  16444. been registered with this component will have their keyStateChanged methods called.
  16445. As soon as one of these returns true, the process will stop, but if they all return
  16446. false, the event will be passed upwards to this component's parent, and so on.
  16447. The default implementation of this method does nothing and returns false.
  16448. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16449. method.
  16450. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16451. */
  16452. virtual bool keyStateChanged();
  16453. /** Called when a modifier key is pressed or released.
  16454. Whenever the shift, control, alt or command keys are pressed or released,
  16455. this method will be called on the component that currently has the keyboard focus.
  16456. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16457. method has been used to enable this.
  16458. The default implementation of this method actually calls its parent's modifierKeysChanged
  16459. method, so that focused components which aren't interested in this will give their
  16460. parents a chance to act on the event instead.
  16461. @see keyStateChanged, ModifierKeys
  16462. */
  16463. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16464. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16465. enum FocusChangeType
  16466. {
  16467. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16468. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16469. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16470. };
  16471. /** Called to indicate that this component has just acquired the keyboard focus.
  16472. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16473. */
  16474. virtual void focusGained (FocusChangeType cause);
  16475. /** Called to indicate that this component has just lost the keyboard focus.
  16476. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16477. */
  16478. virtual void focusLost (FocusChangeType cause);
  16479. /** Called to indicate that one of this component's children has been focused or unfocused.
  16480. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16481. changed. It happens when focus moves from one of this component's children (at any depth)
  16482. to a component that isn't contained in this one, (or vice-versa).
  16483. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16484. */
  16485. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16486. /** Returns true if the mouse is currently over this component.
  16487. If the mouse isn't over the component, this will return false, even if the
  16488. mouse is currently being dragged - so you can use this in your mouseDrag
  16489. method to find out whether it's really over the component or not.
  16490. Note that when the mouse button is being held down, then the only component
  16491. for which this method will return true is the one that was originally
  16492. clicked on.
  16493. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16494. */
  16495. bool isMouseOver() const throw();
  16496. /** Returns true if the mouse button is currently held down in this component.
  16497. Note that this is a test to see whether the mouse is being pressed in this
  16498. component, so it'll return false if called on component A when the mouse
  16499. is actually being dragged in component B.
  16500. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16501. */
  16502. bool isMouseButtonDown() const throw();
  16503. /** True if the mouse is over this component, or if it's being dragged in this component.
  16504. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16505. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16506. */
  16507. bool isMouseOverOrDragging() const throw();
  16508. /** Returns true if a mouse button is currently down.
  16509. Unlike isMouseButtonDown, this will test the current state of the
  16510. buttons without regard to which component (if any) it has been
  16511. pressed in.
  16512. @see isMouseButtonDown, ModifierKeys
  16513. */
  16514. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16515. /** Returns the mouse's current position, relative to this component.
  16516. The co-ordinates are relative to the component's top-left corner.
  16517. */
  16518. void getMouseXYRelative (int& x, int& y) const throw();
  16519. /** Returns the component that's currently underneath the mouse.
  16520. @returns the component or 0 if there isn't one.
  16521. @see contains, getComponentAt
  16522. */
  16523. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16524. /** Allows the mouse to move beyond the edges of the screen.
  16525. Calling this method when the mouse button is currently pressed inside this component
  16526. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16527. the edges of the screen.
  16528. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16529. can be used for things like custom slider controls or dragging objects around, where
  16530. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16531. The unbounded mode is automatically turned off when the mouse button is released, or
  16532. it can be turned off explicitly by calling this method again.
  16533. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16534. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16535. hidden; if true, it will only be hidden when it
  16536. is moved beyond the edge of the screen
  16537. */
  16538. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16539. bool keepCursorVisibleUntilOffscreen = false) throw();
  16540. /** Called when this component's size has been changed.
  16541. A component can implement this method to do things such as laying out its
  16542. child components when its width or height changes.
  16543. The method is called synchronously as a result of the setBounds or setSize
  16544. methods, so repeatedly changing a components size will repeatedly call its
  16545. resized method (unlike things like repainting, where multiple calls to repaint
  16546. are coalesced together).
  16547. If the component is a top-level window on the desktop, its size could also
  16548. be changed by operating-system factors beyond the application's control.
  16549. @see moved, setSize
  16550. */
  16551. virtual void resized();
  16552. /** Called when this component's position has been changed.
  16553. This is called when the position relative to its parent changes, not when
  16554. its absolute position on the screen changes (so it won't be called for
  16555. all child components when a parent component is moved).
  16556. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16557. or any of the other repositioning methods, and like resized(), it will be
  16558. called each time those methods are called.
  16559. If the component is a top-level window on the desktop, its position could also
  16560. be changed by operating-system factors beyond the application's control.
  16561. @see resized, setBounds
  16562. */
  16563. virtual void moved();
  16564. /** Called when one of this component's children is moved or resized.
  16565. If the parent wants to know about changes to its immediate children (not
  16566. to children of its children), this is the method to override.
  16567. @see moved, resized, parentSizeChanged
  16568. */
  16569. virtual void childBoundsChanged (Component* child);
  16570. /** Called when this component's immediate parent has been resized.
  16571. If the component is a top-level window, this indicates that the screen size
  16572. has changed.
  16573. @see childBoundsChanged, moved, resized
  16574. */
  16575. virtual void parentSizeChanged();
  16576. /** Called when this component has been moved to the front of its siblings.
  16577. The component may have been brought to the front by the toFront() method, or
  16578. by the operating system if it's a top-level window.
  16579. @see toFront
  16580. */
  16581. virtual void broughtToFront();
  16582. /** Adds a listener to be told about changes to the component hierarchy or position.
  16583. Component listeners get called when this component's size, position or children
  16584. change - see the ComponentListener class for more details.
  16585. @param newListener the listener to register - if this is already registered, it
  16586. will be ignored.
  16587. @see ComponentListener, removeComponentListener
  16588. */
  16589. void addComponentListener (ComponentListener* const newListener) throw();
  16590. /** Removes a component listener.
  16591. @see addComponentListener
  16592. */
  16593. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16594. /** Dispatches a numbered message to this component.
  16595. This is a quick and cheap way of allowing simple asynchronous messages to
  16596. be sent to components. It's also safe, because if the component that you
  16597. send the message to is a null or dangling pointer, this won't cause an error.
  16598. The command ID is later delivered to the component's handleCommandMessage() method by
  16599. the application's message queue.
  16600. @see handleCommandMessage
  16601. */
  16602. void postCommandMessage (const int commandId) throw();
  16603. /** Called to handle a command that was sent by postCommandMessage().
  16604. This is called by the message thread when a command message arrives, and
  16605. the component can override this method to process it in any way it needs to.
  16606. @see postCommandMessage
  16607. */
  16608. virtual void handleCommandMessage (int commandId);
  16609. /** Runs a component modally, waiting until the loop terminates.
  16610. This method first makes the component visible, brings it to the front and
  16611. gives it the keyboard focus.
  16612. It then runs a loop, dispatching messages from the system message queue, but
  16613. blocking all mouse or keyboard messages from reaching any components other
  16614. than this one and its children.
  16615. This loop continues until the component's exitModalState() method is called (or
  16616. the component is deleted), and then this method returns, returning the value
  16617. passed into exitModalState().
  16618. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16619. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16620. */
  16621. int runModalLoop();
  16622. /** Puts the component into a modal state.
  16623. This makes the component modal, so that messages are blocked from reaching
  16624. any components other than this one and its children, but unlike runModalLoop(),
  16625. this method returns immediately.
  16626. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16627. get the focus, which is usually what you'll want it to do. If not, it will leave
  16628. the focus unchanged.
  16629. @see exitModalState, runModalLoop
  16630. */
  16631. void enterModalState (const bool takeKeyboardFocus = true);
  16632. /** Ends a component's modal state.
  16633. If this component is currently modal, this will turn of its modalness, and return
  16634. a value to the runModalLoop() method that might have be running its modal loop.
  16635. @see runModalLoop, enterModalState, isCurrentlyModal
  16636. */
  16637. void exitModalState (const int returnValue);
  16638. /** Returns true if this component is the modal one.
  16639. It's possible to have nested modal components, e.g. a pop-up dialog box
  16640. that launches another pop-up, but this will only return true for
  16641. the one at the top of the stack.
  16642. @see getCurrentlyModalComponent
  16643. */
  16644. bool isCurrentlyModal() const throw();
  16645. /** Returns the component that is currently modal.
  16646. @returns the modal component, or null if no components are modal
  16647. @see runModalLoop, isCurrentlyModal
  16648. */
  16649. static Component* JUCE_CALLTYPE getCurrentlyModalComponent() throw();
  16650. /** Checks whether there's a modal component somewhere that's stopping this one
  16651. from receiving messages.
  16652. If there is a modal component, its canModalEventBeSentToComponent() method
  16653. will be called to see if it will still allow this component to receive events.
  16654. @see runModalLoop, getCurrentlyModalComponent
  16655. */
  16656. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16657. /** When a component is modal, this callback allows it to choose which other
  16658. components can still receive events.
  16659. When a modal component is active and the user clicks on a non-modal component,
  16660. this method is called on the modal component, and if it returns true, the
  16661. event is allowed to reach its target. If it returns false, the event is blocked
  16662. and the inputAttemptWhenModal() callback is made.
  16663. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16664. implementation just returns false in all cases.
  16665. */
  16666. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16667. /** Called when the user tries to click on a component that is blocked by another
  16668. modal component.
  16669. When a component is modal and the user clicks on one of the other components,
  16670. the modal component will receive this callback.
  16671. The default implementation of this method will play a beep, and bring the currently
  16672. modal component to the front, but it can be overridden to do other tasks.
  16673. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16674. */
  16675. virtual void inputAttemptWhenModal();
  16676. /** Returns one of the component's properties as a string.
  16677. @param keyName the name of the property to retrieve
  16678. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16679. properties, then it will check whether the parent component has
  16680. the key.
  16681. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16682. */
  16683. const String getComponentProperty (const String& keyName,
  16684. const bool useParentComponentIfNotFound,
  16685. const String& defaultReturnValue = String::empty) const throw();
  16686. /** Returns one of the properties as an integer.
  16687. @param keyName the name of the property to retrieve
  16688. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16689. properties, then it will check whether the parent component has
  16690. the key.
  16691. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16692. */
  16693. int getComponentPropertyInt (const String& keyName,
  16694. const bool useParentComponentIfNotFound,
  16695. const int defaultReturnValue = 0) const throw();
  16696. /** Returns one of the properties as an double.
  16697. @param keyName the name of the property to retrieve
  16698. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16699. properties, then it will check whether the parent component has
  16700. the key.
  16701. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16702. */
  16703. double getComponentPropertyDouble (const String& keyName,
  16704. const bool useParentComponentIfNotFound,
  16705. const double defaultReturnValue = 0.0) const throw();
  16706. /** Returns one of the properties as an boolean.
  16707. The result will be true if the string found for this key name can be parsed as a non-zero
  16708. integer.
  16709. @param keyName the name of the property to retrieve
  16710. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16711. properties, then it will check whether the parent component has
  16712. the key.
  16713. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16714. */
  16715. bool getComponentPropertyBool (const String& keyName,
  16716. const bool useParentComponentIfNotFound,
  16717. const bool defaultReturnValue = false) const throw();
  16718. /** Returns one of the properties as an colour.
  16719. @param keyName the name of the property to retrieve
  16720. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16721. properties, then it will check whether the parent component has
  16722. the key.
  16723. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16724. */
  16725. const Colour getComponentPropertyColour (const String& keyName,
  16726. const bool useParentComponentIfNotFound,
  16727. const Colour& defaultReturnValue = Colours::black) const throw();
  16728. /** Sets a named property as a string.
  16729. @param keyName the name of the property to set. (This mustn't be an empty string)
  16730. @param value the new value to set it to
  16731. @see removeComponentProperty
  16732. */
  16733. void setComponentProperty (const String& keyName, const String& value) throw();
  16734. /** Sets a named property to an integer.
  16735. @param keyName the name of the property to set. (This mustn't be an empty string)
  16736. @param value the new value to set it to
  16737. @see removeComponentProperty
  16738. */
  16739. void setComponentProperty (const String& keyName, const int value) throw();
  16740. /** Sets a named property to a double.
  16741. @param keyName the name of the property to set. (This mustn't be an empty string)
  16742. @param value the new value to set it to
  16743. @see removeComponentProperty
  16744. */
  16745. void setComponentProperty (const String& keyName, const double value) throw();
  16746. /** Sets a named property to a boolean.
  16747. @param keyName the name of the property to set. (This mustn't be an empty string)
  16748. @param value the new value to set it to
  16749. @see removeComponentProperty
  16750. */
  16751. void setComponentProperty (const String& keyName, const bool value) throw();
  16752. /** Sets a named property to a colour.
  16753. @param keyName the name of the property to set. (This mustn't be an empty string)
  16754. @param newColour the new colour to set it to
  16755. @see removeComponentProperty
  16756. */
  16757. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16758. /** Deletes a named component property.
  16759. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16760. @see setComponentProperty, getComponentProperty
  16761. */
  16762. void removeComponentProperty (const String& keyName) throw();
  16763. /** Returns the complete set of properties that have been set for this component.
  16764. If no properties have been set, this will return a null pointer.
  16765. @see getComponentProperty, setComponentProperty
  16766. */
  16767. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16768. /** Looks for a colour that has been registered with the given colour ID number.
  16769. If a colour has been set for this ID number using setColour(), then it is
  16770. returned. If none has been set, the method will try calling the component's
  16771. LookAndFeel class's findColour() method. If none has been registered with the
  16772. look-and-feel either, it will just return black.
  16773. The colour IDs for various purposes are stored as enums in the components that
  16774. they are relevent to - for an example, see Slider::ColourIds,
  16775. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16776. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16777. */
  16778. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16779. /** Registers a colour to be used for a particular purpose.
  16780. Changing a colour will cause a synchronous callback to the colourChanged()
  16781. method, which your component can override if it needs to do something when
  16782. colours are altered.
  16783. For more details about colour IDs, see the comments for findColour().
  16784. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16785. */
  16786. void setColour (const int colourId, const Colour& colour);
  16787. /** If a colour has been set with setColour(), this will remove it.
  16788. This allows you to make a colour revert to its default state.
  16789. */
  16790. void removeColour (const int colourId);
  16791. /** Returns true if the specified colour ID has been explicitly set for this
  16792. component using the setColour() method.
  16793. */
  16794. bool isColourSpecified (const int colourId) const throw();
  16795. /** This looks for any colours that have been specified for this component,
  16796. and copies them to the specified target component.
  16797. */
  16798. void copyAllExplicitColoursTo (Component& target) const throw();
  16799. /** This method is called when a colour is changed by the setColour() method.
  16800. @see setColour, findColour
  16801. */
  16802. virtual void colourChanged();
  16803. /** Returns the underlying native window handle for this component.
  16804. This is platform-dependent and strictly for power-users only!
  16805. */
  16806. void* getWindowHandle() const throw();
  16807. /** When created, each component is given a number to uniquely identify it.
  16808. The number is incremented each time a new component is created, so it's a more
  16809. unique way of identifying a component than using its memory location (which
  16810. may be reused after the component is deleted, of course).
  16811. */
  16812. uint32 getComponentUID() const throw() { return componentUID; }
  16813. juce_UseDebuggingNewOperator
  16814. private:
  16815. friend class ComponentPeer;
  16816. friend class InternalDragRepeater;
  16817. static Component* currentlyFocusedComponent;
  16818. static Component* componentUnderMouse;
  16819. String componentName_;
  16820. Component* parentComponent_;
  16821. uint32 componentUID;
  16822. Rectangle bounds_;
  16823. unsigned short numDeepMouseListeners;
  16824. Array <Component*> childComponentList_;
  16825. LookAndFeel* lookAndFeel_;
  16826. MouseCursor cursor_;
  16827. ImageEffectFilter* effect_;
  16828. Image* bufferedImage_;
  16829. VoidArray* mouseListeners_;
  16830. VoidArray* keyListeners_;
  16831. VoidArray* componentListeners_;
  16832. PropertySet* propertySet_;
  16833. struct ComponentFlags
  16834. {
  16835. bool hasHeavyweightPeerFlag : 1;
  16836. bool visibleFlag : 1;
  16837. bool opaqueFlag : 1;
  16838. bool ignoresMouseClicksFlag : 1;
  16839. bool allowChildMouseClicksFlag : 1;
  16840. bool wantsFocusFlag : 1;
  16841. bool isFocusContainerFlag : 1;
  16842. bool dontFocusOnMouseClickFlag : 1;
  16843. bool alwaysOnTopFlag : 1;
  16844. bool bufferToImageFlag : 1;
  16845. bool bringToFrontOnClickFlag : 1;
  16846. bool repaintOnMouseActivityFlag : 1;
  16847. bool draggingFlag : 1;
  16848. bool mouseOverFlag : 1;
  16849. bool mouseInsideFlag : 1;
  16850. bool currentlyModalFlag : 1;
  16851. bool isDisabledFlag : 1;
  16852. bool childCompFocusedFlag : 1;
  16853. #ifdef JUCE_DEBUG
  16854. bool isInsidePaintCall : 1;
  16855. #endif
  16856. };
  16857. union
  16858. {
  16859. uint32 componentFlags_;
  16860. ComponentFlags flags;
  16861. };
  16862. void internalMouseEnter (int x, int y, const int64 time);
  16863. void internalMouseExit (int x, int y, const int64 time);
  16864. void internalMouseDown (int x, int y);
  16865. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16866. void internalMouseDrag (int x, int y, const int64 time);
  16867. void internalMouseMove (int x, int y, const int64 time);
  16868. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  16869. void internalBroughtToFront();
  16870. void internalFocusGain (const FocusChangeType cause);
  16871. void internalFocusLoss (const FocusChangeType cause);
  16872. void internalChildFocusChange (FocusChangeType cause);
  16873. void internalModalInputAttempt();
  16874. void internalModifierKeysChanged();
  16875. void internalChildrenChanged();
  16876. void internalHierarchyChanged();
  16877. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  16878. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  16879. void repaintParent() throw();
  16880. void sendFakeMouseMove() const;
  16881. void takeKeyboardFocus (const FocusChangeType cause);
  16882. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  16883. static void giveAwayFocus();
  16884. void sendEnablementChangeMessage();
  16885. static void* runModalLoopCallback (void*);
  16886. void subtractObscuredRegions (RectangleList& result,
  16887. const int deltaX, const int deltaY,
  16888. const Rectangle& clipRect,
  16889. const Component* const compToAvoid) const throw();
  16890. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  16891. const int deltaX, const int deltaY) const throw();
  16892. // how much of the component is not off the edges of its parents
  16893. const Rectangle getUnclippedArea() const;
  16894. void sendVisibilityChangeMessage();
  16895. // This is included here just to cause a compile error if your code is still handling
  16896. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  16897. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  16898. // implement its methods instead of this Component method).
  16899. virtual void filesDropped (const StringArray&, int, int) {}
  16900. // components aren't allowed to have copy constructors, as this would mess up parent
  16901. // hierarchies. You might need to give your subclasses a private dummy constructor like
  16902. // this one to avoid compiler warnings.
  16903. Component (const Component&);
  16904. const Component& operator= (const Component&);
  16905. protected:
  16906. /** @internal */
  16907. virtual void internalRepaint (int x, int y, int w, int h);
  16908. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  16909. /** Overridden from the MessageListener parent class.
  16910. You can override this if you really need to, but be sure to pass your unwanted messages up
  16911. to this base class implementation, as the Component class needs to send itself messages
  16912. to work properly.
  16913. */
  16914. void handleMessage (const Message&);
  16915. };
  16916. #endif // __JUCE_COMPONENT_JUCEHEADER__
  16917. /********* End of inlined file: juce_Component.h *********/
  16918. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  16919. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16920. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16921. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  16922. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16923. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16924. /** A type used to hold the unique ID for an application command.
  16925. This is a numeric type, so it can be stored as an integer.
  16926. @see ApplicationCommandInfo, ApplicationCommandManager,
  16927. ApplicationCommandTarget, KeyPressMappingSet
  16928. */
  16929. typedef int CommandID;
  16930. /** A set of general-purpose application command IDs.
  16931. Because these commands are likely to be used in most apps, they're defined
  16932. here to help different apps to use the same numeric values for them.
  16933. Of course you don't have to use these, but some of them are used internally by
  16934. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  16935. @see ApplicationCommandInfo, ApplicationCommandManager,
  16936. ApplicationCommandTarget, KeyPressMappingSet
  16937. */
  16938. namespace StandardApplicationCommandIDs
  16939. {
  16940. /** This command ID should be used to send a "Quit the App" command.
  16941. This command is recognised by the JUCEApplication class, so if it is invoked
  16942. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  16943. object will catch it and call JUCEApplication::systemRequestedQuit().
  16944. */
  16945. static const CommandID quit = 0x1001;
  16946. /** The command ID that should be used to send a "Delete" command. */
  16947. static const CommandID del = 0x1002;
  16948. /** The command ID that should be used to send a "Cut" command. */
  16949. static const CommandID cut = 0x1003;
  16950. /** The command ID that should be used to send a "Copy to clipboard" command. */
  16951. static const CommandID copy = 0x1004;
  16952. /** The command ID that should be used to send a "Paste from clipboard" command. */
  16953. static const CommandID paste = 0x1005;
  16954. /** The command ID that should be used to send a "Select all" command. */
  16955. static const CommandID selectAll = 0x1006;
  16956. /** The command ID that should be used to send a "Deselect all" command. */
  16957. static const CommandID deselectAll = 0x1007;
  16958. }
  16959. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16960. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  16961. /**
  16962. Holds information describing an application command.
  16963. This object is used to pass information about a particular command, such as its
  16964. name, description and other usage flags.
  16965. When an ApplicationCommandTarget is asked to provide information about the commands
  16966. it can perform, this is the structure gets filled-in to describe each one.
  16967. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  16968. ApplicationCommandManager
  16969. */
  16970. struct JUCE_API ApplicationCommandInfo
  16971. {
  16972. ApplicationCommandInfo (const CommandID commandID) throw();
  16973. /** Sets a number of the structures values at once.
  16974. The meanings of each of the parameters is described below, in the appropriate
  16975. member variable's description.
  16976. */
  16977. void setInfo (const String& shortName,
  16978. const String& description,
  16979. const String& categoryName,
  16980. const int flags) throw();
  16981. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  16982. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  16983. is false, the bit is set.
  16984. */
  16985. void setActive (const bool isActive) throw();
  16986. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  16987. */
  16988. void setTicked (const bool isTicked) throw();
  16989. /** Handy method for adding a keypress to the defaultKeypresses array.
  16990. This is just so you can write things like:
  16991. @code
  16992. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  16993. @endcode
  16994. instead of
  16995. @code
  16996. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  16997. @endcode
  16998. */
  16999. void addDefaultKeypress (const int keyCode,
  17000. const ModifierKeys& modifiers) throw();
  17001. /** The command's unique ID number.
  17002. */
  17003. CommandID commandID;
  17004. /** A short name to describe the command.
  17005. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17006. You can use the setInfo() method to quickly set this and some of the command's
  17007. other properties.
  17008. */
  17009. String shortName;
  17010. /** A longer description of the command.
  17011. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17012. pop-up tooltip describing what the command does.
  17013. You can use the setInfo() method to quickly set this and some of the command's
  17014. other properties.
  17015. */
  17016. String description;
  17017. /** A named category that the command fits into.
  17018. You can give your commands any category you like, and these will be displayed in
  17019. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17020. commands together.
  17021. You can use the setInfo() method to quickly set this and some of the command's
  17022. other properties.
  17023. */
  17024. String categoryName;
  17025. /** A list of zero or more keypresses that should be used as the default keys for
  17026. this command.
  17027. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17028. this list to initialise the default set of key-to-command mappings.
  17029. @see addDefaultKeypress
  17030. */
  17031. Array <KeyPress> defaultKeypresses;
  17032. /** Flags describing the ways in which this command should be used.
  17033. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17034. variable.
  17035. */
  17036. enum CommandFlags
  17037. {
  17038. /** Indicates that the command can't currently be performed.
  17039. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17040. not currently permissable to perform the command. If the flag is set, then
  17041. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17042. command or show themselves as not being enabled.
  17043. @see ApplicationCommandInfo::setActive
  17044. */
  17045. isDisabled = 1 << 0,
  17046. /** Indicates that the command should have a tick next to it on a menu.
  17047. If your command is shown on a menu and this is set, it'll show a tick next to
  17048. it. Other components such as buttons may also use this flag to indicate that it
  17049. is a value that can be toggled, and is currently in the 'on' state.
  17050. @see ApplicationCommandInfo::setTicked
  17051. */
  17052. isTicked = 1 << 1,
  17053. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17054. it will call the command twice, once on key-down and again on key-up.
  17055. @see ApplicationCommandTarget::InvocationInfo
  17056. */
  17057. wantsKeyUpDownCallbacks = 1 << 2,
  17058. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17059. command in its list.
  17060. */
  17061. hiddenFromKeyEditor = 1 << 3,
  17062. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17063. command in its list, but won't allow the assigned keypress to be changed.
  17064. */
  17065. readOnlyInKeyEditor = 1 << 4,
  17066. /** If this flag is present and the command is invoked from a keypress, then any
  17067. buttons or menus that are also connected to the command will not flash to
  17068. indicate that they've been triggered.
  17069. */
  17070. dontTriggerVisualFeedback = 1 << 5
  17071. };
  17072. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17073. You can use the setInfo() method to quickly set this and some of the command's
  17074. other properties.
  17075. */
  17076. int flags;
  17077. };
  17078. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17079. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17080. /**
  17081. A command target publishes a list of command IDs that it can perform.
  17082. An ApplicationCommandManager despatches commands to targets, which must be
  17083. able to provide information about what commands they can handle.
  17084. To create a target, you'll need to inherit from this class, implementing all of
  17085. its pure virtual methods.
  17086. For info about how a target is chosen to receive a command, see
  17087. ApplicationCommandManager::getFirstCommandTarget().
  17088. @see ApplicationCommandManager, ApplicationCommandInfo
  17089. */
  17090. class JUCE_API ApplicationCommandTarget
  17091. {
  17092. public:
  17093. /** Creates a command target. */
  17094. ApplicationCommandTarget();
  17095. /** Destructor. */
  17096. virtual ~ApplicationCommandTarget();
  17097. /**
  17098. */
  17099. struct JUCE_API InvocationInfo
  17100. {
  17101. InvocationInfo (const CommandID commandID) throw();
  17102. /** The UID of the command that should be performed. */
  17103. CommandID commandID;
  17104. /** The command's flags.
  17105. See ApplicationCommandInfo for a description of these flag values.
  17106. */
  17107. int commandFlags;
  17108. /** The types of context in which the command might be called. */
  17109. enum InvocationMethod
  17110. {
  17111. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17112. fromKeyPress, /**< The command is being invoked by a key-press. */
  17113. fromMenu, /**< The command is being invoked by a menu selection. */
  17114. fromButton /**< The command is being invoked by a button click. */
  17115. };
  17116. /** The type of event that triggered this command. */
  17117. InvocationMethod invocationMethod;
  17118. /** If triggered by a keypress or menu, this will be the component that had the
  17119. keyboard focus at the time.
  17120. If triggered by a button, it may be set to that component, or it may be null.
  17121. */
  17122. Component* originatingComponent;
  17123. /** The keypress that was used to invoke it.
  17124. Note that this will be an invalid keypress if the command was invoked
  17125. by some other means than a keyboard shortcut.
  17126. */
  17127. KeyPress keyPress;
  17128. /** True if the callback is being invoked when the key is pressed,
  17129. false if the key is being released.
  17130. @see KeyPressMappingSet::addCommand()
  17131. */
  17132. bool isKeyDown;
  17133. /** If the key is being released, this indicates how long it had been held
  17134. down for.
  17135. (Only relevant if isKeyDown is false.)
  17136. */
  17137. int millisecsSinceKeyPressed;
  17138. };
  17139. /** This must return the next target to try after this one.
  17140. When a command is being sent, and the first target can't handle
  17141. that command, this method is used to determine the next target that should
  17142. be tried.
  17143. It may return 0 if it doesn't know of another target.
  17144. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17145. method to return a parent component that might want to handle it.
  17146. @see invoke
  17147. */
  17148. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17149. /** This must return a complete list of commands that this target can handle.
  17150. Your target should add all the command IDs that it handles to the array that is
  17151. passed-in.
  17152. */
  17153. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17154. /** This must provide details about one of the commands that this target can perform.
  17155. This will be called with one of the command IDs that the target provided in its
  17156. getAllCommands() methods.
  17157. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17158. suitable information about the command. (The commandID field will already have been filled-in
  17159. by the caller).
  17160. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17161. set all the fields at once.
  17162. If the command is currently inactive for some reason, this method must use
  17163. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17164. bit of the ApplicationCommandInfo::flags field).
  17165. Any default key-presses for the command should be appended to the
  17166. ApplicationCommandInfo::defaultKeypresses field.
  17167. Note that if you change something that affects the status of the commands
  17168. that would be returned by this method (e.g. something that makes some commands
  17169. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17170. to cause the manager to refresh its status.
  17171. */
  17172. virtual void getCommandInfo (const CommandID commandID,
  17173. ApplicationCommandInfo& result) = 0;
  17174. /** This must actually perform the specified command.
  17175. If this target is able to perform the command specified by the commandID field of the
  17176. InvocationInfo structure, then it should do so, and must return true.
  17177. If it can't handle this command, it should return false, which tells the caller to pass
  17178. the command on to the next target in line.
  17179. @see invoke, ApplicationCommandManager::invoke
  17180. */
  17181. virtual bool perform (const InvocationInfo& info) = 0;
  17182. /** Makes this target invoke a command.
  17183. Your code can call this method to invoke a command on this target, but normally
  17184. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17185. ApplicationCommandManager::invokeDirectly().
  17186. If this target can perform the given command, it will call its perform() method to
  17187. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17188. to try, and the command will be passed along to it.
  17189. @param invocationInfo this must be correctly filled-in, describing the context for
  17190. the invocation.
  17191. @param asynchronously if false, the command will be performed before this method returns.
  17192. If true, a message will be posted so that the command will be performed
  17193. later on the message thread, and this method will return immediately.
  17194. @see perform, ApplicationCommandManager::invoke
  17195. */
  17196. bool invoke (const InvocationInfo& invocationInfo,
  17197. const bool asynchronously);
  17198. /** Invokes a given command directly on this target.
  17199. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17200. structure.
  17201. */
  17202. bool invokeDirectly (const CommandID commandID,
  17203. const bool asynchronously);
  17204. /** Searches this target and all subsequent ones for the first one that can handle
  17205. the specified command.
  17206. This will use getNextCommandTarget() to determine the chain of targets to try
  17207. after this one.
  17208. */
  17209. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17210. /** Checks whether this command can currently be performed by this target.
  17211. This will return true only if a call to getCommandInfo() doesn't set the
  17212. isDisabled flag to indicate that the command is inactive.
  17213. */
  17214. bool isCommandActive (const CommandID commandID);
  17215. /** If this object is a Component, this method will seach upwards in its current
  17216. UI hierarchy for the next parent component that implements the
  17217. ApplicationCommandTarget class.
  17218. If your target is a Component, this is a very handy method to use in your
  17219. getNextCommandTarget() implementation.
  17220. */
  17221. ApplicationCommandTarget* findFirstTargetParentComponent();
  17222. juce_UseDebuggingNewOperator
  17223. private:
  17224. // (for async invocation of commands)
  17225. class CommandTargetMessageInvoker : public MessageListener
  17226. {
  17227. public:
  17228. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17229. ~CommandTargetMessageInvoker();
  17230. void handleMessage (const Message& message);
  17231. private:
  17232. ApplicationCommandTarget* const owner;
  17233. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17234. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17235. };
  17236. CommandTargetMessageInvoker* messageInvoker;
  17237. friend class CommandTargetMessageInvoker;
  17238. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17239. };
  17240. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17241. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17242. /********* Start of inlined file: juce_ActionListener.h *********/
  17243. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17244. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17245. /**
  17246. Receives callbacks to indicate that some kind of event has occurred.
  17247. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17248. about something that's happened.
  17249. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17250. */
  17251. class JUCE_API ActionListener
  17252. {
  17253. public:
  17254. /** Destructor. */
  17255. virtual ~ActionListener() {}
  17256. /** Overridden by your subclass to receive the callback.
  17257. @param message the string that was specified when the event was triggered
  17258. by a call to ActionListenerList::sendActionMessage()
  17259. */
  17260. virtual void actionListenerCallback (const String& message) = 0;
  17261. };
  17262. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17263. /********* End of inlined file: juce_ActionListener.h *********/
  17264. /**
  17265. An instance of this class is used to specify initialisation and shutdown
  17266. code for the application.
  17267. An application that wants to run in the JUCE framework needs to declare a
  17268. subclass of JUCEApplication and implement its various pure virtual methods.
  17269. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17270. to declare an instance of this class and generate a suitable platform-specific
  17271. main() function.
  17272. e.g. @code
  17273. class MyJUCEApp : public JUCEApplication
  17274. {
  17275. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17276. // objects, which you must create in the initialise() method.
  17277. MyApplicationWindow* myMainWindow;
  17278. public:
  17279. MyJUCEApp()
  17280. : myMainWindow (0)
  17281. {
  17282. // never create any Juce objects in the constructor - do all your initialisation
  17283. // in the initialise() method.
  17284. }
  17285. ~MyJUCEApp()
  17286. {
  17287. // all your shutdown code must have already been done in the shutdown() method -
  17288. // nothing should happen in this destructor.
  17289. }
  17290. void initialise (const String& commandLine)
  17291. {
  17292. myMainWindow = new MyApplicationWindow();
  17293. myMainWindow->setBounds (100, 100, 400, 500);
  17294. myMainWindow->setVisible (true);
  17295. }
  17296. void shutdown()
  17297. {
  17298. delete myMainWindow;
  17299. }
  17300. const String getApplicationName()
  17301. {
  17302. return T("Super JUCE-o-matic");
  17303. }
  17304. const String getApplicationVersion()
  17305. {
  17306. return T("1.0");
  17307. }
  17308. };
  17309. // this creates wrapper code to actually launch the app properly.
  17310. START_JUCE_APPLICATION (MyJUCEApp)
  17311. @endcode
  17312. Because this object will be created before Juce has properly initialised, you must
  17313. NEVER add any member variable objects that will be automatically constructed. Likewise
  17314. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17315. you want to add to the class must be pointers, which you should instantiate during the
  17316. initialise() method, and delete in the shutdown() method.
  17317. @see MessageManager, DeletedAtShutdown
  17318. */
  17319. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17320. private ActionListener
  17321. {
  17322. protected:
  17323. /** Constructs a JUCE app object.
  17324. If subclasses implement a constructor or destructor, they shouldn't call any
  17325. JUCE code in there - put your startup/shutdown code in initialise() and
  17326. shutdown() instead.
  17327. */
  17328. JUCEApplication();
  17329. public:
  17330. /** Destructor.
  17331. If subclasses implement a constructor or destructor, they shouldn't call any
  17332. JUCE code in there - put your startup/shutdown code in initialise() and
  17333. shutdown() instead.
  17334. */
  17335. virtual ~JUCEApplication();
  17336. /** Returns the global instance of the application object being run. */
  17337. static JUCEApplication* getInstance() throw();
  17338. /** Called when the application starts.
  17339. This will be called once to let the application do whatever initialisation
  17340. it needs, create its windows, etc.
  17341. After the method returns, the normal event-dispatch loop will be run,
  17342. until the quit() method is called, at which point the shutdown()
  17343. method will be called to let the application clear up anything it needs
  17344. to delete.
  17345. If during the initialise() method, the application decides not to start-up
  17346. after all, it can just call the quit() method and the event loop won't be run.
  17347. @param commandLineParameters the line passed in does not include the
  17348. name of the executable, just the parameter list.
  17349. @see shutdown, quit
  17350. */
  17351. virtual void initialise (const String& commandLineParameters) = 0;
  17352. /** Returns true if the application hasn't yet completed its initialise() method
  17353. and entered the main event loop.
  17354. This is handy for things like splash screens to know when the app's up-and-running
  17355. properly.
  17356. */
  17357. bool isInitialising() const throw();
  17358. /* Called to allow the application to clear up before exiting.
  17359. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17360. terminate, and this method will get called to allow the app to sort itself
  17361. out.
  17362. Be careful that nothing happens in this method that might rely on messages
  17363. being sent, or any kind of window activity, because the message loop is no
  17364. longer running at this point.
  17365. @see DeletedAtShutdown
  17366. */
  17367. virtual void shutdown() = 0;
  17368. /** Returns the application's name.
  17369. An application must implement this to name itself.
  17370. */
  17371. virtual const String getApplicationName() = 0;
  17372. /** Returns the application's version number.
  17373. An application can implement this to give itself a version.
  17374. (The default implementation of this just returns an empty string).
  17375. */
  17376. virtual const String getApplicationVersion();
  17377. /** Checks whether multiple instances of the app are allowed.
  17378. If you application class returns true for this, more than one instance is
  17379. permitted to run (except on the Mac where this isn't possible).
  17380. If it's false, the second instance won't start, but it you will still get a
  17381. callback to anotherInstanceStarted() to tell you about this - which
  17382. gives you a chance to react to what the user was trying to do.
  17383. */
  17384. virtual bool moreThanOneInstanceAllowed();
  17385. /** Indicates that the user has tried to start up another instance of the app.
  17386. This will get called even if moreThanOneInstanceAllowed() is false.
  17387. */
  17388. virtual void anotherInstanceStarted (const String& commandLine);
  17389. /** Called when the operating system is trying to close the application.
  17390. The default implementation of this method is to call quit(), but it may
  17391. be overloaded to ignore the request or do some other special behaviour
  17392. instead. For example, you might want to offer the user the chance to save
  17393. their changes before quitting, and give them the chance to cancel.
  17394. If you want to send a quit signal to your app, this is the correct method
  17395. to call, because it means that requests that come from the system get handled
  17396. in the same way as those from your own application code. So e.g. you'd
  17397. call this method from a "quit" item on a menu bar.
  17398. */
  17399. virtual void systemRequestedQuit();
  17400. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17401. callback will be triggered, in case you want to log them or do some other
  17402. type of error-handling.
  17403. If the type of exception is derived from the std::exception class, the pointer
  17404. passed-in will be valid. If the exception is of unknown type, this pointer
  17405. will be null.
  17406. */
  17407. virtual void unhandledException (const std::exception* e,
  17408. const String& sourceFilename,
  17409. const int lineNumber);
  17410. /** Signals that the main message loop should stop and the application should terminate.
  17411. This isn't synchronous, it just posts a quit message to the main queue, and
  17412. when this message arrives, the message loop will stop, the shutdown() method
  17413. will be called, and the app will exit.
  17414. Note that this will cause an unconditional quit to happen, so if you need an
  17415. extra level before this, e.g. to give the user the chance to save their work
  17416. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17417. method - see that method's help for more info.
  17418. @see MessageManager, DeletedAtShutdown
  17419. */
  17420. static void quit();
  17421. /** Sets the value that should be returned as the application's exit code when the
  17422. app quits.
  17423. This is the value that's returned by the main() function. Normally you'd leave this
  17424. as 0 unless you want to indicate an error code.
  17425. @see getApplicationReturnValue
  17426. */
  17427. void setApplicationReturnValue (const int newReturnValue) throw();
  17428. /** Returns the value that has been set as the application's exit code.
  17429. @see setApplicationReturnValue
  17430. */
  17431. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17432. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17433. /** @internal */
  17434. static int main (String& commandLine, JUCEApplication* const newApp);
  17435. /** @internal */
  17436. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17437. /** @internal */
  17438. static void sendUnhandledException (const std::exception* const e,
  17439. const char* const sourceFile,
  17440. const int lineNumber);
  17441. /** @internal */
  17442. ApplicationCommandTarget* getNextCommandTarget();
  17443. /** @internal */
  17444. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17445. /** @internal */
  17446. void getAllCommands (Array <CommandID>& commands);
  17447. /** @internal */
  17448. bool perform (const InvocationInfo& info);
  17449. /** @internal */
  17450. void actionListenerCallback (const String& message);
  17451. private:
  17452. int appReturnValue;
  17453. bool stillInitialising;
  17454. static int shutdownAppAndClearUp();
  17455. };
  17456. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17457. /********* End of inlined file: juce_Application.h *********/
  17458. #endif
  17459. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17460. #endif
  17461. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17462. #endif
  17463. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17464. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17465. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17466. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17467. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17468. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17469. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17470. /**
  17471. Has a callback method that is triggered asynchronously.
  17472. This object allows an asynchronous callback function to be triggered, for
  17473. tasks such as coalescing multiple updates into a single callback later on.
  17474. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17475. message thread calling handleAsyncUpdate() as soon as it can.
  17476. */
  17477. class JUCE_API AsyncUpdater
  17478. {
  17479. public:
  17480. /** Creates an AsyncUpdater object. */
  17481. AsyncUpdater() throw();
  17482. /** Destructor.
  17483. If there are any pending callbacks when the object is deleted, these are lost.
  17484. */
  17485. virtual ~AsyncUpdater();
  17486. /** Causes the callback to be triggered at a later time.
  17487. This method returns immediately, having made sure that a callback
  17488. to the handleAsyncUpdate() method will occur as soon as possible.
  17489. If an update callback is already pending but hasn't happened yet, calls
  17490. to this method will be ignored.
  17491. It's thread-safe to call this method from any number of threads without
  17492. needing to worry about locking.
  17493. */
  17494. void triggerAsyncUpdate() throw();
  17495. /** This will stop any pending updates from happening.
  17496. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17497. callback happens, this will cancel the handleAsyncUpdate() callback.
  17498. */
  17499. void cancelPendingUpdate() throw();
  17500. /** If an update has been triggered and is pending, this will invoke it
  17501. synchronously.
  17502. Use this as a kind of "flush" operation - if an update is pending, the
  17503. handleAsyncUpdate() method will be called immediately; if no update is
  17504. pending, then nothing will be done.
  17505. */
  17506. void handleUpdateNowIfNeeded();
  17507. /** Called back to do whatever your class needs to do.
  17508. This method is called by the message thread at the next convenient time
  17509. after the triggerAsyncUpdate() method has been called.
  17510. */
  17511. virtual void handleAsyncUpdate() = 0;
  17512. private:
  17513. class AsyncUpdaterInternal : public MessageListener
  17514. {
  17515. public:
  17516. AsyncUpdaterInternal() throw() {}
  17517. ~AsyncUpdaterInternal() {}
  17518. void handleMessage (const Message&);
  17519. AsyncUpdater* owner;
  17520. private:
  17521. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17522. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17523. };
  17524. AsyncUpdaterInternal internalAsyncHandler;
  17525. bool asyncMessagePending;
  17526. };
  17527. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17528. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17529. /********* Start of inlined file: juce_Desktop.h *********/
  17530. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17531. #define __JUCE_DESKTOP_JUCEHEADER__
  17532. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17533. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17534. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17535. /**
  17536. Classes derived from this will be automatically deleted when the application exits.
  17537. After JUCEApplication::shutdown() has been called, any objects derived from
  17538. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17539. order to that in which they were created.
  17540. So if you've got a singleton and don't want to have to explicitly delete it, just
  17541. inherit from this and it'll be taken care of.
  17542. */
  17543. class JUCE_API DeletedAtShutdown
  17544. {
  17545. protected:
  17546. /** Creates a DeletedAtShutdown object. */
  17547. DeletedAtShutdown() throw();
  17548. /** Destructor.
  17549. It's ok to delete these objects explicitly - it's only the ones left
  17550. dangling at the end that will be deleted automatically.
  17551. */
  17552. virtual ~DeletedAtShutdown();
  17553. public:
  17554. /** Deletes all extant objects.
  17555. This shouldn't be used by applications, as it's called automatically
  17556. in the shutdown code of the JUCEApplication class.
  17557. */
  17558. static void deleteAll();
  17559. private:
  17560. DeletedAtShutdown (const DeletedAtShutdown&);
  17561. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17562. };
  17563. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17564. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17565. /********* Start of inlined file: juce_Timer.h *********/
  17566. #ifndef __JUCE_TIMER_JUCEHEADER__
  17567. #define __JUCE_TIMER_JUCEHEADER__
  17568. class InternalTimerThread;
  17569. /**
  17570. Repeatedly calls a user-defined method at a specified time interval.
  17571. A Timer's timerCallback() method will be repeatedly called at a given
  17572. interval. Initially when a Timer object is created, they will do nothing
  17573. until the startTimer() method is called, then the message thread will
  17574. start calling it back until stopTimer() is called.
  17575. The time interval isn't guaranteed to be precise to any more than maybe
  17576. 10-20ms, and the intervals may end up being much longer than requested if the
  17577. system is busy. Because it's the message thread that is doing the callbacks,
  17578. any messages that take a significant amount of time to process will block
  17579. all the timers for that period.
  17580. If you need to have a single callback that is shared by multiple timers with
  17581. different frequencies, then the MultiTimer class allows you to do that - its
  17582. structure is very similar to the Timer class, but contains multiple timers
  17583. internally, each one identified by an ID number.
  17584. @see MultiTimer
  17585. */
  17586. class JUCE_API Timer
  17587. {
  17588. protected:
  17589. /** Creates a Timer.
  17590. When created, the timer is stopped, so use startTimer() to get it going.
  17591. */
  17592. Timer() throw();
  17593. /** Creates a copy of another timer.
  17594. Note that this timer won't be started, even if the one you're copying
  17595. is running.
  17596. */
  17597. Timer (const Timer& other) throw();
  17598. public:
  17599. /** Destructor. */
  17600. virtual ~Timer();
  17601. /** The user-defined callback routine that actually gets called periodically.
  17602. It's perfectly ok to call startTimer() or stopTimer() from within this
  17603. callback to change the subsequent intervals.
  17604. */
  17605. virtual void timerCallback() = 0;
  17606. /** Starts the timer and sets the length of interval required.
  17607. If the timer is already started, this will reset it, so the
  17608. time between calling this method and the next timer callback
  17609. will not be less than the interval length passed in.
  17610. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17611. rounded up to 1)
  17612. */
  17613. void startTimer (const int intervalInMilliseconds) throw();
  17614. /** Stops the timer.
  17615. No more callbacks will be made after this method returns.
  17616. If this is called from a different thread, any callbacks that may
  17617. be currently executing may be allowed to finish before the method
  17618. returns.
  17619. */
  17620. void stopTimer() throw();
  17621. /** Checks if the timer has been started.
  17622. @returns true if the timer is running.
  17623. */
  17624. bool isTimerRunning() const throw() { return periodMs > 0; }
  17625. /** Returns the timer's interval.
  17626. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17627. */
  17628. int getTimerInterval() const throw() { return periodMs; }
  17629. private:
  17630. friend class InternalTimerThread;
  17631. int countdownMs, periodMs;
  17632. Timer* previous;
  17633. Timer* next;
  17634. const Timer& operator= (const Timer&);
  17635. };
  17636. #endif // __JUCE_TIMER_JUCEHEADER__
  17637. /********* End of inlined file: juce_Timer.h *********/
  17638. /**
  17639. Classes can implement this interface and register themselves with the Desktop class
  17640. to receive callbacks when the currently focused component changes.
  17641. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17642. */
  17643. class JUCE_API FocusChangeListener
  17644. {
  17645. public:
  17646. /** Destructor. */
  17647. virtual ~FocusChangeListener() {}
  17648. /** Callback to indicate that the currently focused component has changed. */
  17649. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17650. };
  17651. /**
  17652. Describes and controls aspects of the computer's desktop.
  17653. */
  17654. class JUCE_API Desktop : private DeletedAtShutdown,
  17655. private Timer,
  17656. private AsyncUpdater
  17657. {
  17658. public:
  17659. /** There's only one dektop object, and this method will return it.
  17660. */
  17661. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17662. /** Returns a list of the positions of all the monitors available.
  17663. The first rectangle in the list will be the main monitor area.
  17664. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17665. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17666. */
  17667. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17668. /** Returns the position and size of the main monitor.
  17669. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17670. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17671. */
  17672. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17673. /** Returns the position and size of the monitor which contains this co-ordinate.
  17674. If none of the monitors contains the point, this will just return the
  17675. main monitor.
  17676. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17677. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17678. */
  17679. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17680. /** Returns the mouse position.
  17681. The co-ordinates are relative to the top-left of the main monitor.
  17682. */
  17683. static void getMousePosition (int& x, int& y) throw();
  17684. /** Makes the mouse pointer jump to a given location.
  17685. The co-ordinates are relative to the top-left of the main monitor.
  17686. */
  17687. static void setMousePosition (int x, int y) throw();
  17688. /** Returns the last position at which a mouse button was pressed.
  17689. */
  17690. static void getLastMouseDownPosition (int& x, int& y) throw();
  17691. /** Returns the number of times the mouse button has been clicked since the
  17692. app started.
  17693. Each mouse-down event increments this number by 1.
  17694. */
  17695. static int getMouseButtonClickCounter() throw();
  17696. /** This lets you prevent the screensaver from becoming active.
  17697. Handy if you're running some sort of presentation app where having a screensaver
  17698. appear would be annoying.
  17699. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17700. won't enable a screensaver unless the user has actually set one up).
  17701. The disablement will only happen while the Juce application is the foreground
  17702. process - if another task is running in front of it, then the screensaver will
  17703. be unaffected.
  17704. @see isScreenSaverEnabled
  17705. */
  17706. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17707. /** Returns true if the screensaver has not been turned off.
  17708. This will return the last value passed into setScreenSaverEnabled(). Note that
  17709. it won't tell you whether the user is actually using a screen saver, just
  17710. whether this app is deliberately preventing one from running.
  17711. @see setScreenSaverEnabled
  17712. */
  17713. static bool isScreenSaverEnabled() throw();
  17714. /** Registers a MouseListener that will receive all mouse events that occur on
  17715. any component.
  17716. @see removeGlobalMouseListener
  17717. */
  17718. void addGlobalMouseListener (MouseListener* const listener) throw();
  17719. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17720. method.
  17721. @see addGlobalMouseListener
  17722. */
  17723. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17724. /** Registers a MouseListener that will receive a callback whenever the focused
  17725. component changes.
  17726. */
  17727. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17728. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17729. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17730. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  17731. The component must already be on the desktop for this method to work. It will
  17732. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  17733. etc will be hidden.
  17734. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  17735. the component that's currently being used will be resized back to the size
  17736. and position it was in before being put into this mode.
  17737. */
  17738. void setKioskModeComponent (Component* componentToUse);
  17739. /** Returns the component that is currently being used in kiosk-mode.
  17740. This is the component that was last set by setKioskModeComponent(). If none
  17741. has been set, this returns 0.
  17742. */
  17743. Component* getKioskModeComponent() const { return kioskModeComponent; }
  17744. /** Returns the number of components that are currently active as top-level
  17745. desktop windows.
  17746. @see getComponent, Component::addToDesktop
  17747. */
  17748. int getNumComponents() const throw();
  17749. /** Returns one of the top-level desktop window components.
  17750. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17751. index is out-of-range.
  17752. @see getNumComponents, Component::addToDesktop
  17753. */
  17754. Component* getComponent (const int index) const throw();
  17755. /** Finds the component at a given screen location.
  17756. This will drill down into top-level windows to find the child component at
  17757. the given position.
  17758. Returns 0 if the co-ordinates are inside a non-Juce window.
  17759. */
  17760. Component* findComponentAt (const int screenX,
  17761. const int screenY) const;
  17762. juce_UseDebuggingNewOperator
  17763. /** Tells this object to refresh its idea of what the screen resolution is.
  17764. (Called internally by the native code).
  17765. */
  17766. void refreshMonitorSizes() throw();
  17767. /** True if the OS supports semitransparent windows */
  17768. static bool canUseSemiTransparentWindows() throw();
  17769. private:
  17770. friend class Component;
  17771. friend class ComponentPeer;
  17772. SortedSet <void*> mouseListeners, focusListeners;
  17773. VoidArray desktopComponents;
  17774. friend class DeletedAtShutdown;
  17775. friend class TopLevelWindowManager;
  17776. Desktop() throw();
  17777. ~Desktop() throw();
  17778. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17779. int lastMouseX, lastMouseY;
  17780. Component* kioskModeComponent;
  17781. Rectangle kioskComponentOriginalBounds;
  17782. void timerCallback();
  17783. void sendMouseMove();
  17784. void resetTimer() throw();
  17785. int getNumDisplayMonitors() const throw();
  17786. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17787. void addDesktopComponent (Component* const c) throw();
  17788. void removeDesktopComponent (Component* const c) throw();
  17789. void componentBroughtToFront (Component* const c) throw();
  17790. void triggerFocusCallback() throw();
  17791. void handleAsyncUpdate();
  17792. Desktop (const Desktop&);
  17793. const Desktop& operator= (const Desktop&);
  17794. };
  17795. #endif // __JUCE_DESKTOP_JUCEHEADER__
  17796. /********* End of inlined file: juce_Desktop.h *********/
  17797. class KeyPressMappingSet;
  17798. class ApplicationCommandManagerListener;
  17799. /**
  17800. One of these objects holds a list of all the commands your app can perform,
  17801. and despatches these commands when needed.
  17802. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  17803. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  17804. to invoke automatically, which means you don't have to handle the result of a menu
  17805. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  17806. which can choose which events they want to handle.
  17807. This architecture also allows for nested ApplicationCommandTargets, so that for example
  17808. you could have two different objects, one inside the other, both of which can respond to
  17809. a "delete" command. Depending on which one has focus, the command will be sent to the
  17810. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  17811. method.
  17812. To set up your app to use commands, you'll need to do the following:
  17813. - Create a global ApplicationCommandManager to hold the list of all possible
  17814. commands. (This will also manage a set of key-mappings for them).
  17815. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  17816. This allows the object to provide a list of commands that it can perform, and
  17817. to handle them.
  17818. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  17819. or ApplicationCommandManager::registerCommand().
  17820. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  17821. method to access the key-mapper object, which you will need to register as a key-listener
  17822. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  17823. about setting this up.
  17824. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  17825. cause these commands to be invoked automatically.
  17826. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  17827. When a command is invoked, the ApplicationCommandManager will try to choose the best
  17828. ApplicationCommandTarget to receive the specified command. To do this it will use the
  17829. current keyboard focus to see which component might be interested, and will search the
  17830. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  17831. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  17832. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  17833. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  17834. point if the command still hasn't been performed, it will be passed to the current
  17835. JUCEApplication object (which is itself an ApplicationCommandTarget).
  17836. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  17837. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  17838. the object yourself.
  17839. @see ApplicationCommandTarget, ApplicationCommandInfo
  17840. */
  17841. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  17842. private FocusChangeListener
  17843. {
  17844. public:
  17845. /** Creates an ApplicationCommandManager.
  17846. Once created, you'll need to register all your app's commands with it, using
  17847. ApplicationCommandManager::registerAllCommandsForTarget() or
  17848. ApplicationCommandManager::registerCommand().
  17849. */
  17850. ApplicationCommandManager();
  17851. /** Destructor.
  17852. Make sure that you don't delete this if pointers to it are still being used by
  17853. objects such as PopupMenus or Buttons.
  17854. */
  17855. virtual ~ApplicationCommandManager();
  17856. /** Clears the current list of all commands.
  17857. Note that this will also clear the contents of the KeyPressMappingSet.
  17858. */
  17859. void clearCommands();
  17860. /** Adds a command to the list of registered commands.
  17861. @see registerAllCommandsForTarget
  17862. */
  17863. void registerCommand (const ApplicationCommandInfo& newCommand);
  17864. /** Adds all the commands that this target publishes to the manager's list.
  17865. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  17866. to get details about all the commands that this target can do, and will call
  17867. registerCommand() to add each one to the manger's list.
  17868. @see registerCommand
  17869. */
  17870. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  17871. /** Removes the command with a specified ID.
  17872. Note that this will also remove any key mappings that are mapped to the command.
  17873. */
  17874. void removeCommand (const CommandID commandID);
  17875. /** This should be called to tell the manager that one of its registered commands may have changed
  17876. its active status.
  17877. Because the command manager only finds out whether a command is active or inactive by querying
  17878. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  17879. allows things like buttons to update their enablement, etc.
  17880. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  17881. for any registered listeners.
  17882. */
  17883. void commandStatusChanged();
  17884. /** Returns the number of commands that have been registered.
  17885. @see registerCommand
  17886. */
  17887. int getNumCommands() const throw() { return commands.size(); }
  17888. /** Returns the details about one of the registered commands.
  17889. The index is between 0 and (getNumCommands() - 1).
  17890. */
  17891. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  17892. /** Returns the details about a given command ID.
  17893. This will search the list of registered commands for one with the given command
  17894. ID number, and return its associated info. If no matching command is found, this
  17895. will return 0.
  17896. */
  17897. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  17898. /** Returns the name field for a command.
  17899. An empty string is returned if no command with this ID has been registered.
  17900. @see getDescriptionOfCommand
  17901. */
  17902. const String getNameOfCommand (const CommandID commandID) const throw();
  17903. /** Returns the description field for a command.
  17904. An empty string is returned if no command with this ID has been registered. If the
  17905. command has no description, this will return its short name field instead.
  17906. @see getNameOfCommand
  17907. */
  17908. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  17909. /** Returns the list of categories.
  17910. This will go through all registered commands, and return a list of all the distict
  17911. categoryName values from their ApplicationCommandInfo structure.
  17912. @see getCommandsInCategory()
  17913. */
  17914. const StringArray getCommandCategories() const throw();
  17915. /** Returns a list of all the command UIDs in a particular category.
  17916. @see getCommandCategories()
  17917. */
  17918. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  17919. /** Returns the manager's internal set of key mappings.
  17920. This object can be used to edit the keypresses. To actually link this object up
  17921. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  17922. class.
  17923. @see KeyPressMappingSet
  17924. */
  17925. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  17926. /** Invokes the given command directly, sending it to the default target.
  17927. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17928. structure.
  17929. */
  17930. bool invokeDirectly (const CommandID commandID,
  17931. const bool asynchronously);
  17932. /** Sends a command to the default target.
  17933. This will choose a target using getFirstCommandTarget(), and send the specified command
  17934. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  17935. first target can't handle the command, it will be passed on to targets further down the
  17936. chain (see ApplicationCommandTarget::invoke() for more info).
  17937. @param invocationInfo this must be correctly filled-in, describing the context for
  17938. the invocation.
  17939. @param asynchronously if false, the command will be performed before this method returns.
  17940. If true, a message will be posted so that the command will be performed
  17941. later on the message thread, and this method will return immediately.
  17942. @see ApplicationCommandTarget::invoke
  17943. */
  17944. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  17945. const bool asynchronously);
  17946. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  17947. Whenever the manager needs to know which target a command should be sent to, it calls
  17948. this method to determine the first one to try.
  17949. By default, this method will return the target that was set by calling setFirstCommandTarget().
  17950. If no target is set, it will return the result of findDefaultComponentTarget().
  17951. If you need to make sure all commands go via your own custom target, then you can
  17952. either use setFirstCommandTarget() to specify a single target, or override this method
  17953. if you need more complex logic to choose one.
  17954. It may return 0 if no targets are available.
  17955. @see getTargetForCommand, invoke, invokeDirectly
  17956. */
  17957. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  17958. /** Sets a target to be returned by getFirstCommandTarget().
  17959. If this is set to 0, then getFirstCommandTarget() will by default return the
  17960. result of findDefaultComponentTarget().
  17961. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  17962. deleting the target object.
  17963. */
  17964. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  17965. /** Tries to find the best target to use to perform a given command.
  17966. This will call getFirstCommandTarget() to find the preferred target, and will
  17967. check whether that target can handle the given command. If it can't, then it'll use
  17968. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  17969. so on until no more are available.
  17970. If no targets are found that can perform the command, this method will return 0.
  17971. If a target is found, then it will get the target to fill-in the upToDateInfo
  17972. structure with the latest info about that command, so that the caller can see
  17973. whether the command is disabled, ticked, etc.
  17974. */
  17975. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  17976. ApplicationCommandInfo& upToDateInfo);
  17977. /** Registers a listener that will be called when various events occur. */
  17978. void addListener (ApplicationCommandManagerListener* const listener) throw();
  17979. /** Deregisters a previously-added listener. */
  17980. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  17981. /** Looks for a suitable command target based on which Components have the keyboard focus.
  17982. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  17983. but is exposed here in case it's useful.
  17984. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  17985. windows, etc., and using the findTargetForComponent() method.
  17986. */
  17987. static ApplicationCommandTarget* findDefaultComponentTarget();
  17988. /** Examines this component and all its parents in turn, looking for the first one
  17989. which is a ApplicationCommandTarget.
  17990. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  17991. that class.
  17992. */
  17993. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  17994. juce_UseDebuggingNewOperator
  17995. private:
  17996. OwnedArray <ApplicationCommandInfo> commands;
  17997. SortedSet <void*> listeners;
  17998. KeyPressMappingSet* keyMappings;
  17999. ApplicationCommandTarget* firstTarget;
  18000. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18001. void handleAsyncUpdate();
  18002. void globalFocusChanged (Component*);
  18003. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18004. // version of this method.
  18005. virtual short getFirstCommandTarget() { return 0; }
  18006. };
  18007. /**
  18008. A listener that receives callbacks from an ApplicationCommandManager when
  18009. commands are invoked or the command list is changed.
  18010. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18011. */
  18012. class JUCE_API ApplicationCommandManagerListener
  18013. {
  18014. public:
  18015. /** Destructor. */
  18016. virtual ~ApplicationCommandManagerListener() {}
  18017. /** Called when an app command is about to be invoked. */
  18018. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18019. /** Called when commands are registered or deregistered from the
  18020. command manager, or when commands are made active or inactive.
  18021. Note that if you're using this to watch for changes to whether a command is disabled,
  18022. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18023. whenever the status of your command might have changed.
  18024. */
  18025. virtual void applicationCommandListChanged() = 0;
  18026. };
  18027. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18028. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18029. #endif
  18030. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18031. #endif
  18032. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18033. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18034. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18035. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18036. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18037. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18038. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18039. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18040. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18041. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18042. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18043. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18044. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18045. /********* Start of inlined file: juce_ChangeListener.h *********/
  18046. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18047. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18048. /**
  18049. Receives callbacks about changes to some kind of object.
  18050. Many objects use a ChangeListenerList to keep a set of listeners which they
  18051. will inform when something changes. A subclass of ChangeListener
  18052. is used to receive these callbacks.
  18053. Note that the major difference between an ActionListener and a ChangeListener
  18054. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18055. callbacks, but ActionListeners perform one callback for every event posted.
  18056. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18057. */
  18058. class JUCE_API ChangeListener
  18059. {
  18060. public:
  18061. /** Destructor. */
  18062. virtual ~ChangeListener() {}
  18063. /** Overridden by your subclass to receive the callback.
  18064. @param objectThatHasChanged the value that was passed to the
  18065. ChangeListenerList::sendChangeMessage() method
  18066. */
  18067. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18068. };
  18069. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18070. /********* End of inlined file: juce_ChangeListener.h *********/
  18071. /**
  18072. A set of ChangeListeners.
  18073. Listeners can be added and removed from the list, and change messages can be
  18074. broadcast to all the listeners.
  18075. @see ChangeListener, ChangeBroadcaster
  18076. */
  18077. class JUCE_API ChangeListenerList : public MessageListener
  18078. {
  18079. public:
  18080. /** Creates an empty list. */
  18081. ChangeListenerList() throw();
  18082. /** Destructor. */
  18083. ~ChangeListenerList() throw();
  18084. /** Adds a listener to the list.
  18085. (Trying to add a listener that's already on the list will have no effect).
  18086. */
  18087. void addChangeListener (ChangeListener* const listener) throw();
  18088. /** Removes a listener from the list.
  18089. If the listener isn't on the list, this won't have any effect.
  18090. */
  18091. void removeChangeListener (ChangeListener* const listener) throw();
  18092. /** Removes all listeners from the list. */
  18093. void removeAllChangeListeners() throw();
  18094. /** Posts an asynchronous change message to all the listeners.
  18095. If a message has already been sent and hasn't yet been delivered, this
  18096. method won't send another - in this way it coalesces multiple frequent
  18097. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18098. with the ActionListener, which posts a new event for every call to its
  18099. sendActionMessage() method.
  18100. Only listeners which are on the list when the change event is delivered
  18101. will receive the event - and this may include listeners that weren't on
  18102. the list when the change message was sent.
  18103. @param objectThatHasChanged this pointer is passed to the
  18104. ChangeListener::changeListenerCallback() method,
  18105. and can be any value the application needs
  18106. @see sendSynchronousChangeMessage
  18107. */
  18108. void sendChangeMessage (void* objectThatHasChanged) throw();
  18109. /** This will synchronously callback all the ChangeListeners.
  18110. Use this if you need to synchronously force a call to all the
  18111. listeners' ChangeListener::changeListenerCallback() methods.
  18112. */
  18113. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18114. /** If a change message has been sent but not yet dispatched, this will
  18115. use sendSynchronousChangeMessage() to make the callback immediately.
  18116. */
  18117. void dispatchPendingMessages();
  18118. /** @internal */
  18119. void handleMessage (const Message&);
  18120. juce_UseDebuggingNewOperator
  18121. private:
  18122. SortedSet <void*> listeners;
  18123. CriticalSection lock;
  18124. void* lastChangedObject;
  18125. bool messagePending;
  18126. ChangeListenerList (const ChangeListenerList&);
  18127. const ChangeListenerList& operator= (const ChangeListenerList&);
  18128. };
  18129. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18130. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18131. /** Manages a list of ChangeListeners, and can send them messages.
  18132. To quickly add methods to your class that can add/remove change
  18133. listeners and broadcast to them, you can derive from this.
  18134. @see ChangeListenerList, ChangeListener
  18135. */
  18136. class JUCE_API ChangeBroadcaster
  18137. {
  18138. public:
  18139. /** Creates an ChangeBroadcaster. */
  18140. ChangeBroadcaster() throw();
  18141. /** Destructor. */
  18142. virtual ~ChangeBroadcaster();
  18143. /** Adds a listener to the list.
  18144. (Trying to add a listener that's already on the list will have no effect).
  18145. */
  18146. void addChangeListener (ChangeListener* const listener) throw();
  18147. /** Removes a listener from the list.
  18148. If the listener isn't on the list, this won't have any effect.
  18149. */
  18150. void removeChangeListener (ChangeListener* const listener) throw();
  18151. /** Removes all listeners from the list. */
  18152. void removeAllChangeListeners() throw();
  18153. /** Broadcasts a change message to all the registered listeners.
  18154. The message will be delivered asynchronously by the event thread, so this
  18155. method will not directly call any of the listeners. For a synchronous
  18156. message, use sendSynchronousChangeMessage().
  18157. @see ChangeListenerList::sendActionMessage
  18158. */
  18159. void sendChangeMessage (void* objectThatHasChanged) throw();
  18160. /** Sends a synchronous change message to all the registered listeners.
  18161. @see ChangeListenerList::sendSynchronousChangeMessage
  18162. */
  18163. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18164. /** If a change message has been sent but not yet dispatched, this will
  18165. use sendSynchronousChangeMessage() to make the callback immediately.
  18166. */
  18167. void dispatchPendingMessages();
  18168. private:
  18169. ChangeListenerList changeListenerList;
  18170. ChangeBroadcaster (const ChangeBroadcaster&);
  18171. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18172. };
  18173. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18174. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18175. /** Wrapper on a file that stores a list of key/value data pairs.
  18176. Useful for storing application settings, etc. See the PropertySet class for
  18177. the interfaces that read and write values.
  18178. Not designed for very large amounts of data, as it keeps all the values in
  18179. memory and writes them out to disk lazily when they are changed.
  18180. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18181. with it, and these will be signalled when a value changes.
  18182. @see PropertySet
  18183. */
  18184. class JUCE_API PropertiesFile : public PropertySet,
  18185. public ChangeBroadcaster,
  18186. private Timer
  18187. {
  18188. public:
  18189. enum FileFormatOptions
  18190. {
  18191. ignoreCaseOfKeyNames = 1,
  18192. storeAsBinary = 2,
  18193. storeAsCompressedBinary = 4,
  18194. storeAsXML = 8
  18195. };
  18196. /**
  18197. Creates a PropertiesFile object.
  18198. @param file the file to use
  18199. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18200. is changed, the object will wait for this amount
  18201. of time and then save the file. If zero, the file
  18202. will be written to disk immediately on being changed
  18203. (which might be slow, as it'll re-write synchronously
  18204. each time a value-change method is called). If it is
  18205. less than zero, the file won't be saved until
  18206. save() or saveIfNeeded() are explicitly called.
  18207. @param options a combination of the flags in the FileFormatOptions
  18208. enum, which specify the type of file to save, and other
  18209. options.
  18210. */
  18211. PropertiesFile (const File& file,
  18212. const int millisecondsBeforeSaving,
  18213. const int options) throw();
  18214. /** Destructor.
  18215. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18216. */
  18217. ~PropertiesFile();
  18218. /** This will flush all the values to disk if they've changed since the last
  18219. time they were saved.
  18220. Returns false if it fails to write to the file for some reason (maybe because
  18221. it's read-only or the directory doesn't exist or something).
  18222. @see save
  18223. */
  18224. bool saveIfNeeded();
  18225. /** This will force a write-to-disk of the current values, regardless of whether
  18226. anything has changed since the last save.
  18227. Returns false if it fails to write to the file for some reason (maybe because
  18228. it's read-only or the directory doesn't exist or something).
  18229. @see saveIfNeeded
  18230. */
  18231. bool save();
  18232. /** Returns true if the properties have been altered since the last time they were
  18233. saved.
  18234. */
  18235. bool needsToBeSaved() const throw();
  18236. /** Returns the file that's being used. */
  18237. const File getFile() const throw();
  18238. /** Handy utility to create a properties file in whatever the standard OS-specific
  18239. location is for these things.
  18240. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18241. creates a PropertiesFile object with the specified properties. See
  18242. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18243. what the parameters do.
  18244. @see getDefaultAppSettingsFile
  18245. */
  18246. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18247. const String& fileNameSuffix,
  18248. const String& folderName,
  18249. const bool commonToAllUsers,
  18250. const int millisecondsBeforeSaving,
  18251. const int propertiesFileOptions);
  18252. /** Handy utility to choose a file in the standard OS-dependent location for application
  18253. settings files.
  18254. So on a Mac, this will return a file called:
  18255. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18256. On Windows it'll return something like:
  18257. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18258. On Linux it'll return
  18259. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18260. If you pass an empty string as the folder name, it'll use the app name for this (or
  18261. omit the folder name on the Mac).
  18262. If commonToAllUsers is true, then this will return the same file for all users of the
  18263. computer, regardless of the current user. If it is false, the file will be specific to
  18264. only the current user. Use this to choose whether you're saving settings that are common
  18265. or user-specific.
  18266. */
  18267. static const File getDefaultAppSettingsFile (const String& applicationName,
  18268. const String& fileNameSuffix,
  18269. const String& folderName,
  18270. const bool commonToAllUsers);
  18271. juce_UseDebuggingNewOperator
  18272. protected:
  18273. virtual void propertyChanged();
  18274. private:
  18275. File file;
  18276. int timerInterval;
  18277. const int options;
  18278. bool needsWriting;
  18279. void timerCallback();
  18280. PropertiesFile (const PropertiesFile&);
  18281. const PropertiesFile& operator= (const PropertiesFile&);
  18282. };
  18283. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18284. /********* End of inlined file: juce_PropertiesFile.h *********/
  18285. /**
  18286. Manages a collection of properties.
  18287. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18288. as a singleton.
  18289. It holds two different PropertiesFile objects internally, one for user-specific
  18290. settings (stored in your user directory), and one for settings that are common to
  18291. all users (stored in a folder accessible to all users).
  18292. The class manages the creation of these files on-demand, allowing access via the
  18293. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18294. methods like testWriteAccess() to check that the files can be saved.
  18295. If you're using one of these as a singleton, then your app's start-up code should
  18296. first of all call setStorageParameters() to tell it the parameters to use to create
  18297. the properties files.
  18298. @see PropertiesFile
  18299. */
  18300. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18301. {
  18302. public:
  18303. /**
  18304. Creates an ApplicationProperties object.
  18305. Before using it, you must call setStorageParameters() to give it the info
  18306. it needs to create the property files.
  18307. */
  18308. ApplicationProperties() throw();
  18309. /** Destructor.
  18310. */
  18311. ~ApplicationProperties();
  18312. juce_DeclareSingleton (ApplicationProperties, false)
  18313. /** Gives the object the information it needs to create the appropriate properties files.
  18314. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18315. info about how these parameters are used.
  18316. */
  18317. void setStorageParameters (const String& applicationName,
  18318. const String& fileNameSuffix,
  18319. const String& folderName,
  18320. const int millisecondsBeforeSaving,
  18321. const int propertiesFileOptions) throw();
  18322. /** Tests whether the files can be successfully written to, and can show
  18323. an error message if not.
  18324. Returns true if none of the tests fail.
  18325. @param testUserSettings if true, the user settings file will be tested
  18326. @param testCommonSettings if true, the common settings file will be tested
  18327. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18328. message box if either of the tests fail
  18329. */
  18330. bool testWriteAccess (const bool testUserSettings,
  18331. const bool testCommonSettings,
  18332. const bool showWarningDialogOnFailure);
  18333. /** Returns the user settings file.
  18334. The first time this is called, it will create and load the properties file.
  18335. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18336. the common settings are used as a second-chance place to look. This is done via the
  18337. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18338. to the fallback for the user settings.
  18339. @see getCommonSettings
  18340. */
  18341. PropertiesFile* getUserSettings() throw();
  18342. /** Returns the common settings file.
  18343. The first time this is called, it will create and load the properties file.
  18344. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18345. read-only (e.g. because the user doesn't have permission to write
  18346. to shared files), then this will return the user settings instead,
  18347. (like getUserSettings() would do). This is handy if you'd like to
  18348. write a value to the common settings, but if that's no possible,
  18349. then you'd rather write to the user settings than none at all.
  18350. If returnUserPropsIfReadOnly is false, this method will always return
  18351. the common settings, even if any changes to them can't be saved.
  18352. @see getUserSettings
  18353. */
  18354. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18355. /** Saves both files if they need to be saved.
  18356. @see PropertiesFile::saveIfNeeded
  18357. */
  18358. bool saveIfNeeded();
  18359. /** Flushes and closes both files if they are open.
  18360. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18361. and closes both files. They will then be re-opened the next time getUserSettings()
  18362. or getCommonSettings() is called.
  18363. */
  18364. void closeFiles();
  18365. juce_UseDebuggingNewOperator
  18366. private:
  18367. PropertiesFile* userProps;
  18368. PropertiesFile* commonProps;
  18369. String appName, fileSuffix, folderName;
  18370. int msBeforeSaving, options;
  18371. int commonSettingsAreReadOnly;
  18372. ApplicationProperties (const ApplicationProperties&);
  18373. const ApplicationProperties& operator= (const ApplicationProperties&);
  18374. void openFiles() throw();
  18375. };
  18376. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18377. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18378. #endif
  18379. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18380. #endif
  18381. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18382. #endif
  18383. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18384. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18385. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18386. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18387. /**
  18388. Handles reading/writing to the system's clipboard.
  18389. */
  18390. class JUCE_API SystemClipboard
  18391. {
  18392. public:
  18393. /** Copies a string of text onto the clipboard */
  18394. static void copyTextToClipboard (const String& text) throw();
  18395. /** Gets the current clipboard's contents.
  18396. Obviously this might have come from another app, so could contain
  18397. anything..
  18398. */
  18399. static const String getTextFromClipboard() throw();
  18400. };
  18401. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18402. /********* End of inlined file: juce_SystemClipboard.h *********/
  18403. #endif
  18404. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18405. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18406. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18407. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18408. /********* Start of inlined file: juce_MidiMessage.h *********/
  18409. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18410. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18411. /**
  18412. Encapsulates a MIDI message.
  18413. @see MidiMessageSequence, MidiOutput, MidiInput
  18414. */
  18415. class JUCE_API MidiMessage
  18416. {
  18417. public:
  18418. /** Creates a 3-byte short midi message.
  18419. @param byte1 message byte 1
  18420. @param byte2 message byte 2
  18421. @param byte3 message byte 3
  18422. @param timeStamp the time to give the midi message - this value doesn't
  18423. use any particular units, so will be application-specific
  18424. */
  18425. MidiMessage (const int byte1,
  18426. const int byte2,
  18427. const int byte3,
  18428. const double timeStamp = 0) throw();
  18429. /** Creates a 2-byte short midi message.
  18430. @param byte1 message byte 1
  18431. @param byte2 message byte 2
  18432. @param timeStamp the time to give the midi message - this value doesn't
  18433. use any particular units, so will be application-specific
  18434. */
  18435. MidiMessage (const int byte1,
  18436. const int byte2,
  18437. const double timeStamp = 0) throw();
  18438. /** Creates a 1-byte short midi message.
  18439. @param byte1 message byte 1
  18440. @param timeStamp the time to give the midi message - this value doesn't
  18441. use any particular units, so will be application-specific
  18442. */
  18443. MidiMessage (const int byte1,
  18444. const double timeStamp = 0) throw();
  18445. /** Creates a midi message from a block of data. */
  18446. MidiMessage (const uint8* const data,
  18447. const int dataSize,
  18448. const double timeStamp = 0) throw();
  18449. /** Reads the next midi message from some data.
  18450. This will read as many bytes from a data stream as it needs to make a
  18451. complete message, and will return the number of bytes it used. This lets
  18452. you read a sequence of midi messages from a file or stream.
  18453. @param data the data to read from
  18454. @param size the maximum number of bytes it's allowed to read
  18455. @param numBytesUsed returns the number of bytes that were actually needed
  18456. @param lastStatusByte in a sequence of midi messages, the initial byte
  18457. can be dropped from a message if it's the same as the
  18458. first byte of the previous message, so this lets you
  18459. supply the byte to use if the first byte of the message
  18460. has in fact been dropped.
  18461. @param timeStamp the time to give the midi message - this value doesn't
  18462. use any particular units, so will be application-specific
  18463. */
  18464. MidiMessage (const uint8* data,
  18465. int size,
  18466. int& numBytesUsed,
  18467. uint8 lastStatusByte,
  18468. double timeStamp = 0) throw();
  18469. /** Creates a copy of another midi message. */
  18470. MidiMessage (const MidiMessage& other) throw();
  18471. /** Creates a copy of another midi message, with a different timestamp. */
  18472. MidiMessage (const MidiMessage& other,
  18473. const double newTimeStamp) throw();
  18474. /** Destructor. */
  18475. ~MidiMessage() throw();
  18476. /** Copies this message from another one. */
  18477. const MidiMessage& operator= (const MidiMessage& other) throw();
  18478. /** Returns a pointer to the raw midi data.
  18479. @see getRawDataSize
  18480. */
  18481. uint8* getRawData() const throw() { return data; }
  18482. /** Returns the number of bytes of data in the message.
  18483. @see getRawData
  18484. */
  18485. int getRawDataSize() const throw() { return size; }
  18486. /** Returns the timestamp associated with this message.
  18487. The units for the timestamp will be application-specific.
  18488. @see setTimeStamp, addToTimeStamp
  18489. */
  18490. double getTimeStamp() const throw() { return timeStamp; }
  18491. /** Changes the message's associated timestamp.
  18492. The units for the timestamp will be application-specific.
  18493. @see addToTimeStamp, getTimeStamp
  18494. */
  18495. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18496. /** Adds a value to the message's timestamp.
  18497. The units for the timestamp will be application-specific.
  18498. */
  18499. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18500. /** Returns the midi channel associated with the message.
  18501. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18502. if it's a sysex)
  18503. @see isForChannel, setChannel
  18504. */
  18505. int getChannel() const throw();
  18506. /** Returns true if the message applies to the given midi channel.
  18507. @param channelNumber the channel number to look for, in the range 1 to 16
  18508. @see getChannel, setChannel
  18509. */
  18510. bool isForChannel (const int channelNumber) const throw();
  18511. /** Changes the message's midi channel.
  18512. This won't do anything for non-channel messages like sysexes.
  18513. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18514. */
  18515. void setChannel (const int newChannelNumber) throw();
  18516. /** Returns true if this is a system-exclusive message.
  18517. */
  18518. bool isSysEx() const throw();
  18519. /** Returns a pointer to the sysex data inside the message.
  18520. If this event isn't a sysex event, it'll return 0.
  18521. @see getSysExDataSize
  18522. */
  18523. const uint8* getSysExData() const throw();
  18524. /** Returns the size of the sysex data.
  18525. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18526. @see getSysExData
  18527. */
  18528. int getSysExDataSize() const throw();
  18529. /** Returns true if this message is a 'key-down' event.
  18530. This will return false for a note-on event with a velocity of 0.
  18531. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18532. */
  18533. bool isNoteOn() const throw();
  18534. /** Creates a key-down message (using a floating-point velocity).
  18535. @param channel the midi channel, in the range 1 to 16
  18536. @param noteNumber the key number, 0 to 127
  18537. @param velocity in the range 0 to 1.0
  18538. @see isNoteOn
  18539. */
  18540. static const MidiMessage noteOn (const int channel,
  18541. const int noteNumber,
  18542. const float velocity) throw();
  18543. /** Creates a key-down message (using an integer velocity).
  18544. @param channel the midi channel, in the range 1 to 16
  18545. @param noteNumber the key number, 0 to 127
  18546. @param velocity in the range 0 to 127
  18547. @see isNoteOn
  18548. */
  18549. static const MidiMessage noteOn (const int channel,
  18550. const int noteNumber,
  18551. const uint8 velocity) throw();
  18552. /** Returns true if this message is a 'key-up' event.
  18553. This will also return true for a note-on event with a velocity of 0.
  18554. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18555. */
  18556. bool isNoteOff() const throw();
  18557. /** Creates a key-up message.
  18558. @param channel the midi channel, in the range 1 to 16
  18559. @param noteNumber the key number, 0 to 127
  18560. @see isNoteOff
  18561. */
  18562. static const MidiMessage noteOff (const int channel,
  18563. const int noteNumber) throw();
  18564. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18565. @see isNoteOn, isNoteOff
  18566. */
  18567. bool isNoteOnOrOff() const throw();
  18568. /** Returns the midi note number for note-on and note-off messages.
  18569. If the message isn't a note-on or off, the value returned will be
  18570. meaningless.
  18571. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18572. */
  18573. int getNoteNumber() const throw();
  18574. /** Changes the midi note number of a note-on or note-off message.
  18575. If the message isn't a note on or off, this will do nothing.
  18576. */
  18577. void setNoteNumber (const int newNoteNumber) throw();
  18578. /** Returns the velocity of a note-on or note-off message.
  18579. The value returned will be in the range 0 to 127.
  18580. If the message isn't a note-on or off event, it will return 0.
  18581. @see getFloatVelocity
  18582. */
  18583. uint8 getVelocity() const throw();
  18584. /** Returns the velocity of a note-on or note-off message.
  18585. The value returned will be in the range 0 to 1.0
  18586. If the message isn't a note-on or off event, it will return 0.
  18587. @see getVelocity, setVelocity
  18588. */
  18589. float getFloatVelocity() const throw();
  18590. /** Changes the velocity of a note-on or note-off message.
  18591. If the message isn't a note on or off, this will do nothing.
  18592. @param newVelocity the new velocity, in the range 0 to 1.0
  18593. @see getFloatVelocity, multiplyVelocity
  18594. */
  18595. void setVelocity (const float newVelocity) throw();
  18596. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18597. If the message isn't a note on or off, this will do nothing.
  18598. @param scaleFactor the value by which to multiply the velocity
  18599. @see setVelocity
  18600. */
  18601. void multiplyVelocity (const float scaleFactor) throw();
  18602. /** Returns true if the message is a program (patch) change message.
  18603. @see getProgramChangeNumber, getGMInstrumentName
  18604. */
  18605. bool isProgramChange() const throw();
  18606. /** Returns the new program number of a program change message.
  18607. If the message isn't a program change, the value returned will be
  18608. nonsense.
  18609. @see isProgramChange, getGMInstrumentName
  18610. */
  18611. int getProgramChangeNumber() const throw();
  18612. /** Creates a program-change message.
  18613. @param channel the midi channel, in the range 1 to 16
  18614. @param programNumber the midi program number, 0 to 127
  18615. @see isProgramChange, getGMInstrumentName
  18616. */
  18617. static const MidiMessage programChange (const int channel,
  18618. const int programNumber) throw();
  18619. /** Returns true if the message is a pitch-wheel move.
  18620. @see getPitchWheelValue, pitchWheel
  18621. */
  18622. bool isPitchWheel() const throw();
  18623. /** Returns the pitch wheel position from a pitch-wheel move message.
  18624. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18625. If called for messages which aren't pitch wheel events, the number returned will be
  18626. nonsense.
  18627. @see isPitchWheel
  18628. */
  18629. int getPitchWheelValue() const throw();
  18630. /** Creates a pitch-wheel move message.
  18631. @param channel the midi channel, in the range 1 to 16
  18632. @param position the wheel position, in the range 0 to 16383
  18633. @see isPitchWheel
  18634. */
  18635. static const MidiMessage pitchWheel (const int channel,
  18636. const int position) throw();
  18637. /** Returns true if the message is an aftertouch event.
  18638. For aftertouch events, use the getNoteNumber() method to find out the key
  18639. that it applies to, and getAftertouchValue() to find out the amount. Use
  18640. getChannel() to find out the channel.
  18641. @see getAftertouchValue, getNoteNumber
  18642. */
  18643. bool isAftertouch() const throw();
  18644. /** Returns the amount of aftertouch from an aftertouch messages.
  18645. The value returned is in the range 0 to 127, and will be nonsense for messages
  18646. other than aftertouch messages.
  18647. @see isAftertouch
  18648. */
  18649. int getAfterTouchValue() const throw();
  18650. /** Creates an aftertouch message.
  18651. @param channel the midi channel, in the range 1 to 16
  18652. @param noteNumber the key number, 0 to 127
  18653. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18654. @see isAftertouch
  18655. */
  18656. static const MidiMessage aftertouchChange (const int channel,
  18657. const int noteNumber,
  18658. const int aftertouchAmount) throw();
  18659. /** Returns true if the message is a channel-pressure change event.
  18660. This is like aftertouch, but common to the whole channel rather than a specific
  18661. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18662. to find out the channel.
  18663. @see channelPressureChange
  18664. */
  18665. bool isChannelPressure() const throw();
  18666. /** Returns the pressure from a channel pressure change message.
  18667. @returns the pressure, in the range 0 to 127
  18668. @see isChannelPressure, channelPressureChange
  18669. */
  18670. int getChannelPressureValue() const throw();
  18671. /** Creates a channel-pressure change event.
  18672. @param channel the midi channel: 1 to 16
  18673. @param pressure the pressure, 0 to 127
  18674. @see isChannelPressure
  18675. */
  18676. static const MidiMessage channelPressureChange (const int channel,
  18677. const int pressure) throw();
  18678. /** Returns true if this is a midi controller message.
  18679. @see getControllerNumber, getControllerValue, controllerEvent
  18680. */
  18681. bool isController() const throw();
  18682. /** Returns the controller number of a controller message.
  18683. The name of the controller can be looked up using the getControllerName() method.
  18684. Note that the value returned is invalid for messages that aren't controller changes.
  18685. @see isController, getControllerName, getControllerValue
  18686. */
  18687. int getControllerNumber() const throw();
  18688. /** Returns the controller value from a controller message.
  18689. A value 0 to 127 is returned to indicate the new controller position.
  18690. Note that the value returned is invalid for messages that aren't controller changes.
  18691. @see isController, getControllerNumber
  18692. */
  18693. int getControllerValue() const throw();
  18694. /** Creates a controller message.
  18695. @param channel the midi channel, in the range 1 to 16
  18696. @param controllerType the type of controller
  18697. @param value the controller value
  18698. @see isController
  18699. */
  18700. static const MidiMessage controllerEvent (const int channel,
  18701. const int controllerType,
  18702. const int value) throw();
  18703. /** Checks whether this message is an all-notes-off message.
  18704. @see allNotesOff
  18705. */
  18706. bool isAllNotesOff() const throw();
  18707. /** Checks whether this message is an all-sound-off message.
  18708. @see allSoundOff
  18709. */
  18710. bool isAllSoundOff() const throw();
  18711. /** Creates an all-notes-off message.
  18712. @param channel the midi channel, in the range 1 to 16
  18713. @see isAllNotesOff
  18714. */
  18715. static const MidiMessage allNotesOff (const int channel) throw();
  18716. /** Creates an all-sound-off message.
  18717. @param channel the midi channel, in the range 1 to 16
  18718. @see isAllSoundOff
  18719. */
  18720. static const MidiMessage allSoundOff (const int channel) throw();
  18721. /** Creates an all-controllers-off message.
  18722. @param channel the midi channel, in the range 1 to 16
  18723. */
  18724. static const MidiMessage allControllersOff (const int channel) throw();
  18725. /** Returns true if this event is a meta-event.
  18726. Meta-events are things like tempo changes, track names, etc.
  18727. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18728. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18729. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18730. */
  18731. bool isMetaEvent() const throw();
  18732. /** Returns a meta-event's type number.
  18733. If the message isn't a meta-event, this will return -1.
  18734. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18735. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18736. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18737. */
  18738. int getMetaEventType() const throw();
  18739. /** Returns a pointer to the data in a meta-event.
  18740. @see isMetaEvent, getMetaEventLength
  18741. */
  18742. const uint8* getMetaEventData() const throw();
  18743. /** Returns the length of the data for a meta-event.
  18744. @see isMetaEvent, getMetaEventData
  18745. */
  18746. int getMetaEventLength() const throw();
  18747. /** Returns true if this is a 'track' meta-event. */
  18748. bool isTrackMetaEvent() const throw();
  18749. /** Returns true if this is an 'end-of-track' meta-event. */
  18750. bool isEndOfTrackMetaEvent() const throw();
  18751. /** Creates an end-of-track meta-event.
  18752. @see isEndOfTrackMetaEvent
  18753. */
  18754. static const MidiMessage endOfTrack() throw();
  18755. /** Returns true if this is an 'track name' meta-event.
  18756. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18757. */
  18758. bool isTrackNameEvent() const throw();
  18759. /** Returns true if this is a 'text' meta-event.
  18760. @see getTextFromTextMetaEvent
  18761. */
  18762. bool isTextMetaEvent() const throw();
  18763. /** Returns the text from a text meta-event.
  18764. @see isTextMetaEvent
  18765. */
  18766. const String getTextFromTextMetaEvent() const throw();
  18767. /** Returns true if this is a 'tempo' meta-event.
  18768. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18769. */
  18770. bool isTempoMetaEvent() const throw();
  18771. /** Returns the tick length from a tempo meta-event.
  18772. @param timeFormat the 16-bit time format value from the midi file's header.
  18773. @returns the tick length (in seconds).
  18774. @see isTempoMetaEvent
  18775. */
  18776. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18777. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18778. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18779. */
  18780. double getTempoSecondsPerQuarterNote() const throw();
  18781. /** Creates a tempo meta-event.
  18782. @see isTempoMetaEvent
  18783. */
  18784. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18785. /** Returns true if this is a 'time-signature' meta-event.
  18786. @see getTimeSignatureInfo
  18787. */
  18788. bool isTimeSignatureMetaEvent() const throw();
  18789. /** Returns the time-signature values from a time-signature meta-event.
  18790. @see isTimeSignatureMetaEvent
  18791. */
  18792. void getTimeSignatureInfo (int& numerator,
  18793. int& denominator) const throw();
  18794. /** Creates a time-signature meta-event.
  18795. @see isTimeSignatureMetaEvent
  18796. */
  18797. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  18798. const int denominator) throw();
  18799. /** Returns true if this is a 'key-signature' meta-event.
  18800. @see getKeySignatureNumberOfSharpsOrFlats
  18801. */
  18802. bool isKeySignatureMetaEvent() const throw();
  18803. /** Returns the key from a key-signature meta-event.
  18804. @see isKeySignatureMetaEvent
  18805. */
  18806. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  18807. /** Returns true if this is a 'channel' meta-event.
  18808. A channel meta-event specifies the midi channel that should be used
  18809. for subsequent meta-events.
  18810. @see getMidiChannelMetaEventChannel
  18811. */
  18812. bool isMidiChannelMetaEvent() const throw();
  18813. /** Returns the channel number from a channel meta-event.
  18814. @returns the channel, in the range 1 to 16.
  18815. @see isMidiChannelMetaEvent
  18816. */
  18817. int getMidiChannelMetaEventChannel() const throw();
  18818. /** Creates a midi channel meta-event.
  18819. @param channel the midi channel, in the range 1 to 16
  18820. @see isMidiChannelMetaEvent
  18821. */
  18822. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  18823. /** Returns true if this is an active-sense message. */
  18824. bool isActiveSense() const throw();
  18825. /** Returns true if this is a midi start event.
  18826. @see midiStart
  18827. */
  18828. bool isMidiStart() const throw();
  18829. /** Creates a midi start event. */
  18830. static const MidiMessage midiStart() throw();
  18831. /** Returns true if this is a midi continue event.
  18832. @see midiContinue
  18833. */
  18834. bool isMidiContinue() const throw();
  18835. /** Creates a midi continue event. */
  18836. static const MidiMessage midiContinue() throw();
  18837. /** Returns true if this is a midi stop event.
  18838. @see midiStop
  18839. */
  18840. bool isMidiStop() const throw();
  18841. /** Creates a midi stop event. */
  18842. static const MidiMessage midiStop() throw();
  18843. /** Returns true if this is a midi clock event.
  18844. @see midiClock, songPositionPointer
  18845. */
  18846. bool isMidiClock() const throw();
  18847. /** Creates a midi clock event. */
  18848. static const MidiMessage midiClock() throw();
  18849. /** Returns true if this is a song-position-pointer message.
  18850. @see getSongPositionPointerMidiBeat, songPositionPointer
  18851. */
  18852. bool isSongPositionPointer() const throw();
  18853. /** Returns the midi beat-number of a song-position-pointer message.
  18854. @see isSongPositionPointer, songPositionPointer
  18855. */
  18856. int getSongPositionPointerMidiBeat() const throw();
  18857. /** Creates a song-position-pointer message.
  18858. The position is a number of midi beats from the start of the song, where 1 midi
  18859. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  18860. are 4 midi beats in a quarter-note.
  18861. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  18862. */
  18863. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  18864. /** Returns true if this is a quarter-frame midi timecode message.
  18865. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  18866. */
  18867. bool isQuarterFrame() const throw();
  18868. /** Returns the sequence number of a quarter-frame midi timecode message.
  18869. This will be a value between 0 and 7.
  18870. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  18871. */
  18872. int getQuarterFrameSequenceNumber() const throw();
  18873. /** Returns the value from a quarter-frame message.
  18874. This will be the lower nybble of the message's data-byte, a value
  18875. between 0 and 15
  18876. */
  18877. int getQuarterFrameValue() const throw();
  18878. /** Creates a quarter-frame MTC message.
  18879. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  18880. @param value a value 0 to 15 for the lower nybble of the message's data byte
  18881. */
  18882. static const MidiMessage quarterFrame (const int sequenceNumber,
  18883. const int value) throw();
  18884. /** SMPTE timecode types.
  18885. Used by the getFullFrameParameters() and fullFrame() methods.
  18886. */
  18887. enum SmpteTimecodeType
  18888. {
  18889. fps24 = 0,
  18890. fps25 = 1,
  18891. fps30drop = 2,
  18892. fps30 = 3
  18893. };
  18894. /** Returns true if this is a full-frame midi timecode message.
  18895. */
  18896. bool isFullFrame() const throw();
  18897. /** Extracts the timecode information from a full-frame midi timecode message.
  18898. You should only call this on messages where you've used isFullFrame() to
  18899. check that they're the right kind.
  18900. */
  18901. void getFullFrameParameters (int& hours,
  18902. int& minutes,
  18903. int& seconds,
  18904. int& frames,
  18905. SmpteTimecodeType& timecodeType) const throw();
  18906. /** Creates a full-frame MTC message.
  18907. */
  18908. static const MidiMessage fullFrame (const int hours,
  18909. const int minutes,
  18910. const int seconds,
  18911. const int frames,
  18912. SmpteTimecodeType timecodeType);
  18913. /** Types of MMC command.
  18914. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  18915. */
  18916. enum MidiMachineControlCommand
  18917. {
  18918. mmc_stop = 1,
  18919. mmc_play = 2,
  18920. mmc_deferredplay = 3,
  18921. mmc_fastforward = 4,
  18922. mmc_rewind = 5,
  18923. mmc_recordStart = 6,
  18924. mmc_recordStop = 7,
  18925. mmc_pause = 9
  18926. };
  18927. /** Checks whether this is an MMC message.
  18928. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  18929. */
  18930. bool isMidiMachineControlMessage() const throw();
  18931. /** For an MMC message, this returns its type.
  18932. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  18933. calling this method.
  18934. */
  18935. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  18936. /** Creates an MMC message.
  18937. */
  18938. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  18939. /** Checks whether this is an MMC "goto" message.
  18940. If it is, the parameters passed-in are set to the time that the message contains.
  18941. @see midiMachineControlGoto
  18942. */
  18943. bool isMidiMachineControlGoto (int& hours,
  18944. int& minutes,
  18945. int& seconds,
  18946. int& frames) const throw();
  18947. /** Creates an MMC "goto" message.
  18948. This messages tells the device to go to a specific frame.
  18949. @see isMidiMachineControlGoto
  18950. */
  18951. static const MidiMessage midiMachineControlGoto (int hours,
  18952. int minutes,
  18953. int seconds,
  18954. int frames);
  18955. /** Creates a master-volume change message.
  18956. @param volume the volume, 0 to 1.0
  18957. */
  18958. static const MidiMessage masterVolume (const float volume) throw();
  18959. /** Creates a system-exclusive message.
  18960. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  18961. */
  18962. static const MidiMessage createSysExMessage (const uint8* sysexData,
  18963. const int dataSize) throw();
  18964. /** Reads a midi variable-length integer.
  18965. @param data the data to read the number from
  18966. @param numBytesUsed on return, this will be set to the number of bytes that were read
  18967. */
  18968. static int readVariableLengthVal (const uint8* data,
  18969. int& numBytesUsed) throw();
  18970. /** Based on the first byte of a short midi message, this uses a lookup table
  18971. to return the message length (either 1, 2, or 3 bytes).
  18972. The value passed in must be 0x80 or higher.
  18973. */
  18974. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  18975. /** Returns the name of a midi note number.
  18976. E.g "C", "D#", etc.
  18977. @param noteNumber the midi note number, 0 to 127
  18978. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  18979. they'll be flattened, e.g. "Db"
  18980. @param includeOctaveNumber if true, the octave number will be appended to the string,
  18981. e.g. "C#4"
  18982. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  18983. number that will be used for middle C's octave
  18984. @see getMidiNoteInHertz
  18985. */
  18986. static const String getMidiNoteName (int noteNumber,
  18987. bool useSharps,
  18988. bool includeOctaveNumber,
  18989. int octaveNumForMiddleC) throw();
  18990. /** Returns the frequency of a midi note number.
  18991. @see getMidiNoteName
  18992. */
  18993. static const double getMidiNoteInHertz (int noteNumber) throw();
  18994. /** Returns the standard name of a GM instrument.
  18995. @param midiInstrumentNumber the program number 0 to 127
  18996. @see getProgramChangeNumber
  18997. */
  18998. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  18999. /** Returns the name of a bank of GM instruments.
  19000. @param midiBankNumber the bank, 0 to 15
  19001. */
  19002. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19003. /** Returns the standard name of a channel 10 percussion sound.
  19004. @param midiNoteNumber the key number, 35 to 81
  19005. */
  19006. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19007. /** Returns the name of a controller type number.
  19008. @see getControllerNumber
  19009. */
  19010. static const String getControllerName (int controllerNumber) throw();
  19011. juce_UseDebuggingNewOperator
  19012. private:
  19013. double timeStamp;
  19014. uint8* data;
  19015. int message, size;
  19016. };
  19017. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19018. /********* End of inlined file: juce_MidiMessage.h *********/
  19019. /**
  19020. Holds a sequence of time-stamped midi events.
  19021. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19022. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19023. @see MidiMessage
  19024. */
  19025. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19026. {
  19027. public:
  19028. /** Creates an empty MidiBuffer. */
  19029. MidiBuffer() throw();
  19030. /** Creates a copy of another MidiBuffer. */
  19031. MidiBuffer (const MidiBuffer& other) throw();
  19032. /** Makes a copy of another MidiBuffer. */
  19033. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19034. /** Destructor */
  19035. ~MidiBuffer() throw();
  19036. /** Removes all events from the buffer. */
  19037. void clear() throw();
  19038. /** Removes all events between two times from the buffer.
  19039. All events for which (start <= event position < start + numSamples) will
  19040. be removed.
  19041. */
  19042. void clear (const int start,
  19043. const int numSamples) throw();
  19044. /** Returns true if the buffer is empty.
  19045. To actually retrieve the events, use a MidiBuffer::Iterator object
  19046. */
  19047. bool isEmpty() const throw();
  19048. /** Counts the number of events in the buffer.
  19049. This is actually quite a slow operation, as it has to iterate through all
  19050. the events, so you might prefer to call isEmpty() if that's all you need
  19051. to know.
  19052. */
  19053. int getNumEvents() const throw();
  19054. /** Adds an event to the buffer.
  19055. The sample number will be used to determine the position of the event in
  19056. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19057. ignored.
  19058. If an event is added whose sample position is the same as one or more events
  19059. already in the buffer, the new event will be placed after the existing ones.
  19060. To retrieve events, use a MidiBuffer::Iterator object
  19061. */
  19062. void addEvent (const MidiMessage& midiMessage,
  19063. const int sampleNumber) throw();
  19064. /** Adds an event to the buffer from raw midi data.
  19065. The sample number will be used to determine the position of the event in
  19066. the buffer, which is always kept sorted.
  19067. If an event is added whose sample position is the same as one or more events
  19068. already in the buffer, the new event will be placed after the existing ones.
  19069. The event data will be inspected to calculate the number of bytes in length that
  19070. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19071. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19072. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19073. add an event at all.
  19074. To retrieve events, use a MidiBuffer::Iterator object
  19075. */
  19076. void addEvent (const uint8* const rawMidiData,
  19077. const int maxBytesOfMidiData,
  19078. const int sampleNumber) throw();
  19079. /** Adds some events from another buffer to this one.
  19080. @param otherBuffer the buffer containing the events you want to add
  19081. @param startSample the lowest sample number in the source buffer for which
  19082. events should be added. Any source events whose timestamp is
  19083. less than this will be ignored
  19084. @param numSamples the valid range of samples from the source buffer for which
  19085. events should be added - i.e. events in the source buffer whose
  19086. timestamp is greater than or equal to (startSample + numSamples)
  19087. will be ignored. If this value is less than 0, all events after
  19088. startSample will be taken.
  19089. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19090. that are added to this buffer
  19091. */
  19092. void addEvents (const MidiBuffer& otherBuffer,
  19093. const int startSample,
  19094. const int numSamples,
  19095. const int sampleDeltaToAdd) throw();
  19096. /** Returns the sample number of the first event in the buffer.
  19097. If the buffer's empty, this will just return 0.
  19098. */
  19099. int getFirstEventTime() const throw();
  19100. /** Returns the sample number of the last event in the buffer.
  19101. If the buffer's empty, this will just return 0.
  19102. */
  19103. int getLastEventTime() const throw();
  19104. /**
  19105. Used to iterate through the events in a MidiBuffer.
  19106. Note that altering the buffer while an iterator is using it isn't a
  19107. safe operation.
  19108. @see MidiBuffer
  19109. */
  19110. class Iterator
  19111. {
  19112. public:
  19113. /** Creates an Iterator for this MidiBuffer. */
  19114. Iterator (const MidiBuffer& buffer) throw();
  19115. /** Destructor. */
  19116. ~Iterator() throw();
  19117. /** Repositions the iterator so that the next event retrieved will be the first
  19118. one whose sample position is at greater than or equal to the given position.
  19119. */
  19120. void setNextSamplePosition (const int samplePosition) throw();
  19121. /** Retrieves a copy of the next event from the buffer.
  19122. @param result on return, this will be the message (the MidiMessage's timestamp
  19123. is not set)
  19124. @param samplePosition on return, this will be the position of the event
  19125. @returns true if an event was found, or false if the iterator has reached
  19126. the end of the buffer
  19127. */
  19128. bool getNextEvent (MidiMessage& result,
  19129. int& samplePosition) throw();
  19130. /** Retrieves the next event from the buffer.
  19131. @param midiData on return, this pointer will be set to a block of data containing
  19132. the midi message. Note that to make it fast, this is a pointer
  19133. directly into the MidiBuffer's internal data, so is only valid
  19134. temporarily until the MidiBuffer is altered.
  19135. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19136. midi message
  19137. @param samplePosition on return, this will be the position of the event
  19138. @returns true if an event was found, or false if the iterator has reached
  19139. the end of the buffer
  19140. */
  19141. bool getNextEvent (const uint8* &midiData,
  19142. int& numBytesOfMidiData,
  19143. int& samplePosition) throw();
  19144. juce_UseDebuggingNewOperator
  19145. private:
  19146. const MidiBuffer& buffer;
  19147. const uint8* data;
  19148. Iterator (const Iterator&);
  19149. const Iterator& operator= (const Iterator&);
  19150. };
  19151. juce_UseDebuggingNewOperator
  19152. private:
  19153. friend class MidiBuffer::Iterator;
  19154. int bytesUsed;
  19155. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19156. };
  19157. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19158. /********* End of inlined file: juce_MidiBuffer.h *********/
  19159. #endif
  19160. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19161. /********* Start of inlined file: juce_MidiFile.h *********/
  19162. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19163. #define __JUCE_MIDIFILE_JUCEHEADER__
  19164. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19165. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19166. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19167. /**
  19168. A sequence of timestamped midi messages.
  19169. This allows the sequence to be manipulated, and also to be read from and
  19170. written to a standard midi file.
  19171. @see MidiMessage, MidiFile
  19172. */
  19173. class JUCE_API MidiMessageSequence
  19174. {
  19175. public:
  19176. /** Creates an empty midi sequence object. */
  19177. MidiMessageSequence();
  19178. /** Creates a copy of another sequence. */
  19179. MidiMessageSequence (const MidiMessageSequence& other);
  19180. /** Replaces this sequence with another one. */
  19181. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19182. /** Destructor. */
  19183. ~MidiMessageSequence();
  19184. /** Structure used to hold midi events in the sequence.
  19185. These structures act as 'handles' on the events as they are moved about in
  19186. the list, and make it quick to find the matching note-offs for note-on events.
  19187. @see MidiMessageSequence::getEventPointer
  19188. */
  19189. class MidiEventHolder
  19190. {
  19191. public:
  19192. /** Destructor. */
  19193. ~MidiEventHolder();
  19194. /** The message itself, whose timestamp is used to specify the event's time.
  19195. */
  19196. MidiMessage message;
  19197. /** The matching note-off event (if this is a note-on event).
  19198. If this isn't a note-on, this pointer will be null.
  19199. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19200. note-offs up-to-date after events have been moved around in the sequence
  19201. or deleted.
  19202. */
  19203. MidiEventHolder* noteOffObject;
  19204. juce_UseDebuggingNewOperator
  19205. private:
  19206. friend class MidiMessageSequence;
  19207. MidiEventHolder (const MidiMessage& message);
  19208. };
  19209. /** Clears the sequence. */
  19210. void clear();
  19211. /** Returns the number of events in the sequence. */
  19212. int getNumEvents() const;
  19213. /** Returns a pointer to one of the events. */
  19214. MidiEventHolder* getEventPointer (const int index) const;
  19215. /** Returns the time of the note-up that matches the note-on at this index.
  19216. If the event at this index isn't a note-on, it'll just return 0.
  19217. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19218. */
  19219. double getTimeOfMatchingKeyUp (const int index) const;
  19220. /** Returns the index of the note-up that matches the note-on at this index.
  19221. If the event at this index isn't a note-on, it'll just return -1.
  19222. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19223. */
  19224. int getIndexOfMatchingKeyUp (const int index) const;
  19225. /** Returns the index of an event. */
  19226. int getIndexOf (MidiEventHolder* const event) const;
  19227. /** Returns the index of the first event on or after the given timestamp.
  19228. If the time is beyond the end of the sequence, this will return the
  19229. number of events.
  19230. */
  19231. int getNextIndexAtTime (const double timeStamp) const;
  19232. /** Returns the timestamp of the first event in the sequence.
  19233. @see getEndTime
  19234. */
  19235. double getStartTime() const;
  19236. /** Returns the timestamp of the last event in the sequence.
  19237. @see getStartTime
  19238. */
  19239. double getEndTime() const;
  19240. /** Returns the timestamp of the event at a given index.
  19241. If the index is out-of-range, this will return 0.0
  19242. */
  19243. double getEventTime (const int index) const;
  19244. /** Inserts a midi message into the sequence.
  19245. The index at which the new message gets inserted will depend on its timestamp,
  19246. because the sequence is kept sorted.
  19247. Remember to call updateMatchedPairs() after adding note-on events.
  19248. @param newMessage the new message to add (an internal copy will be made)
  19249. @param timeAdjustment an optional value to add to the timestamp of the message
  19250. that will be inserted
  19251. @see updateMatchedPairs
  19252. */
  19253. void addEvent (const MidiMessage& newMessage,
  19254. double timeAdjustment = 0);
  19255. /** Deletes one of the events in the sequence.
  19256. Remember to call updateMatchedPairs() after removing events.
  19257. @param index the index of the event to delete
  19258. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19259. if the event you're removing is a note-on
  19260. */
  19261. void deleteEvent (const int index,
  19262. const bool deleteMatchingNoteUp);
  19263. /** Merges another sequence into this one.
  19264. Remember to call updateMatchedPairs() after using this method.
  19265. @param other the sequence to add from
  19266. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19267. as they are read from the other sequence
  19268. @param firstAllowableDestTime events will not be added if their time is earlier
  19269. than this time. (This is after their time has been adjusted
  19270. by the timeAdjustmentDelta)
  19271. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19272. or greater than this time. (This is after their time has
  19273. been adjusted by the timeAdjustmentDelta)
  19274. */
  19275. void addSequence (const MidiMessageSequence& other,
  19276. double timeAdjustmentDelta,
  19277. double firstAllowableDestTime,
  19278. double endOfAllowableDestTimes);
  19279. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19280. Call this after moving messages about or deleting/adding messages, and it
  19281. will scan the list and make sure all the note-offs in the MidiEventHolder
  19282. structures are pointing at the correct ones.
  19283. */
  19284. void updateMatchedPairs();
  19285. /** Copies all the messages for a particular midi channel to another sequence.
  19286. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19287. @param destSequence the sequence that the chosen events should be copied to
  19288. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19289. channel) will also be copied across.
  19290. @see extractSysExMessages
  19291. */
  19292. void extractMidiChannelMessages (const int channelNumberToExtract,
  19293. MidiMessageSequence& destSequence,
  19294. const bool alsoIncludeMetaEvents) const;
  19295. /** Copies all midi sys-ex messages to another sequence.
  19296. @param destSequence this is the sequence to which any sys-exes in this sequence
  19297. will be added
  19298. @see extractMidiChannelMessages
  19299. */
  19300. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19301. /** Removes any messages in this sequence that have a specific midi channel.
  19302. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19303. */
  19304. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19305. /** Removes any sys-ex messages from this sequence.
  19306. */
  19307. void deleteSysExMessages();
  19308. /** Adds an offset to the timestamps of all events in the sequence.
  19309. @param deltaTime the amount to add to each timestamp.
  19310. */
  19311. void addTimeToMessages (const double deltaTime);
  19312. /** Scans through the sequence to determine the state of any midi controllers at
  19313. a given time.
  19314. This will create a sequence of midi controller changes that can be
  19315. used to set all midi controllers to the state they would be in at the
  19316. specified time within this sequence.
  19317. As well as controllers, it will also recreate the midi program number
  19318. and pitch bend position.
  19319. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19320. for other channels will be ignored.
  19321. @param time the time at which you want to find out the state - there are
  19322. no explicit units for this time measurement, it's the same units
  19323. as used for the timestamps of the messages
  19324. @param resultMessages an array to which midi controller-change messages will be added. This
  19325. will be the minimum number of controller changes to recreate the
  19326. state at the required time.
  19327. */
  19328. void createControllerUpdatesForTime (const int channelNumber,
  19329. const double time,
  19330. OwnedArray<MidiMessage>& resultMessages);
  19331. juce_UseDebuggingNewOperator
  19332. /** @internal */
  19333. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19334. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19335. private:
  19336. friend class MidiComparator;
  19337. friend class MidiFile;
  19338. OwnedArray <MidiEventHolder> list;
  19339. void sort();
  19340. };
  19341. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19342. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19343. /**
  19344. Reads/writes standard midi format files.
  19345. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19346. can then get the individual midi tracks from it using the getTrack() method.
  19347. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19348. to it using the addTrack() method, and then call its writeTo() method to stream
  19349. it out.
  19350. @see MidiMessageSequence
  19351. */
  19352. class JUCE_API MidiFile
  19353. {
  19354. public:
  19355. /** Creates an empty MidiFile object.
  19356. */
  19357. MidiFile() throw();
  19358. /** Destructor. */
  19359. ~MidiFile() throw();
  19360. /** Returns the number of tracks in the file.
  19361. @see getTrack, addTrack
  19362. */
  19363. int getNumTracks() const throw();
  19364. /** Returns a pointer to one of the tracks in the file.
  19365. @returns a pointer to the track, or 0 if the index is out-of-range
  19366. @see getNumTracks, addTrack
  19367. */
  19368. const MidiMessageSequence* getTrack (const int index) const throw();
  19369. /** Adds a midi track to the file.
  19370. This will make its own internal copy of the sequence that is passed-in.
  19371. @see getNumTracks, getTrack
  19372. */
  19373. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19374. /** Removes all midi tracks from the file.
  19375. @see getNumTracks
  19376. */
  19377. void clear() throw();
  19378. /** Returns the raw time format code that will be written to a stream.
  19379. After reading a midi file, this method will return the time-format that
  19380. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19381. or setSmpteTimeFormat() methods.
  19382. If the value returned is positive, it indicates the number of midi ticks
  19383. per quarter-note - see setTicksPerQuarterNote().
  19384. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19385. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19386. */
  19387. short getTimeFormat() const throw();
  19388. /** Sets the time format to use when this file is written to a stream.
  19389. If this is called, the file will be written as bars/beats using the
  19390. specified resolution, rather than SMPTE absolute times, as would be
  19391. used if setSmpteTimeFormat() had been called instead.
  19392. @param ticksPerQuarterNote e.g. 96, 960
  19393. @see setSmpteTimeFormat
  19394. */
  19395. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19396. /** Sets the time format to use when this file is written to a stream.
  19397. If this is called, the file will be written using absolute times, rather
  19398. than bars/beats as would be the case if setTicksPerBeat() had been called
  19399. instead.
  19400. @param framesPerSecond must be 24, 25, 29 or 30
  19401. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19402. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19403. timing, setSmpteTimeFormat (25, 40)
  19404. @see setTicksPerBeat
  19405. */
  19406. void setSmpteTimeFormat (const int framesPerSecond,
  19407. const int subframeResolution) throw();
  19408. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19409. Useful for finding the positions of all the tempo changes in a file.
  19410. @param tempoChangeEvents a list to which all the events will be added
  19411. */
  19412. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19413. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19414. Useful for finding the positions of all the tempo changes in a file.
  19415. @param timeSigEvents a list to which all the events will be added
  19416. */
  19417. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19418. /** Returns the latest timestamp in any of the tracks.
  19419. (Useful for finding the length of the file).
  19420. */
  19421. double getLastTimestamp() const;
  19422. /** Reads a midi file format stream.
  19423. After calling this, you can get the tracks that were read from the file by using the
  19424. getNumTracks() and getTrack() methods.
  19425. The timestamps of the midi events in the tracks will represent their positions in
  19426. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19427. method.
  19428. @returns true if the stream was read successfully
  19429. */
  19430. bool readFrom (InputStream& sourceStream);
  19431. /** Writes the midi tracks as a standard midi file.
  19432. @returns true if the operation succeeded.
  19433. */
  19434. bool writeTo (OutputStream& destStream);
  19435. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19436. This will use the midi time format and tempo/time signature info in the
  19437. tracks to convert all the timestamps to absolute values in seconds.
  19438. */
  19439. void convertTimestampTicksToSeconds();
  19440. juce_UseDebuggingNewOperator
  19441. /** @internal */
  19442. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19443. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19444. private:
  19445. MidiMessageSequence* tracks [128];
  19446. short numTracks, timeFormat;
  19447. MidiFile (const MidiFile&);
  19448. const MidiFile& operator= (const MidiFile&);
  19449. void readNextTrack (const char* data, int size);
  19450. void writeTrack (OutputStream& mainOut, const int trackNum);
  19451. };
  19452. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19453. /********* End of inlined file: juce_MidiFile.h *********/
  19454. #endif
  19455. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19456. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19457. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19458. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19459. class MidiKeyboardState;
  19460. /**
  19461. Receives events from a MidiKeyboardState object.
  19462. @see MidiKeyboardState
  19463. */
  19464. class JUCE_API MidiKeyboardStateListener
  19465. {
  19466. public:
  19467. MidiKeyboardStateListener() throw() {}
  19468. virtual ~MidiKeyboardStateListener() {}
  19469. /** Called when one of the MidiKeyboardState's keys is pressed.
  19470. This will be called synchronously when the state is either processing a
  19471. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19472. when a note is being played with its MidiKeyboardState::noteOn() method.
  19473. Note that this callback could happen from an audio callback thread, so be
  19474. careful not to block, and avoid any UI activity in the callback.
  19475. */
  19476. virtual void handleNoteOn (MidiKeyboardState* source,
  19477. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19478. /** Called when one of the MidiKeyboardState's keys is released.
  19479. This will be called synchronously when the state is either processing a
  19480. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19481. when a note is being played with its MidiKeyboardState::noteOff() method.
  19482. Note that this callback could happen from an audio callback thread, so be
  19483. careful not to block, and avoid any UI activity in the callback.
  19484. */
  19485. virtual void handleNoteOff (MidiKeyboardState* source,
  19486. int midiChannel, int midiNoteNumber) = 0;
  19487. };
  19488. /**
  19489. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19490. This object can parse a stream of midi events, using them to update its idea
  19491. of which keys are pressed for each individiual midi channel.
  19492. When keys go up or down, it can broadcast these events to listener objects.
  19493. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19494. methods, and midi messages for these events will be merged into the
  19495. midi stream that gets processed by processNextMidiBuffer().
  19496. */
  19497. class JUCE_API MidiKeyboardState
  19498. {
  19499. public:
  19500. MidiKeyboardState();
  19501. ~MidiKeyboardState();
  19502. /** Resets the state of the object.
  19503. All internal data for all the channels is reset, but no events are sent as a
  19504. result.
  19505. If you want to release any keys that are currently down, and to send out note-up
  19506. midi messages for this, use the allNotesOff() method instead.
  19507. */
  19508. void reset();
  19509. /** Returns true if the given midi key is currently held down for the given midi channel.
  19510. The channel number must be between 1 and 16. If you want to see if any notes are
  19511. on for a range of channels, use the isNoteOnForChannels() method.
  19512. */
  19513. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19514. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19515. The channel mask has a bit set for each midi channel you want to test for - bit
  19516. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19517. If a note is on for at least one of the specified channels, this returns true.
  19518. */
  19519. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19520. /** Turns a specified note on.
  19521. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19522. next call to processNextMidiBuffer().
  19523. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19524. gone down.
  19525. */
  19526. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19527. /** Turns a specified note off.
  19528. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19529. next call to processNextMidiBuffer().
  19530. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19531. gone up.
  19532. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19533. */
  19534. void noteOff (const int midiChannel, const int midiNoteNumber);
  19535. /** This will turn off any currently-down notes for the given midi channel.
  19536. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19537. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19538. and events being added to the midi stream.
  19539. */
  19540. void allNotesOff (const int midiChannel);
  19541. /** Looks at a key-up/down event and uses it to update the state of this object.
  19542. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19543. instead.
  19544. */
  19545. void processNextMidiEvent (const MidiMessage& message);
  19546. /** Scans a midi stream for up/down events and adds its own events to it.
  19547. This will look for any up/down events and use them to update the internal state,
  19548. synchronously making suitable callbacks to the listeners.
  19549. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19550. and noteOff() calls will be added into the buffer.
  19551. Only the section of the buffer whose timestamps are between startSample and
  19552. (startSample + numSamples) will be affected, and any events added will be placed
  19553. between these times.
  19554. If you're going to use this method, you'll need to keep calling it regularly for
  19555. it to work satisfactorily.
  19556. To process a single midi event at a time, use the processNextMidiEvent() method
  19557. instead.
  19558. */
  19559. void processNextMidiBuffer (MidiBuffer& buffer,
  19560. const int startSample,
  19561. const int numSamples,
  19562. const bool injectIndirectEvents);
  19563. /** Registers a listener for callbacks when keys go up or down.
  19564. @see removeListener
  19565. */
  19566. void addListener (MidiKeyboardStateListener* const listener) throw();
  19567. /** Deregisters a listener.
  19568. @see addListener
  19569. */
  19570. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19571. juce_UseDebuggingNewOperator
  19572. private:
  19573. CriticalSection lock;
  19574. uint16 noteStates [128];
  19575. MidiBuffer eventsToAdd;
  19576. VoidArray listeners;
  19577. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19578. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19579. MidiKeyboardState (const MidiKeyboardState&);
  19580. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19581. };
  19582. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19583. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19584. #endif
  19585. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19586. #endif
  19587. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19588. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19589. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19590. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19591. /********* Start of inlined file: juce_MidiInput.h *********/
  19592. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19593. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19594. class MidiInput;
  19595. /**
  19596. Receives midi messages from a midi input device.
  19597. This class is overridden to handle incoming midi messages. See the MidiInput
  19598. class for more details.
  19599. @see MidiInput
  19600. */
  19601. class JUCE_API MidiInputCallback
  19602. {
  19603. public:
  19604. /** Destructor. */
  19605. virtual ~MidiInputCallback() {}
  19606. /** Receives an incoming message.
  19607. A MidiInput object will call this method when a midi event arrives. It'll be
  19608. called on a high-priority system thread, so avoid doing anything time-consuming
  19609. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19610. for queueing incoming messages for use later.
  19611. @param source the MidiInput object that generated the message
  19612. @param message the incoming message. The message's timestamp is set to a value
  19613. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19614. time when the message arrived.
  19615. */
  19616. virtual void handleIncomingMidiMessage (MidiInput* source,
  19617. const MidiMessage& message) = 0;
  19618. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19619. If a long sysex message is broken up into multiple packets, this callback is made
  19620. for each packet that arrives until the message is finished, at which point
  19621. the normal handleIncomingMidiMessage() callback will be made with the entire
  19622. message.
  19623. The message passed in will contain the start of a sysex, but won't be finished
  19624. with the terminating 0xf7 byte.
  19625. */
  19626. virtual void handlePartialSysexMessage (MidiInput* source,
  19627. const uint8* messageData,
  19628. const int numBytesSoFar,
  19629. const double timestamp)
  19630. {
  19631. // (this bit is just to avoid compiler warnings about unused variables)
  19632. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19633. }
  19634. };
  19635. /**
  19636. Represents a midi input device.
  19637. To create one of these, use the static getDevices() method to find out what inputs are
  19638. available, and then use the openDevice() method to try to open one.
  19639. @see MidiOutput
  19640. */
  19641. class JUCE_API MidiInput
  19642. {
  19643. public:
  19644. /** Returns a list of the available midi input devices.
  19645. You can open one of the devices by passing its index into the
  19646. openDevice() method.
  19647. @see getDefaultDeviceIndex, openDevice
  19648. */
  19649. static const StringArray getDevices();
  19650. /** Returns the index of the default midi input device to use.
  19651. This refers to the index in the list returned by getDevices().
  19652. */
  19653. static int getDefaultDeviceIndex();
  19654. /** Tries to open one of the midi input devices.
  19655. This will return a MidiInput object if it manages to open it. You can then
  19656. call start() and stop() on this device, and delete it when no longer needed.
  19657. If the device can't be opened, this will return a null pointer.
  19658. @param deviceIndex the index of a device from the list returned by getDevices()
  19659. @param callback the object that will receive the midi messages from this device.
  19660. @see MidiInputCallback, getDevices
  19661. */
  19662. static MidiInput* openDevice (int deviceIndex,
  19663. MidiInputCallback* callback);
  19664. #if JUCE_LINUX || DOXYGEN
  19665. /** LINUX ONLY - This will try to create a new midi input device.
  19666. This will attempt to create a new midi input device with the specified name,
  19667. for other apps to connect to.
  19668. Returns 0 if a device can't be created.
  19669. @param deviceName the name to use for the new device
  19670. @param callback the object that will receive the midi messages from this device.
  19671. */
  19672. static MidiInput* createNewDevice (const String& deviceName,
  19673. MidiInputCallback* callback);
  19674. #endif
  19675. /** Destructor. */
  19676. ~MidiInput();
  19677. /** Returns the name of this device.
  19678. */
  19679. const String getName() const throw() { return name; }
  19680. /** Allows you to set a custom name for the device, in case you don't like the name
  19681. it was given when created.
  19682. */
  19683. void setName (const String& newName) throw() { name = newName; }
  19684. /** Starts the device running.
  19685. After calling this, the device will start sending midi messages to the
  19686. MidiInputCallback object that was specified when the openDevice() method
  19687. was called.
  19688. @see stop
  19689. */
  19690. void start();
  19691. /** Stops the device running.
  19692. @see start
  19693. */
  19694. void stop();
  19695. juce_UseDebuggingNewOperator
  19696. private:
  19697. String name;
  19698. void* internal;
  19699. MidiInput (const String& name);
  19700. MidiInput (const MidiInput&);
  19701. };
  19702. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19703. /********* End of inlined file: juce_MidiInput.h *********/
  19704. /**
  19705. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19706. processing by a block-based audio callback.
  19707. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19708. so it can easily use a midi input or keyboard component as its source.
  19709. @see MidiMessage, MidiInput
  19710. */
  19711. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19712. public MidiInputCallback
  19713. {
  19714. public:
  19715. /** Creates a MidiMessageCollector. */
  19716. MidiMessageCollector();
  19717. /** Destructor. */
  19718. ~MidiMessageCollector();
  19719. /** Clears any messages from the queue.
  19720. You need to call this method before starting to use the collector, so that
  19721. it knows the correct sample rate to use.
  19722. */
  19723. void reset (const double sampleRate);
  19724. /** Takes an incoming real-time message and adds it to the queue.
  19725. The message's timestamp is taken, and it will be ready for retrieval as part
  19726. of the block returned by the next call to removeNextBlockOfMessages().
  19727. This method is fully thread-safe when overlapping calls are made with
  19728. removeNextBlockOfMessages().
  19729. */
  19730. void addMessageToQueue (const MidiMessage& message);
  19731. /** Removes all the pending messages from the queue as a buffer.
  19732. This will also correct the messages' timestamps to make sure they're in
  19733. the range 0 to numSamples - 1.
  19734. This call should be made regularly by something like an audio processing
  19735. callback, because the time that it happens is used in calculating the
  19736. midi event positions.
  19737. This method is fully thread-safe when overlapping calls are made with
  19738. addMessageToQueue().
  19739. */
  19740. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19741. const int numSamples);
  19742. /** @internal */
  19743. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19744. /** @internal */
  19745. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19746. /** @internal */
  19747. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19748. juce_UseDebuggingNewOperator
  19749. private:
  19750. double lastCallbackTime;
  19751. CriticalSection midiCallbackLock;
  19752. MidiBuffer incomingMessages;
  19753. double sampleRate;
  19754. MidiMessageCollector (const MidiMessageCollector&);
  19755. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19756. };
  19757. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19758. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19759. #endif
  19760. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19761. #endif
  19762. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19763. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19764. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19765. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19766. /**
  19767. A set of routines to convert buffers of 32-bit floating point data to and from
  19768. various integer formats.
  19769. */
  19770. class JUCE_API AudioDataConverters
  19771. {
  19772. public:
  19773. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19774. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19775. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19776. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19777. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19778. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19779. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19780. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19781. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19782. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19783. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19784. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19785. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19786. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19787. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19788. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19789. enum DataFormat
  19790. {
  19791. int16LE,
  19792. int16BE,
  19793. int24LE,
  19794. int24BE,
  19795. int32LE,
  19796. int32BE,
  19797. float32LE,
  19798. float32BE,
  19799. };
  19800. static void convertFloatToFormat (const DataFormat destFormat,
  19801. const float* source, void* dest, int numSamples);
  19802. static void convertFormatToFloat (const DataFormat sourceFormat,
  19803. const void* source, float* dest, int numSamples);
  19804. static void interleaveSamples (const float** source, float* dest,
  19805. const int numSamples, const int numChannels);
  19806. static void deinterleaveSamples (const float* source, float** dest,
  19807. const int numSamples, const int numChannels);
  19808. };
  19809. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19810. /********* End of inlined file: juce_AudioDataConverters.h *********/
  19811. #endif
  19812. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19813. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  19814. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19815. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19816. class AudioFormatReader;
  19817. class AudioFormatWriter;
  19818. /**
  19819. A multi-channel buffer of 32-bit floating point audio samples.
  19820. */
  19821. class JUCE_API AudioSampleBuffer
  19822. {
  19823. public:
  19824. /** Creates a buffer with a specified number of channels and samples.
  19825. The contents of the buffer will initially be undefined, so use clear() to
  19826. set all the samples to zero.
  19827. The buffer will allocate its memory internally, and this will be released
  19828. when the buffer is deleted.
  19829. */
  19830. AudioSampleBuffer (const int numChannels,
  19831. const int numSamples) throw();
  19832. /** Creates a buffer using a pre-allocated block of memory.
  19833. Note that if the buffer is resized or its number of channels is changed, it
  19834. will re-allocate memory internally and copy the existing data to this new area,
  19835. so it will then stop directly addressing this memory.
  19836. @param dataToReferTo a pre-allocated array containing pointers to the data
  19837. for each channel that should be used by this buffer. The
  19838. buffer will only refer to this memory, it won't try to delete
  19839. it when the buffer is deleted or resized.
  19840. @param numChannels the number of channels to use - this must correspond to the
  19841. number of elements in the array passed in
  19842. @param numSamples the number of samples to use - this must correspond to the
  19843. size of the arrays passed in
  19844. */
  19845. AudioSampleBuffer (float** dataToReferTo,
  19846. const int numChannels,
  19847. const int numSamples) throw();
  19848. /** Copies another buffer.
  19849. This buffer will make its own copy of the other's data, unless the buffer was created
  19850. using an external data buffer, in which case boths buffers will just point to the same
  19851. shared block of data.
  19852. */
  19853. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  19854. /** Copies another buffer onto this one.
  19855. This buffer's size will be changed to that of the other buffer.
  19856. */
  19857. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  19858. /** Destructor.
  19859. This will free any memory allocated by the buffer.
  19860. */
  19861. virtual ~AudioSampleBuffer() throw();
  19862. /** Returns the number of channels of audio data that this buffer contains.
  19863. @see getSampleData
  19864. */
  19865. int getNumChannels() const throw() { return numChannels; }
  19866. /** Returns the number of samples allocated in each of the buffer's channels.
  19867. @see getSampleData
  19868. */
  19869. int getNumSamples() const throw() { return size; }
  19870. /** Returns a pointer to a sample in one of the buffer's channels.
  19871. For speed, this doesn't check whether the channel and sample number
  19872. are legal, so be careful when using it!
  19873. */
  19874. float* getSampleData (const int channelNumber,
  19875. const int sampleOffset = 0) const throw();
  19876. /** Chages the buffer's size or number of channels.
  19877. This can expand or contract the buffer's length, and add or remove channels.
  19878. If keepExistingContent is true, it will try to preserve as much of the
  19879. old data as it can in the new buffer.
  19880. If clearExtraSpace is true, then any extra channels or space that is
  19881. allocated will be also be cleared. If false, then this space is left
  19882. uninitialised.
  19883. If avoidReallocating is true, then changing the buffer's size won't reduce the
  19884. amount of memory that is currently allocated (but it will still increase it if
  19885. the new size is bigger than the amount it currently has). If this is false, then
  19886. a new allocation will be done so that the buffer uses takes up the minimum amount
  19887. of memory that it needs.
  19888. */
  19889. void setSize (const int newNumChannels,
  19890. const int newNumSamples,
  19891. const bool keepExistingContent = false,
  19892. const bool clearExtraSpace = false,
  19893. const bool avoidReallocating = false) throw();
  19894. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  19895. There's also a constructor that lets you specify arrays like this, but this
  19896. lets you change the channels dynamically.
  19897. Note that if the buffer is resized or its number of channels is changed, it
  19898. will re-allocate memory internally and copy the existing data to this new area,
  19899. so it will then stop directly addressing this memory.
  19900. @param dataToReferTo a pre-allocated array containing pointers to the data
  19901. for each channel that should be used by this buffer. The
  19902. buffer will only refer to this memory, it won't try to delete
  19903. it when the buffer is deleted or resized.
  19904. @param numChannels the number of channels to use - this must correspond to the
  19905. number of elements in the array passed in
  19906. @param numSamples the number of samples to use - this must correspond to the
  19907. size of the arrays passed in
  19908. */
  19909. void setDataToReferTo (float** dataToReferTo,
  19910. const int numChannels,
  19911. const int numSamples) throw();
  19912. /** Clears all the samples in all channels. */
  19913. void clear() throw();
  19914. /** Clears a specified region of all the channels.
  19915. For speed, this doesn't check whether the channel and sample number
  19916. are in-range, so be careful!
  19917. */
  19918. void clear (const int startSample,
  19919. const int numSamples) throw();
  19920. /** Clears a specified region of just one channel.
  19921. For speed, this doesn't check whether the channel and sample number
  19922. are in-range, so be careful!
  19923. */
  19924. void clear (const int channel,
  19925. const int startSample,
  19926. const int numSamples) throw();
  19927. /** Applies a gain multiple to a region of one channel.
  19928. For speed, this doesn't check whether the channel and sample number
  19929. are in-range, so be careful!
  19930. */
  19931. void applyGain (const int channel,
  19932. const int startSample,
  19933. int numSamples,
  19934. const float gain) throw();
  19935. /** Applies a gain multiple to a region of all the channels.
  19936. For speed, this doesn't check whether the sample numbers
  19937. are in-range, so be careful!
  19938. */
  19939. void applyGain (const int startSample,
  19940. const int numSamples,
  19941. const float gain) throw();
  19942. /** Applies a range of gains to a region of a channel.
  19943. The gain that is applied to each sample will vary from
  19944. startGain on the first sample to endGain on the last Sample,
  19945. so it can be used to do basic fades.
  19946. For speed, this doesn't check whether the sample numbers
  19947. are in-range, so be careful!
  19948. */
  19949. void applyGainRamp (const int channel,
  19950. const int startSample,
  19951. int numSamples,
  19952. float startGain,
  19953. float endGain) throw();
  19954. /** Adds samples from another buffer to this one.
  19955. @param destChannel the channel within this buffer to add the samples to
  19956. @param destStartSample the start sample within this buffer's channel
  19957. @param source the source buffer to add from
  19958. @param sourceChannel the channel within the source buffer to read from
  19959. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  19960. @param numSamples the number of samples to process
  19961. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  19962. added to this buffer's samples
  19963. @see copyFrom
  19964. */
  19965. void addFrom (const int destChannel,
  19966. const int destStartSample,
  19967. const AudioSampleBuffer& source,
  19968. const int sourceChannel,
  19969. const int sourceStartSample,
  19970. int numSamples,
  19971. const float gainToApplyToSource = 1.0f) throw();
  19972. /** Adds samples from an array of floats to one of the channels.
  19973. @param destChannel the channel within this buffer to add the samples to
  19974. @param destStartSample the start sample within this buffer's channel
  19975. @param source the source data to use
  19976. @param numSamples the number of samples to process
  19977. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  19978. added to this buffer's samples
  19979. @see copyFrom
  19980. */
  19981. void addFrom (const int destChannel,
  19982. const int destStartSample,
  19983. const float* source,
  19984. int numSamples,
  19985. const float gainToApplyToSource = 1.0f) throw();
  19986. /** Adds samples from an array of floats, applying a gain ramp to them.
  19987. @param destChannel the channel within this buffer to add the samples to
  19988. @param destStartSample the start sample within this buffer's channel
  19989. @param source the source data to use
  19990. @param numSamples the number of samples to process
  19991. @param startGain the gain to apply to the first sample (this is multiplied with
  19992. the source samples before they are added to this buffer)
  19993. @param endGain the gain to apply to the final sample. The gain is linearly
  19994. interpolated between the first and last samples.
  19995. */
  19996. void addFromWithRamp (const int destChannel,
  19997. const int destStartSample,
  19998. const float* source,
  19999. int numSamples,
  20000. float startGain,
  20001. float endGain) throw();
  20002. /** Copies samples from another buffer to this one.
  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 sourceChannel the channel within the source buffer to read from
  20007. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20008. @param numSamples the number of samples to process
  20009. @see addFrom
  20010. */
  20011. void copyFrom (const int destChannel,
  20012. const int destStartSample,
  20013. const AudioSampleBuffer& source,
  20014. const int sourceChannel,
  20015. const int sourceStartSample,
  20016. int numSamples) throw();
  20017. /** Copies samples from an array of floats into one of the channels.
  20018. @param destChannel the channel within this buffer to copy the samples to
  20019. @param destStartSample the start sample within this buffer's channel
  20020. @param source the source buffer to read from
  20021. @param numSamples the number of samples to process
  20022. @see addFrom
  20023. */
  20024. void copyFrom (const int destChannel,
  20025. const int destStartSample,
  20026. const float* source,
  20027. int numSamples) throw();
  20028. /** Finds the highest and lowest sample values in a given range.
  20029. @param channel the channel to read from
  20030. @param startSample the start sample within the channel
  20031. @param numSamples the number of samples to check
  20032. @param minVal on return, the lowest value that was found
  20033. @param maxVal on return, the highest value that was found
  20034. */
  20035. void findMinMax (const int channel,
  20036. const int startSample,
  20037. int numSamples,
  20038. float& minVal,
  20039. float& maxVal) const throw();
  20040. /** Finds the highest absolute sample value within a region of a channel.
  20041. */
  20042. float getMagnitude (const int channel,
  20043. const int startSample,
  20044. const int numSamples) const throw();
  20045. /** Finds the highest absolute sample value within a region on all channels.
  20046. */
  20047. float getMagnitude (const int startSample,
  20048. const int numSamples) const throw();
  20049. /** Returns the root mean squared level for a region of a channel.
  20050. */
  20051. float getRMSLevel (const int channel,
  20052. const int startSample,
  20053. const int numSamples) const throw();
  20054. /** Fills a section of the buffer using an AudioReader as its source.
  20055. This will convert the reader's fixed- or floating-point data to
  20056. the buffer's floating-point format, and will try to intelligently
  20057. cope with mismatches between the number of channels in the reader
  20058. and the buffer.
  20059. @see writeToAudioWriter
  20060. */
  20061. void readFromAudioReader (AudioFormatReader* reader,
  20062. const int startSample,
  20063. const int numSamples,
  20064. const int readerStartSample,
  20065. const bool useReaderLeftChan,
  20066. const bool useReaderRightChan) throw();
  20067. /** Writes a section of this buffer to an audio writer.
  20068. This saves you having to mess about with channels or floating/fixed
  20069. point conversion.
  20070. @see readFromAudioReader
  20071. */
  20072. void writeToAudioWriter (AudioFormatWriter* writer,
  20073. const int startSample,
  20074. const int numSamples) const throw();
  20075. juce_UseDebuggingNewOperator
  20076. private:
  20077. int numChannels, size, allocatedBytes;
  20078. float** channels;
  20079. float* allocatedData;
  20080. };
  20081. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20082. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20083. #endif
  20084. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20085. /********* Start of inlined file: juce_IIRFilter.h *********/
  20086. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20087. #define __JUCE_IIRFILTER_JUCEHEADER__
  20088. /**
  20089. An IIR filter that can perform low, high, or band-pass filtering on an
  20090. audio signal.
  20091. @see IIRFilterAudioSource
  20092. */
  20093. class JUCE_API IIRFilter
  20094. {
  20095. public:
  20096. /** Creates a filter.
  20097. Initially the filter is inactive, so will have no effect on samples that
  20098. you process with it. Use the appropriate method to turn it into the type
  20099. of filter needed.
  20100. */
  20101. IIRFilter() throw();
  20102. /** Creates a copy of another filter. */
  20103. IIRFilter (const IIRFilter& other) throw();
  20104. /** Destructor. */
  20105. ~IIRFilter() throw();
  20106. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20107. Note that this clears the processing state, but the type of filter and
  20108. its coefficients aren't changed. To put a filter into an inactive state, use
  20109. the makeInactive() method.
  20110. */
  20111. void reset() throw();
  20112. /** Performs the filter operation on the given set of samples.
  20113. */
  20114. void processSamples (float* const samples,
  20115. const int numSamples) throw();
  20116. /** Processes a single sample, without any locking or checking.
  20117. Use this if you need fast processing of a single value, but be aware that
  20118. this isn't thread-safe in the way that processSamples() is.
  20119. */
  20120. float processSingleSampleRaw (const float sample) throw();
  20121. /** Sets the filter up to act as a low-pass filter.
  20122. */
  20123. void makeLowPass (const double sampleRate,
  20124. const double frequency) throw();
  20125. /** Sets the filter up to act as a high-pass filter.
  20126. */
  20127. void makeHighPass (const double sampleRate,
  20128. const double frequency) throw();
  20129. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20130. The gain is a scale factor that the low frequencies are multiplied by, so values
  20131. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20132. attenuate them.
  20133. */
  20134. void makeLowShelf (const double sampleRate,
  20135. const double cutOffFrequency,
  20136. const double Q,
  20137. const float gainFactor) throw();
  20138. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20139. The gain is a scale factor that the high frequencies are multiplied by, so values
  20140. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20141. attenuate them.
  20142. */
  20143. void makeHighShelf (const double sampleRate,
  20144. const double cutOffFrequency,
  20145. const double Q,
  20146. const float gainFactor) throw();
  20147. /** Sets the filter up to act as a band pass filter centred around a
  20148. frequency, with a variable Q and gain.
  20149. The gain is a scale factor that the centre frequencies are multiplied by, so
  20150. values greater than 1.0 will boost the centre frequencies, values less than
  20151. 1.0 will attenuate them.
  20152. */
  20153. void makeBandPass (const double sampleRate,
  20154. const double centreFrequency,
  20155. const double Q,
  20156. const float gainFactor) throw();
  20157. /** Clears the filter's coefficients so that it becomes inactive.
  20158. */
  20159. void makeInactive() throw();
  20160. /** Makes this filter duplicate the set-up of another one.
  20161. */
  20162. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20163. juce_UseDebuggingNewOperator
  20164. protected:
  20165. CriticalSection processLock;
  20166. void setCoefficients (double c1, double c2, double c3,
  20167. double c4, double c5, double c6) throw();
  20168. bool active;
  20169. float coefficients[6];
  20170. float x1, x2, y1, y2;
  20171. // (use the copyCoefficientsFrom() method instead of this operator)
  20172. const IIRFilter& operator= (const IIRFilter&);
  20173. };
  20174. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20175. /********* End of inlined file: juce_IIRFilter.h *********/
  20176. #endif
  20177. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20178. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20179. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20180. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20181. /**
  20182. A subclass of AudioPlayHead can supply information about the position and
  20183. status of a moving play head during audio playback.
  20184. One of these can be supplied to an AudioProcessor object so that it can find
  20185. out about the position of the audio that it is rendering.
  20186. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20187. */
  20188. class JUCE_API AudioPlayHead
  20189. {
  20190. protected:
  20191. AudioPlayHead() {}
  20192. public:
  20193. virtual ~AudioPlayHead() {}
  20194. /** Frame rate types. */
  20195. enum FrameRateType
  20196. {
  20197. fps24 = 0,
  20198. fps25 = 1,
  20199. fps2997 = 2,
  20200. fps30 = 3,
  20201. fps2997drop = 4,
  20202. fps30drop = 5,
  20203. fpsUnknown = 99
  20204. };
  20205. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20206. */
  20207. struct CurrentPositionInfo
  20208. {
  20209. /** The tempo in BPM */
  20210. double bpm;
  20211. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20212. int timeSigNumerator;
  20213. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20214. int timeSigDenominator;
  20215. /** The current play position, in seconds from the start of the edit. */
  20216. double timeInSeconds;
  20217. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20218. double editOriginTime;
  20219. /** The current play position in pulses-per-quarter-note.
  20220. This is the number of quarter notes since the edit start.
  20221. */
  20222. double ppqPosition;
  20223. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20224. This is the number of quarter notes from the start of the edit to the
  20225. start of the current bar.
  20226. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20227. it's not available, the value will be 0.
  20228. */
  20229. double ppqPositionOfLastBarStart;
  20230. /** The video frame rate, if applicable. */
  20231. FrameRateType frameRate;
  20232. /** True if the transport is currently playing. */
  20233. bool isPlaying;
  20234. /** True if the transport is currently recording.
  20235. (When isRecording is true, then isPlaying will also be true).
  20236. */
  20237. bool isRecording;
  20238. };
  20239. /** Fills-in the given structure with details about the transport's
  20240. position at the start of the current processing block.
  20241. */
  20242. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20243. };
  20244. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20245. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20246. #endif
  20247. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20248. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20249. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20250. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20251. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20252. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20253. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20254. class AudioProcessor;
  20255. /**
  20256. Base class for the component that acts as the GUI for an AudioProcessor.
  20257. Derive your editor component from this class, and create an instance of it
  20258. by overriding the AudioProcessor::createEditor() method.
  20259. @see AudioProcessor, GenericAudioProcessorEditor
  20260. */
  20261. class JUCE_API AudioProcessorEditor : public Component
  20262. {
  20263. protected:
  20264. /** Creates an editor for the specified processor.
  20265. */
  20266. AudioProcessorEditor (AudioProcessor* const owner);
  20267. public:
  20268. /** Destructor. */
  20269. ~AudioProcessorEditor();
  20270. /** Returns a pointer to the processor that this editor represents. */
  20271. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20272. private:
  20273. AudioProcessor* const owner;
  20274. };
  20275. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20276. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20277. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20278. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20279. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20280. class AudioProcessor;
  20281. /**
  20282. Base class for listeners that want to know about changes to an AudioProcessor.
  20283. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20284. @see AudioProcessor
  20285. */
  20286. class JUCE_API AudioProcessorListener
  20287. {
  20288. public:
  20289. /** Destructor. */
  20290. virtual ~AudioProcessorListener() {}
  20291. /** Receives a callback when a parameter is changed.
  20292. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20293. many audio processors will change their parameter during their audio callback.
  20294. This means that not only has your handler code got to be completely thread-safe,
  20295. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20296. this event on your message thread, use this callback to trigger an AsyncUpdater
  20297. or ChangeBroadcaster which you can respond to on the message thread.
  20298. */
  20299. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20300. int parameterIndex,
  20301. float newValue) = 0;
  20302. /** Called to indicate that something else in the plugin has changed, like its
  20303. program, number of parameters, etc.
  20304. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20305. call it during their audio callback. This means that not only has your handler code
  20306. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20307. blocking. If you need to handle this event on your message thread, use this callback
  20308. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20309. message thread.
  20310. */
  20311. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20312. /** Indicates that a parameter change gesture has started.
  20313. E.g. if the user is dragging a slider, this would be called when they first
  20314. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20315. called when they release it.
  20316. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20317. call it during their audio callback. This means that not only has your handler code
  20318. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20319. blocking. If you need to handle this event on your message thread, use this callback
  20320. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20321. message thread.
  20322. @see audioProcessorParameterChangeGestureEnd
  20323. */
  20324. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20325. int parameterIndex);
  20326. /** Indicates that a parameter change gesture has finished.
  20327. E.g. if the user is dragging a slider, this would be called when they release
  20328. the mouse button.
  20329. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20330. call it during their audio callback. This means that not only has your handler code
  20331. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20332. blocking. If you need to handle this event on your message thread, use this callback
  20333. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20334. message thread.
  20335. @see audioPluginParameterChangeGestureStart
  20336. */
  20337. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20338. int parameterIndex);
  20339. };
  20340. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20341. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20342. /**
  20343. Base class for audio processing filters or plugins.
  20344. This is intended to act as a base class of audio filter that is general enough to
  20345. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20346. It is also used by the plugin hosting code as the wrapper around an instance
  20347. of a loaded plugin.
  20348. Derive your filter class from this base class, and if you're building a plugin,
  20349. you should implement a global function called createPluginFilter() which creates
  20350. and returns a new instance of your subclass.
  20351. */
  20352. class JUCE_API AudioProcessor
  20353. {
  20354. protected:
  20355. /** Constructor.
  20356. You can also do your initialisation tasks in the initialiseFilterInfo()
  20357. call, which will be made after this object has been created.
  20358. */
  20359. AudioProcessor();
  20360. public:
  20361. /** Destructor. */
  20362. virtual ~AudioProcessor();
  20363. /** Returns the name of this processor.
  20364. */
  20365. virtual const String getName() const = 0;
  20366. /** Called before playback starts, to let the filter prepare itself.
  20367. The sample rate is the target sample rate, and will remain constant until
  20368. playback stops.
  20369. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20370. samples that will be processed for each callback, but isn't any kind
  20371. of guarantee. The actual block sizes that the host uses may be different
  20372. each time the callback happens, and may be more or less than this value.
  20373. */
  20374. virtual void prepareToPlay (double sampleRate,
  20375. int estimatedSamplesPerBlock) = 0;
  20376. /** Called after playback has stopped, to let the filter free up any resources it
  20377. no longer needs.
  20378. */
  20379. virtual void releaseResources() = 0;
  20380. /** Renders the next block.
  20381. When this method is called, the buffer contains a number of channels which is
  20382. at least as great as the maximum number of input and output channels that
  20383. this filter is using. It will be filled with the filter's input data and
  20384. should be replaced with the filter's output.
  20385. So for example if your filter has 2 input channels and 4 output channels, then
  20386. the buffer will contain 4 channels, the first two being filled with the
  20387. input data. Your filter should read these, do its processing, and replace
  20388. the contents of all 4 channels with its output.
  20389. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20390. all filled with data, and your filter should overwrite the first 2 of these
  20391. with its output. But be VERY careful not to write anything to the last 3
  20392. channels, as these might be mapped to memory that the host assumes is read-only!
  20393. Note that if you have more outputs than inputs, then only those channels that
  20394. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20395. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20396. but the last two channels may contain garbage, so you should be careful not to
  20397. let this pass through without being overwritten or cleared.
  20398. Also note that the buffer may have more channels than are strictly necessary,
  20399. but your should only read/write from the ones that your filter is supposed to
  20400. be using.
  20401. The number of samples in these buffers is NOT guaranteed to be the same for every
  20402. callback, and may be more or less than the estimated value given to prepareToPlay().
  20403. Your code must be able to cope with variable-sized blocks, or you're going to get
  20404. clicks and crashes!
  20405. If the filter is receiving a midi input, then the midiMessages array will be filled
  20406. with the midi messages for this block. Each message's timestamp will indicate the
  20407. message's time, as a number of samples from the start of the block.
  20408. Any messages left in the midi buffer when this method has finished are assumed to
  20409. be the filter's midi output. This means that your filter should be careful to
  20410. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20411. Be very careful about what you do in this callback - it's going to be called by
  20412. the audio thread, so any kind of interaction with the UI is absolutely
  20413. out of the question. If you change a parameter in here and need to tell your UI to
  20414. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20415. the UI components register as listeners, and then call sendChangeMessage() inside the
  20416. processBlock() method to send out an asynchronous message. You could also use
  20417. the AsyncUpdater class in a similar way.
  20418. */
  20419. virtual void processBlock (AudioSampleBuffer& buffer,
  20420. MidiBuffer& midiMessages) = 0;
  20421. /** Returns the current AudioPlayHead object that should be used to find
  20422. out the state and position of the playhead.
  20423. You can call this from your processBlock() method, and use the AudioPlayHead
  20424. object to get the details about the time of the start of the block currently
  20425. being processed.
  20426. If the host hasn't supplied a playhead object, this will return 0.
  20427. */
  20428. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20429. /** Returns the current sample rate.
  20430. This can be called from your processBlock() method - it's not guaranteed
  20431. to be valid at any other time, and may return 0 if it's unknown.
  20432. */
  20433. double getSampleRate() const throw() { return sampleRate; }
  20434. /** Returns the current typical block size that is being used.
  20435. This can be called from your processBlock() method - it's not guaranteed
  20436. to be valid at any other time.
  20437. Remember it's not the ONLY block size that may be used when calling
  20438. processBlock, it's just the normal one. The actual block sizes used may be
  20439. larger or smaller than this, and will vary between successive calls.
  20440. */
  20441. int getBlockSize() const throw() { return blockSize; }
  20442. /** Returns the number of input channels that the host will be sending the filter.
  20443. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20444. number of channels that your filter would prefer to have, and this method lets
  20445. you know how many the host is actually using.
  20446. Note that this method is only valid during or after the prepareToPlay()
  20447. method call. Until that point, the number of channels will be unknown.
  20448. */
  20449. int getNumInputChannels() const throw() { return numInputChannels; }
  20450. /** Returns the number of output channels that the host will be sending the filter.
  20451. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20452. number of channels that your filter would prefer to have, and this method lets
  20453. you know how many the host is actually using.
  20454. Note that this method is only valid during or after the prepareToPlay()
  20455. method call. Until that point, the number of channels will be unknown.
  20456. */
  20457. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20458. /** Returns the name of one of the input channels, as returned by the host.
  20459. The host might not supply very useful names for channels, and this might be
  20460. something like "1", "2", "left", "right", etc.
  20461. */
  20462. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20463. /** Returns the name of one of the output channels, as returned by the host.
  20464. The host might not supply very useful names for channels, and this might be
  20465. something like "1", "2", "left", "right", etc.
  20466. */
  20467. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20468. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20469. virtual bool isInputChannelStereoPair (int index) const = 0;
  20470. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20471. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20472. /** This returns the number of samples delay that the filter imposes on the audio
  20473. passing through it.
  20474. The host will call this to find the latency - the filter itself should set this value
  20475. by calling setLatencySamples() as soon as it can during its initialisation.
  20476. */
  20477. int getLatencySamples() const throw() { return latencySamples; }
  20478. /** The filter should call this to set the number of samples delay that it introduces.
  20479. The filter should call this as soon as it can during initialisation, and can call it
  20480. later if the value changes.
  20481. */
  20482. void setLatencySamples (const int newLatency);
  20483. /** Returns true if the processor wants midi messages. */
  20484. virtual bool acceptsMidi() const = 0;
  20485. /** Returns true if the processor produces midi messages. */
  20486. virtual bool producesMidi() const = 0;
  20487. /** This returns a critical section that will automatically be locked while the host
  20488. is calling the processBlock() method.
  20489. Use it from your UI or other threads to lock access to variables that are used
  20490. by the process callback, but obviously be careful not to keep it locked for
  20491. too long, because that could cause stuttering playback. If you need to do something
  20492. that'll take a long time and need the processing to stop while it happens, use the
  20493. suspendProcessing() method instead.
  20494. @see suspendProcessing
  20495. */
  20496. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20497. /** Enables and disables the processing callback.
  20498. If you need to do something time-consuming on a thread and would like to make sure
  20499. the audio processing callback doesn't happen until you've finished, use this
  20500. to disable the callback and re-enable it again afterwards.
  20501. E.g.
  20502. @code
  20503. void loadNewPatch()
  20504. {
  20505. suspendProcessing (true);
  20506. ..do something that takes ages..
  20507. suspendProcessing (false);
  20508. }
  20509. @endcode
  20510. If the host tries to make an audio callback while processing is suspended, the
  20511. filter will return an empty buffer, but won't block the audio thread like it would
  20512. do if you use the getCallbackLock() critical section to synchronise access.
  20513. @see getCallbackLock
  20514. */
  20515. void suspendProcessing (const bool shouldBeSuspended);
  20516. /** Returns true if processing is currently suspended.
  20517. @see suspendProcessing
  20518. */
  20519. bool isSuspended() const throw() { return suspended; }
  20520. /** A plugin can override this to be told when it should reset any playing voices.
  20521. The default implementation does nothing, but a host may call this to tell the
  20522. plugin that it should stop any tails or sounds that have been left running.
  20523. */
  20524. virtual void reset();
  20525. /** Returns true if the processor is being run in an offline mode for rendering.
  20526. If the processor is being run live on realtime signals, this returns false.
  20527. If the mode is unknown, this will assume it's realtime and return false.
  20528. This value may be unreliable until the prepareToPlay() method has been called,
  20529. and could change each time prepareToPlay() is called.
  20530. @see setNonRealtime()
  20531. */
  20532. bool isNonRealtime() const throw() { return nonRealtime; }
  20533. /** Called by the host to tell this processor whether it's being used in a non-realime
  20534. capacity for offline rendering or bouncing.
  20535. Whatever value is passed-in will be
  20536. */
  20537. void setNonRealtime (const bool isNonRealtime) throw();
  20538. /** Creates the filter's UI.
  20539. This can return 0 if you want a UI-less filter, in which case the host may create
  20540. a generic UI that lets the user twiddle the parameters directly.
  20541. If you do want to pass back a component, the component should be created and set to
  20542. the correct size before returning it.
  20543. Remember not to do anything silly like allowing your filter to keep a pointer to
  20544. the component that gets created - it could be deleted later without any warning, which
  20545. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20546. The correct way to handle the connection between an editor component and its
  20547. filter is to use something like a ChangeBroadcaster so that the editor can
  20548. register itself as a listener, and be told when a change occurs. This lets them
  20549. safely unregister themselves when they are deleted.
  20550. Here are a few things to bear in mind when writing an editor:
  20551. - Initially there won't be an editor, until the user opens one, or they might
  20552. not open one at all. Your filter mustn't rely on it being there.
  20553. - An editor object may be deleted and a replacement one created again at any time.
  20554. - It's safe to assume that an editor will be deleted before its filter.
  20555. */
  20556. virtual AudioProcessorEditor* createEditor() = 0;
  20557. /** Returns the active editor, if there is one.
  20558. Bear in mind this can return 0, even if an editor has previously been
  20559. opened.
  20560. */
  20561. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20562. /** Returns the active editor, or if there isn't one, it will create one.
  20563. This may call createEditor() internally to create the component.
  20564. */
  20565. AudioProcessorEditor* createEditorIfNeeded();
  20566. /** This must return the correct value immediately after the object has been
  20567. created, and mustn't change the number of parameters later.
  20568. */
  20569. virtual int getNumParameters() = 0;
  20570. /** Returns the name of a particular parameter. */
  20571. virtual const String getParameterName (int parameterIndex) = 0;
  20572. /** Called by the host to find out the value of one of the filter's parameters.
  20573. The host will expect the value returned to be between 0 and 1.0.
  20574. This could be called quite frequently, so try to make your code efficient.
  20575. It's also likely to be called by non-UI threads, so the code in here should
  20576. be thread-aware.
  20577. */
  20578. virtual float getParameter (int parameterIndex) = 0;
  20579. /** Returns the value of a parameter as a text string. */
  20580. virtual const String getParameterText (int parameterIndex) = 0;
  20581. /** The host will call this method to change the value of one of the filter's parameters.
  20582. The host may call this at any time, including during the audio processing
  20583. callback, so the filter has to process this very fast and avoid blocking.
  20584. If you want to set the value of a parameter internally, e.g. from your
  20585. editor component, then don't call this directly - instead, use the
  20586. setParameterNotifyingHost() method, which will also send a message to
  20587. the host telling it about the change. If the message isn't sent, the host
  20588. won't be able to automate your parameters properly.
  20589. The value passed will be between 0 and 1.0.
  20590. */
  20591. virtual void setParameter (int parameterIndex,
  20592. float newValue) = 0;
  20593. /** Your filter can call this when it needs to change one of its parameters.
  20594. This could happen when the editor or some other internal operation changes
  20595. a parameter. This method will call the setParameter() method to change the
  20596. value, and will then send a message to the host telling it about the change.
  20597. Note that to make sure the host correctly handles automation, you should call
  20598. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20599. tell the host when the user has started and stopped changing the parameter.
  20600. */
  20601. void setParameterNotifyingHost (int parameterIndex,
  20602. float newValue);
  20603. /** Returns true if the host can automate this parameter.
  20604. By default, this returns true for all parameters.
  20605. */
  20606. virtual bool isParameterAutomatable (int parameterIndex) const;
  20607. /** Should return true if this parameter is a "meta" parameter.
  20608. A meta-parameter is a parameter that changes other params. It is used
  20609. by some hosts (e.g. AudioUnit hosts).
  20610. By default this returns false.
  20611. */
  20612. virtual bool isMetaParameter (int parameterIndex) const;
  20613. /** Sends a signal to the host to tell it that the user is about to start changing this
  20614. parameter.
  20615. This allows the host to know when a parameter is actively being held by the user, and
  20616. it may use this information to help it record automation.
  20617. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20618. */
  20619. void beginParameterChangeGesture (int parameterIndex);
  20620. /** Tells the host that the user has finished changing this parameter.
  20621. This allows the host to know when a parameter is actively being held by the user, and
  20622. it may use this information to help it record automation.
  20623. A call to this method must follow a call to beginParameterChangeGesture().
  20624. */
  20625. void endParameterChangeGesture (int parameterIndex);
  20626. /** The filter can call this when something (apart from a parameter value) has changed.
  20627. It sends a hint to the host that something like the program, number of parameters,
  20628. etc, has changed, and that it should update itself.
  20629. */
  20630. void updateHostDisplay();
  20631. /** Returns the number of preset programs the filter supports.
  20632. The value returned must be valid as soon as this object is created, and
  20633. must not change over its lifetime.
  20634. This value shouldn't be less than 1.
  20635. */
  20636. virtual int getNumPrograms() = 0;
  20637. /** Returns the number of the currently active program.
  20638. */
  20639. virtual int getCurrentProgram() = 0;
  20640. /** Called by the host to change the current program.
  20641. */
  20642. virtual void setCurrentProgram (int index) = 0;
  20643. /** Must return the name of a given program. */
  20644. virtual const String getProgramName (int index) = 0;
  20645. /** Called by the host to rename a program.
  20646. */
  20647. virtual void changeProgramName (int index, const String& newName) = 0;
  20648. /** The host will call this method when it wants to save the filter's internal state.
  20649. This must copy any info about the filter's state into the block of memory provided,
  20650. so that the host can store this and later restore it using setStateInformation().
  20651. Note that there's also a getCurrentProgramStateInformation() method, which only
  20652. stores the current program, not the state of the entire filter.
  20653. See also the helper function copyXmlToBinary() for storing settings as XML.
  20654. @see getCurrentProgramStateInformation
  20655. */
  20656. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20657. /** The host will call this method if it wants to save the state of just the filter's
  20658. current program.
  20659. Unlike getStateInformation, this should only return the current program's state.
  20660. Not all hosts support this, and if you don't implement it, the base class
  20661. method just calls getStateInformation() instead. If you do implement it, be
  20662. sure to also implement getCurrentProgramStateInformation.
  20663. @see getStateInformation, setCurrentProgramStateInformation
  20664. */
  20665. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20666. /** This must restore the filter's state from a block of data previously created
  20667. using getStateInformation().
  20668. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20669. to restore just the current program, not the state of the entire filter.
  20670. See also the helper function getXmlFromBinary() for loading settings as XML.
  20671. @see setCurrentProgramStateInformation
  20672. */
  20673. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20674. /** The host will call this method if it wants to restore the state of just the filter's
  20675. current program.
  20676. Not all hosts support this, and if you don't implement it, the base class
  20677. method just calls setStateInformation() instead. If you do implement it, be
  20678. sure to also implement getCurrentProgramStateInformation.
  20679. @see setStateInformation, getCurrentProgramStateInformation
  20680. */
  20681. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20682. /** Adds a listener that will be called when an aspect of this processor changes. */
  20683. void addListener (AudioProcessorListener* const newListener) throw();
  20684. /** Removes a previously added listener. */
  20685. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20686. /** Not for public use - this is called before deleting an editor component. */
  20687. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20688. /** Not for public use - this is called to initialise the processor. */
  20689. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20690. /** Not for public use - this is called to initialise the processor before playing. */
  20691. void setPlayConfigDetails (const int numIns, const int numOuts,
  20692. const double sampleRate,
  20693. const int blockSize) throw();
  20694. juce_UseDebuggingNewOperator
  20695. protected:
  20696. /** Helper function that just converts an xml element into a binary blob.
  20697. Use this in your filter's getStateInformation() method if you want to
  20698. store its state as xml.
  20699. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20700. from a binary blob.
  20701. */
  20702. static void copyXmlToBinary (const XmlElement& xml,
  20703. JUCE_NAMESPACE::MemoryBlock& destData);
  20704. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20705. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20706. an XmlElement object that the caller must delete when no longer needed.
  20707. */
  20708. static XmlElement* getXmlFromBinary (const void* data,
  20709. const int sizeInBytes);
  20710. /** @internal */
  20711. AudioPlayHead* playHead;
  20712. /** @internal */
  20713. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20714. private:
  20715. VoidArray listeners;
  20716. AudioProcessorEditor* activeEditor;
  20717. double sampleRate;
  20718. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20719. bool suspended, nonRealtime;
  20720. CriticalSection callbackLock, listenerLock;
  20721. #ifdef JUCE_DEBUG
  20722. BitArray changingParams;
  20723. #endif
  20724. AudioProcessor (const AudioProcessor&);
  20725. const AudioProcessor& operator= (const AudioProcessor&);
  20726. };
  20727. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20728. /********* End of inlined file: juce_AudioProcessor.h *********/
  20729. #endif
  20730. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20731. #endif
  20732. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20733. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20734. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20735. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20736. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20737. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20738. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20739. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20740. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20741. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20742. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20743. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20744. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20745. /********* Start of inlined file: juce_PluginDescription.h *********/
  20746. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20747. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20748. /**
  20749. A small class to represent some facts about a particular type of plugin.
  20750. This class is for storing and managing the details about a plugin without
  20751. actually having to load an instance of it.
  20752. A KnownPluginList contains a list of PluginDescription objects.
  20753. @see KnownPluginList
  20754. */
  20755. class JUCE_API PluginDescription
  20756. {
  20757. public:
  20758. PluginDescription() throw();
  20759. PluginDescription (const PluginDescription& other) throw();
  20760. const PluginDescription& operator= (const PluginDescription& other) throw();
  20761. ~PluginDescription() throw();
  20762. /** The name of the plugin. */
  20763. String name;
  20764. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  20765. */
  20766. String pluginFormatName;
  20767. /** A category, such as "Dynamics", "Reverbs", etc.
  20768. */
  20769. String category;
  20770. /** The manufacturer. */
  20771. String manufacturerName;
  20772. /** The version. This string doesn't have any particular format. */
  20773. String version;
  20774. /** The binary module file containing the plugin. */
  20775. File file;
  20776. /** The last time the plugin file was changed.
  20777. This is handy when scanning for new or changed plugins.
  20778. */
  20779. Time lastFileModTime;
  20780. /** A unique ID for the plugin.
  20781. Note that this might not be unique between formats, e.g. a VST and some
  20782. other format might actually have the same id.
  20783. @see createIdentifierString
  20784. */
  20785. int uid;
  20786. /** True if the plugin identifies itself as a synthesiser. */
  20787. bool isInstrument;
  20788. /** The number of inputs. */
  20789. int numInputChannels;
  20790. /** The number of outputs. */
  20791. int numOutputChannels;
  20792. /** Returns true if the two descriptions refer the the same plugin.
  20793. This isn't quite as simple as them just having the same file (because of
  20794. shell plugins).
  20795. */
  20796. bool isDuplicateOf (const PluginDescription& other) const;
  20797. /** Returns a string that can be saved and used to uniquely identify the
  20798. plugin again.
  20799. This contains less info than the XML encoding, and is independent of the
  20800. plugin's file location, so can be used to store a plugin ID for use
  20801. across different machines.
  20802. */
  20803. const String createIdentifierString() const throw();
  20804. /** Creates an XML object containing these details.
  20805. @see loadFromXml
  20806. */
  20807. XmlElement* createXml() const;
  20808. /** Reloads the info in this structure from an XML record that was previously
  20809. saved with createXML().
  20810. Returns true if the XML was a valid plugin description.
  20811. */
  20812. bool loadFromXml (const XmlElement& xml);
  20813. juce_UseDebuggingNewOperator
  20814. };
  20815. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20816. /********* End of inlined file: juce_PluginDescription.h *********/
  20817. /**
  20818. Base class for an active instance of a plugin.
  20819. This derives from the AudioProcessor class, and adds some extra functionality
  20820. that helps when wrapping dynamically loaded plugins.
  20821. @see AudioProcessor, AudioPluginFormat
  20822. */
  20823. class JUCE_API AudioPluginInstance : public AudioProcessor
  20824. {
  20825. public:
  20826. /** Destructor.
  20827. Make sure that you delete any UI components that belong to this plugin before
  20828. deleting the plugin.
  20829. */
  20830. virtual ~AudioPluginInstance();
  20831. /** Fills-in the appropriate parts of this plugin description object.
  20832. */
  20833. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  20834. juce_UseDebuggingNewOperator
  20835. protected:
  20836. AudioPluginInstance();
  20837. AudioPluginInstance (const AudioPluginInstance&);
  20838. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  20839. };
  20840. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20841. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  20842. class PluginDescription;
  20843. /**
  20844. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  20845. Use the static getNumFormats() and getFormat() calls to find the types
  20846. of format that are available.
  20847. */
  20848. class JUCE_API AudioPluginFormat
  20849. {
  20850. public:
  20851. /** Destructor. */
  20852. virtual ~AudioPluginFormat();
  20853. /** Returns the format name.
  20854. E.g. "VST", "AudioUnit", etc.
  20855. */
  20856. virtual const String getName() const = 0;
  20857. /** This tries to create descriptions for all the plugin types available in
  20858. a binary module file.
  20859. The file will be some kind of DLL or bundle.
  20860. Normally there will only be one type returned, but some plugins
  20861. (e.g. VST shells) can use a single DLL to create a set of different plugin
  20862. subtypes, so in that case, each subtype is returned as a separate object.
  20863. */
  20864. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  20865. const File& file) = 0;
  20866. /** Tries to recreate a type from a previously generated PluginDescription.
  20867. @see PluginDescription::createInstance
  20868. */
  20869. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  20870. /** Should do a quick check to see if this file or directory might be a plugin of
  20871. this format.
  20872. This is for searching for potential files, so it shouldn't actually try to
  20873. load the plugin or do anything time-consuming.
  20874. */
  20875. virtual bool fileMightContainThisPluginType (const File& file) = 0;
  20876. /** Returns the typical places to look for this kind of plugin.
  20877. Note that if this returns no paths, it means that the format can't be scanned-for
  20878. (i.e. it's an internal format that doesn't live in files)
  20879. */
  20880. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  20881. juce_UseDebuggingNewOperator
  20882. protected:
  20883. AudioPluginFormat() throw();
  20884. AudioPluginFormat (const AudioPluginFormat&);
  20885. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  20886. };
  20887. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20888. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  20889. /**
  20890. This maintains a list of known AudioPluginFormats.
  20891. @see AudioPluginFormat
  20892. */
  20893. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  20894. {
  20895. public:
  20896. AudioPluginFormatManager() throw();
  20897. /** Destructor. */
  20898. ~AudioPluginFormatManager() throw();
  20899. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  20900. /** Adds any formats that it knows about, e.g. VST.
  20901. */
  20902. void addDefaultFormats();
  20903. /** Returns the number of types of format that are available.
  20904. Use getFormat() to get one of them.
  20905. */
  20906. int getNumFormats() throw();
  20907. /** Returns one of the available formats.
  20908. @see getNumFormats
  20909. */
  20910. AudioPluginFormat* getFormat (const int index) throw();
  20911. /** Adds a format to the list.
  20912. The object passed in will be owned and deleted by the manager.
  20913. */
  20914. void addFormat (AudioPluginFormat* const format) throw();
  20915. /** Tries to load the type for this description, by trying all the formats
  20916. that this manager knows about.
  20917. The caller is responsible for deleting the object that is returned.
  20918. If it can't load the plugin, it returns 0 and leaves a message in the
  20919. errorMessage string.
  20920. */
  20921. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  20922. String& errorMessage) const;
  20923. juce_UseDebuggingNewOperator
  20924. private:
  20925. OwnedArray <AudioPluginFormat> formats;
  20926. AudioPluginFormatManager (const AudioPluginFormatManager&);
  20927. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  20928. };
  20929. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20930. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  20931. /********* Start of inlined file: juce_KnownPluginList.h *********/
  20932. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  20933. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  20934. /********* Start of inlined file: juce_PopupMenu.h *********/
  20935. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  20936. #define __JUCE_POPUPMENU_JUCEHEADER__
  20937. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  20938. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20939. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20940. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  20941. @see PopupMenu::addCustomItem
  20942. */
  20943. class JUCE_API PopupMenuCustomComponent : public Component
  20944. {
  20945. public:
  20946. /** Destructor. */
  20947. ~PopupMenuCustomComponent();
  20948. /** Chooses the size that this component would like to have.
  20949. Note that the size which this method returns isn't necessarily the one that
  20950. the menu will give it, as it will be stretched to fit the other items in
  20951. the menu.
  20952. */
  20953. virtual void getIdealSize (int& idealWidth,
  20954. int& idealHeight) = 0;
  20955. /** Dismisses the menu indicating that this item has been chosen.
  20956. This will cause the menu to exit from its modal state, returning
  20957. this item's id as the result.
  20958. */
  20959. void triggerMenuItem();
  20960. /** Returns true if this item should be highlighted because the mouse is
  20961. over it.
  20962. You can call this method in your paint() method to find out whether
  20963. to draw a highlight.
  20964. */
  20965. bool isItemHighlighted() const throw() { return isHighlighted; }
  20966. protected:
  20967. /** Constructor.
  20968. If isTriggeredAutomatically is true, then the menu will automatically detect
  20969. a click on this component and use that to trigger it. If it's false, then it's
  20970. up to your class to manually trigger the item if it wants to.
  20971. */
  20972. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  20973. private:
  20974. friend class MenuItemInfo;
  20975. friend class MenuItemComponent;
  20976. friend class PopupMenuWindow;
  20977. int refCount_;
  20978. bool isHighlighted, isTriggeredAutomatically;
  20979. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  20980. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  20981. };
  20982. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  20983. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  20984. /** Creates and displays a popup-menu.
  20985. To show a popup-menu, you create one of these, add some items to it, then
  20986. call its show() method, which returns the id of the item the user selects.
  20987. E.g. @code
  20988. void MyWidget::mouseDown (const MouseEvent& e)
  20989. {
  20990. PopupMenu m;
  20991. m.addItem (1, "item 1");
  20992. m.addItem (2, "item 2");
  20993. const int result = m.show();
  20994. if (result == 0)
  20995. {
  20996. // user dismissed the menu without picking anything
  20997. }
  20998. else if (result == 1)
  20999. {
  21000. // user picked item 1
  21001. }
  21002. else if (result == 2)
  21003. {
  21004. // user picked item 2
  21005. }
  21006. }
  21007. @endcode
  21008. Submenus are easy too: @code
  21009. void MyWidget::mouseDown (const MouseEvent& e)
  21010. {
  21011. PopupMenu subMenu;
  21012. subMenu.addItem (1, "item 1");
  21013. subMenu.addItem (2, "item 2");
  21014. PopupMenu mainMenu;
  21015. mainMenu.addItem (3, "item 3");
  21016. mainMenu.addSubMenu ("other choices", subMenu);
  21017. const int result = m.show();
  21018. ...etc
  21019. }
  21020. @endcode
  21021. */
  21022. class JUCE_API PopupMenu
  21023. {
  21024. public:
  21025. /** Creates an empty popup menu. */
  21026. PopupMenu() throw();
  21027. /** Creates a copy of another menu. */
  21028. PopupMenu (const PopupMenu& other) throw();
  21029. /** Destructor. */
  21030. ~PopupMenu() throw();
  21031. /** Copies this menu from another one. */
  21032. const PopupMenu& operator= (const PopupMenu& other) throw();
  21033. /** Resets the menu, removing all its items. */
  21034. void clear() throw();
  21035. /** Appends a new text item for this menu to show.
  21036. @param itemResultId the number that will be returned from the show() method
  21037. if the user picks this item. The value should never be
  21038. zero, because that's used to indicate that the user didn't
  21039. select anything.
  21040. @param itemText the text to show.
  21041. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21042. picked
  21043. @param isTicked if true, the item will be shown with a tick next to it
  21044. @param iconToUse if this is non-zero, it should be an image that will be
  21045. displayed to the left of the item. This method will take its
  21046. own copy of the image passed-in, so there's no need to keep
  21047. it hanging around.
  21048. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21049. */
  21050. void addItem (const int itemResultId,
  21051. const String& itemText,
  21052. const bool isActive = true,
  21053. const bool isTicked = false,
  21054. const Image* const iconToUse = 0) throw();
  21055. /** Adds an item that represents one of the commands in a command manager object.
  21056. @param commandManager the manager to use to trigger the command and get information
  21057. about it
  21058. @param commandID the ID of the command
  21059. @param displayName if this is non-empty, then this string will be used instead of
  21060. the command's registered name
  21061. */
  21062. void addCommandItem (ApplicationCommandManager* commandManager,
  21063. const int commandID,
  21064. const String& displayName = String::empty) throw();
  21065. /** Appends a text item with a special colour.
  21066. This is the same as addItem(), but specifies a colour to use for the
  21067. text, which will override the default colours that are used by the
  21068. current look-and-feel. See addItem() for a description of the parameters.
  21069. */
  21070. void addColouredItem (const int itemResultId,
  21071. const String& itemText,
  21072. const Colour& itemTextColour,
  21073. const bool isActive = true,
  21074. const bool isTicked = false,
  21075. const Image* const iconToUse = 0) throw();
  21076. /** Appends a custom menu item.
  21077. This will add a user-defined component to use as a menu item. The component
  21078. passed in will be deleted by this menu when it's no longer needed.
  21079. @see PopupMenuCustomComponent
  21080. */
  21081. void addCustomItem (const int itemResultId,
  21082. PopupMenuCustomComponent* const customComponent) throw();
  21083. /** Appends a custom menu item that can't be used to trigger a result.
  21084. This will add a user-defined component to use as a menu item. Unlike the
  21085. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21086. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21087. delete the component when it's finished, so it's the caller's responsibility
  21088. to manage the component that is passed-in.
  21089. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21090. detection of a mouse-click on your component, and use that to trigger the
  21091. menu ID specified in itemResultId. If this is false, the menu item can't
  21092. be triggered, so itemResultId is not used.
  21093. @see PopupMenuCustomComponent
  21094. */
  21095. void addCustomItem (const int itemResultId,
  21096. Component* customComponent,
  21097. int idealWidth, int idealHeight,
  21098. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21099. /** Appends a sub-menu.
  21100. If the menu that's passed in is empty, it will appear as an inactive item.
  21101. */
  21102. void addSubMenu (const String& subMenuName,
  21103. const PopupMenu& subMenu,
  21104. const bool isActive = true,
  21105. Image* const iconToUse = 0,
  21106. const bool isTicked = false) throw();
  21107. /** Appends a separator to the menu, to help break it up into sections.
  21108. The menu class is smart enough not to display separators at the top or bottom
  21109. of the menu, and it will replace mutliple adjacent separators with a single
  21110. one, so your code can be quite free and easy about adding these, and it'll
  21111. always look ok.
  21112. */
  21113. void addSeparator() throw();
  21114. /** Adds a non-clickable text item to the menu.
  21115. This is a bold-font items which can be used as a header to separate the items
  21116. into named groups.
  21117. */
  21118. void addSectionHeader (const String& title) throw();
  21119. /** Returns the number of items that the menu currently contains.
  21120. (This doesn't count separators).
  21121. */
  21122. int getNumItems() const throw();
  21123. /** Returns true if the menu contains a command item that triggers the given command. */
  21124. bool containsCommandItem (const int commandID) const throw();
  21125. /** Returns true if the menu contains any items that can be used. */
  21126. bool containsAnyActiveItems() const throw();
  21127. /** Displays the menu and waits for the user to pick something.
  21128. This will display the menu modally, and return the ID of the item that the
  21129. user picks. If they click somewhere off the menu to get rid of it without
  21130. choosing anything, this will return 0.
  21131. The current location of the mouse will be used as the position to show the
  21132. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21133. on where this point is on the screen, the menu will appear above, below or
  21134. to the side of the point.
  21135. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21136. then when the menu first appears, it will make sure
  21137. that this item is visible. So if the menu has too many
  21138. items to fit on the screen, it will be scrolled to a
  21139. position where this item is visible.
  21140. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21141. than this if some items are too long to fit.
  21142. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21143. vertical column, the menu may be laid out as a series of
  21144. columns - this is the maximum number allowed. To use the
  21145. default value for this (probably about 7), you can pass
  21146. in zero.
  21147. @param standardItemHeight if this is non-zero, it will be used as the standard
  21148. height for menu items (apart from custom items)
  21149. @see showAt
  21150. */
  21151. int show (const int itemIdThatMustBeVisible = 0,
  21152. const int minimumWidth = 0,
  21153. const int maximumNumColumns = 0,
  21154. const int standardItemHeight = 0);
  21155. /** Displays the menu at a specific location.
  21156. This is the same as show(), but uses a specific location (in global screen
  21157. co-ordinates) rather than the current mouse position.
  21158. Note that the co-ordinates don't specify the top-left of the menu - they
  21159. indicate a point of interest, and the menu will position itself nearby to
  21160. this point, trying to keep it fully on-screen.
  21161. @see show()
  21162. */
  21163. int showAt (const int screenX,
  21164. const int screenY,
  21165. const int itemIdThatMustBeVisible = 0,
  21166. const int minimumWidth = 0,
  21167. const int maximumNumColumns = 0,
  21168. const int standardItemHeight = 0);
  21169. /** Displays the menu as if it's attached to a component such as a button.
  21170. This is similar to showAt(), but will position it next to the given component, e.g.
  21171. so that the menu's edge is aligned with that of the component. This is intended for
  21172. things like buttons that trigger a pop-up menu.
  21173. */
  21174. int showAt (Component* componentToAttachTo,
  21175. const int itemIdThatMustBeVisible = 0,
  21176. const int minimumWidth = 0,
  21177. const int maximumNumColumns = 0,
  21178. const int standardItemHeight = 0);
  21179. /** Closes any menus that are currently open.
  21180. This might be useful if you have a situation where your window is being closed
  21181. by some means other than a user action, and you'd like to make sure that menus
  21182. aren't left hanging around.
  21183. */
  21184. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21185. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21186. This can be called before show() if you need a customised menu. Be careful
  21187. not to delete the LookAndFeel object before the menu has been deleted.
  21188. */
  21189. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21190. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21191. These constants can be used either via the LookAndFeel::setColour()
  21192. method for the look and feel that is set for this menu with setLookAndFeel()
  21193. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21194. */
  21195. enum ColourIds
  21196. {
  21197. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21198. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21199. colour is specified when the item is added). */
  21200. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21201. addSectionHeader() method). */
  21202. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21203. highlighted menu item. */
  21204. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21205. highlighted item. */
  21206. };
  21207. /**
  21208. Allows you to iterate through the items in a pop-up menu, and examine
  21209. their properties.
  21210. To use this, just create one and repeatedly call its next() method. When this
  21211. returns true, all the member variables of the iterator are filled-out with
  21212. information describing the menu item. When it returns false, the end of the
  21213. list has been reached.
  21214. */
  21215. class JUCE_API MenuItemIterator
  21216. {
  21217. public:
  21218. /** Creates an iterator that will scan through the items in the specified
  21219. menu.
  21220. Be careful not to add any items to a menu while it is being iterated,
  21221. or things could get out of step.
  21222. */
  21223. MenuItemIterator (const PopupMenu& menu) throw();
  21224. /** Destructor. */
  21225. ~MenuItemIterator() throw();
  21226. /** Returns true if there is another item, and sets up all this object's
  21227. member variables to reflect that item's properties.
  21228. */
  21229. bool next() throw();
  21230. String itemName;
  21231. const PopupMenu* subMenu;
  21232. int itemId;
  21233. bool isSeparator;
  21234. bool isTicked;
  21235. bool isEnabled;
  21236. bool isCustomComponent;
  21237. bool isSectionHeader;
  21238. const Colour* customColour;
  21239. const Image* customImage;
  21240. ApplicationCommandManager* commandManager;
  21241. juce_UseDebuggingNewOperator
  21242. private:
  21243. const PopupMenu& menu;
  21244. int index;
  21245. MenuItemIterator (const MenuItemIterator&);
  21246. const MenuItemIterator& operator= (const MenuItemIterator&);
  21247. };
  21248. juce_UseDebuggingNewOperator
  21249. private:
  21250. friend class PopupMenuWindow;
  21251. friend class MenuItemIterator;
  21252. VoidArray items;
  21253. LookAndFeel* lookAndFeel;
  21254. bool separatorPending;
  21255. void addSeparatorIfPending();
  21256. int showMenu (const int x, const int y, const int w, const int h,
  21257. const int itemIdThatMustBeVisible,
  21258. const int minimumWidth,
  21259. const int maximumNumColumns,
  21260. const int standardItemHeight,
  21261. const bool alignToRectangle,
  21262. Component* const componentAttachedTo) throw();
  21263. friend class MenuBarComponent;
  21264. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21265. const int itemIdThatMustBeVisible,
  21266. const int minimumWidth,
  21267. const int maximumNumColumns,
  21268. const int standardItemHeight,
  21269. const bool alignToRectangle,
  21270. Component* menuBarComponent,
  21271. ApplicationCommandManager** managerOfChosenCommand,
  21272. Component* const componentAttachedTo) throw();
  21273. };
  21274. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21275. /********* End of inlined file: juce_PopupMenu.h *********/
  21276. /**
  21277. Manages a list of plugin types.
  21278. This can be easily edited, saved and loaded, and used to create instances of
  21279. the plugin types in it.
  21280. @see PluginListComponent
  21281. */
  21282. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21283. {
  21284. public:
  21285. /** Creates an empty list.
  21286. */
  21287. KnownPluginList();
  21288. /** Destructor. */
  21289. ~KnownPluginList();
  21290. /** Clears the list. */
  21291. void clear();
  21292. /** Returns the number of types currently in the list.
  21293. @see getType
  21294. */
  21295. int getNumTypes() const throw() { return types.size(); }
  21296. /** Returns one of the types.
  21297. @see getNumTypes
  21298. */
  21299. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21300. /** Looks for a type in the list which comes from this file.
  21301. */
  21302. PluginDescription* getTypeForFile (const File& file) const throw();
  21303. /** Looks for a type in the list which matches a plugin type ID.
  21304. The identifierString parameter must have been created by
  21305. PluginDescription::createIdentifierString().
  21306. */
  21307. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21308. /** Adds a type manually from its description. */
  21309. bool addType (const PluginDescription& type);
  21310. /** Removes a type. */
  21311. void removeType (const int index) throw();
  21312. /** Looks for all types that can be loaded from a given file, and adds them
  21313. to the list.
  21314. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21315. re-tested if it's not already in the list, or if the file's modification
  21316. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21317. false, the file will always be reloaded and tested.
  21318. Returns true if any new types were added, and all the types found in this
  21319. file (even if it was already known and hasn't been re-scanned) get returned
  21320. in the array.
  21321. */
  21322. bool scanAndAddFile (const File& possiblePluginFile,
  21323. const bool dontRescanIfAlreadyInList,
  21324. OwnedArray <PluginDescription>& typesFound);
  21325. /** Returns true if the specified file is already known about and if it
  21326. hasn't been modified since our entry was created.
  21327. */
  21328. bool isListingUpToDate (const File& possiblePluginFile) const throw();
  21329. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21330. If any types are found in the files, their descriptions are returned in the array.
  21331. */
  21332. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21333. OwnedArray <PluginDescription>& typesFound);
  21334. /** Sort methods used to change the order of the plugins in the list.
  21335. */
  21336. enum SortMethod
  21337. {
  21338. defaultOrder = 0,
  21339. sortAlphabetically,
  21340. sortByCategory,
  21341. sortByManufacturer,
  21342. sortByFileSystemLocation
  21343. };
  21344. /** Adds all the plugin types to a popup menu so that the user can select one.
  21345. Depending on the sort method, it may add sub-menus for categories,
  21346. manufacturers, etc.
  21347. Use getIndexChosenByMenu() to find out the type that was chosen.
  21348. */
  21349. void addToMenu (PopupMenu& menu,
  21350. const SortMethod sortMethod) const;
  21351. /** Converts a menu item index that has been chosen into its index in this list.
  21352. Returns -1 if it's not an ID that was used.
  21353. @see addToMenu
  21354. */
  21355. int getIndexChosenByMenu (const int menuResultCode) const;
  21356. /** Sorts the list. */
  21357. void sort (const SortMethod method);
  21358. /** Creates some XML that can be used to store the state of this list.
  21359. */
  21360. XmlElement* createXml() const;
  21361. /** Recreates the state of this list from its stored XML format.
  21362. */
  21363. void recreateFromXml (const XmlElement& xml);
  21364. juce_UseDebuggingNewOperator
  21365. private:
  21366. OwnedArray <PluginDescription> types;
  21367. KnownPluginList (const KnownPluginList&);
  21368. const KnownPluginList& operator= (const KnownPluginList&);
  21369. };
  21370. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21371. /********* End of inlined file: juce_KnownPluginList.h *********/
  21372. /**
  21373. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21374. Use one of these objects if you want to wire-up a set of AudioProcessors
  21375. and play back the result.
  21376. Processors can be added to the graph as "nodes" using addNode(), and once
  21377. added, you can connect any of their input or output channels to other
  21378. nodes using addConnection().
  21379. To play back a graph through an audio device, you might want to use an
  21380. AudioProcessorPlayer object.
  21381. */
  21382. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21383. public AsyncUpdater
  21384. {
  21385. public:
  21386. /** Creates an empty graph.
  21387. */
  21388. AudioProcessorGraph();
  21389. /** Destructor.
  21390. Any processor objects that have been added to the graph will also be deleted.
  21391. */
  21392. ~AudioProcessorGraph();
  21393. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21394. To create a node, call AudioProcessorGraph::addNode().
  21395. */
  21396. class Node : public ReferenceCountedObject
  21397. {
  21398. public:
  21399. /** Destructor.
  21400. */
  21401. ~Node();
  21402. /** The ID number assigned to this node.
  21403. This is assigned by the graph that owns it, and can't be changed.
  21404. */
  21405. const uint32 id;
  21406. /** The actual processor object that this node represents.
  21407. */
  21408. AudioProcessor* const processor;
  21409. /** A set of user-definable properties that are associated with this node.
  21410. This can be used to attach values to the node for whatever purpose seems
  21411. useful. For example, you might store an x and y position if your application
  21412. is displaying the nodes on-screen.
  21413. */
  21414. PropertySet properties;
  21415. /** A convenient typedef for referring to a pointer to a node object.
  21416. */
  21417. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21418. juce_UseDebuggingNewOperator
  21419. private:
  21420. friend class AudioProcessorGraph;
  21421. bool isPrepared;
  21422. Node (const uint32 id, AudioProcessor* const processor) throw();
  21423. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21424. void unprepare();
  21425. Node (const Node&);
  21426. const Node& operator= (const Node&);
  21427. };
  21428. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21429. To create a connection, use AudioProcessorGraph::addConnection().
  21430. */
  21431. struct Connection
  21432. {
  21433. public:
  21434. /** The ID number of the node which is the input source for this connection.
  21435. @see AudioProcessorGraph::getNodeForId
  21436. */
  21437. uint32 sourceNodeId;
  21438. /** The index of the output channel of the source node from which this
  21439. connection takes its data.
  21440. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21441. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21442. index of an audio output channel in the source node.
  21443. */
  21444. int sourceChannelIndex;
  21445. /** The ID number of the node which is the destination for this connection.
  21446. @see AudioProcessorGraph::getNodeForId
  21447. */
  21448. uint32 destNodeId;
  21449. /** The index of the input channel of the destination node to which this
  21450. connection delivers its data.
  21451. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21452. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21453. index of an audio input channel in the destination node.
  21454. */
  21455. int destChannelIndex;
  21456. juce_UseDebuggingNewOperator
  21457. private:
  21458. };
  21459. /** Deletes all nodes and connections from this graph.
  21460. Any processor objects in the graph will be deleted.
  21461. */
  21462. void clear();
  21463. /** Returns the number of nodes in the graph. */
  21464. int getNumNodes() const throw() { return nodes.size(); }
  21465. /** Returns a pointer to one of the nodes in the graph.
  21466. This will return 0 if the index is out of range.
  21467. @see getNodeForId
  21468. */
  21469. Node* getNode (const int index) const throw() { return nodes [index]; }
  21470. /** Searches the graph for a node with the given ID number and returns it.
  21471. If no such node was found, this returns 0.
  21472. @see getNode
  21473. */
  21474. Node* getNodeForId (const uint32 nodeId) const throw();
  21475. /** Adds a node to the graph.
  21476. This creates a new node in the graph, for the specified processor. Once you have
  21477. added a processor to the graph, the graph owns it and will delete it later when
  21478. it is no longer needed.
  21479. The optional nodeId parameter lets you specify an ID to use for the node, but
  21480. if the value is already in use, this new node will overwrite the old one.
  21481. If this succeeds, it returns a pointer to the newly-created node.
  21482. */
  21483. Node* addNode (AudioProcessor* const newProcessor,
  21484. uint32 nodeId = 0);
  21485. /** Deletes a node within the graph which has the specified ID.
  21486. This will also delete any connections that are attached to this node.
  21487. */
  21488. bool removeNode (const uint32 nodeId);
  21489. /** Returns the number of connections in the graph. */
  21490. int getNumConnections() const throw() { return connections.size(); }
  21491. /** Returns a pointer to one of the connections in the graph. */
  21492. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21493. /** Searches for a connection between some specified channels.
  21494. If no such connection is found, this returns 0.
  21495. */
  21496. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21497. const int sourceChannelIndex,
  21498. const uint32 destNodeId,
  21499. const int destChannelIndex) const throw();
  21500. /** Returns true if there is a connection between any of the channels of
  21501. two specified nodes.
  21502. */
  21503. bool isConnected (const uint32 possibleSourceNodeId,
  21504. const uint32 possibleDestNodeId) const throw();
  21505. /** Returns true if it would be legal to connect the specified points.
  21506. */
  21507. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21508. const uint32 destNodeId, const int destChannelIndex) const throw();
  21509. /** Attempts to connect two specified channels of two nodes.
  21510. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21511. to an audio one or other such nonsense), then it'll return false.
  21512. */
  21513. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21514. const uint32 destNodeId, const int destChannelIndex);
  21515. /** Deletes the connection with the specified index.
  21516. Returns true if a connection was actually deleted.
  21517. */
  21518. void removeConnection (const int index);
  21519. /** Deletes any connection between two specified points.
  21520. Returns true if a connection was actually deleted.
  21521. */
  21522. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21523. const uint32 destNodeId, const int destChannelIndex);
  21524. /** Removes all connections from the specified node.
  21525. */
  21526. bool disconnectNode (const uint32 nodeId);
  21527. /** Performs a sanity checks of all the connections.
  21528. This might be useful if some of the processors are doing things like changing
  21529. their channel counts, which could render some connections obsolete.
  21530. */
  21531. bool removeIllegalConnections();
  21532. /** A special number that represents the midi channel of a node.
  21533. This is used as a channel index value if you want to refer to the midi input
  21534. or output instead of an audio channel.
  21535. */
  21536. static const int midiChannelIndex;
  21537. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21538. in order to use the audio that comes into and out of the graph itself.
  21539. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21540. node in the graph which delivers the audio that is coming into the parent
  21541. graph. This allows you to stream the data to other nodes and process the
  21542. incoming audio.
  21543. Likewise, one of these in "output" mode can be sent data which it will add to
  21544. the sum of data being sent to the graph's output.
  21545. @see AudioProcessorGraph
  21546. */
  21547. class AudioGraphIOProcessor : public AudioPluginInstance
  21548. {
  21549. public:
  21550. /** Specifies the mode in which this processor will operate.
  21551. */
  21552. enum IODeviceType
  21553. {
  21554. audioInputNode, /**< In this mode, the processor has output channels
  21555. representing all the audio input channels that are
  21556. coming into its parent audio graph. */
  21557. audioOutputNode, /**< In this mode, the processor has input channels
  21558. representing all the audio output channels that are
  21559. going out of its parent audio graph. */
  21560. midiInputNode, /**< In this mode, the processor has a midi output which
  21561. delivers the same midi data that is arriving at its
  21562. parent graph. */
  21563. midiOutputNode /**< In this mode, the processor has a midi input and
  21564. any data sent to it will be passed out of the parent
  21565. graph. */
  21566. };
  21567. /** Returns the mode of this processor. */
  21568. IODeviceType getType() const throw() { return type; }
  21569. /** Returns the parent graph to which this processor belongs, or 0 if it
  21570. hasn't yet been added to one. */
  21571. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21572. /** True if this is an audio or midi input. */
  21573. bool isInput() const throw();
  21574. /** True if this is an audio or midi output. */
  21575. bool isOutput() const throw();
  21576. AudioGraphIOProcessor (const IODeviceType type);
  21577. ~AudioGraphIOProcessor();
  21578. const String getName() const;
  21579. void fillInPluginDescription (PluginDescription& d) const;
  21580. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21581. void releaseResources();
  21582. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21583. const String getInputChannelName (const int channelIndex) const;
  21584. const String getOutputChannelName (const int channelIndex) const;
  21585. bool isInputChannelStereoPair (int index) const;
  21586. bool isOutputChannelStereoPair (int index) const;
  21587. bool acceptsMidi() const;
  21588. bool producesMidi() const;
  21589. AudioProcessorEditor* createEditor();
  21590. int getNumParameters();
  21591. const String getParameterName (int);
  21592. float getParameter (int);
  21593. const String getParameterText (int);
  21594. void setParameter (int, float);
  21595. int getNumPrograms();
  21596. int getCurrentProgram();
  21597. void setCurrentProgram (int);
  21598. const String getProgramName (int);
  21599. void changeProgramName (int, const String&);
  21600. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21601. void setStateInformation (const void* data, int sizeInBytes);
  21602. /** @internal */
  21603. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21604. juce_UseDebuggingNewOperator
  21605. private:
  21606. const IODeviceType type;
  21607. AudioProcessorGraph* graph;
  21608. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21609. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21610. };
  21611. // AudioProcessor methods:
  21612. const String getName() const;
  21613. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21614. void releaseResources();
  21615. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21616. const String getInputChannelName (const int channelIndex) const;
  21617. const String getOutputChannelName (const int channelIndex) const;
  21618. bool isInputChannelStereoPair (int index) const;
  21619. bool isOutputChannelStereoPair (int index) const;
  21620. bool acceptsMidi() const;
  21621. bool producesMidi() const;
  21622. AudioProcessorEditor* createEditor() { return 0; }
  21623. int getNumParameters() { return 0; }
  21624. const String getParameterName (int) { return String::empty; }
  21625. float getParameter (int) { return 0; }
  21626. const String getParameterText (int) { return String::empty; }
  21627. void setParameter (int, float) { }
  21628. int getNumPrograms() { return 0; }
  21629. int getCurrentProgram() { return 0; }
  21630. void setCurrentProgram (int) { }
  21631. const String getProgramName (int) { return String::empty; }
  21632. void changeProgramName (int, const String&) { }
  21633. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21634. void setStateInformation (const void* data, int sizeInBytes);
  21635. /** @internal */
  21636. void handleAsyncUpdate();
  21637. juce_UseDebuggingNewOperator
  21638. private:
  21639. ReferenceCountedArray <Node> nodes;
  21640. OwnedArray <Connection> connections;
  21641. int lastNodeId;
  21642. AudioSampleBuffer renderingBuffers;
  21643. OwnedArray <MidiBuffer> midiBuffers;
  21644. CriticalSection renderLock;
  21645. VoidArray renderingOps;
  21646. friend class AudioGraphIOProcessor;
  21647. AudioSampleBuffer* currentAudioInputBuffer;
  21648. AudioSampleBuffer currentAudioOutputBuffer;
  21649. MidiBuffer* currentMidiInputBuffer;
  21650. MidiBuffer currentMidiOutputBuffer;
  21651. void clearRenderingSequence();
  21652. void buildRenderingSequence();
  21653. bool isAnInputTo (const uint32 possibleInputId,
  21654. const uint32 possibleDestinationId,
  21655. const int recursionCheck) const throw();
  21656. AudioProcessorGraph (const AudioProcessorGraph&);
  21657. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21658. };
  21659. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21660. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21661. #endif
  21662. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21663. #endif
  21664. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21665. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21666. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21667. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21668. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21669. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21670. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21671. class AudioIODevice;
  21672. /**
  21673. One of these is passed to an AudioIODevice object to stream the audio data
  21674. in and out.
  21675. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21676. method on its own high-priority audio thread, when it needs to send or receive
  21677. the next block of data.
  21678. @see AudioIODevice, AudioDeviceManager
  21679. */
  21680. class JUCE_API AudioIODeviceCallback
  21681. {
  21682. public:
  21683. /** Destructor. */
  21684. virtual ~AudioIODeviceCallback() {}
  21685. /** Processes a block of incoming and outgoing audio data.
  21686. The subclass's implementation should use the incoming audio for whatever
  21687. purposes it needs to, and must fill all the output channels with the next
  21688. block of output data before returning.
  21689. The channel data is arranged with the same array indices as the channel name
  21690. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21691. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21692. associated channel, so remember to check for this.
  21693. @param inputChannelData a set of arrays containing the audio data for each
  21694. incoming channel - this data is valid until the function
  21695. returns. There will be one channel of data for each input
  21696. channel that was enabled when the audio device was opened
  21697. (see AudioIODevice::open())
  21698. @param numInputChannels the number of pointers to channel data in the
  21699. inputChannelData array.
  21700. @param outputChannelData a set of arrays which need to be filled with the data
  21701. that should be sent to each outgoing channel of the device.
  21702. There will be one channel of data for each output channel
  21703. that was enabled when the audio device was opened (see
  21704. AudioIODevice::open())
  21705. The initial contents of the array is undefined, so the
  21706. callback function must fill all the channels with zeros if
  21707. its output is silence. Failing to do this could cause quite
  21708. an unpleasant noise!
  21709. @param numOutputChannels the number of pointers to channel data in the
  21710. outputChannelData array.
  21711. @param numSamples the number of samples in each channel of the input and
  21712. output arrays. The number of samples will depend on the
  21713. audio device's buffer size and will usually remain constant,
  21714. although this isn't guaranteed, so make sure your code can
  21715. cope with reasonable changes in the buffer size from one
  21716. callback to the next.
  21717. */
  21718. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21719. int numInputChannels,
  21720. float** outputChannelData,
  21721. int numOutputChannels,
  21722. int numSamples) = 0;
  21723. /** Called to indicate that the device is about to start calling back.
  21724. This will be called just before the audio callbacks begin, either when this
  21725. callback has just been added to an audio device, or after the device has been
  21726. restarted because of a sample-rate or block-size change.
  21727. You can use this opportunity to find out the sample rate and block size
  21728. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21729. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21730. @param device the audio IO device that will be used to drive the callback.
  21731. Note that if you're going to store this this pointer, it is
  21732. only valid until the next time that audioDeviceStopped is called.
  21733. */
  21734. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21735. /** Called to indicate that the device has stopped.
  21736. */
  21737. virtual void audioDeviceStopped() = 0;
  21738. };
  21739. /**
  21740. Base class for an audio device with synchronised input and output channels.
  21741. Subclasses of this are used to implement different protocols such as DirectSound,
  21742. ASIO, CoreAudio, etc.
  21743. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21744. documentation for that class for more info.
  21745. For an easier way of managing audio devices and their settings, have a look at the
  21746. AudioDeviceManager class.
  21747. @see AudioIODeviceType, AudioDeviceManager
  21748. */
  21749. class JUCE_API AudioIODevice
  21750. {
  21751. public:
  21752. /** Destructor. */
  21753. virtual ~AudioIODevice();
  21754. /** Returns the device's name, (as set in the constructor). */
  21755. const String& getName() const throw() { return name; }
  21756. /** Returns the type of the device.
  21757. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21758. */
  21759. const String& getTypeName() const throw() { return typeName; }
  21760. /** Returns the names of all the available output channels on this device.
  21761. To find out which of these are currently in use, call getActiveOutputChannels().
  21762. */
  21763. virtual const StringArray getOutputChannelNames() = 0;
  21764. /** Returns the names of all the available input channels on this device.
  21765. To find out which of these are currently in use, call getActiveInputChannels().
  21766. */
  21767. virtual const StringArray getInputChannelNames() = 0;
  21768. /** Returns the number of sample-rates this device supports.
  21769. To find out which rates are available on this device, use this method to
  21770. find out how many there are, and getSampleRate() to get the rates.
  21771. @see getSampleRate
  21772. */
  21773. virtual int getNumSampleRates() = 0;
  21774. /** Returns one of the sample-rates this device supports.
  21775. To find out which rates are available on this device, use getNumSampleRates() to
  21776. find out how many there are, and getSampleRate() to get the individual rates.
  21777. The sample rate is set by the open() method.
  21778. (Note that for DirectSound some rates might not work, depending on combinations
  21779. of i/o channels that are being opened).
  21780. @see getNumSampleRates
  21781. */
  21782. virtual double getSampleRate (int index) = 0;
  21783. /** Returns the number of sizes of buffer that are available.
  21784. @see getBufferSizeSamples, getDefaultBufferSize
  21785. */
  21786. virtual int getNumBufferSizesAvailable() = 0;
  21787. /** Returns one of the possible buffer-sizes.
  21788. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21789. @returns a number of samples
  21790. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21791. */
  21792. virtual int getBufferSizeSamples (int index) = 0;
  21793. /** Returns the default buffer-size to use.
  21794. @returns a number of samples
  21795. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21796. */
  21797. virtual int getDefaultBufferSize() = 0;
  21798. /** Tries to open the device ready to play.
  21799. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21800. input channel should be enabled
  21801. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  21802. output channel should be enabled
  21803. @param sampleRate the sample rate to try to use - to find out which rates are
  21804. available, see getNumSampleRates() and getSampleRate()
  21805. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  21806. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  21807. @returns an error description if there's a problem, or an empty string if it succeeds in
  21808. opening the device
  21809. @see close
  21810. */
  21811. virtual const String open (const BitArray& inputChannels,
  21812. const BitArray& outputChannels,
  21813. double sampleRate,
  21814. int bufferSizeSamples) = 0;
  21815. /** Closes and releases the device if it's open. */
  21816. virtual void close() = 0;
  21817. /** Returns true if the device is still open.
  21818. A device might spontaneously close itself if something goes wrong, so this checks if
  21819. it's still open.
  21820. */
  21821. virtual bool isOpen() = 0;
  21822. /** Starts the device actually playing.
  21823. This must be called after the device has been opened.
  21824. @param callback the callback to use for streaming the data.
  21825. @see AudioIODeviceCallback, open
  21826. */
  21827. virtual void start (AudioIODeviceCallback* callback) = 0;
  21828. /** Stops the device playing.
  21829. Once a device has been started, this will stop it. Any pending calls to the
  21830. callback class will be flushed before this method returns.
  21831. */
  21832. virtual void stop() = 0;
  21833. /** Returns true if the device is still calling back.
  21834. The device might mysteriously stop, so this checks whether it's
  21835. still playing.
  21836. */
  21837. virtual bool isPlaying() = 0;
  21838. /** Returns the last error that happened if anything went wrong. */
  21839. virtual const String getLastError() = 0;
  21840. /** Returns the buffer size that the device is currently using.
  21841. If the device isn't actually open, this value doesn't really mean much.
  21842. */
  21843. virtual int getCurrentBufferSizeSamples() = 0;
  21844. /** Returns the sample rate that the device is currently using.
  21845. If the device isn't actually open, this value doesn't really mean much.
  21846. */
  21847. virtual double getCurrentSampleRate() = 0;
  21848. /** Returns the device's current physical bit-depth.
  21849. If the device isn't actually open, this value doesn't really mean much.
  21850. */
  21851. virtual int getCurrentBitDepth() = 0;
  21852. /** Returns a mask showing which of the available output channels are currently
  21853. enabled.
  21854. @see getOutputChannelNames
  21855. */
  21856. virtual const BitArray getActiveOutputChannels() const = 0;
  21857. /** Returns a mask showing which of the available input channels are currently
  21858. enabled.
  21859. @see getInputChannelNames
  21860. */
  21861. virtual const BitArray getActiveInputChannels() const = 0;
  21862. /** Returns the device's output latency.
  21863. This is the delay in samples between a callback getting a block of data, and
  21864. that data actually getting played.
  21865. */
  21866. virtual int getOutputLatencyInSamples() = 0;
  21867. /** Returns the device's input latency.
  21868. This is the delay in samples between some audio actually arriving at the soundcard,
  21869. and the callback getting passed this block of data.
  21870. */
  21871. virtual int getInputLatencyInSamples() = 0;
  21872. /** True if this device can show a pop-up control panel for editing its settings.
  21873. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  21874. to display it.
  21875. */
  21876. virtual bool hasControlPanel() const;
  21877. /** Shows a device-specific control panel if there is one.
  21878. This should only be called for devices which return true from hasControlPanel().
  21879. */
  21880. virtual bool showControlPanel();
  21881. protected:
  21882. /** Creates a device, setting its name and type member variables. */
  21883. AudioIODevice (const String& deviceName,
  21884. const String& typeName);
  21885. /** @internal */
  21886. String name, typeName;
  21887. };
  21888. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21889. /********* End of inlined file: juce_AudioIODevice.h *********/
  21890. /**
  21891. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  21892. To use one of these, just make it the callback used by your AudioIODevice, and
  21893. give it a processor to use by calling setProcessor().
  21894. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  21895. input to send both streams through the processor.
  21896. @see AudioProcessor, AudioProcessorGraph
  21897. */
  21898. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  21899. public MidiInputCallback
  21900. {
  21901. public:
  21902. /**
  21903. */
  21904. AudioProcessorPlayer();
  21905. /** Destructor. */
  21906. virtual ~AudioProcessorPlayer();
  21907. /** Sets the processor that should be played.
  21908. The processor that is passed in will not be deleted or owned by this object.
  21909. To stop anything playing, pass in 0 to this method.
  21910. */
  21911. void setProcessor (AudioProcessor* const processorToPlay);
  21912. /** Returns the current audio processor that is being played.
  21913. */
  21914. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  21915. /** Returns a midi message collector that you can pass midi messages to if you
  21916. want them to be injected into the midi stream that is being sent to the
  21917. processor.
  21918. */
  21919. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  21920. /** @internal */
  21921. void audioDeviceIOCallback (const float** inputChannelData,
  21922. int totalNumInputChannels,
  21923. float** outputChannelData,
  21924. int totalNumOutputChannels,
  21925. int numSamples);
  21926. /** @internal */
  21927. void audioDeviceAboutToStart (AudioIODevice* device);
  21928. /** @internal */
  21929. void audioDeviceStopped();
  21930. /** @internal */
  21931. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  21932. juce_UseDebuggingNewOperator
  21933. private:
  21934. AudioProcessor* processor;
  21935. CriticalSection lock;
  21936. double sampleRate;
  21937. int blockSize;
  21938. bool isPrepared;
  21939. int numInputChans, numOutputChans;
  21940. float* channels [128];
  21941. AudioSampleBuffer tempBuffer;
  21942. MidiBuffer incomingMidi;
  21943. MidiMessageCollector messageCollector;
  21944. AudioProcessorPlayer (const AudioProcessorPlayer&);
  21945. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  21946. };
  21947. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21948. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  21949. #endif
  21950. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  21951. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  21952. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  21953. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  21954. /********* Start of inlined file: juce_PropertyPanel.h *********/
  21955. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  21956. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  21957. /********* Start of inlined file: juce_PropertyComponent.h *********/
  21958. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  21959. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  21960. class EditableProperty;
  21961. /**
  21962. A base class for a component that goes in a PropertyPanel and displays one of
  21963. an item's properties.
  21964. Subclasses of this are used to display a property in various forms, e.g. a
  21965. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  21966. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  21967. A subclass must implement the refresh() method which will be called to tell the
  21968. component to update itself, and is also responsible for calling this it when the
  21969. item that it refers to is changed.
  21970. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  21971. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  21972. */
  21973. class JUCE_API PropertyComponent : public Component
  21974. {
  21975. public:
  21976. /** Creates a PropertyComponent.
  21977. @param propertyName the name is stored as this component's name, and is
  21978. used as the name displayed next to this component in
  21979. a property panel
  21980. @param preferredHeight the height that the component should be given - some
  21981. items may need to be larger than a normal row height.
  21982. This value can also be set if a subclass changes the
  21983. preferredHeight member variable.
  21984. */
  21985. PropertyComponent (const String& propertyName,
  21986. const int preferredHeight = 25);
  21987. /** Destructor. */
  21988. ~PropertyComponent();
  21989. /** Returns this item's preferred height.
  21990. This value is specified either in the constructor or by a subclass changing the
  21991. preferredHeight member variable.
  21992. */
  21993. int getPreferredHeight() const throw() { return preferredHeight; }
  21994. /** Updates the property component if the item it refers to has changed.
  21995. A subclass must implement this method, and other objects may call it to
  21996. force it to refresh itself.
  21997. The subclass should be economical in the amount of work is done, so for
  21998. example it should check whether it really needs to do a repaint rather than
  21999. just doing one every time this method is called, as it may be called when
  22000. the value being displayed hasn't actually changed.
  22001. */
  22002. virtual void refresh() = 0;
  22003. /** The default paint method fills the background and draws a label for the
  22004. item's name.
  22005. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22006. */
  22007. void paint (Graphics& g);
  22008. /** The default resize method positions any child component to the right of this
  22009. one, based on the look and feel's default label size.
  22010. */
  22011. void resized();
  22012. /** By default, this just repaints the component. */
  22013. void enablementChanged();
  22014. juce_UseDebuggingNewOperator
  22015. protected:
  22016. /** Used by the PropertyPanel to determine how high this component needs to be.
  22017. A subclass can update this value in its constructor but shouldn't alter it later
  22018. as changes won't necessarily be picked up.
  22019. */
  22020. int preferredHeight;
  22021. };
  22022. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22023. /********* End of inlined file: juce_PropertyComponent.h *********/
  22024. /********* Start of inlined file: juce_Viewport.h *********/
  22025. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22026. #define __JUCE_VIEWPORT_JUCEHEADER__
  22027. /********* Start of inlined file: juce_ScrollBar.h *********/
  22028. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22029. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22030. /********* Start of inlined file: juce_Button.h *********/
  22031. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22032. #define __JUCE_BUTTON_JUCEHEADER__
  22033. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22034. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22035. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22036. /********* Start of inlined file: juce_TooltipClient.h *********/
  22037. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22038. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22039. /**
  22040. Components that want to use pop-up tooltips should implement this interface.
  22041. A TooltipWindow will wait for the mouse to hover over a component that
  22042. implements the TooltipClient interface, and when it finds one, it will display
  22043. the tooltip returned by its getTooltip() method.
  22044. @see TooltipWindow, SettableTooltipClient
  22045. */
  22046. class JUCE_API TooltipClient
  22047. {
  22048. public:
  22049. /** Destructor. */
  22050. virtual ~TooltipClient() {}
  22051. /** Returns the string that this object wants to show as its tooltip. */
  22052. virtual const String getTooltip() = 0;
  22053. };
  22054. /**
  22055. An implementation of TooltipClient that stores the tooltip string and a method
  22056. for changing it.
  22057. This makes it easy to add a tooltip to a custom component, by simply adding this
  22058. as a base class and calling setTooltip().
  22059. Many of the Juce widgets already use this as a base class to implement their
  22060. tooltips.
  22061. @see TooltipClient, TooltipWindow
  22062. */
  22063. class JUCE_API SettableTooltipClient : public TooltipClient
  22064. {
  22065. public:
  22066. /** Destructor. */
  22067. virtual ~SettableTooltipClient() {}
  22068. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22069. virtual const String getTooltip() { return tooltipString; }
  22070. juce_UseDebuggingNewOperator
  22071. protected:
  22072. String tooltipString;
  22073. };
  22074. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22075. /********* End of inlined file: juce_TooltipClient.h *********/
  22076. /**
  22077. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22078. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22079. object.
  22080. The TooltipWindow object will then stay invisible, waiting until the mouse
  22081. hovers for the specified length of time - it will then see if it's currently
  22082. over a component which implements the TooltipClient interface, and if so,
  22083. it will make itself visible to show the tooltip in the appropriate place.
  22084. @see TooltipClient, SettableTooltipClient
  22085. */
  22086. class JUCE_API TooltipWindow : public Component,
  22087. private Timer
  22088. {
  22089. public:
  22090. /** Creates a tooltip window.
  22091. Make sure your app only creates one instance of this class, otherwise you'll
  22092. get multiple overlaid tooltips appearing. The window will initially be invisible
  22093. and will make itself visible when it needs to display a tip.
  22094. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22095. methods.
  22096. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22097. otherwise the tooltip will be added to the given parent
  22098. component.
  22099. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22100. before a tooltip will be shown
  22101. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22102. */
  22103. TooltipWindow (Component* parentComponent = 0,
  22104. const int millisecondsBeforeTipAppears = 700);
  22105. /** Destructor. */
  22106. ~TooltipWindow();
  22107. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22108. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22109. methods.
  22110. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22111. */
  22112. enum ColourIds
  22113. {
  22114. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22115. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22116. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22117. };
  22118. juce_UseDebuggingNewOperator
  22119. private:
  22120. const int millisecondsBeforeTipAppears;
  22121. int mouseX, mouseY, mouseClicks;
  22122. unsigned int lastMouseMoveTime, lastHideTime;
  22123. Component* lastComponentUnderMouse;
  22124. bool changedCompsSinceShown;
  22125. String tip;
  22126. void paint (Graphics& g);
  22127. void mouseEnter (const MouseEvent& e);
  22128. void timerCallback();
  22129. void showFor (Component* const c);
  22130. void hide();
  22131. TooltipWindow (const TooltipWindow&);
  22132. const TooltipWindow& operator= (const TooltipWindow&);
  22133. };
  22134. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22135. /********* End of inlined file: juce_TooltipWindow.h *********/
  22136. class Button;
  22137. /**
  22138. Used to receive callbacks when a button is clicked.
  22139. @see Button::addButtonListener, Button::removeButtonListener
  22140. */
  22141. class JUCE_API ButtonListener
  22142. {
  22143. public:
  22144. /** Destructor. */
  22145. virtual ~ButtonListener() {}
  22146. /** Called when the button is clicked. */
  22147. virtual void buttonClicked (Button* button) = 0;
  22148. /** Called when the button's state changes. */
  22149. virtual void buttonStateChanged (Button*) {}
  22150. };
  22151. /**
  22152. A base class for buttons.
  22153. This contains all the logic for button behaviours such as enabling/disabling,
  22154. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22155. and radio groups, etc.
  22156. @see TextButton, DrawableButton, ToggleButton
  22157. */
  22158. class JUCE_API Button : public Component,
  22159. public SettableTooltipClient,
  22160. public ApplicationCommandManagerListener,
  22161. private KeyListener
  22162. {
  22163. protected:
  22164. /** Creates a button.
  22165. @param buttonName the text to put in the button (the component's name is also
  22166. initially set to this string, but these can be changed later
  22167. using the setName() and setButtonText() methods)
  22168. */
  22169. Button (const String& buttonName);
  22170. public:
  22171. /** Destructor. */
  22172. virtual ~Button();
  22173. /** Changes the button's text.
  22174. @see getButtonText
  22175. */
  22176. void setButtonText (const String& newText) throw();
  22177. /** Returns the text displayed in the button.
  22178. @see setButtonText
  22179. */
  22180. const String getButtonText() const throw() { return text; }
  22181. /** Returns true if the button is currently being held down by the mouse.
  22182. @see isOver
  22183. */
  22184. bool isDown() const throw();
  22185. /** Returns true if the mouse is currently over the button.
  22186. This will be also be true if the mouse is being held down.
  22187. @see isDown
  22188. */
  22189. bool isOver() const throw();
  22190. /** A button has an on/off state associated with it, and this changes that.
  22191. By default buttons are 'off' and for simple buttons that you click to perform
  22192. an action you won't change this. Toggle buttons, however will want to
  22193. change their state when turned on or off.
  22194. @param shouldBeOn whether to set the button's toggle state to be on or
  22195. off. If it's a member of a button group, this will
  22196. always try to turn it on, and to turn off any other
  22197. buttons in the group
  22198. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22199. the button will be repainted but no notification will
  22200. be sent
  22201. @see getToggleState, setRadioGroupId
  22202. */
  22203. void setToggleState (const bool shouldBeOn,
  22204. const bool sendChangeNotification);
  22205. /** Returns true if the button in 'on'.
  22206. By default buttons are 'off' and for simple buttons that you click to perform
  22207. an action you won't change this. Toggle buttons, however will want to
  22208. change their state when turned on or off.
  22209. @see setToggleState
  22210. */
  22211. bool getToggleState() const throw() { return isOn; }
  22212. /** This tells the button to automatically flip the toggle state when
  22213. the button is clicked.
  22214. If set to true, then before the clicked() callback occurs, the toggle-state
  22215. of the button is flipped.
  22216. */
  22217. void setClickingTogglesState (const bool shouldToggle) throw();
  22218. /** Returns true if this button is set to be an automatic toggle-button.
  22219. This returns the last value that was passed to setClickingTogglesState().
  22220. */
  22221. bool getClickingTogglesState() const throw();
  22222. /** Enables the button to act as a member of a mutually-exclusive group
  22223. of 'radio buttons'.
  22224. If the group ID is set to a non-zero number, then this button will
  22225. act as part of a group of buttons with the same ID, only one of
  22226. which can be 'on' at the same time. Note that when it's part of
  22227. a group, clicking a toggle-button that's 'on' won't turn it off.
  22228. To find other buttons with the same ID, this button will search through
  22229. its sibling components for ToggleButtons, so all the buttons for a
  22230. particular group must be placed inside the same parent component.
  22231. Set the group ID back to zero if you want it to act as a normal toggle
  22232. button again.
  22233. @see getRadioGroupId
  22234. */
  22235. void setRadioGroupId (const int newGroupId);
  22236. /** Returns the ID of the group to which this button belongs.
  22237. (See setRadioGroupId() for an explanation of this).
  22238. */
  22239. int getRadioGroupId() const throw() { return radioGroupId; }
  22240. /** Registers a listener to receive events when this button's state changes.
  22241. If the listener is already registered, this will not register it again.
  22242. @see removeButtonListener
  22243. */
  22244. void addButtonListener (ButtonListener* const newListener) throw();
  22245. /** Removes a previously-registered button listener
  22246. @see addButtonListener
  22247. */
  22248. void removeButtonListener (ButtonListener* const listener) throw();
  22249. /** Causes the button to act as if it's been clicked.
  22250. This will asynchronously make the button draw itself going down and up, and
  22251. will then call back the clicked() method as if mouse was clicked on it.
  22252. @see clicked
  22253. */
  22254. virtual void triggerClick();
  22255. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22256. When the button is pressed, it will use the given manager to trigger the
  22257. command ID.
  22258. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22259. before this button is. To disable the command triggering, call this method and
  22260. pass 0 for the parameters.
  22261. If generateTooltip is true, then the button's tooltip will be automatically
  22262. generated based on the name of this command and its current shortcut key.
  22263. @see addShortcut, getCommandID
  22264. */
  22265. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22266. const int commandID,
  22267. const bool generateTooltip);
  22268. /** Returns the command ID that was set by setCommandToTrigger().
  22269. */
  22270. int getCommandID() const throw() { return commandID; }
  22271. /** Assigns a shortcut key to trigger the button.
  22272. The button registers itself with its top-level parent component for keypresses.
  22273. Note that a different way of linking buttons to keypresses is by using the
  22274. setKeyPressToTrigger() method to invoke a command - the difference being that
  22275. setting a shortcut allows the button to be temporarily linked to a keypress
  22276. only while it's on-screen.
  22277. @see clearShortcuts
  22278. */
  22279. void addShortcut (const KeyPress& key);
  22280. /** Removes all key shortcuts that had been set for this button.
  22281. @see addShortcut
  22282. */
  22283. void clearShortcuts();
  22284. /** Returns true if the given keypress is a shortcut for this button.
  22285. @see addShortcut
  22286. */
  22287. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22288. /** Sets an auto-repeat speed for the button when it is held down.
  22289. (Auto-repeat is disabled by default).
  22290. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22291. triggering the next click. If this is zero, auto-repeat
  22292. is disabled
  22293. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22294. triggered
  22295. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22296. get faster, the longer the button is held down, up to the
  22297. minimum interval specified here
  22298. */
  22299. void setRepeatSpeed (const int initialDelayInMillisecs,
  22300. const int repeatDelayInMillisecs,
  22301. const int minimumDelayInMillisecs = -1) throw();
  22302. /** Sets whether the button click should happen when the mouse is pressed or released.
  22303. By default the button is only considered to have been clicked when the mouse is
  22304. released, but setting this to true will make it call the clicked() method as soon
  22305. as the button is pressed.
  22306. This is useful if the button is being used to show a pop-up menu, as it allows
  22307. the click to be used as a drag onto the menu.
  22308. */
  22309. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22310. /** Returns the number of milliseconds since the last time the button
  22311. went into the 'down' state.
  22312. */
  22313. uint32 getMillisecondsSinceButtonDown() const throw();
  22314. /** (overridden from Component to do special stuff). */
  22315. void setVisible (bool shouldBeVisible);
  22316. /** Sets the tooltip for this button.
  22317. @see TooltipClient, TooltipWindow
  22318. */
  22319. void setTooltip (const String& newTooltip);
  22320. // (implementation of the TooltipClient method)
  22321. const String getTooltip();
  22322. /** A combination of these flags are used by setConnectedEdges().
  22323. */
  22324. enum ConnectedEdgeFlags
  22325. {
  22326. ConnectedOnLeft = 1,
  22327. ConnectedOnRight = 2,
  22328. ConnectedOnTop = 4,
  22329. ConnectedOnBottom = 8
  22330. };
  22331. /** Hints about which edges of the button might be connected to adjoining buttons.
  22332. The value passed in is a bitwise combination of any of the values in the
  22333. ConnectedEdgeFlags enum.
  22334. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22335. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22336. without rounded corners on the edges that connect. It's only a hint, so the
  22337. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22338. button.
  22339. */
  22340. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22341. /** Returns the set of flags passed into setConnectedEdges(). */
  22342. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22343. /** Indicates whether the button adjoins another one on its left edge.
  22344. @see setConnectedEdges
  22345. */
  22346. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22347. /** Indicates whether the button adjoins another one on its right edge.
  22348. @see setConnectedEdges
  22349. */
  22350. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22351. /** Indicates whether the button adjoins another one on its top edge.
  22352. @see setConnectedEdges
  22353. */
  22354. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22355. /** Indicates whether the button adjoins another one on its bottom edge.
  22356. @see setConnectedEdges
  22357. */
  22358. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22359. /** Used by setState(). */
  22360. enum ButtonState
  22361. {
  22362. buttonNormal,
  22363. buttonOver,
  22364. buttonDown
  22365. };
  22366. /** Can be used to force the button into a particular state.
  22367. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22368. from happening.
  22369. The state that you set here will only last until it is automatically changed when the mouse
  22370. enters or exits the button, or the mouse-button is pressed or released.
  22371. */
  22372. void setState (const ButtonState newState);
  22373. juce_UseDebuggingNewOperator
  22374. protected:
  22375. /** This method is called when the button has been clicked.
  22376. Subclasses can override this to perform whatever they actions they need
  22377. to do.
  22378. Alternatively, a ButtonListener can be added to the button, and these listeners
  22379. will be called when the click occurs.
  22380. @see triggerClick
  22381. */
  22382. virtual void clicked();
  22383. /** This method is called when the button has been clicked.
  22384. By default it just calls clicked(), but you might want to override it to handle
  22385. things like clicking when a modifier key is pressed, etc.
  22386. @see ModifierKeys
  22387. */
  22388. virtual void clicked (const ModifierKeys& modifiers);
  22389. /** Subclasses should override this to actually paint the button's contents.
  22390. It's better to use this than the paint method, because it gives you information
  22391. about the over/down state of the button.
  22392. @param g the graphics context to use
  22393. @param isMouseOverButton true if the button is either in the 'over' or
  22394. 'down' state
  22395. @param isButtonDown true if the button should be drawn in the 'down' position
  22396. */
  22397. virtual void paintButton (Graphics& g,
  22398. bool isMouseOverButton,
  22399. bool isButtonDown) = 0;
  22400. /** Called when the button's up/down/over state changes.
  22401. Subclasses can override this if they need to do something special when the button
  22402. goes up or down.
  22403. @see isDown, isOver
  22404. */
  22405. virtual void buttonStateChanged();
  22406. /** @internal */
  22407. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22408. /** @internal */
  22409. void handleCommandMessage (int commandId);
  22410. /** @internal */
  22411. void mouseEnter (const MouseEvent& e);
  22412. /** @internal */
  22413. void mouseExit (const MouseEvent& e);
  22414. /** @internal */
  22415. void mouseDown (const MouseEvent& e);
  22416. /** @internal */
  22417. void mouseDrag (const MouseEvent& e);
  22418. /** @internal */
  22419. void mouseUp (const MouseEvent& e);
  22420. /** @internal */
  22421. bool keyPressed (const KeyPress& key);
  22422. /** @internal */
  22423. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22424. /** @internal */
  22425. bool keyStateChanged (Component* originatingComponent);
  22426. /** @internal */
  22427. void paint (Graphics& g);
  22428. /** @internal */
  22429. void parentHierarchyChanged();
  22430. /** @internal */
  22431. void focusGained (FocusChangeType cause);
  22432. /** @internal */
  22433. void focusLost (FocusChangeType cause);
  22434. /** @internal */
  22435. void enablementChanged();
  22436. /** @internal */
  22437. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22438. /** @internal */
  22439. void applicationCommandListChanged();
  22440. private:
  22441. Array <KeyPress> shortcuts;
  22442. Component* keySource;
  22443. String text;
  22444. SortedSet <void*> buttonListeners;
  22445. friend class InternalButtonRepeatTimer;
  22446. Timer* repeatTimer;
  22447. uint32 buttonPressTime, lastTimeCallbackTime;
  22448. ApplicationCommandManager* commandManagerToUse;
  22449. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22450. int radioGroupId, commandID, connectedEdgeFlags;
  22451. ButtonState buttonState;
  22452. bool isOn : 1;
  22453. bool clickTogglesState : 1;
  22454. bool needsToRelease : 1;
  22455. bool needsRepainting : 1;
  22456. bool isKeyDown : 1;
  22457. bool triggerOnMouseDown : 1;
  22458. bool generateTooltip : 1;
  22459. void repeatTimerCallback() throw();
  22460. Timer& getRepeatTimer() throw();
  22461. ButtonState updateState (const MouseEvent* const e) throw();
  22462. bool isShortcutPressed() const throw();
  22463. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22464. void flashButtonState() throw();
  22465. void sendClickMessage (const ModifierKeys& modifiers);
  22466. void sendStateMessage();
  22467. Button (const Button&);
  22468. const Button& operator= (const Button&);
  22469. };
  22470. #endif // __JUCE_BUTTON_JUCEHEADER__
  22471. /********* End of inlined file: juce_Button.h *********/
  22472. class ScrollBar;
  22473. /**
  22474. A class for receiving events from a ScrollBar.
  22475. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22476. method, and it will be called when the bar's position changes.
  22477. @see ScrollBar::addListener, ScrollBar::removeListener
  22478. */
  22479. class JUCE_API ScrollBarListener
  22480. {
  22481. public:
  22482. /** Destructor. */
  22483. virtual ~ScrollBarListener() {}
  22484. /** Called when a ScrollBar is moved.
  22485. @param scrollBarThatHasMoved the bar that has moved
  22486. @param newRangeStart the new range start of this bar
  22487. */
  22488. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22489. const double newRangeStart) = 0;
  22490. };
  22491. /**
  22492. A scrollbar component.
  22493. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22494. sets the range of values it can represent. Then you can use setCurrentRange() to
  22495. change the position and size of the scrollbar's 'thumb'.
  22496. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22497. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22498. they moved it to.
  22499. The scrollbar will adjust its own visibility according to whether its thumb size
  22500. allows it to actually be scrolled.
  22501. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22502. instead of handling a scrollbar directly.
  22503. @see ScrollBarListener
  22504. */
  22505. class JUCE_API ScrollBar : public Component,
  22506. public AsyncUpdater,
  22507. private Timer
  22508. {
  22509. public:
  22510. /** Creates a Scrollbar.
  22511. @param isVertical whether it should be a vertical or horizontal bar
  22512. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22513. */
  22514. ScrollBar (const bool isVertical,
  22515. const bool buttonsAreVisible = true);
  22516. /** Destructor. */
  22517. ~ScrollBar();
  22518. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22519. bool isVertical() const throw() { return vertical; }
  22520. /** Changes the scrollbar's direction.
  22521. You'll also need to resize the bar appropriately - this just changes its internal
  22522. layout.
  22523. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22524. */
  22525. void setOrientation (const bool shouldBeVertical) throw();
  22526. /** Shows or hides the scrollbar's buttons. */
  22527. void setButtonVisibility (const bool buttonsAreVisible);
  22528. /** Tells the scrollbar whether to make itself invisible when not needed.
  22529. The default behaviour is for a scrollbar to become invisible when the thumb
  22530. fills the whole of its range (i.e. when it can't be moved). Setting this
  22531. value to false forces the bar to always be visible.
  22532. */
  22533. void setAutoHide (const bool shouldHideWhenFullRange);
  22534. /** Sets the minimum and maximum values that the bar will move between.
  22535. The bar's thumb will always be constrained so that the top of the thumb
  22536. will be >= minimum, and the bottom of the thumb <= maximum.
  22537. @see setCurrentRange
  22538. */
  22539. void setRangeLimits (const double minimum,
  22540. const double maximum) throw();
  22541. /** Returns the lower value that the thumb can be set to.
  22542. This is the value set by setRangeLimits().
  22543. */
  22544. double getMinimumRangeLimit() const throw() { return minimum; }
  22545. /** Returns the upper value that the thumb can be set to.
  22546. This is the value set by setRangeLimits().
  22547. */
  22548. double getMaximumRangeLimit() const throw() { return maximum; }
  22549. /** Changes the position of the scrollbar's 'thumb'.
  22550. This sets both the position and size of the thumb - to just set the position without
  22551. changing the size, you can use setCurrentRangeStart().
  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. @param newStart the top (or left) of the thumb, in the range
  22556. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22557. value is beyond these limits, it will be clipped.
  22558. @param newSize the size of the thumb, such that
  22559. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22560. size is beyond these limits, it will be clipped.
  22561. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22562. */
  22563. void setCurrentRange (double newStart,
  22564. double newSize) throw();
  22565. /** Moves the bar's thumb position.
  22566. This will move the thumb position without changing the thumb size. Note
  22567. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22568. If this method call actually changes the scrollbar's position, it will trigger an
  22569. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22570. are registered.
  22571. @see setCurrentRange
  22572. */
  22573. void setCurrentRangeStart (double newStart) throw();
  22574. /** Returns the position of the top of the thumb.
  22575. @see setCurrentRangeStart
  22576. */
  22577. double getCurrentRangeStart() const throw() { return rangeStart; }
  22578. /** Returns the current size of the thumb.
  22579. @see setCurrentRange
  22580. */
  22581. double getCurrentRangeSize() const throw() { return rangeSize; }
  22582. /** Sets the amount by which the up and down buttons will move the bar.
  22583. The value here is in terms of the total range, and is added or subtracted
  22584. from the thumb position when the user clicks an up/down (or left/right) button.
  22585. */
  22586. void setSingleStepSize (const double newSingleStepSize) throw();
  22587. /** Moves the scrollbar by a number of single-steps.
  22588. This will move the bar by a multiple of its single-step interval (as
  22589. specified using the setSingleStepSize() method).
  22590. A positive value here will move the bar down or to the right, a negative
  22591. value moves it up or to the left.
  22592. */
  22593. void moveScrollbarInSteps (const int howManySteps) throw();
  22594. /** Moves the scroll bar up or down in pages.
  22595. This will move the bar by a multiple of its current thumb size, effectively
  22596. doing a page-up or down.
  22597. A positive value here will move the bar down or to the right, a negative
  22598. value moves it up or to the left.
  22599. */
  22600. void moveScrollbarInPages (const int howManyPages) throw();
  22601. /** Scrolls to the top (or left).
  22602. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22603. */
  22604. void scrollToTop() throw();
  22605. /** Scrolls to the bottom (or right).
  22606. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22607. */
  22608. void scrollToBottom() throw();
  22609. /** Changes the delay before the up and down buttons autorepeat when they are held
  22610. down.
  22611. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22612. @see Button::setRepeatSpeed
  22613. */
  22614. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22615. const int repeatDelayInMillisecs,
  22616. const int minimumDelayInMillisecs = -1) throw();
  22617. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22618. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22619. methods.
  22620. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22621. */
  22622. enum ColourIds
  22623. {
  22624. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22625. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22626. 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. */
  22627. };
  22628. /** Registers a listener that will be called when the scrollbar is moved. */
  22629. void addListener (ScrollBarListener* const listener) throw();
  22630. /** Deregisters a previously-registered listener. */
  22631. void removeListener (ScrollBarListener* const listener) throw();
  22632. /** @internal */
  22633. bool keyPressed (const KeyPress& key);
  22634. /** @internal */
  22635. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22636. /** @internal */
  22637. void lookAndFeelChanged();
  22638. /** @internal */
  22639. void handleAsyncUpdate();
  22640. /** @internal */
  22641. void mouseDown (const MouseEvent& e);
  22642. /** @internal */
  22643. void mouseDrag (const MouseEvent& e);
  22644. /** @internal */
  22645. void mouseUp (const MouseEvent& e);
  22646. /** @internal */
  22647. void paint (Graphics& g);
  22648. /** @internal */
  22649. void resized();
  22650. juce_UseDebuggingNewOperator
  22651. private:
  22652. double minimum, maximum;
  22653. double rangeStart, rangeSize;
  22654. double singleStepSize, dragStartRange;
  22655. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22656. int dragStartMousePos, lastMousePos;
  22657. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22658. bool vertical, isDraggingThumb, alwaysVisible;
  22659. Button* upButton;
  22660. Button* downButton;
  22661. SortedSet <void*> listeners;
  22662. void updateThumbPosition() throw();
  22663. void timerCallback();
  22664. ScrollBar (const ScrollBar&);
  22665. const ScrollBar& operator= (const ScrollBar&);
  22666. };
  22667. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22668. /********* End of inlined file: juce_ScrollBar.h *********/
  22669. /**
  22670. A Viewport is used to contain a larger child component, and allows the child
  22671. to be automatically scrolled around.
  22672. To use a Viewport, just create one and set the component that goes inside it
  22673. using the setViewedComponent() method. When the child component changes size,
  22674. the Viewport will adjust its scrollbars accordingly.
  22675. A subclass of the viewport can be created which will receive calls to its
  22676. visibleAreaChanged() method when the subcomponent changes position or size.
  22677. */
  22678. class JUCE_API Viewport : public Component,
  22679. private ComponentListener,
  22680. private ScrollBarListener
  22681. {
  22682. public:
  22683. /** Creates a Viewport.
  22684. The viewport is initially empty - use the setViewedComponent() method to
  22685. add a child component for it to manage.
  22686. */
  22687. Viewport (const String& componentName = String::empty);
  22688. /** Destructor. */
  22689. ~Viewport();
  22690. /** Sets the component that this viewport will contain and scroll around.
  22691. This will add the given component to this Viewport and position it at
  22692. (0, 0).
  22693. (Don't add or remove any child components directly using the normal
  22694. Component::addChildComponent() methods).
  22695. @param newViewedComponent the component to add to this viewport (this pointer
  22696. may be null). The component passed in will be deleted
  22697. by the Viewport when it's no longer needed
  22698. @see getViewedComponent
  22699. */
  22700. void setViewedComponent (Component* const newViewedComponent);
  22701. /** Returns the component that's currently being used inside the Viewport.
  22702. @see setViewedComponent
  22703. */
  22704. Component* getViewedComponent() const throw() { return contentComp; }
  22705. /** Changes the position of the viewed component.
  22706. The inner component will be moved so that the pixel at the top left of
  22707. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22708. within the inner component.
  22709. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22710. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22711. */
  22712. void setViewPosition (const int xPixelsOffset,
  22713. const int yPixelsOffset);
  22714. /** Changes the view position as a proportion of the distance it can move.
  22715. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22716. visible area in the top-left, and (1, 1) would put it as far down and
  22717. to the right as it's possible to go whilst keeping the child component
  22718. on-screen.
  22719. */
  22720. void setViewPositionProportionately (const double proportionX,
  22721. const double proportionY);
  22722. /** Returns the position within the child component of the top-left of its visible area.
  22723. @see getViewWidth, setViewPosition
  22724. */
  22725. int getViewPositionX() const throw() { return lastVX; }
  22726. /** Returns the position within the child component of the top-left of its visible area.
  22727. @see getViewHeight, setViewPosition
  22728. */
  22729. int getViewPositionY() const throw() { return lastVY; }
  22730. /** Returns the width of the visible area of the child component.
  22731. This may be less than the width of this Viewport if there's a vertical scrollbar
  22732. or if the child component is itself smaller.
  22733. */
  22734. int getViewWidth() const throw() { return lastVW; }
  22735. /** Returns the height of the visible area of the child component.
  22736. This may be less than the height of this Viewport if there's a horizontal scrollbar
  22737. or if the child component is itself smaller.
  22738. */
  22739. int getViewHeight() const throw() { return lastVH; }
  22740. /** Returns the width available within this component for the contents.
  22741. This will be the width of the viewport component minus the width of a
  22742. vertical scrollbar (if visible).
  22743. */
  22744. int getMaximumVisibleWidth() const throw();
  22745. /** Returns the height available within this component for the contents.
  22746. This will be the height of the viewport component minus the space taken up
  22747. by a horizontal scrollbar (if visible).
  22748. */
  22749. int getMaximumVisibleHeight() const throw();
  22750. /** Callback method that is called when the visible area changes.
  22751. This will be called when the visible area is moved either be scrolling or
  22752. by calls to setViewPosition(), etc.
  22753. */
  22754. virtual void visibleAreaChanged (int visibleX, int visibleY,
  22755. int visibleW, int visibleH);
  22756. /** Turns scrollbars on or off.
  22757. If set to false, the scrollbars won't ever appear. When true (the default)
  22758. they will appear only when needed.
  22759. */
  22760. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  22761. const bool showHorizontalScrollbarIfNeeded);
  22762. /** True if the vertical scrollbar is enabled.
  22763. @see setScrollBarsShown
  22764. */
  22765. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  22766. /** True if the horizontal scrollbar is enabled.
  22767. @see setScrollBarsShown
  22768. */
  22769. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  22770. /** Changes the width of the scrollbars.
  22771. If this isn't specified, the default width from the LookAndFeel class will be used.
  22772. @see LookAndFeel::getDefaultScrollbarWidth
  22773. */
  22774. void setScrollBarThickness (const int thickness);
  22775. /** Returns the thickness of the scrollbars.
  22776. @see setScrollBarThickness
  22777. */
  22778. int getScrollBarThickness() const throw();
  22779. /** Changes the distance that a single-step click on a scrollbar button
  22780. will move the viewport.
  22781. */
  22782. void setSingleStepSizes (const int stepX, const int stepY);
  22783. /** Shows or hides the buttons on any scrollbars that are used.
  22784. @see ScrollBar::setButtonVisibility
  22785. */
  22786. void setScrollBarButtonVisibility (const bool buttonsVisible);
  22787. /** Returns a pointer to the scrollbar component being used.
  22788. Handy if you need to customise the bar somehow.
  22789. */
  22790. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  22791. /** Returns a pointer to the scrollbar component being used.
  22792. Handy if you need to customise the bar somehow.
  22793. */
  22794. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  22795. juce_UseDebuggingNewOperator
  22796. /** @internal */
  22797. void resized();
  22798. /** @internal */
  22799. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  22800. /** @internal */
  22801. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22802. /** @internal */
  22803. bool keyPressed (const KeyPress& key);
  22804. /** @internal */
  22805. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  22806. /** @internal */
  22807. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22808. private:
  22809. Component* contentComp;
  22810. int lastVX, lastVY, lastVW, lastVH;
  22811. int scrollBarThickness;
  22812. int singleStepX, singleStepY;
  22813. bool showHScrollbar, showVScrollbar;
  22814. Component* contentHolder;
  22815. ScrollBar* verticalScrollBar;
  22816. ScrollBar* horizontalScrollBar;
  22817. void updateVisibleRegion();
  22818. Viewport (const Viewport&);
  22819. const Viewport& operator= (const Viewport&);
  22820. };
  22821. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  22822. /********* End of inlined file: juce_Viewport.h *********/
  22823. /**
  22824. A panel that holds a list of PropertyComponent objects.
  22825. This panel displays a list of PropertyComponents, and allows them to be organised
  22826. into collapsible sections.
  22827. To use, simply create one of these and add your properties to it with addProperties()
  22828. or addSection().
  22829. @see PropertyComponent
  22830. */
  22831. class JUCE_API PropertyPanel : public Component
  22832. {
  22833. public:
  22834. /** Creates an empty property panel. */
  22835. PropertyPanel();
  22836. /** Destructor. */
  22837. ~PropertyPanel();
  22838. /** Deletes all property components from the panel.
  22839. */
  22840. void clear();
  22841. /** Adds a set of properties to the panel.
  22842. The components in the list will be owned by this object and will be automatically
  22843. deleted later on when no longer needed.
  22844. These properties are added without them being inside a named section. If you
  22845. want them to be kept together in a collapsible section, use addSection() instead.
  22846. */
  22847. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  22848. /** Adds a set of properties to the panel.
  22849. These properties are added at the bottom of the list, under a section heading with
  22850. a plus/minus button that allows it to be opened and closed.
  22851. The components in the list will be owned by this object and will be automatically
  22852. deleted later on when no longer needed.
  22853. To add properies without them being in a section, use addProperties().
  22854. */
  22855. void addSection (const String& sectionTitle,
  22856. const Array <PropertyComponent*>& newPropertyComponents,
  22857. const bool shouldSectionInitiallyBeOpen = true);
  22858. /** Calls the refresh() method of all PropertyComponents in the panel */
  22859. void refreshAll() const;
  22860. /** Returns a list of all the names of sections in the panel.
  22861. These are the sections that have been added with addSection().
  22862. */
  22863. const StringArray getSectionNames() const;
  22864. /** Returns true if the section at this index is currently open.
  22865. The index is from 0 up to the number of items returned by getSectionNames().
  22866. */
  22867. bool isSectionOpen (const int sectionIndex) const;
  22868. /** Opens or closes one of the sections.
  22869. The index is from 0 up to the number of items returned by getSectionNames().
  22870. */
  22871. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  22872. /** Enables or disables one of the sections.
  22873. The index is from 0 up to the number of items returned by getSectionNames().
  22874. */
  22875. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  22876. /** Saves the current state of open/closed sections so it can be restored later.
  22877. The caller is responsible for deleting the object that is returned.
  22878. To restore this state, use restoreOpennessState().
  22879. @see restoreOpennessState
  22880. */
  22881. XmlElement* getOpennessState() const;
  22882. /** Restores a previously saved arrangement of open/closed sections.
  22883. This will try to restore a snapshot of the panel's state that was created by
  22884. the getOpennessState() method. If any of the sections named in the original
  22885. XML aren't present, they will be ignored.
  22886. @see getOpennessState
  22887. */
  22888. void restoreOpennessState (const XmlElement& newState);
  22889. /** Sets a message to be displayed when there are no properties in the panel.
  22890. The default message is "nothing selected".
  22891. */
  22892. void setMessageWhenEmpty (const String& newMessage);
  22893. /** Returns the message that is displayed when there are no properties.
  22894. @see setMessageWhenEmpty
  22895. */
  22896. const String& getMessageWhenEmpty() const throw();
  22897. /** @internal */
  22898. void paint (Graphics& g);
  22899. /** @internal */
  22900. void resized();
  22901. juce_UseDebuggingNewOperator
  22902. private:
  22903. Viewport* viewport;
  22904. Component* propertyHolderComponent;
  22905. String messageWhenEmpty;
  22906. void updatePropHolderLayout() const;
  22907. void updatePropHolderLayout (const int width) const;
  22908. };
  22909. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  22910. /********* End of inlined file: juce_PropertyPanel.h *********/
  22911. /**
  22912. A type of UI component that displays the parameters of an AudioProcessor as
  22913. a simple list of sliders.
  22914. This can be used for showing an editor for a processor that doesn't supply
  22915. its own custom editor.
  22916. @see AudioProcessor
  22917. */
  22918. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  22919. {
  22920. public:
  22921. GenericAudioProcessorEditor (AudioProcessor* const owner);
  22922. ~GenericAudioProcessorEditor();
  22923. void paint (Graphics& g);
  22924. void resized();
  22925. juce_UseDebuggingNewOperator
  22926. private:
  22927. PropertyPanel* panel;
  22928. };
  22929. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22930. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22931. #endif
  22932. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22933. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  22934. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22935. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22936. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  22937. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22938. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22939. /********* Start of inlined file: juce_AudioSource.h *********/
  22940. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22941. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  22942. /**
  22943. Used by AudioSource::getNextAudioBlock().
  22944. */
  22945. struct JUCE_API AudioSourceChannelInfo
  22946. {
  22947. /** The destination buffer to fill with audio data.
  22948. When the AudioSource::getNextAudioBlock() method is called, the active section
  22949. of this buffer should be filled with whatever output the source produces.
  22950. Only the samples specified by the startSample and numSamples members of this structure
  22951. should be affected by the call.
  22952. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22953. method can be treated as the input if the source is performing some kind of filter operation,
  22954. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22955. a handy way of doing this.
  22956. The number of channels in the buffer could be anything, so the AudioSource
  22957. must cope with this in whatever way is appropriate for its function.
  22958. */
  22959. AudioSampleBuffer* buffer;
  22960. /** The first sample in the buffer from which the callback is expected
  22961. to write data. */
  22962. int startSample;
  22963. /** The number of samples in the buffer which the callback is expected to
  22964. fill with data. */
  22965. int numSamples;
  22966. /** Convenient method to clear the buffer if the source is not producing any data. */
  22967. void clearActiveBufferRegion() const
  22968. {
  22969. if (buffer != 0)
  22970. buffer->clear (startSample, numSamples);
  22971. }
  22972. };
  22973. /**
  22974. Base class for objects that can produce a continuous stream of audio.
  22975. @see AudioFormatReaderSource, ResamplingAudioSource
  22976. */
  22977. class JUCE_API AudioSource
  22978. {
  22979. protected:
  22980. /** Creates an AudioSource. */
  22981. AudioSource() throw() {}
  22982. public:
  22983. /** Destructor. */
  22984. virtual ~AudioSource() {}
  22985. /** Tells the source to prepare for playing.
  22986. The source can use this opportunity to initialise anything it needs to.
  22987. Note that this method could be called more than once in succession without
  22988. a matching call to releaseResources(), so make sure your code is robust and
  22989. can handle that kind of situation.
  22990. @param samplesPerBlockExpected the number of samples that the source
  22991. will be expected to supply each time its
  22992. getNextAudioBlock() method is called. This
  22993. number may vary slightly, because it will be dependent
  22994. on audio hardware callbacks, and these aren't
  22995. guaranteed to always use a constant block size, so
  22996. the source should be able to cope with small variations.
  22997. @param sampleRate the sample rate that the output will be used at - this
  22998. is needed by sources such as tone generators.
  22999. @see releaseResources, getNextAudioBlock
  23000. */
  23001. virtual void prepareToPlay (int samplesPerBlockExpected,
  23002. double sampleRate) = 0;
  23003. /** Allows the source to release anything it no longer needs after playback has stopped.
  23004. This will be called when the source is no longer going to have its getNextAudioBlock()
  23005. method called, so it should release any spare memory, etc. that it might have
  23006. allocated during the prepareToPlay() call.
  23007. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23008. releaseResources(), and it may be called more than once in succession, so make sure your
  23009. code is robust and doesn't make any assumptions about when it will be called.
  23010. @see prepareToPlay, getNextAudioBlock
  23011. */
  23012. virtual void releaseResources() = 0;
  23013. /** Called repeatedly to fetch subsequent blocks of audio data.
  23014. After calling the prepareToPlay() method, this callback will be made each
  23015. time the audio playback hardware (or whatever other destination the audio
  23016. data is going to) needs another block of data.
  23017. It will generally be called on a high-priority system thread, or possibly even
  23018. an interrupt, so be careful not to do too much work here, as that will cause
  23019. audio glitches!
  23020. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23021. */
  23022. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23023. };
  23024. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23025. /********* End of inlined file: juce_AudioSource.h *********/
  23026. /**
  23027. A type of AudioSource which can be repositioned.
  23028. The basic AudioSource just streams continuously with no idea of a current
  23029. time or length, so the PositionableAudioSource is used for a finite stream
  23030. that has a current read position.
  23031. @see AudioSource, AudioTransportSource
  23032. */
  23033. class JUCE_API PositionableAudioSource : public AudioSource
  23034. {
  23035. protected:
  23036. /** Creates the PositionableAudioSource. */
  23037. PositionableAudioSource() throw() {}
  23038. public:
  23039. /** Destructor */
  23040. ~PositionableAudioSource() {}
  23041. /** Tells the stream to move to a new position.
  23042. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23043. should return samples from this position.
  23044. Note that this may be called on a different thread to getNextAudioBlock(),
  23045. so the subclass should make sure it's synchronised.
  23046. */
  23047. virtual void setNextReadPosition (int newPosition) = 0;
  23048. /** Returns the position from which the next block will be returned.
  23049. @see setNextReadPosition
  23050. */
  23051. virtual int getNextReadPosition() const = 0;
  23052. /** Returns the total length of the stream (in samples). */
  23053. virtual int getTotalLength() const = 0;
  23054. /** Returns true if this source is actually playing in a loop. */
  23055. virtual bool isLooping() const = 0;
  23056. };
  23057. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23058. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23059. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23060. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23061. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23062. class AudioFormat;
  23063. /**
  23064. Reads samples from an audio file stream.
  23065. A subclass that reads a specific type of audio format will be created by
  23066. an AudioFormat object.
  23067. @see AudioFormat, AudioFormatWriter
  23068. */
  23069. class JUCE_API AudioFormatReader
  23070. {
  23071. protected:
  23072. /** Creates an AudioFormatReader object.
  23073. @param sourceStream the stream to read from - this will be deleted
  23074. by this object when it is no longer needed. (Some
  23075. specialised readers might not use this parameter and
  23076. can leave it as 0).
  23077. @param formatName the description that will be returned by the getFormatName()
  23078. method
  23079. */
  23080. AudioFormatReader (InputStream* const sourceStream,
  23081. const String& formatName);
  23082. public:
  23083. /** Destructor. */
  23084. virtual ~AudioFormatReader();
  23085. /** Returns a description of what type of format this is.
  23086. E.g. "AIFF"
  23087. */
  23088. const String getFormatName() const throw() { return formatName; }
  23089. /** Reads samples from the stream.
  23090. @param destSamples an array of buffers into which the sample data for each
  23091. channel will be written.
  23092. If the format is fixed-point, each channel will be written
  23093. as an array of 32-bit signed integers using the full
  23094. range -0x80000000 to 0x7fffffff, regardless of the source's
  23095. bit-depth. If it is a floating-point format, you should cast
  23096. the resulting array to a (float**) to get the values (in the
  23097. range -1.0 to 1.0 or beyond)
  23098. If the format is stereo, then destSamples[0] is the left channel
  23099. data, and destSamples[1] is the right channel.
  23100. The array passed in should be zero-terminated, and it's ok to
  23101. pass in an array with a different number of channels than
  23102. the number in the stream, so if you pass in an array with only
  23103. one channel and the stream is stereo, the reader will
  23104. put a merged sum of the stereo channels into the single
  23105. destination channel.
  23106. @param startSample the offset into the audio stream from which the samples
  23107. should be read, as a number of samples from the start of the
  23108. stream. It's ok for this to be beyond the start or end of the
  23109. available data - any samples that can't be read will be padded
  23110. with zeros.
  23111. @param numSamples the number of samples to read. If this is greater than the
  23112. number of samples available, the result will be padded with
  23113. zeros
  23114. @returns true if the operation succeeded, false if there was an error. Note
  23115. that reading sections of data beyond the extent of the stream isn't an
  23116. error - the reader should just return zeros for these regions
  23117. @see readMaxLevels
  23118. */
  23119. virtual bool read (int** destSamples,
  23120. int64 startSample,
  23121. int numSamples) = 0;
  23122. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23123. This will read a block of samples from the stream, and measure the
  23124. highest and lowest sample levels from the channels in that section, returning
  23125. these as normalised floating-point levels.
  23126. @param startSample the offset into the audio stream to start reading from. It's
  23127. ok for this to be beyond the start or end of the stream.
  23128. @param numSamples how many samples to read
  23129. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23130. @param highestLeft on return, this is the highest absolute sample from the left channel
  23131. @param lowestRight on return, this is the lowest absolute sample from the right
  23132. channel (if there is one)
  23133. @param highestRight on return, this is the highest absolute sample from the right
  23134. channel (if there is one)
  23135. @see read
  23136. */
  23137. virtual void readMaxLevels (int64 startSample,
  23138. int64 numSamples,
  23139. float& lowestLeft,
  23140. float& highestLeft,
  23141. float& lowestRight,
  23142. float& highestRight);
  23143. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23144. This will read from the source, either forwards or backwards between two sample
  23145. positions, until it finds a sample whose magnitude lies between two specified levels.
  23146. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23147. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23148. points when you're searching for a continuous range of samples
  23149. @param startSample the first sample to look at
  23150. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23151. the search will go backwards
  23152. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23153. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23154. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23155. of this many consecutive samples, all of which lie
  23156. within the target range. When it finds such a sequence,
  23157. it returns the position of the first in-range sample
  23158. it found (i.e. the earliest one if scanning forwards, the
  23159. latest one if scanning backwards)
  23160. */
  23161. int64 searchForLevel (int64 startSample,
  23162. int64 numSamplesToSearch,
  23163. const double magnitudeRangeMinimum,
  23164. const double magnitudeRangeMaximum,
  23165. const int minimumConsecutiveSamples);
  23166. /** The sample-rate of the stream. */
  23167. double sampleRate;
  23168. /** The number of bits per sample, e.g. 16, 24, 32. */
  23169. unsigned int bitsPerSample;
  23170. /** The total number of samples in the audio stream. */
  23171. int64 lengthInSamples;
  23172. /** The total number of channels in the audio stream. */
  23173. unsigned int numChannels;
  23174. /** Indicates whether the data is floating-point or fixed. */
  23175. bool usesFloatingPointData;
  23176. /** A set of metadata values that the reader has pulled out of the stream.
  23177. Exactly what these values are depends on the format, so you can
  23178. check out the format implementation code to see what kind of stuff
  23179. they understand.
  23180. */
  23181. StringPairArray metadataValues;
  23182. /** The input stream, for use by subclasses. */
  23183. InputStream* input;
  23184. juce_UseDebuggingNewOperator
  23185. private:
  23186. String formatName;
  23187. AudioFormatReader (const AudioFormatReader&);
  23188. const AudioFormatReader& operator= (const AudioFormatReader&);
  23189. };
  23190. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23191. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23192. /**
  23193. A type of AudioSource that will read from an AudioFormatReader.
  23194. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23195. */
  23196. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23197. {
  23198. public:
  23199. /** Creates an AudioFormatReaderSource for a given reader.
  23200. @param sourceReader the reader to use as the data source
  23201. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23202. when this object is deleted; if false it will be
  23203. left up to the caller to manage its lifetime
  23204. */
  23205. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23206. const bool deleteReaderWhenThisIsDeleted);
  23207. /** Destructor. */
  23208. ~AudioFormatReaderSource();
  23209. /** Toggles loop-mode.
  23210. If set to true, it will continuously loop the input source. If false,
  23211. it will just emit silence after the source has finished.
  23212. @see isLooping
  23213. */
  23214. void setLooping (const bool shouldLoop) throw();
  23215. /** Returns whether loop-mode is turned on or not. */
  23216. bool isLooping() const { return looping; }
  23217. /** Returns the reader that's being used. */
  23218. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23219. /** Implementation of the AudioSource method. */
  23220. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23221. /** Implementation of the AudioSource method. */
  23222. void releaseResources();
  23223. /** Implementation of the AudioSource method. */
  23224. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23225. /** Implements the PositionableAudioSource method. */
  23226. void setNextReadPosition (int newPosition);
  23227. /** Implements the PositionableAudioSource method. */
  23228. int getNextReadPosition() const;
  23229. /** Implements the PositionableAudioSource method. */
  23230. int getTotalLength() const;
  23231. juce_UseDebuggingNewOperator
  23232. private:
  23233. AudioFormatReader* reader;
  23234. bool deleteReader;
  23235. int volatile nextPlayPos;
  23236. bool volatile looping;
  23237. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23238. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23239. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23240. };
  23241. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23242. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23243. #endif
  23244. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23245. #endif
  23246. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23247. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23248. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23249. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23250. /**
  23251. Wrapper class to continuously stream audio from an audio source to an
  23252. AudioIODevice.
  23253. This object acts as an AudioIODeviceCallback, so can be attached to an
  23254. output device, and will stream audio from an AudioSource.
  23255. */
  23256. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23257. {
  23258. public:
  23259. /** Creates an empty AudioSourcePlayer. */
  23260. AudioSourcePlayer();
  23261. /** Destructor.
  23262. Make sure this object isn't still being used by an AudioIODevice before
  23263. deleting it!
  23264. */
  23265. virtual ~AudioSourcePlayer();
  23266. /** Changes the current audio source to play from.
  23267. If the source passed in is already being used, this method will do nothing.
  23268. If the source is not null, its prepareToPlay() method will be called
  23269. before it starts being used for playback.
  23270. If there's another source currently playing, its releaseResources() method
  23271. will be called after it has been swapped for the new one.
  23272. @param newSource the new source to use - this will NOT be deleted
  23273. by this object when no longer needed, so it's the
  23274. caller's responsibility to manage it.
  23275. */
  23276. void setSource (AudioSource* newSource);
  23277. /** Returns the source that's playing.
  23278. May return 0 if there's no source.
  23279. */
  23280. AudioSource* getCurrentSource() const throw() { return source; }
  23281. /** Sets a gain to apply to the audio data. */
  23282. void setGain (const float newGain) throw();
  23283. /** Implementation of the AudioIODeviceCallback method. */
  23284. void audioDeviceIOCallback (const float** inputChannelData,
  23285. int totalNumInputChannels,
  23286. float** outputChannelData,
  23287. int totalNumOutputChannels,
  23288. int numSamples);
  23289. /** Implementation of the AudioIODeviceCallback method. */
  23290. void audioDeviceAboutToStart (AudioIODevice* device);
  23291. /** Implementation of the AudioIODeviceCallback method. */
  23292. void audioDeviceStopped();
  23293. juce_UseDebuggingNewOperator
  23294. private:
  23295. CriticalSection readLock;
  23296. AudioSource* source;
  23297. double sampleRate;
  23298. int bufferSize;
  23299. float* channels [128];
  23300. float* outputChans [128];
  23301. const float* inputChans [128];
  23302. AudioSampleBuffer tempBuffer;
  23303. float lastGain, gain;
  23304. AudioSourcePlayer (const AudioSourcePlayer&);
  23305. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23306. };
  23307. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23308. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23309. #endif
  23310. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23311. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23312. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23313. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23314. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23315. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23316. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23317. /**
  23318. An AudioSource which takes another source as input, and buffers it using a thread.
  23319. Create this as a wrapper around another thread, and it will read-ahead with
  23320. a background thread to smooth out playback. You can either create one of these
  23321. directly, or use it indirectly using an AudioTransportSource.
  23322. @see PositionableAudioSource, AudioTransportSource
  23323. */
  23324. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23325. {
  23326. public:
  23327. /** Creates a BufferingAudioSource.
  23328. @param source the input source to read from
  23329. @param deleteSourceWhenDeleted if true, then the input source object will
  23330. be deleted when this object is deleted
  23331. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23332. */
  23333. BufferingAudioSource (PositionableAudioSource* source,
  23334. const bool deleteSourceWhenDeleted,
  23335. int numberOfSamplesToBuffer);
  23336. /** Destructor.
  23337. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23338. flag was set in the constructor.
  23339. */
  23340. ~BufferingAudioSource();
  23341. /** Implementation of the AudioSource method. */
  23342. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23343. /** Implementation of the AudioSource method. */
  23344. void releaseResources();
  23345. /** Implementation of the AudioSource method. */
  23346. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23347. /** Implements the PositionableAudioSource method. */
  23348. void setNextReadPosition (int newPosition);
  23349. /** Implements the PositionableAudioSource method. */
  23350. int getNextReadPosition() const;
  23351. /** Implements the PositionableAudioSource method. */
  23352. int getTotalLength() const { return source->getTotalLength(); }
  23353. /** Implements the PositionableAudioSource method. */
  23354. bool isLooping() const { return source->isLooping(); }
  23355. juce_UseDebuggingNewOperator
  23356. private:
  23357. PositionableAudioSource* source;
  23358. bool deleteSourceWhenDeleted;
  23359. int numberOfSamplesToBuffer;
  23360. AudioSampleBuffer buffer;
  23361. CriticalSection bufferStartPosLock;
  23362. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23363. bool wasSourceLooping;
  23364. double volatile sampleRate;
  23365. friend class SharedBufferingAudioSourceThread;
  23366. bool readNextBufferChunk();
  23367. void readBufferSection (int start, int length, int bufferOffset);
  23368. BufferingAudioSource (const BufferingAudioSource&);
  23369. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23370. };
  23371. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23372. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23373. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23374. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23375. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23376. /**
  23377. A type of AudioSource that takes an input source and changes its sample rate.
  23378. @see AudioSource
  23379. */
  23380. class JUCE_API ResamplingAudioSource : public AudioSource
  23381. {
  23382. public:
  23383. /** Creates a ResamplingAudioSource for a given input source.
  23384. @param inputSource the input source to read from
  23385. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23386. this object is deleted
  23387. */
  23388. ResamplingAudioSource (AudioSource* const inputSource,
  23389. const bool deleteInputWhenDeleted);
  23390. /** Destructor. */
  23391. ~ResamplingAudioSource();
  23392. /** Changes the resampling ratio.
  23393. (This value can be changed at any time, even while the source is running).
  23394. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23395. values will speed it up; lower values will slow it
  23396. down. The ratio must be greater than 0
  23397. */
  23398. void setResamplingRatio (const double samplesInPerOutputSample);
  23399. /** Returns the current resampling ratio.
  23400. This is the value that was set by setResamplingRatio().
  23401. */
  23402. double getResamplingRatio() const throw() { return ratio; }
  23403. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23404. void releaseResources();
  23405. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23406. juce_UseDebuggingNewOperator
  23407. private:
  23408. AudioSource* const input;
  23409. const bool deleteInputWhenDeleted;
  23410. double ratio, lastRatio;
  23411. AudioSampleBuffer buffer;
  23412. int bufferPos, sampsInBuffer;
  23413. double subSampleOffset;
  23414. double coefficients[6];
  23415. CriticalSection ratioLock;
  23416. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23417. void createLowPass (const double proportionalRate);
  23418. struct FilterState
  23419. {
  23420. double x1, x2, y1, y2;
  23421. };
  23422. FilterState filterStates[2];
  23423. void resetFilters();
  23424. void applyFilter (float* samples, int num, FilterState& fs);
  23425. ResamplingAudioSource (const ResamplingAudioSource&);
  23426. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23427. };
  23428. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23429. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23430. /**
  23431. An AudioSource that takes a PositionableAudioSource and allows it to be
  23432. played, stopped, started, etc.
  23433. This can also be told use a buffer and background thread to read ahead, and
  23434. if can correct for different sample-rates.
  23435. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23436. to control playback of an audio file.
  23437. @see AudioSource, AudioSourcePlayer
  23438. */
  23439. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23440. public ChangeBroadcaster
  23441. {
  23442. public:
  23443. /** Creates an AudioTransportSource.
  23444. After creating one of these, use the setSource() method to select an input source.
  23445. */
  23446. AudioTransportSource();
  23447. /** Destructor. */
  23448. ~AudioTransportSource();
  23449. /** Sets the reader that is being used as the input source.
  23450. This will stop playback, reset the position to 0 and change to the new reader.
  23451. The source passed in will not be deleted by this object, so must be managed by
  23452. the caller.
  23453. @param newSource the new input source to use. This may be zero
  23454. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23455. is zero, no reading ahead will be done; if it's
  23456. greater than zero, a BufferingAudioSource will be used
  23457. to do the reading-ahead
  23458. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23459. rate of the source, and playback will be sample-rate
  23460. adjusted to maintain playback at the correct pitch. If
  23461. this is 0, no sample-rate adjustment will be performed
  23462. */
  23463. void setSource (PositionableAudioSource* const newSource,
  23464. int readAheadBufferSize = 0,
  23465. double sourceSampleRateToCorrectFor = 0.0);
  23466. /** Changes the current playback position in the source stream.
  23467. The next time the getNextAudioBlock() method is called, this
  23468. is the time from which it'll read data.
  23469. @see getPosition
  23470. */
  23471. void setPosition (double newPosition);
  23472. /** Returns the position that the next data block will be read from
  23473. This is a time in seconds.
  23474. */
  23475. double getCurrentPosition() const;
  23476. /** Returns true if the player has stopped because its input stream ran out of data.
  23477. */
  23478. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23479. /** Starts playing (if a source has been selected).
  23480. If it starts playing, this will send a message to any ChangeListeners
  23481. that are registered with this object.
  23482. */
  23483. void start();
  23484. /** Stops playing.
  23485. If it's actually playing, this will send a message to any ChangeListeners
  23486. that are registered with this object.
  23487. */
  23488. void stop();
  23489. /** Returns true if it's currently playing. */
  23490. bool isPlaying() const throw() { return playing; }
  23491. /** Changes the gain to apply to the output.
  23492. @param newGain a factor by which to multiply the outgoing samples,
  23493. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23494. */
  23495. void setGain (const float newGain) throw();
  23496. /** Returns the current gain setting.
  23497. @see setGain
  23498. */
  23499. float getGain() const throw() { return gain; }
  23500. /** Implementation of the AudioSource method. */
  23501. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23502. /** Implementation of the AudioSource method. */
  23503. void releaseResources();
  23504. /** Implementation of the AudioSource method. */
  23505. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23506. /** Implements the PositionableAudioSource method. */
  23507. void setNextReadPosition (int newPosition);
  23508. /** Implements the PositionableAudioSource method. */
  23509. int getNextReadPosition() const;
  23510. /** Implements the PositionableAudioSource method. */
  23511. int getTotalLength() const;
  23512. /** Implements the PositionableAudioSource method. */
  23513. bool isLooping() const;
  23514. juce_UseDebuggingNewOperator
  23515. private:
  23516. PositionableAudioSource* source;
  23517. ResamplingAudioSource* resamplerSource;
  23518. BufferingAudioSource* bufferingSource;
  23519. PositionableAudioSource* positionableSource;
  23520. AudioSource* masterSource;
  23521. CriticalSection callbackLock;
  23522. float volatile gain, lastGain;
  23523. bool volatile playing, stopped;
  23524. double sampleRate, sourceSampleRate;
  23525. int blockSize, readAheadBufferSize;
  23526. bool isPrepared, inputStreamEOF;
  23527. AudioTransportSource (const AudioTransportSource&);
  23528. const AudioTransportSource& operator= (const AudioTransportSource&);
  23529. };
  23530. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23531. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23532. #endif
  23533. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23534. #endif
  23535. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23536. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23537. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23538. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23539. /**
  23540. An AudioSource that takes the audio from another source, and re-maps its
  23541. input and output channels to a different arrangement.
  23542. You can use this to increase or decrease the number of channels that an
  23543. audio source uses, or to re-order those channels.
  23544. Call the reset() method before using it to set up a default mapping, and then
  23545. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23546. create an appropriate mapping, otherwise no channels will be connected and
  23547. it'll produce silence.
  23548. @see AudioSource
  23549. */
  23550. class ChannelRemappingAudioSource : public AudioSource
  23551. {
  23552. public:
  23553. /** Creates a remapping source that will pass on audio from the given input.
  23554. @param source the input source to use. Make sure that this doesn't
  23555. get deleted before the ChannelRemappingAudioSource object
  23556. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23557. when this object is deleted, if false, the caller is
  23558. responsible for its deletion
  23559. */
  23560. ChannelRemappingAudioSource (AudioSource* const source,
  23561. const bool deleteSourceWhenDeleted);
  23562. /** Destructor. */
  23563. ~ChannelRemappingAudioSource();
  23564. /** Specifies a number of channels that this audio source must produce from its
  23565. getNextAudioBlock() callback.
  23566. */
  23567. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23568. /** Clears any mapped channels.
  23569. After this, no channels are mapped, so this object will produce silence. Create
  23570. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23571. */
  23572. void clearAllMappings() throw();
  23573. /** Creates an input channel mapping.
  23574. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23575. data will be sent to destChannelIndex of our input source.
  23576. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23577. source specified when this object was created).
  23578. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23579. during our getNextAudioBlock() callback
  23580. */
  23581. void setInputChannelMapping (const int destChannelIndex,
  23582. const int sourceChannelIndex) throw();
  23583. /** Creates an output channel mapping.
  23584. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23585. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23586. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23587. (i.e. the source specified when this object was created).
  23588. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23589. during our getNextAudioBlock() callback
  23590. */
  23591. void setOutputChannelMapping (const int sourceChannelIndex,
  23592. const int destChannelIndex) throw();
  23593. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23594. our input audio source.
  23595. */
  23596. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23597. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23598. source will be sent to.
  23599. */
  23600. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23601. /** Returns an XML object to encapsulate the state of the mappings.
  23602. @see restoreFromXml
  23603. */
  23604. XmlElement* createXml() const throw();
  23605. /** Restores the mappings from an XML object created by createXML().
  23606. @see createXml
  23607. */
  23608. void restoreFromXml (const XmlElement& e) throw();
  23609. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23610. void releaseResources();
  23611. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23612. juce_UseDebuggingNewOperator
  23613. private:
  23614. int requiredNumberOfChannels;
  23615. Array <int> remappedInputs, remappedOutputs;
  23616. AudioSource* const source;
  23617. const bool deleteSourceWhenDeleted;
  23618. AudioSampleBuffer buffer;
  23619. AudioSourceChannelInfo remappedInfo;
  23620. CriticalSection lock;
  23621. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23622. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23623. };
  23624. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23625. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23626. #endif
  23627. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23628. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23629. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23630. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23631. /**
  23632. An AudioSource that performs an IIR filter on another source.
  23633. */
  23634. class JUCE_API IIRFilterAudioSource : public AudioSource
  23635. {
  23636. public:
  23637. /** Creates a IIRFilterAudioSource for a given input source.
  23638. @param inputSource the input source to read from
  23639. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23640. this object is deleted
  23641. */
  23642. IIRFilterAudioSource (AudioSource* const inputSource,
  23643. const bool deleteInputWhenDeleted);
  23644. /** Destructor. */
  23645. ~IIRFilterAudioSource();
  23646. /** Changes the filter to use the same parameters as the one being passed in.
  23647. */
  23648. void setFilterParameters (const IIRFilter& newSettings);
  23649. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23650. void releaseResources();
  23651. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23652. juce_UseDebuggingNewOperator
  23653. private:
  23654. AudioSource* const input;
  23655. const bool deleteInputWhenDeleted;
  23656. OwnedArray <IIRFilter> iirFilters;
  23657. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23658. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23659. };
  23660. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23661. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23662. #endif
  23663. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23664. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23665. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23666. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23667. /**
  23668. An AudioSource that mixes together the output of a set of other AudioSources.
  23669. Input sources can be added and removed while the mixer is running as long as their
  23670. prepareToPlay() and releaseResources() methods are called before and after adding
  23671. them to the mixer.
  23672. */
  23673. class JUCE_API MixerAudioSource : public AudioSource
  23674. {
  23675. public:
  23676. /** Creates a MixerAudioSource.
  23677. */
  23678. MixerAudioSource();
  23679. /** Destructor. */
  23680. ~MixerAudioSource();
  23681. /** Adds an input source to the mixer.
  23682. If the mixer is running you'll need to make sure that the input source
  23683. is ready to play by calling its prepareToPlay() method before adding it.
  23684. If the mixer is stopped, then its input sources will be automatically
  23685. prepared when the mixer's prepareToPlay() method is called.
  23686. @param newInput the source to add to the mixer
  23687. @param deleteWhenRemoved if true, then this source will be deleted when
  23688. the mixer is deleted or when removeAllInputs() is
  23689. called (unless the source is previously removed
  23690. with the removeInputSource method)
  23691. */
  23692. void addInputSource (AudioSource* newInput,
  23693. const bool deleteWhenRemoved);
  23694. /** Removes an input source.
  23695. If the mixer is running, this will remove the source but not call its
  23696. releaseResources() method, so the caller might want to do this manually.
  23697. @param input the source to remove
  23698. @param deleteSource whether to delete this source after it's been removed
  23699. */
  23700. void removeInputSource (AudioSource* input,
  23701. const bool deleteSource);
  23702. /** Removes all the input sources.
  23703. If the mixer is running, this will remove the sources but not call their
  23704. releaseResources() method, so the caller might want to do this manually.
  23705. Any sources which were added with the deleteWhenRemoved flag set will be
  23706. deleted by this method.
  23707. */
  23708. void removeAllInputs();
  23709. /** Implementation of the AudioSource method.
  23710. This will call prepareToPlay() on all its input sources.
  23711. */
  23712. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23713. /** Implementation of the AudioSource method.
  23714. This will call releaseResources() on all its input sources.
  23715. */
  23716. void releaseResources();
  23717. /** Implementation of the AudioSource method. */
  23718. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23719. juce_UseDebuggingNewOperator
  23720. private:
  23721. VoidArray inputs;
  23722. BitArray inputsToDelete;
  23723. CriticalSection lock;
  23724. AudioSampleBuffer tempBuffer;
  23725. double currentSampleRate;
  23726. int bufferSizeExpected;
  23727. MixerAudioSource (const MixerAudioSource&);
  23728. const MixerAudioSource& operator= (const MixerAudioSource&);
  23729. };
  23730. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23731. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23732. #endif
  23733. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23734. #endif
  23735. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23736. #endif
  23737. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23738. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23739. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23740. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23741. /**
  23742. A simple AudioSource that generates a sine wave.
  23743. */
  23744. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  23745. {
  23746. public:
  23747. /** Creates a ToneGeneratorAudioSource. */
  23748. ToneGeneratorAudioSource();
  23749. /** Destructor. */
  23750. ~ToneGeneratorAudioSource();
  23751. /** Sets the signal's amplitude. */
  23752. void setAmplitude (const float newAmplitude);
  23753. /** Sets the signal's frequency. */
  23754. void setFrequency (const double newFrequencyHz);
  23755. /** Implementation of the AudioSource method. */
  23756. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23757. /** Implementation of the AudioSource method. */
  23758. void releaseResources();
  23759. /** Implementation of the AudioSource method. */
  23760. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23761. juce_UseDebuggingNewOperator
  23762. private:
  23763. double frequency, sampleRate;
  23764. double currentPhase, phasePerSample;
  23765. float amplitude;
  23766. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  23767. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  23768. };
  23769. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23770. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23771. #endif
  23772. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23773. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  23774. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23775. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23776. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  23777. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23778. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23779. class AudioDeviceManager;
  23780. class Component;
  23781. /**
  23782. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  23783. To get a list of available audio driver types, use the createDeviceTypes()
  23784. method. Each of the objects returned can then be used to list the available
  23785. devices of that type. E.g.
  23786. @code
  23787. OwnedArray <AudioIODeviceType> types;
  23788. AudioIODeviceType::createDeviceTypes (types);
  23789. for (int i = 0; i < types.size(); ++i)
  23790. {
  23791. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  23792. types[i]->scanForDevices(); // This must be called before getting the list of devices
  23793. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  23794. for (int j = 0; j < deviceNames.size(); ++j)
  23795. {
  23796. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  23797. ...
  23798. }
  23799. }
  23800. @endcode
  23801. For an easier way of managing audio devices and their settings, have a look at the
  23802. AudioDeviceManager class.
  23803. @see AudioIODevice, AudioDeviceManager
  23804. */
  23805. class JUCE_API AudioIODeviceType
  23806. {
  23807. public:
  23808. /** Returns the name of this type of driver that this object manages.
  23809. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  23810. */
  23811. const String& getTypeName() const throw() { return typeName; }
  23812. /** Refreshes the object's cached list of known devices.
  23813. This must be called at least once before calling getDeviceNames() or any of
  23814. the other device creation methods.
  23815. */
  23816. virtual void scanForDevices() = 0;
  23817. /** Returns the list of available devices of this type.
  23818. The scanForDevices() method must have been called to create this list.
  23819. @param wantInputNames only really used by DirectSound where devices are split up
  23820. into inputs and outputs, this indicates whether to use
  23821. the input or output name to refer to a pair of devices.
  23822. */
  23823. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  23824. /** Returns the name of the default device.
  23825. This will be one of the names from the getDeviceNames() list.
  23826. @param forInput if true, this means that a default input device should be
  23827. returned; if false, it should return the default output
  23828. */
  23829. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  23830. /** Returns the index of a given device in the list of device names.
  23831. If asInput is true, it shows the index in the inputs list, otherwise it
  23832. looks for it in the outputs list.
  23833. */
  23834. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  23835. /** Returns true if two different devices can be used for the input and output.
  23836. */
  23837. virtual bool hasSeparateInputsAndOutputs() const = 0;
  23838. /** Creates one of the devices of this type.
  23839. The deviceName must be one of the strings returned by getDeviceNames(), and
  23840. scanForDevices() must have been called before this method is used.
  23841. */
  23842. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  23843. const String& inputDeviceName) = 0;
  23844. struct DeviceSetupDetails
  23845. {
  23846. AudioDeviceManager* manager;
  23847. int minNumInputChannels, maxNumInputChannels;
  23848. int minNumOutputChannels, maxNumOutputChannels;
  23849. bool useStereoPairs;
  23850. };
  23851. /** Destructor. */
  23852. virtual ~AudioIODeviceType();
  23853. protected:
  23854. AudioIODeviceType (const tchar* const typeName);
  23855. private:
  23856. String typeName;
  23857. AudioIODeviceType (const AudioIODeviceType&);
  23858. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  23859. };
  23860. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23861. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  23862. /********* Start of inlined file: juce_MidiOutput.h *********/
  23863. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  23864. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  23865. /**
  23866. Represents a midi output device.
  23867. To create one of these, use the static getDevices() method to find out what
  23868. outputs are available, then use the openDevice() method to try to open one.
  23869. @see MidiInput
  23870. */
  23871. class JUCE_API MidiOutput : private Thread
  23872. {
  23873. public:
  23874. /** Returns a list of the available midi output devices.
  23875. You can open one of the devices by passing its index into the
  23876. openDevice() method.
  23877. @see getDefaultDeviceIndex, openDevice
  23878. */
  23879. static const StringArray getDevices();
  23880. /** Returns the index of the default midi output device to use.
  23881. This refers to the index in the list returned by getDevices().
  23882. */
  23883. static int getDefaultDeviceIndex();
  23884. /** Tries to open one of the midi output devices.
  23885. This will return a MidiOutput object if it manages to open it. You can then
  23886. send messages to this device, and delete it when no longer needed.
  23887. If the device can't be opened, this will return a null pointer.
  23888. @param deviceIndex the index of a device from the list returned by getDevices()
  23889. @see getDevices
  23890. */
  23891. static MidiOutput* openDevice (int deviceIndex);
  23892. #if JUCE_LINUX || DOXYGEN
  23893. /** LINUX ONLY - This will try to create a new midi output device.
  23894. This will attempt to create a new midi output device that other apps can connect
  23895. to and use as their midi input.
  23896. Returns 0 if a device can't be created.
  23897. @param deviceName the name to use for the new device
  23898. */
  23899. static MidiOutput* createNewDevice (const String& deviceName);
  23900. #endif
  23901. /** Destructor. */
  23902. ~MidiOutput();
  23903. /** Makes this device output a midi message.
  23904. @see MidiMessage
  23905. */
  23906. void sendMessageNow (const MidiMessage& message);
  23907. /** Sends a midi reset to the device. */
  23908. void reset();
  23909. /** Returns the current volume setting for this device. */
  23910. bool getVolume (float& leftVol,
  23911. float& rightVol);
  23912. /** Changes the overall volume for this device. */
  23913. void setVolume (float leftVol,
  23914. float rightVol);
  23915. /** This lets you supply a block of messages that will be sent out at some point
  23916. in the future.
  23917. The MidiOutput class has an internal thread that can send out timestamped
  23918. messages - this appends a set of messages to its internal buffer, ready for
  23919. sending.
  23920. This will only work if you've already started the thread with startBackgroundThread().
  23921. A time is supplied, at which the block of messages should be sent. This time uses
  23922. the same time base as Time::getMillisecondCounter(), and must be in the future.
  23923. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  23924. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  23925. samplesPerSecondForBuffer value is needed to convert this sample position to a
  23926. real time.
  23927. */
  23928. void sendBlockOfMessages (const MidiBuffer& buffer,
  23929. const double millisecondCounterToStartAt,
  23930. double samplesPerSecondForBuffer) throw();
  23931. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  23932. */
  23933. void clearAllPendingMessages() throw();
  23934. /** Starts up a background thread so that the device can send blocks of data.
  23935. Call this to get the device ready, before using sendBlockOfMessages().
  23936. */
  23937. void startBackgroundThread() throw();
  23938. /** Stops the background thread, and clears any pending midi events.
  23939. @see startBackgroundThread
  23940. */
  23941. void stopBackgroundThread() throw();
  23942. juce_UseDebuggingNewOperator
  23943. private:
  23944. void* internal;
  23945. struct PendingMessage
  23946. {
  23947. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  23948. MidiMessage message;
  23949. PendingMessage* next;
  23950. juce_UseDebuggingNewOperator
  23951. };
  23952. CriticalSection lock;
  23953. PendingMessage* firstMessage;
  23954. MidiOutput() throw();
  23955. MidiOutput (const MidiOutput&);
  23956. void run();
  23957. };
  23958. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  23959. /********* End of inlined file: juce_MidiOutput.h *********/
  23960. /********* Start of inlined file: juce_ComboBox.h *********/
  23961. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  23962. #define __JUCE_COMBOBOX_JUCEHEADER__
  23963. /********* Start of inlined file: juce_Label.h *********/
  23964. #ifndef __JUCE_LABEL_JUCEHEADER__
  23965. #define __JUCE_LABEL_JUCEHEADER__
  23966. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  23967. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23968. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23969. /**
  23970. Object for monitoring a component, and later testing whether it's still valid.
  23971. Slightly obscure, this one, but it's used internally for making sure that
  23972. after some callbacks, a component hasn't been deleted. It's more reliable than
  23973. just using isValidComponent(), which can provide false-positives if a new
  23974. component is created at the same memory location as an old one.
  23975. */
  23976. class JUCE_API ComponentDeletionWatcher
  23977. {
  23978. public:
  23979. /** Creates a watcher for a given component.
  23980. The component must be valid at the time it's passed in.
  23981. */
  23982. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  23983. /** Destructor. */
  23984. ~ComponentDeletionWatcher() throw();
  23985. /** Returns true if the component has been deleted since the time that this
  23986. object was created.
  23987. */
  23988. bool hasBeenDeleted() const throw();
  23989. /** Returns the component that's being watched, or null if it has been deleted. */
  23990. const Component* getComponent() const throw();
  23991. juce_UseDebuggingNewOperator
  23992. private:
  23993. const Component* const componentToWatch;
  23994. const uint32 componentUID;
  23995. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  23996. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  23997. };
  23998. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23999. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24000. /********* Start of inlined file: juce_TextEditor.h *********/
  24001. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24002. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24003. /********* Start of inlined file: juce_UndoManager.h *********/
  24004. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24005. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24006. /********* Start of inlined file: juce_UndoableAction.h *********/
  24007. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24008. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24009. /**
  24010. Used by the UndoManager class to store an action which can be done
  24011. and undone.
  24012. @see UndoManager
  24013. */
  24014. class JUCE_API UndoableAction
  24015. {
  24016. protected:
  24017. /** Creates an action. */
  24018. UndoableAction() throw() {}
  24019. public:
  24020. /** Destructor. */
  24021. virtual ~UndoableAction() {}
  24022. /** Overridden by a subclass to perform the action.
  24023. This method is called by the UndoManager, and shouldn't be used directly by
  24024. applications.
  24025. Be careful not to make any calls in a perform() method that could call
  24026. recursively back into the UndoManager::perform() method
  24027. @returns true if the action could be performed.
  24028. @see UndoManager::perform
  24029. */
  24030. virtual bool perform() = 0;
  24031. /** Overridden by a subclass to undo the action.
  24032. This method is called by the UndoManager, and shouldn't be used directly by
  24033. applications.
  24034. Be careful not to make any calls in an undo() method that could call
  24035. recursively back into the UndoManager::perform() method
  24036. @returns true if the action could be undone without any errors.
  24037. @see UndoManager::perform
  24038. */
  24039. virtual bool undo() = 0;
  24040. /** Returns a value to indicate how much memory this object takes up.
  24041. Because the UndoManager keeps a list of UndoableActions, this is used
  24042. to work out how much space each one will take up, so that the UndoManager
  24043. can work out how many to keep.
  24044. The default value returned here is 10 - units are arbitrary and
  24045. don't have to be accurate.
  24046. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24047. UndoManager::setMaxNumberOfStoredUnits
  24048. */
  24049. virtual int getSizeInUnits() { return 10; }
  24050. };
  24051. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24052. /********* End of inlined file: juce_UndoableAction.h *********/
  24053. /**
  24054. Manages a list of undo/redo commands.
  24055. An UndoManager object keeps a list of past actions and can use these actions
  24056. to move backwards and forwards through an undo history.
  24057. To use it, create subclasses of UndoableAction which perform all the
  24058. actions you need, then when you need to actually perform an action, create one
  24059. and pass it to the UndoManager's perform() method.
  24060. The manager also uses the concept of 'transactions' to group the actions
  24061. together - all actions performed between calls to beginNewTransaction() are
  24062. grouped together and are all undone/redone as a group.
  24063. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24064. when actions are performed or undone.
  24065. @see UndoableAction
  24066. */
  24067. class JUCE_API UndoManager : public ChangeBroadcaster
  24068. {
  24069. public:
  24070. /** Creates an UndoManager.
  24071. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24072. to indicate how much storage it takes up
  24073. (UndoableAction::getSizeInUnits()), so this
  24074. lets you specify the maximum total number of
  24075. units that the undomanager is allowed to
  24076. keep in memory before letting the older actions
  24077. drop off the end of the list.
  24078. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24079. that will be kept, even if this involves exceeding
  24080. the amount of space specified in maxNumberOfUnitsToKeep
  24081. */
  24082. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24083. const int minimumTransactionsToKeep = 30);
  24084. /** Destructor. */
  24085. ~UndoManager();
  24086. /** Deletes all stored actions in the list. */
  24087. void clearUndoHistory();
  24088. /** Returns the current amount of space to use for storing UndoableAction objects.
  24089. @see setMaxNumberOfStoredUnits
  24090. */
  24091. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24092. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24093. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24094. to indicate how much storage it takes up
  24095. (UndoableAction::getSizeInUnits()), so this
  24096. lets you specify the maximum total number of
  24097. units that the undomanager is allowed to
  24098. keep in memory before letting the older actions
  24099. drop off the end of the list.
  24100. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24101. that will be kept, even if this involves exceeding
  24102. the amount of space specified in maxNumberOfUnitsToKeep
  24103. @see getNumberOfUnitsTakenUpByStoredCommands
  24104. */
  24105. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24106. const int minimumTransactionsToKeep);
  24107. /** Performs an action and adds it to the undo history list.
  24108. @param action the action to perform - this will be deleted by the UndoManager
  24109. when no longer needed
  24110. @param actionName if this string is non-empty, the current transaction will be
  24111. given this name; if it's empty, the current transaction name will
  24112. be left unchanged. See setCurrentTransactionName()
  24113. @returns true if the command succeeds - see UndoableAction::perform
  24114. @see beginNewTransaction
  24115. */
  24116. bool perform (UndoableAction* const action,
  24117. const String& actionName = String::empty);
  24118. /** Starts a new group of actions that together will be treated as a single transaction.
  24119. All actions that are passed to the perform() method between calls to this
  24120. method are grouped together and undone/redone together by a single call to
  24121. undo() or redo().
  24122. @param actionName a description of the transaction that is about to be
  24123. performed
  24124. */
  24125. void beginNewTransaction (const String& actionName = String::empty);
  24126. /** Changes the name stored for the current transaction.
  24127. Each transaction is given a name when the beginNewTransaction() method is
  24128. called, but this can be used to change that name without starting a new
  24129. transaction.
  24130. */
  24131. void setCurrentTransactionName (const String& newName);
  24132. /** Returns true if there's at least one action in the list to undo.
  24133. @see getUndoDescription, undo, canRedo
  24134. */
  24135. bool canUndo() const;
  24136. /** Returns the description of the transaction that would be next to get undone.
  24137. The description returned is the one that was passed into beginNewTransaction
  24138. before the set of actions was performed.
  24139. @see undo
  24140. */
  24141. const String getUndoDescription() const;
  24142. /** Tries to roll-back the last transaction.
  24143. @returns true if the transaction can be undone, and false if it fails, or
  24144. if there aren't any transactions to undo
  24145. */
  24146. bool undo();
  24147. /** Tries to roll-back any actions that were added to the current transaction.
  24148. This will perform an undo() only if there are some actions in the undo list
  24149. that were added after the last call to beginNewTransaction().
  24150. This is useful because it lets you call beginNewTransaction(), then
  24151. perform an operation which may or may not actually perform some actions, and
  24152. then call this method to get rid of any actions that might have been done
  24153. without it rolling back the previous transaction if nothing was actually
  24154. done.
  24155. @returns true if any actions were undone.
  24156. */
  24157. bool undoCurrentTransactionOnly();
  24158. /** Returns a list of the UndoableAction objects that have been performed during the
  24159. transaction that is currently open.
  24160. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24161. were to be called now.
  24162. The first item in the list is the earliest action performed.
  24163. */
  24164. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24165. /** Returns true if there's at least one action in the list to redo.
  24166. @see getRedoDescription, redo, canUndo
  24167. */
  24168. bool canRedo() const;
  24169. /** Returns the description of the transaction that would be next to get redone.
  24170. The description returned is the one that was passed into beginNewTransaction
  24171. before the set of actions was performed.
  24172. @see redo
  24173. */
  24174. const String getRedoDescription() const;
  24175. /** Tries to redo the last transaction that was undone.
  24176. @returns true if the transaction can be redone, and false if it fails, or
  24177. if there aren't any transactions to redo
  24178. */
  24179. bool redo();
  24180. juce_UseDebuggingNewOperator
  24181. private:
  24182. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24183. StringArray transactionNames;
  24184. String currentTransactionName;
  24185. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24186. bool newTransaction, reentrancyCheck;
  24187. // disallow copy constructor
  24188. UndoManager (const UndoManager&);
  24189. const UndoManager& operator= (const UndoManager&);
  24190. };
  24191. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24192. /********* End of inlined file: juce_UndoManager.h *********/
  24193. class TextEditor;
  24194. class TextHolderComponent;
  24195. /**
  24196. Receives callbacks from a TextEditor component when it changes.
  24197. @see TextEditor::addListener
  24198. */
  24199. class JUCE_API TextEditorListener
  24200. {
  24201. public:
  24202. /** Destructor. */
  24203. virtual ~TextEditorListener() {}
  24204. /** Called when the user changes the text in some way. */
  24205. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24206. /** Called when the user presses the return key. */
  24207. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24208. /** Called when the user presses the escape key. */
  24209. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24210. /** Called when the text editor loses focus. */
  24211. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24212. };
  24213. /**
  24214. A component containing text that can be edited.
  24215. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24216. fonts and colours.
  24217. @see TextEditorListener, Label
  24218. */
  24219. class JUCE_API TextEditor : public Component,
  24220. public SettableTooltipClient
  24221. {
  24222. public:
  24223. /** Creates a new, empty text editor.
  24224. @param componentName the name to pass to the component for it to use as its name
  24225. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24226. for all characters that are drawn on screen - e.g. to create
  24227. a password-style textbox containing circular blobs instead of text,
  24228. you could set this value to 0x25cf, which is the unicode character
  24229. for a black splodge (not all fonts include this, though), or 0x2022,
  24230. which is a bullet (probably the best choice for linux).
  24231. */
  24232. TextEditor (const String& componentName = String::empty,
  24233. const tchar passwordCharacter = 0);
  24234. /** Destructor. */
  24235. virtual ~TextEditor();
  24236. /** Puts the editor into either multi- or single-line mode.
  24237. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24238. editor.
  24239. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24240. on if you want a multi-line editor with line-breaks.
  24241. @see isMultiLine, setReturnKeyStartsNewLine
  24242. */
  24243. void setMultiLine (const bool shouldBeMultiLine,
  24244. const bool shouldWordWrap = true);
  24245. /** Returns true if the editor is in multi-line mode.
  24246. */
  24247. bool isMultiLine() const throw();
  24248. /** Changes the behaviour of the return key.
  24249. If set to true, the return key will insert a new-line into the text; if false
  24250. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24251. method. By default this is set to false, and when true it will only insert
  24252. new-lines when in multi-line mode (see setMultiLine()).
  24253. */
  24254. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24255. /** Returns the value set by setReturnKeyStartsNewLine().
  24256. See setReturnKeyStartsNewLine() for more info.
  24257. */
  24258. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24259. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24260. or whether it gets ignored.
  24261. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24262. between components.
  24263. */
  24264. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24265. /** Returns true if the tab key is being used for input.
  24266. @see setTabKeyUsedAsCharacter
  24267. */
  24268. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24269. /** Changes the editor to read-only mode.
  24270. By default, the text editor is not read-only. If you're making it read-only, you
  24271. might also want to call setCaretVisible (false) to get rid of the caret.
  24272. The text can still be highlighted and copied when in read-only mode.
  24273. @see isReadOnly, setCaretVisible
  24274. */
  24275. void setReadOnly (const bool shouldBeReadOnly);
  24276. /** Returns true if the editor is in read-only mode.
  24277. */
  24278. bool isReadOnly() const throw();
  24279. /** Makes the caret visible or invisible.
  24280. By default the caret is visible.
  24281. @see setCaretColour, setCaretPosition
  24282. */
  24283. void setCaretVisible (const bool shouldBeVisible) throw();
  24284. /** Returns true if the caret is enabled.
  24285. @see setCaretVisible
  24286. */
  24287. bool isCaretVisible() const throw() { return caretVisible; }
  24288. /** Enables/disables a vertical scrollbar.
  24289. (This only applies when in multi-line mode). When the text gets too long to fit
  24290. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24291. this is enabled, the scrollbar will be hidden unless it's needed.
  24292. By default the scrollbar is enabled.
  24293. */
  24294. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24295. /** Returns true if scrollbars are enabled.
  24296. @see setScrollbarsShown
  24297. */
  24298. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24299. /** Changes the password character used to disguise the text.
  24300. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24301. for all characters that are drawn on screen - e.g. to create
  24302. a password-style textbox containing circular blobs instead of text,
  24303. you could set this value to 0x25cf, which is the unicode character
  24304. for a black splodge (not all fonts include this, though), or 0x2022,
  24305. which is a bullet (probably the best choice for linux).
  24306. */
  24307. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24308. /** Returns the current password character.
  24309. @see setPasswordCharacter
  24310. l */
  24311. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24312. /** Allows a right-click menu to appear for the editor.
  24313. (This defaults to being enabled).
  24314. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24315. of options such as cut/copy/paste, undo/redo, etc.
  24316. */
  24317. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24318. /** Returns true if the right-click menu is enabled.
  24319. @see setPopupMenuEnabled
  24320. */
  24321. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24322. /** Returns true if a popup-menu is currently being displayed.
  24323. */
  24324. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24325. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24326. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24327. methods.
  24328. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24329. */
  24330. enum ColourIds
  24331. {
  24332. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24333. transparent if necessary. */
  24334. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24335. that because the editor can contain multiple colours, calling this
  24336. method won't change the colour of existing text - to do that, call
  24337. applyFontToAllText() after calling this method.*/
  24338. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24339. the text - this can be transparent if you don't want to show any
  24340. highlighting.*/
  24341. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24342. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24343. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24344. the edge of the component. */
  24345. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24346. the edge of the component when it has focus. */
  24347. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24348. around the edge of the editor. */
  24349. };
  24350. /** Sets the font to use for newly added text.
  24351. This will change the font that will be used next time any text is added or entered
  24352. into the editor. It won't change the font of any existing text - to do that, use
  24353. applyFontToAllText() instead.
  24354. @see applyFontToAllText
  24355. */
  24356. void setFont (const Font& newFont) throw();
  24357. /** Applies a font to all the text in the editor.
  24358. This will also set the current font to use for any new text that's added.
  24359. @see setFont
  24360. */
  24361. void applyFontToAllText (const Font& newFont);
  24362. /** Returns the font that's currently being used for new text.
  24363. @see setFont
  24364. */
  24365. const Font getFont() const throw();
  24366. /** If set to true, focusing on the editor will highlight all its text.
  24367. (Set to false by default).
  24368. This is useful for boxes where you expect the user to re-enter all the
  24369. text when they focus on the component, rather than editing what's already there.
  24370. */
  24371. void setSelectAllWhenFocused (const bool b) throw();
  24372. /** Sets limits on the characters that can be entered.
  24373. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24374. limit is set
  24375. @param allowedCharacters if this is non-empty, then only characters that occur in
  24376. this string are allowed to be entered into the editor.
  24377. */
  24378. void setInputRestrictions (const int maxTextLength,
  24379. const String& allowedCharacters = String::empty) throw();
  24380. /** When the text editor is empty, it can be set to display a message.
  24381. This is handy for things like telling the user what to type in the box - the
  24382. string is only displayed, it's not taken to actually be the contents of
  24383. the editor.
  24384. */
  24385. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24386. /** Changes the size of the scrollbars that are used.
  24387. Handy if you need smaller scrollbars for a small text box.
  24388. */
  24389. void setScrollBarThickness (const int newThicknessPixels);
  24390. /** Shows or hides the buttons on any scrollbars that are used.
  24391. @see ScrollBar::setButtonVisibility
  24392. */
  24393. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24394. /** Registers a listener to be told when things happen to the text.
  24395. @see removeListener
  24396. */
  24397. void addListener (TextEditorListener* const newListener) throw();
  24398. /** Deregisters a listener.
  24399. @see addListener
  24400. */
  24401. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24402. /** Returns the entire contents of the editor. */
  24403. const String getText() const throw();
  24404. /** Returns a section of the contents of the editor. */
  24405. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24406. /** Returns true if there are no characters in the editor.
  24407. This is more efficient than calling getText().isEmpty().
  24408. */
  24409. bool isEmpty() const throw();
  24410. /** Sets the entire content of the editor.
  24411. This will clear the editor and insert the given text (using the current text colour
  24412. and font). You can set the current text colour using
  24413. @code setColour (TextEditor::textColourId, ...);
  24414. @endcode
  24415. @param newText the text to add
  24416. @param sendTextChangeMessage if true, this will cause a change message to
  24417. be sent to all the listeners.
  24418. @see insertText
  24419. */
  24420. void setText (const String& newText,
  24421. const bool sendTextChangeMessage = true);
  24422. /** Inserts some text at the current cursor position.
  24423. If a section of the text is highlighted, it will be replaced by
  24424. this string, otherwise it will be inserted.
  24425. To delete a section of text, you can use setHighlightedRegion() to
  24426. highlight it, and call insertTextAtCursor (String::empty).
  24427. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24428. */
  24429. void insertTextAtCursor (String textToInsert);
  24430. /** Deletes all the text from the editor. */
  24431. void clear();
  24432. /** Deletes the currently selected region, and puts it on the clipboard.
  24433. @see copy, paste, SystemClipboard
  24434. */
  24435. void cut();
  24436. /** Copies any currently selected region to the clipboard.
  24437. @see cut, paste, SystemClipboard
  24438. */
  24439. void copy();
  24440. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24441. @see cut, copy, SystemClipboard
  24442. */
  24443. void paste();
  24444. /** Moves the caret to be in front of a given character.
  24445. @see getCaretPosition
  24446. */
  24447. void setCaretPosition (const int newIndex) throw();
  24448. /** Returns the current index of the caret.
  24449. @see setCaretPosition
  24450. */
  24451. int getCaretPosition() const throw();
  24452. /** Attempts to scroll the text editor so that the caret ends up at
  24453. a specified position.
  24454. This won't affect the caret's position within the text, it tries to scroll
  24455. the entire editor vertically and horizontally so that the caret is sitting
  24456. at the given position (relative to the top-left of this component).
  24457. Depending on the amount of text available, it might not be possible to
  24458. scroll far enough for the caret to reach this exact position, but it
  24459. will go as far as it can in that direction.
  24460. */
  24461. void scrollEditorToPositionCaret (const int desiredCaretX,
  24462. const int desiredCaretY) throw();
  24463. /** Get the graphical position of the caret.
  24464. The rectangle returned is relative to the component's top-left corner.
  24465. @see scrollEditorToPositionCaret
  24466. */
  24467. const Rectangle getCaretRectangle() throw();
  24468. /** Selects a section of the text.
  24469. */
  24470. void setHighlightedRegion (int startIndex,
  24471. int numberOfCharactersToHighlight) throw();
  24472. /** Returns the first character that is selected.
  24473. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24474. will return 0.
  24475. @see setHighlightedRegion, getHighlightedRegionLength
  24476. */
  24477. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24478. /** Returns the number of characters that are selected.
  24479. @see setHighlightedRegion, getHighlightedRegionStart
  24480. */
  24481. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24482. /** Returns the section of text that is currently selected. */
  24483. const String getHighlightedText() const throw();
  24484. /** Finds the index of the character at a given position.
  24485. The co-ordinates are relative to the component's top-left.
  24486. */
  24487. int getTextIndexAt (const int x, const int y) throw();
  24488. /** Returns the total width of the text, as it is currently laid-out.
  24489. This may be larger than the size of the TextEditor, and can change when
  24490. the TextEditor is resized or the text changes.
  24491. */
  24492. int getTextWidth() const throw();
  24493. /** Returns the maximum height of the text, as it is currently laid-out.
  24494. This may be larger than the size of the TextEditor, and can change when
  24495. the TextEditor is resized or the text changes.
  24496. */
  24497. int getTextHeight() const throw();
  24498. /** Changes the size of the gap at the top and left-edge of the editor.
  24499. By default there's a gap of 4 pixels.
  24500. */
  24501. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24502. /** Changes the size of border left around the edge of the component.
  24503. @see getBorder
  24504. */
  24505. void setBorder (const BorderSize& border) throw();
  24506. /** Returns the size of border around the edge of the component.
  24507. @see setBorder
  24508. */
  24509. const BorderSize getBorder() const throw();
  24510. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24511. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24512. set to false, it won't.
  24513. */
  24514. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24515. /** @internal */
  24516. void paint (Graphics& g);
  24517. /** @internal */
  24518. void paintOverChildren (Graphics& g);
  24519. /** @internal */
  24520. void mouseDown (const MouseEvent& e);
  24521. /** @internal */
  24522. void mouseUp (const MouseEvent& e);
  24523. /** @internal */
  24524. void mouseDrag (const MouseEvent& e);
  24525. /** @internal */
  24526. void mouseDoubleClick (const MouseEvent& e);
  24527. /** @internal */
  24528. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24529. /** @internal */
  24530. bool keyPressed (const KeyPress& key);
  24531. /** @internal */
  24532. bool keyStateChanged();
  24533. /** @internal */
  24534. void focusGained (FocusChangeType cause);
  24535. /** @internal */
  24536. void focusLost (FocusChangeType cause);
  24537. /** @internal */
  24538. void resized();
  24539. /** @internal */
  24540. void enablementChanged();
  24541. /** @internal */
  24542. void colourChanged();
  24543. juce_UseDebuggingNewOperator
  24544. protected:
  24545. /** This adds the items to the popup menu.
  24546. By default it adds the cut/copy/paste items, but you can override this if
  24547. you need to replace these with your own items.
  24548. If you want to add your own items to the existing ones, you can override this,
  24549. call the base class's addPopupMenuItems() method, then append your own items.
  24550. When the menu has been shown, performPopupMenuAction() will be called to
  24551. perform the item that the user has chosen.
  24552. The default menu items will be added using item IDs in the range
  24553. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24554. menu IDs.
  24555. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24556. a pointer to the info about it, or may be null if the menu is being triggered
  24557. by some other means.
  24558. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24559. */
  24560. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24561. const MouseEvent* mouseClickEvent);
  24562. /** This is called to perform one of the items that was shown on the popup menu.
  24563. If you've overridden addPopupMenuItems(), you should also override this
  24564. to perform the actions that you've added.
  24565. If you've overridden addPopupMenuItems() but have still left the default items
  24566. on the menu, remember to call the superclass's performPopupMenuAction()
  24567. so that it can perform the default actions if that's what the user clicked on.
  24568. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24569. */
  24570. virtual void performPopupMenuAction (const int menuItemID);
  24571. /** Scrolls the minimum distance needed to get the caret into view. */
  24572. void scrollToMakeSureCursorIsVisible() throw();
  24573. /** @internal */
  24574. void moveCaret (int newCaretPos) throw();
  24575. /** @internal */
  24576. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24577. /** Used internally to dispatch a text-change message. */
  24578. void textChanged() throw();
  24579. /** Counts the number of characters in the text.
  24580. This is quicker than getting the text as a string if you just need to know
  24581. the length.
  24582. */
  24583. int getTotalNumChars() throw();
  24584. /** Begins a new transaction in the UndoManager.
  24585. */
  24586. void newTransaction() throw();
  24587. /** Used internally to trigger an undo or redo. */
  24588. void doUndoRedo (const bool isRedo);
  24589. /** Can be overridden to intercept return key presses directly */
  24590. virtual void returnPressed();
  24591. /** Can be overridden to intercept escape key presses directly */
  24592. virtual void escapePressed();
  24593. /** @internal */
  24594. void handleCommandMessage (int commandId);
  24595. private:
  24596. Viewport* viewport;
  24597. TextHolderComponent* textHolder;
  24598. BorderSize borderSize;
  24599. bool readOnly : 1;
  24600. bool multiline : 1;
  24601. bool wordWrap : 1;
  24602. bool returnKeyStartsNewLine : 1;
  24603. bool caretVisible : 1;
  24604. bool popupMenuEnabled : 1;
  24605. bool selectAllTextWhenFocused : 1;
  24606. bool scrollbarVisible : 1;
  24607. bool wasFocused : 1;
  24608. bool caretFlashState : 1;
  24609. bool keepCursorOnScreen : 1;
  24610. bool tabKeyUsed : 1;
  24611. bool menuActive : 1;
  24612. UndoManager undoManager;
  24613. float cursorX, cursorY, cursorHeight;
  24614. int maxTextLength;
  24615. int selectionStart, selectionEnd;
  24616. int leftIndent, topIndent;
  24617. unsigned int lastTransactionTime;
  24618. Font currentFont;
  24619. int totalNumChars, caretPosition;
  24620. VoidArray sections;
  24621. String textToShowWhenEmpty;
  24622. Colour colourForTextWhenEmpty;
  24623. tchar passwordCharacter;
  24624. enum
  24625. {
  24626. notDragging,
  24627. draggingSelectionStart,
  24628. draggingSelectionEnd
  24629. } dragType;
  24630. String allowedCharacters;
  24631. SortedSet <void*> listeners;
  24632. friend class TextEditorInsertAction;
  24633. friend class TextEditorRemoveAction;
  24634. void coalesceSimilarSections() throw();
  24635. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24636. void clearInternal (UndoManager* const um) throw();
  24637. void insert (const String& text,
  24638. const int insertIndex,
  24639. const Font& font,
  24640. const Colour& colour,
  24641. UndoManager* const um,
  24642. const int caretPositionToMoveTo) throw();
  24643. void reinsert (const int insertIndex,
  24644. const VoidArray& sections) throw();
  24645. void remove (const int startIndex,
  24646. int endIndex,
  24647. UndoManager* const um,
  24648. const int caretPositionToMoveTo) throw();
  24649. void getCharPosition (const int index,
  24650. float& x, float& y,
  24651. float& lineHeight) const throw();
  24652. void updateCaretPosition() throw();
  24653. int indexAtPosition (const float x,
  24654. const float y) throw();
  24655. int findWordBreakAfter (const int position) const throw();
  24656. int findWordBreakBefore (const int position) const throw();
  24657. friend class TextHolderComponent;
  24658. friend class TextEditorViewport;
  24659. void drawContent (Graphics& g);
  24660. void updateTextHolderSize() throw();
  24661. float getWordWrapWidth() const throw();
  24662. void timerCallbackInt();
  24663. void repaintCaret();
  24664. void repaintText (int textStartIndex, int textEndIndex);
  24665. TextEditor (const TextEditor&);
  24666. const TextEditor& operator= (const TextEditor&);
  24667. };
  24668. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24669. /********* End of inlined file: juce_TextEditor.h *********/
  24670. class Label;
  24671. /**
  24672. A class for receiving events from a Label.
  24673. You can register a LabelListener with a Label using the Label::addListener()
  24674. method, and it will be called when the text of the label changes, either because
  24675. of a call to Label::setText() or by the user editing the text (if the label is
  24676. editable).
  24677. @see Label::addListener, Label::removeListener
  24678. */
  24679. class JUCE_API LabelListener
  24680. {
  24681. public:
  24682. /** Destructor. */
  24683. virtual ~LabelListener() {}
  24684. /** Called when a Label's text has changed.
  24685. */
  24686. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24687. };
  24688. /**
  24689. A component that displays a text string, and can optionally become a text
  24690. editor when clicked.
  24691. */
  24692. class JUCE_API Label : public Component,
  24693. public SettableTooltipClient,
  24694. protected TextEditorListener,
  24695. private ComponentListener
  24696. {
  24697. public:
  24698. /** Creates a Label.
  24699. @param componentName the name to give the component
  24700. @param labelText the text to show in the label
  24701. */
  24702. Label (const String& componentName,
  24703. const String& labelText);
  24704. /** Destructor. */
  24705. ~Label();
  24706. /** Changes the label text.
  24707. If broadcastChangeMessage is true and the new text is different to the current
  24708. text, then the class will broadcast a change message to any LabelListeners that
  24709. are registered.
  24710. */
  24711. void setText (const String& newText,
  24712. const bool broadcastChangeMessage);
  24713. /** Returns the label's current text.
  24714. @param returnActiveEditorContents if this is true and the label is currently
  24715. being edited, then this method will return the
  24716. text as it's being shown in the editor. If false,
  24717. then the value returned here won't be updated until
  24718. the user has finished typing and pressed the return
  24719. key.
  24720. */
  24721. const String getText (const bool returnActiveEditorContents = false) const throw();
  24722. /** Changes the font to use to draw the text.
  24723. @see getFont
  24724. */
  24725. void setFont (const Font& newFont) throw();
  24726. /** Returns the font currently being used.
  24727. @see setFont
  24728. */
  24729. const Font& getFont() const throw();
  24730. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24731. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24732. methods.
  24733. Note that you can also use the constants from TextEditor::ColourIds to change the
  24734. colour of the text editor that is opened when a label is editable.
  24735. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24736. */
  24737. enum ColourIds
  24738. {
  24739. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  24740. textColourId = 0x1000281, /**< The colour for the text. */
  24741. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  24742. Leave this transparent to not have an outline. */
  24743. };
  24744. /** Sets the style of justification to be used for positioning the text.
  24745. (The default is Justification::centredLeft)
  24746. */
  24747. void setJustificationType (const Justification& justification) throw();
  24748. /** Returns the type of justification, as set in setJustificationType(). */
  24749. const Justification getJustificationType() const throw() { return justification; }
  24750. /** Changes the gap that is left between the edge of the component and the text.
  24751. By default there's a small gap left at the sides of the component to allow for
  24752. the drawing of the border, but you can change this if necessary.
  24753. */
  24754. void setBorderSize (int horizontalBorder, int verticalBorder);
  24755. /** Returns the size of the horizontal gap being left around the text.
  24756. */
  24757. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  24758. /** Returns the size of the vertical gap being left around the text.
  24759. */
  24760. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  24761. /** Makes this label "stick to" another component.
  24762. This will cause the label to follow another component around, staying
  24763. either to its left or above it.
  24764. @param owner the component to follow
  24765. @param onLeft if true, the label will stay on the left of its component; if
  24766. false, it will stay above it.
  24767. */
  24768. void attachToComponent (Component* owner,
  24769. const bool onLeft);
  24770. /** If this label has been attached to another component using attachToComponent, this
  24771. returns the other component.
  24772. Returns 0 if the label is not attached.
  24773. */
  24774. Component* getAttachedComponent() const throw() { return ownerComponent; }
  24775. /** If the label is attached to the left of another component, this returns true.
  24776. Returns false if the label is above the other component. This is only relevent if
  24777. attachToComponent() has been called.
  24778. */
  24779. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  24780. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  24781. using ellipsis.
  24782. @see Graphics::drawFittedText
  24783. */
  24784. void setMinimumHorizontalScale (const float newScale);
  24785. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  24786. /** Registers a listener that will be called when the label's text changes. */
  24787. void addListener (LabelListener* const listener) throw();
  24788. /** Deregisters a previously-registered listener. */
  24789. void removeListener (LabelListener* const listener) throw();
  24790. /** Makes the label turn into a TextEditor when clicked.
  24791. By default this is turned off.
  24792. If turned on, then single- or double-clicking will turn the label into
  24793. an editor. If the user then changes the text, then the ChangeBroadcaster
  24794. base class will be used to send change messages to any listeners that
  24795. have registered.
  24796. If the user changes the text, the textWasEdited() method will be called
  24797. afterwards, and subclasses can override this if they need to do anything
  24798. special.
  24799. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  24800. @param editOnDoubleClick if true, a double-click is needed to start editing
  24801. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  24802. edited will discard any changes; if false, then this will
  24803. commit the changes.
  24804. @see showEditor, setEditorColours, TextEditor
  24805. */
  24806. void setEditable (const bool editOnSingleClick,
  24807. const bool editOnDoubleClick = false,
  24808. const bool lossOfFocusDiscardsChanges = false) throw();
  24809. /** Returns true if this option was set using setEditable(). */
  24810. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  24811. /** Returns true if this option was set using setEditable(). */
  24812. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  24813. /** Returns true if this option has been set in a call to setEditable(). */
  24814. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  24815. /** Returns true if the user can edit this label's text. */
  24816. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  24817. /** Makes the editor appear as if the label had been clicked by the user.
  24818. @see textWasEdited, setEditable
  24819. */
  24820. void showEditor();
  24821. /** Hides the editor if it was being shown.
  24822. @param discardCurrentEditorContents if true, the label's text will be
  24823. reset to whatever it was before the editor
  24824. was shown; if false, the current contents of the
  24825. editor will be used to set the label's text
  24826. before it is hidden.
  24827. */
  24828. void hideEditor (const bool discardCurrentEditorContents);
  24829. /** Returns true if the editor is currently focused and active. */
  24830. bool isBeingEdited() const throw();
  24831. juce_UseDebuggingNewOperator
  24832. protected:
  24833. /** @internal */
  24834. void paint (Graphics& g);
  24835. /** @internal */
  24836. void resized();
  24837. /** @internal */
  24838. void mouseUp (const MouseEvent& e);
  24839. /** @internal */
  24840. void mouseDoubleClick (const MouseEvent& e);
  24841. /** @internal */
  24842. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24843. /** @internal */
  24844. void componentParentHierarchyChanged (Component& component);
  24845. /** @internal */
  24846. void componentVisibilityChanged (Component& component);
  24847. /** @internal */
  24848. void inputAttemptWhenModal();
  24849. /** @internal */
  24850. void focusGained (FocusChangeType);
  24851. /** @internal */
  24852. void enablementChanged();
  24853. /** @internal */
  24854. KeyboardFocusTraverser* createFocusTraverser();
  24855. /** @internal */
  24856. void textEditorTextChanged (TextEditor& editor);
  24857. /** @internal */
  24858. void textEditorReturnKeyPressed (TextEditor& editor);
  24859. /** @internal */
  24860. void textEditorEscapeKeyPressed (TextEditor& editor);
  24861. /** @internal */
  24862. void textEditorFocusLost (TextEditor& editor);
  24863. /** @internal */
  24864. void colourChanged();
  24865. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  24866. Subclasses can override this if they need to customise this component in some way.
  24867. */
  24868. virtual TextEditor* createEditorComponent();
  24869. /** Called after the user changes the text.
  24870. */
  24871. virtual void textWasEdited();
  24872. /** Called when the text has been altered.
  24873. */
  24874. virtual void textWasChanged();
  24875. private:
  24876. String text;
  24877. Font font;
  24878. Justification justification;
  24879. TextEditor* editor;
  24880. SortedSet <void*> listeners;
  24881. Component* ownerComponent;
  24882. ComponentDeletionWatcher* deletionWatcher;
  24883. int horizontalBorderSize, verticalBorderSize;
  24884. float minimumHorizontalScale;
  24885. bool editSingleClick : 1;
  24886. bool editDoubleClick : 1;
  24887. bool lossOfFocusDiscardsChanges : 1;
  24888. bool leftOfOwnerComp : 1;
  24889. bool updateFromTextEditorContents();
  24890. void callChangeListeners();
  24891. Label (const Label&);
  24892. const Label& operator= (const Label&);
  24893. };
  24894. #endif // __JUCE_LABEL_JUCEHEADER__
  24895. /********* End of inlined file: juce_Label.h *********/
  24896. class ComboBox;
  24897. /**
  24898. A class for receiving events from a ComboBox.
  24899. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  24900. method, and it will be called when the selected item in the box changes.
  24901. @see ComboBox::addListener, ComboBox::removeListener
  24902. */
  24903. class JUCE_API ComboBoxListener
  24904. {
  24905. public:
  24906. /** Destructor. */
  24907. virtual ~ComboBoxListener() {}
  24908. /** Called when a ComboBox has its selected item changed.
  24909. */
  24910. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  24911. };
  24912. /**
  24913. A component that lets the user choose from a drop-down list of choices.
  24914. The combo-box has a list of text strings, each with an associated id number,
  24915. that will be shown in the drop-down list when the user clicks on the component.
  24916. The currently selected choice is displayed in the combo-box, and this can
  24917. either be read-only text, or editable.
  24918. To find out when the user selects a different item or edits the text, you
  24919. can register a ComboBoxListener to receive callbacks.
  24920. @see ComboBoxListener
  24921. */
  24922. class JUCE_API ComboBox : public Component,
  24923. public SettableTooltipClient,
  24924. private LabelListener,
  24925. private AsyncUpdater
  24926. {
  24927. public:
  24928. /** Creates a combo-box.
  24929. On construction, the text field will be empty, so you should call the
  24930. setSelectedId() or setText() method to choose the initial value before
  24931. displaying it.
  24932. @param componentName the name to set for the component (see Component::setName())
  24933. */
  24934. ComboBox (const String& componentName);
  24935. /** Destructor. */
  24936. ~ComboBox();
  24937. /** Sets whether the test in the combo-box is editable.
  24938. The default state for a new ComboBox is non-editable, and can only be changed
  24939. by choosing from the drop-down list.
  24940. */
  24941. void setEditableText (const bool isEditable);
  24942. /** Returns true if the text is directly editable.
  24943. @see setEditableText
  24944. */
  24945. bool isTextEditable() const throw();
  24946. /** Sets the style of justification to be used for positioning the text.
  24947. The default is Justification::centredLeft. The text is displayed using a
  24948. Label component inside the ComboBox.
  24949. */
  24950. void setJustificationType (const Justification& justification) throw();
  24951. /** Returns the current justification for the text box.
  24952. @see setJustificationType
  24953. */
  24954. const Justification getJustificationType() const throw();
  24955. /** Adds an item to be shown in the drop-down list.
  24956. @param newItemText the text of the item to show in the list
  24957. @param newItemId an associated ID number that can be set or retrieved - see
  24958. getSelectedId() and setSelectedId()
  24959. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  24960. */
  24961. void addItem (const String& newItemText,
  24962. const int newItemId) throw();
  24963. /** Adds a separator line to the drop-down list.
  24964. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  24965. */
  24966. void addSeparator() throw();
  24967. /** Adds a heading to the drop-down list, so that you can group the items into
  24968. different sections.
  24969. The headings are indented slightly differently to set them apart from the
  24970. items on the list, and obviously can't be selected. You might want to add
  24971. separators between your sections too.
  24972. @see addItem, addSeparator
  24973. */
  24974. void addSectionHeading (const String& headingName) throw();
  24975. /** This allows items in the drop-down list to be selectively disabled.
  24976. When you add an item, it's enabled by default, but you can call this
  24977. method to change its status.
  24978. If you disable an item which is already selected, this won't change the
  24979. current selection - it just stops the user choosing that item from the list.
  24980. */
  24981. void setItemEnabled (const int itemId,
  24982. const bool isEnabled) throw();
  24983. /** Changes the text for an existing item.
  24984. */
  24985. void changeItemText (const int itemId,
  24986. const String& newText) throw();
  24987. /** Removes all the items from the drop-down list.
  24988. If this call causes the content to be cleared, then a change-message
  24989. will be broadcast unless dontSendChangeMessage is true.
  24990. @see addItem, removeItem, getNumItems
  24991. */
  24992. void clear (const bool dontSendChangeMessage = false);
  24993. /** Returns the number of items that have been added to the list.
  24994. Note that this doesn't include headers or separators.
  24995. */
  24996. int getNumItems() const throw();
  24997. /** Returns the text for one of the items in the list.
  24998. Note that this doesn't include headers or separators.
  24999. @param index the item's index from 0 to (getNumItems() - 1)
  25000. */
  25001. const String getItemText (const int index) const throw();
  25002. /** Returns the ID for one of the items in the list.
  25003. Note that this doesn't include headers or separators.
  25004. @param index the item's index from 0 to (getNumItems() - 1)
  25005. */
  25006. int getItemId (const int index) const throw();
  25007. /** Returns the ID 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 0.
  25011. @see setSelectedId, getSelectedItemIndex, getText
  25012. */
  25013. int getSelectedId() 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 that matches
  25016. this ID.
  25017. @param newItemId the new item to select
  25018. @param dontSendChangeMessage if set to true, this method won't trigger a
  25019. change notification
  25020. @see getSelectedId, setSelectedItemIndex, setText
  25021. */
  25022. void setSelectedId (const int newItemId,
  25023. const bool dontSendChangeMessage = false) throw();
  25024. /** Returns the index of the item that's currently shown in the box.
  25025. If no item is selected, or if the text is editable and the user
  25026. has entered something which isn't one of the items in the list, then
  25027. this will return -1.
  25028. @see setSelectedItemIndex, getSelectedId, getText
  25029. */
  25030. int getSelectedItemIndex() const throw();
  25031. /** Sets one of the items to be the current selection.
  25032. This will set the ComboBox's text to that of the item at the given
  25033. index in the list.
  25034. @param newItemIndex the new item to select
  25035. @param dontSendChangeMessage if set to true, this method won't trigger a
  25036. change notification
  25037. @see getSelectedItemIndex, setSelectedId, setText
  25038. */
  25039. void setSelectedItemIndex (const int newItemIndex,
  25040. const bool dontSendChangeMessage = false) throw();
  25041. /** Returns the text that is currently shown in the combo-box's text field.
  25042. If the ComboBox has editable text, then this text may have been edited
  25043. by the user; otherwise it will be one of the items from the list, or
  25044. possibly an empty string if nothing was selected.
  25045. @see setText, getSelectedId, getSelectedItemIndex
  25046. */
  25047. const String getText() const throw();
  25048. /** Sets the contents of the combo-box's text field.
  25049. The text passed-in will be set as the current text regardless of whether
  25050. it is one of the items in the list. If the current text isn't one of the
  25051. items, then getSelectedId() will return -1, otherwise it wil return
  25052. the approriate ID.
  25053. @param newText the text to select
  25054. @param dontSendChangeMessage if set to true, this method won't trigger a
  25055. change notification
  25056. @see getText
  25057. */
  25058. void setText (const String& newText,
  25059. const bool dontSendChangeMessage = false) throw();
  25060. /** Programmatically opens the text editor to allow the user to edit the current item.
  25061. This is the same effect as when the box is clicked-on.
  25062. @see Label::showEditor();
  25063. */
  25064. void showEditor();
  25065. /** Registers a listener that will be called when the box's content changes. */
  25066. void addListener (ComboBoxListener* const listener) throw();
  25067. /** Deregisters a previously-registered listener. */
  25068. void removeListener (ComboBoxListener* const listener) throw();
  25069. /** Sets a message to display when there is no item currently selected.
  25070. @see getTextWhenNothingSelected
  25071. */
  25072. void setTextWhenNothingSelected (const String& newMessage) throw();
  25073. /** Returns the text that is shown when no item is selected.
  25074. @see setTextWhenNothingSelected
  25075. */
  25076. const String getTextWhenNothingSelected() const throw();
  25077. /** Sets the message to show when there are no items in the list, and the user clicks
  25078. on the drop-down box.
  25079. By default it just says "no choices", but this lets you change it to something more
  25080. meaningful.
  25081. */
  25082. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25083. /** Returns the text shown when no items have been added to the list.
  25084. @see setTextWhenNoChoicesAvailable
  25085. */
  25086. const String getTextWhenNoChoicesAvailable() const throw();
  25087. /** Gives the ComboBox a tooltip. */
  25088. void setTooltip (const String& newTooltip);
  25089. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25090. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25091. methods.
  25092. To change the colours of the menu that pops up
  25093. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25094. */
  25095. enum ColourIds
  25096. {
  25097. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25098. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25099. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25100. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25101. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25102. };
  25103. /** @internal */
  25104. void labelTextChanged (Label*);
  25105. /** @internal */
  25106. void enablementChanged();
  25107. /** @internal */
  25108. void colourChanged();
  25109. /** @internal */
  25110. void focusGained (Component::FocusChangeType cause);
  25111. /** @internal */
  25112. void focusLost (Component::FocusChangeType cause);
  25113. /** @internal */
  25114. void handleAsyncUpdate();
  25115. /** @internal */
  25116. const String getTooltip() { return label->getTooltip(); }
  25117. /** @internal */
  25118. void mouseDown (const MouseEvent&);
  25119. /** @internal */
  25120. void mouseDrag (const MouseEvent&);
  25121. /** @internal */
  25122. void mouseUp (const MouseEvent&);
  25123. /** @internal */
  25124. void lookAndFeelChanged();
  25125. /** @internal */
  25126. void paint (Graphics&);
  25127. /** @internal */
  25128. void resized();
  25129. /** @internal */
  25130. bool keyStateChanged();
  25131. /** @internal */
  25132. bool keyPressed (const KeyPress&);
  25133. juce_UseDebuggingNewOperator
  25134. private:
  25135. struct ItemInfo
  25136. {
  25137. String name;
  25138. int itemId;
  25139. bool isEnabled : 1, isHeading : 1;
  25140. bool isSeparator() const throw();
  25141. bool isRealItem() const throw();
  25142. };
  25143. OwnedArray <ItemInfo> items;
  25144. int currentIndex;
  25145. bool isButtonDown;
  25146. bool separatorPending;
  25147. bool menuActive;
  25148. SortedSet <void*> listeners;
  25149. Label* label;
  25150. String textWhenNothingSelected, noChoicesMessage;
  25151. void showPopup();
  25152. ItemInfo* getItemForId (const int itemId) const throw();
  25153. ItemInfo* getItemForIndex (const int index) const throw();
  25154. ComboBox (const ComboBox&);
  25155. const ComboBox& operator= (const ComboBox&);
  25156. };
  25157. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25158. /********* End of inlined file: juce_ComboBox.h *********/
  25159. /**
  25160. Manages the state of some audio and midi i/o devices.
  25161. This class keeps tracks of a currently-selected audio device, through
  25162. with which it continuously streams data from an audio callback, as well as
  25163. one or more midi inputs.
  25164. The idea is that your application will create one global instance of this object,
  25165. and let it take care of creating and deleting specific types of audio devices
  25166. internally. So when the device is changed, your callbacks will just keep running
  25167. without having to worry about this.
  25168. The manager can save and reload all of its device settings as XML, which
  25169. makes it very easy for you to save and reload the audio setup of your
  25170. application.
  25171. And to make it easy to let the user change its settings, there's a component
  25172. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25173. device selection/sample-rate/latency controls.
  25174. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25175. call setAudioCallback() to register your audio callback with it, and use that to process
  25176. your audio data.
  25177. The manager also acts as a handy hub for incoming midi messages, allowing a
  25178. listener to register for messages from either a specific midi device, or from whatever
  25179. the current default midi input device is. The listener then doesn't have to worry about
  25180. re-registering with different midi devices if they are changed or deleted.
  25181. And yet another neat trick is that amount of CPU time being used is measured and
  25182. available with the getCpuUsage() method.
  25183. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25184. listeners whenever one of its settings is changed.
  25185. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25186. */
  25187. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25188. {
  25189. public:
  25190. /** Creates a default AudioDeviceManager.
  25191. Initially no audio device will be selected. You should call the initialise() method
  25192. and register an audio callback with setAudioCallback() before it'll be able to
  25193. actually make any noise.
  25194. */
  25195. AudioDeviceManager();
  25196. /** Destructor. */
  25197. ~AudioDeviceManager();
  25198. /** Opens a set of audio devices ready for use.
  25199. This will attempt to open either a default audio device, or one that was
  25200. previously saved as XML.
  25201. @param numInputChannelsNeeded a minimum number of input channels needed
  25202. by your app.
  25203. @param numOutputChannelsNeeded a minimum number of output channels to open
  25204. @param savedState either a previously-saved state that was produced
  25205. by createStateXml(), or 0 if you want the manager
  25206. to choose the best device to open.
  25207. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25208. fails to open, then a default device will be used
  25209. instead. If false, then on failure, no device is
  25210. opened.
  25211. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25212. name, then that will be used as the default device
  25213. (assuming that there wasn't one specified in the XML).
  25214. The string can actually be a simple wildcard, containing "*"
  25215. and "?" characters
  25216. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25217. */
  25218. const String initialise (const int numInputChannelsNeeded,
  25219. const int numOutputChannelsNeeded,
  25220. const XmlElement* const savedState,
  25221. const bool selectDefaultDeviceOnFailure,
  25222. const String& preferredDefaultDeviceName = String::empty);
  25223. /** Returns some XML representing the current state of the manager.
  25224. This stores the current device, its samplerate, block size, etc, and
  25225. can be restored later with initialise().
  25226. */
  25227. XmlElement* createStateXml() const;
  25228. /**
  25229. */
  25230. struct AudioDeviceSetup
  25231. {
  25232. AudioDeviceSetup();
  25233. bool operator== (const AudioDeviceSetup& other) const;
  25234. /**
  25235. */
  25236. String outputDeviceName;
  25237. /**
  25238. */
  25239. String inputDeviceName;
  25240. /**
  25241. */
  25242. double sampleRate;
  25243. /**
  25244. */
  25245. int bufferSize;
  25246. /**
  25247. */
  25248. BitArray inputChannels;
  25249. bool useDefaultInputChannels;
  25250. /**
  25251. */
  25252. BitArray outputChannels;
  25253. bool useDefaultOutputChannels;
  25254. };
  25255. /**
  25256. */
  25257. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25258. /**
  25259. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25260. settings will be taken as having been explicitly chosen by the
  25261. user, and the next time createStateXml() is called, these settings
  25262. will be returned. If it's false, then the device is treated as a
  25263. temporary or default device, and a call to createStateXml() will
  25264. return either the last settings that were made with treatAsChosenDevice
  25265. as true, or the last XML settings that were passed into initialise().
  25266. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25267. */
  25268. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25269. const bool treatAsChosenDevice);
  25270. /** Returns the currently-active audio device. */
  25271. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25272. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25273. void setCurrentAudioDeviceType (const String& type,
  25274. const bool treatAsChosenDevice);
  25275. /** Closes the currently-open device.
  25276. You can call restartLastAudioDevice() later to reopen it in the same state
  25277. that it was just in.
  25278. */
  25279. void closeAudioDevice();
  25280. /** Tries to reload the last audio device that was running.
  25281. Note that this only reloads the last device that was running before
  25282. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25283. and can only be called after a device has been opened with SetAudioDevice().
  25284. If a device is already open, this call will do nothing.
  25285. */
  25286. void restartLastAudioDevice();
  25287. /** Gives the manager an audio callback to use.
  25288. The manager will redirect callbacks from whatever audio device is currently
  25289. in use to this callback object.
  25290. You can pass 0 in here to stop callbacks being made.
  25291. */
  25292. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25293. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25294. Returns a value between 0 and 1.0
  25295. */
  25296. double getCpuUsage() const;
  25297. /** Enables or disables a midi input device.
  25298. The list of devices can be obtained with the MidiInput::getDevices() method.
  25299. Any incoming messages from enabled input devices will be forwarded on to all the
  25300. listeners that have been registered with the addMidiInputCallback() method. They
  25301. can either register for messages from a particular device, or from just the
  25302. "default" midi input.
  25303. Routing the midi input via an AudioDeviceManager means that when a listener
  25304. registers for the default midi input, this default device can be changed by the
  25305. manager without the listeners having to know about it or re-register.
  25306. It also means that a listener can stay registered for a midi input that is disabled
  25307. or not present, so that when the input is re-enabled, the listener will start
  25308. receiving messages again.
  25309. @see addMidiInputCallback, isMidiInputEnabled
  25310. */
  25311. void setMidiInputEnabled (const String& midiInputDeviceName,
  25312. const bool enabled);
  25313. /** Returns true if a given midi input device is being used.
  25314. @see setMidiInputEnabled
  25315. */
  25316. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25317. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25318. The device name can be empty to indicate that it wants events from whatever the
  25319. current "default" device is. Or it can be the name of one of the midi input devices
  25320. (see MidiInput::getDevices() for the names).
  25321. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25322. events forwarded on to listeners.
  25323. */
  25324. void addMidiInputCallback (const String& midiInputDeviceName,
  25325. MidiInputCallback* callback);
  25326. /** Removes a listener that was previously registered with addMidiInputCallback().
  25327. */
  25328. void removeMidiInputCallback (const String& midiInputDeviceName,
  25329. MidiInputCallback* callback);
  25330. /** Sets a midi output device to use as the default.
  25331. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25332. The specified device will be opened automatically and can be retrieved with the
  25333. getDefaultMidiOutput() method.
  25334. Pass in an empty string to deselect all devices. For the default device, you
  25335. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25336. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25337. */
  25338. void setDefaultMidiOutput (const String& deviceName);
  25339. /** Returns the name of the default midi output.
  25340. @see setDefaultMidiOutput, getDefaultMidiOutput
  25341. */
  25342. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25343. /** Returns the current default midi output device.
  25344. If no device has been selected, or the device can't be opened, this will
  25345. return 0.
  25346. @see getDefaultMidiOutputName
  25347. */
  25348. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25349. /**
  25350. */
  25351. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25352. /** Creates a list of available types.
  25353. This will add a set of new AudioIODeviceType objects to the specified list, to
  25354. represent each available types of device.
  25355. You can override this if your app needs to do something specific, like avoid
  25356. using DirectSound devices, etc.
  25357. */
  25358. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25359. /** Plays a beep through the current audio device.
  25360. This is here to allow the audio setup UI panels to easily include a "test"
  25361. button so that the user can check where the audio is coming from.
  25362. */
  25363. void playTestSound();
  25364. /** Turns on level-measuring.
  25365. When enabled, the device manager will measure the peak input level
  25366. across all channels, and you can get this level by calling getCurrentInputLevel().
  25367. This is mainly intended for audio setup UI panels to use to create a mic
  25368. level display, so that the user can check that they've selected the right
  25369. device.
  25370. A simple filter is used to make the level decay smoothly, but this is
  25371. only intended for giving rough feedback, and not for any kind of accurate
  25372. measurement.
  25373. */
  25374. void enableInputLevelMeasurement (const bool enableMeasurement);
  25375. /** Returns the current input level.
  25376. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25377. See enableInputLevelMeasurement() for more info.
  25378. */
  25379. double getCurrentInputLevel() const;
  25380. juce_UseDebuggingNewOperator
  25381. private:
  25382. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25383. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25384. AudioDeviceSetup currentSetup;
  25385. AudioIODevice* currentAudioDevice;
  25386. AudioIODeviceCallback* currentCallback;
  25387. int numInputChansNeeded, numOutputChansNeeded;
  25388. String currentDeviceType;
  25389. BitArray inputChannels, outputChannels;
  25390. XmlElement* lastExplicitSettings;
  25391. mutable bool listNeedsScanning;
  25392. bool useInputNames, inputLevelMeasurementEnabled;
  25393. double inputLevel;
  25394. AudioSampleBuffer* testSound;
  25395. int testSoundPosition;
  25396. StringArray midiInsFromXml;
  25397. OwnedArray <MidiInput> enabledMidiInputs;
  25398. Array <MidiInputCallback*> midiCallbacks;
  25399. Array <MidiInput*> midiCallbackDevices;
  25400. String defaultMidiOutputName;
  25401. MidiOutput* defaultMidiOutput;
  25402. CriticalSection audioCallbackLock, midiCallbackLock;
  25403. double cpuUsageMs, timeToCpuScale;
  25404. class CallbackHandler : public AudioIODeviceCallback,
  25405. public MidiInputCallback
  25406. {
  25407. public:
  25408. AudioDeviceManager* owner;
  25409. void audioDeviceIOCallback (const float** inputChannelData,
  25410. int totalNumInputChannels,
  25411. float** outputChannelData,
  25412. int totalNumOutputChannels,
  25413. int numSamples);
  25414. void audioDeviceAboutToStart (AudioIODevice*);
  25415. void audioDeviceStopped();
  25416. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25417. };
  25418. CallbackHandler callbackHandler;
  25419. friend class CallbackHandler;
  25420. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25421. int totalNumInputChannels,
  25422. float** outputChannelData,
  25423. int totalNumOutputChannels,
  25424. int numSamples);
  25425. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25426. void audioDeviceStoppedInt();
  25427. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25428. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25429. const BitArray& ins, const BitArray& outs);
  25430. void stopDevice();
  25431. void updateXml();
  25432. void createDeviceTypesIfNeeded();
  25433. void scanDevicesIfNeeded();
  25434. void deleteCurrentDevice();
  25435. double chooseBestSampleRate (double preferred) const;
  25436. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25437. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25438. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25439. AudioDeviceManager (const AudioDeviceManager&);
  25440. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25441. };
  25442. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25443. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25444. #endif
  25445. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25446. #endif
  25447. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25448. #endif
  25449. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25450. #endif
  25451. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25452. #endif
  25453. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25454. /********* Start of inlined file: juce_Sampler.h *********/
  25455. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25456. #define __JUCE_SAMPLER_JUCEHEADER__
  25457. /********* Start of inlined file: juce_Synthesiser.h *********/
  25458. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25459. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25460. /**
  25461. Describes one of the sounds that a Synthesiser can play.
  25462. A synthesiser can contain one or more sounds, and a sound can choose which
  25463. midi notes and channels can trigger it.
  25464. The SynthesiserSound is a passive class that just describes what the sound is -
  25465. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25466. more than one SynthesiserVoice to play the same sound at the same time.
  25467. @see Synthesiser, SynthesiserVoice
  25468. */
  25469. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25470. {
  25471. protected:
  25472. SynthesiserSound();
  25473. public:
  25474. /** Destructor. */
  25475. virtual ~SynthesiserSound();
  25476. /** Returns true if this sound should be played when a given midi note is pressed.
  25477. The Synthesiser will use this information when deciding which sounds to trigger
  25478. for a given note.
  25479. */
  25480. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25481. /** Returns true if the sound should be triggered by midi events on a given channel.
  25482. The Synthesiser will use this information when deciding which sounds to trigger
  25483. for a given note.
  25484. */
  25485. virtual bool appliesToChannel (const int midiChannel) = 0;
  25486. /**
  25487. */
  25488. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25489. juce_UseDebuggingNewOperator
  25490. };
  25491. /**
  25492. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25493. A voice plays a single sound at a time, and a synthesiser holds an array of
  25494. voices so that it can play polyphonically.
  25495. @see Synthesiser, SynthesiserSound
  25496. */
  25497. class JUCE_API SynthesiserVoice
  25498. {
  25499. public:
  25500. /** Creates a voice. */
  25501. SynthesiserVoice();
  25502. /** Destructor. */
  25503. virtual ~SynthesiserVoice();
  25504. /** Returns the midi note that this voice is currently playing.
  25505. Returns a value less than 0 if no note is playing.
  25506. */
  25507. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25508. /** Returns the sound that this voice is currently playing.
  25509. Returns 0 if it's not playing.
  25510. */
  25511. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25512. /** Must return true if this voice object is capable of playing the given sound.
  25513. If there are different classes of sound, and different classes of voice, a voice can
  25514. choose which ones it wants to take on.
  25515. A typical implementation of this method may just return true if there's only one type
  25516. of voice and sound, or it might check the type of the sound object passed-in and
  25517. see if it's one that it understands.
  25518. */
  25519. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25520. /** Called to start a new note.
  25521. This will be called during the rendering callback, so must be fast and thread-safe.
  25522. */
  25523. virtual void startNote (const int midiNoteNumber,
  25524. const float velocity,
  25525. SynthesiserSound* sound,
  25526. const int currentPitchWheelPosition) = 0;
  25527. /** Called to stop a note.
  25528. This will be called during the rendering callback, so must be fast and thread-safe.
  25529. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25530. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25531. and allow the synth to reassign it another sound.
  25532. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25533. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25534. finishes playing (during the rendering callback), it must make sure that it calls
  25535. clearCurrentNote().
  25536. */
  25537. virtual void stopNote (const bool allowTailOff) = 0;
  25538. /** Called to let the voice know that the pitch wheel has been moved.
  25539. This will be called during the rendering callback, so must be fast and thread-safe.
  25540. */
  25541. virtual void pitchWheelMoved (const int newValue) = 0;
  25542. /** Called to let the voice know that a midi controller has been moved.
  25543. This will be called during the rendering callback, so must be fast and thread-safe.
  25544. */
  25545. virtual void controllerMoved (const int controllerNumber,
  25546. const int newValue) = 0;
  25547. /** Renders the next block of data for this voice.
  25548. The output audio data must be added to the current contents of the buffer provided.
  25549. Only the region of the buffer between startSample and (startSample + numSamples)
  25550. should be altered by this method.
  25551. If the voice is currently silent, it should just return without doing anything.
  25552. If the sound that the voice is playing finishes during the course of this rendered
  25553. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25554. The size of the blocks that are rendered can change each time it is called, and may
  25555. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25556. the voice's methods will be called to tell it about note and controller events.
  25557. */
  25558. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25559. int startSample,
  25560. int numSamples) = 0;
  25561. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25562. midi channel.
  25563. If it's not currently playing, this will return false.
  25564. */
  25565. bool isPlayingChannel (const int midiChannel) const;
  25566. /** Changes the voice's reference sample rate.
  25567. The rate is set so that subclasses know the output rate and can set their pitch
  25568. accordingly.
  25569. This method is called by the synth, and subclasses can access the current rate with
  25570. the currentSampleRate member.
  25571. */
  25572. void setCurrentPlaybackSampleRate (const double newRate);
  25573. juce_UseDebuggingNewOperator
  25574. protected:
  25575. /** Returns the current target sample rate at which rendering is being done.
  25576. This is available for subclasses so they can pitch things correctly.
  25577. */
  25578. double getSampleRate() const throw() { return currentSampleRate; }
  25579. /** Resets the state of this voice after a sound has finished playing.
  25580. The subclass must call this when it finishes playing a note and becomes available
  25581. to play new ones.
  25582. It must either call it in the stopNote() method, or if the voice is tailing off,
  25583. then it should call it later during the renderNextBlock method, as soon as it
  25584. finishes its tail-off.
  25585. It can also be called at any time during the render callback if the sound happens
  25586. to have finished, e.g. if it's playing a sample and the sample finishes.
  25587. */
  25588. void clearCurrentNote();
  25589. private:
  25590. friend class Synthesiser;
  25591. double currentSampleRate;
  25592. int currentlyPlayingNote;
  25593. uint32 noteOnTime;
  25594. SynthesiserSound::Ptr currentlyPlayingSound;
  25595. };
  25596. /**
  25597. Base class for a musical device that can play sounds.
  25598. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25599. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25600. which can play back one of these sounds.
  25601. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25602. set of sounds, and a set of voices it can use to play them. If you only give it
  25603. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25604. have available.
  25605. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25606. events that go in will be scanned for note on/off messages, and these are used to
  25607. start and stop the voices playing the appropriate sounds.
  25608. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25609. noteOff() and other controller methods.
  25610. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25611. what the target playback rate is. This value is passed on to the voices so that
  25612. they can pitch their output correctly.
  25613. */
  25614. class JUCE_API Synthesiser
  25615. {
  25616. public:
  25617. /** Creates a new synthesiser.
  25618. You'll need to add some sounds and voices before it'll make any sound..
  25619. */
  25620. Synthesiser();
  25621. /** Destructor. */
  25622. virtual ~Synthesiser();
  25623. /** Deletes all voices. */
  25624. void clearVoices();
  25625. /** Returns the number of voices that have been added. */
  25626. int getNumVoices() const throw() { return voices.size(); }
  25627. /** Returns one of the voices that have been added. */
  25628. SynthesiserVoice* getVoice (const int index) const throw();
  25629. /** Adds a new voice to the synth.
  25630. All the voices should be the same class of object and are treated equally.
  25631. The object passed in will be managed by the synthesiser, which will delete
  25632. it later on when no longer needed. The caller should not retain a pointer to the
  25633. voice.
  25634. */
  25635. void addVoice (SynthesiserVoice* const newVoice);
  25636. /** Deletes one of the voices. */
  25637. void removeVoice (const int index);
  25638. /** Deletes all sounds. */
  25639. void clearSounds();
  25640. /** Returns the number of sounds that have been added to the synth. */
  25641. int getNumSounds() const throw() { return sounds.size(); }
  25642. /** Returns one of the sounds. */
  25643. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25644. /** Adds a new sound to the synthesiser.
  25645. The object passed in is reference counted, so will be deleted when it is removed
  25646. from the synthesiser, and when no voices are still using it.
  25647. */
  25648. void addSound (const SynthesiserSound::Ptr& newSound);
  25649. /** Removes and deletes one of the sounds. */
  25650. void removeSound (const int index);
  25651. /** If set to true, then the synth will try to take over an existing voice if
  25652. it runs out and needs to play another note.
  25653. The value of this boolean is passed into findFreeVoice(), so the result will
  25654. depend on the implementation of this method.
  25655. */
  25656. void setNoteStealingEnabled (const bool shouldStealNotes);
  25657. /** Returns true if note-stealing is enabled.
  25658. @see setNoteStealingEnabled
  25659. */
  25660. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25661. /** Triggers a note-on event.
  25662. The default method here will find all the sounds that want to be triggered by
  25663. this note/channel. For each sound, it'll try to find a free voice, and use the
  25664. voice to start playing the sound.
  25665. Subclasses might want to override this if they need a more complex algorithm.
  25666. This method will be called automatically according to the midi data passed into
  25667. renderNextBlock(), but may be called explicitly too.
  25668. */
  25669. virtual void noteOn (const int midiChannel,
  25670. const int midiNoteNumber,
  25671. const float velocity);
  25672. /** Triggers a note-off event.
  25673. This will turn off any voices that are playing a sound for the given note/channel.
  25674. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25675. (if they can do). If this is false, the notes will all be cut off immediately.
  25676. This method will be called automatically according to the midi data passed into
  25677. renderNextBlock(), but may be called explicitly too.
  25678. */
  25679. virtual void noteOff (const int midiChannel,
  25680. const int midiNoteNumber,
  25681. const bool allowTailOff);
  25682. /** Turns off all notes.
  25683. This will turn off any voices that are playing a sound on the given midi channel.
  25684. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25685. which channel they're playing.
  25686. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25687. (if they can do). If this is false, the notes will all be cut off immediately.
  25688. This method will be called automatically according to the midi data passed into
  25689. renderNextBlock(), but may be called explicitly too.
  25690. */
  25691. virtual void allNotesOff (const int midiChannel,
  25692. const bool allowTailOff);
  25693. /** Sends a pitch-wheel message.
  25694. This will send a pitch-wheel message to any voices that are playing sounds on
  25695. the given midi channel.
  25696. This method will be called automatically according to the midi data passed into
  25697. renderNextBlock(), but may be called explicitly too.
  25698. @param midiChannel the midi channel for the event
  25699. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25700. */
  25701. virtual void handlePitchWheel (const int midiChannel,
  25702. const int wheelValue);
  25703. /** Sends a midi controller message.
  25704. This will send a midi controller message to any voices that are playing sounds on
  25705. the given midi channel.
  25706. This method will be called automatically according to the midi data passed into
  25707. renderNextBlock(), but may be called explicitly too.
  25708. @param midiChannel the midi channel for the event
  25709. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  25710. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  25711. */
  25712. virtual void handleController (const int midiChannel,
  25713. const int controllerNumber,
  25714. const int controllerValue);
  25715. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  25716. render.
  25717. This value is propagated to the voices so that they can use it to render the correct
  25718. pitches.
  25719. */
  25720. void setCurrentPlaybackSampleRate (const double sampleRate);
  25721. /** Creates the next block of audio output.
  25722. This will process the next numSamples of data from all the voices, and add that output
  25723. to the audio block supplied, starting from the offset specified. Note that the
  25724. data will be added to the current contents of the buffer, so you should clear it
  25725. before calling this method if necessary.
  25726. The midi events in the inputMidi buffer are parsed for note and controller events,
  25727. and these are used to trigger the voices. Note that the startSample offset applies
  25728. both to the audio output buffer and the midi input buffer, so any midi events
  25729. with timestamps outside the specified region will be ignored.
  25730. */
  25731. void renderNextBlock (AudioSampleBuffer& outputAudio,
  25732. const MidiBuffer& inputMidi,
  25733. int startSample,
  25734. int numSamples);
  25735. juce_UseDebuggingNewOperator
  25736. protected:
  25737. /** This is used to control access to the rendering callback and the note trigger methods. */
  25738. CriticalSection lock;
  25739. OwnedArray <SynthesiserVoice> voices;
  25740. ReferenceCountedArray <SynthesiserSound> sounds;
  25741. /** The last pitch-wheel values for each midi channel. */
  25742. int lastPitchWheelValues [16];
  25743. /** Searches through the voices to find one that's not currently playing, and which
  25744. can play the given sound.
  25745. Returns 0 if all voices are busy and stealing isn't enabled.
  25746. This can be overridden to implement custom voice-stealing algorithms.
  25747. */
  25748. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  25749. const bool stealIfNoneAvailable) const;
  25750. /** Starts a specified voice playing a particular sound.
  25751. You'll probably never need to call this, it's used internally by noteOn(), but
  25752. may be needed by subclasses for custom behaviours.
  25753. */
  25754. void startVoice (SynthesiserVoice* const voice,
  25755. SynthesiserSound* const sound,
  25756. const int midiChannel,
  25757. const int midiNoteNumber,
  25758. const float velocity);
  25759. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  25760. int findFreeVoice (const bool) const { return 0; }
  25761. private:
  25762. double sampleRate;
  25763. uint32 lastNoteOnCounter;
  25764. bool shouldStealNotes;
  25765. Synthesiser (const Synthesiser&);
  25766. const Synthesiser& operator= (const Synthesiser&);
  25767. };
  25768. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  25769. /********* End of inlined file: juce_Synthesiser.h *********/
  25770. /**
  25771. A subclass of SynthesiserSound that represents a sampled audio clip.
  25772. This is a pretty basic sampler, and just attempts to load the whole audio stream
  25773. into memory.
  25774. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25775. give it some SampledSound objects to play.
  25776. @see SamplerVoice, Synthesiser, SynthesiserSound
  25777. */
  25778. class JUCE_API SamplerSound : public SynthesiserSound
  25779. {
  25780. public:
  25781. /** Creates a sampled sound from an audio reader.
  25782. This will attempt to load the audio from the source into memory and store
  25783. it in this object.
  25784. @param name a name for the sample
  25785. @param source the audio to load. This object can be safely deleted by the
  25786. caller after this constructor returns
  25787. @param midiNotes the set of midi keys that this sound should be played on. This
  25788. is used by the SynthesiserSound::appliesToNote() method
  25789. @param midiNoteForNormalPitch the midi note at which the sample should be played
  25790. with its natural rate. All other notes will be pitched
  25791. up or down relative to this one
  25792. @param attackTimeSecs the attack (fade-in) time, in seconds
  25793. @param releaseTimeSecs the decay (fade-out) time, in seconds
  25794. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  25795. source, in seconds
  25796. */
  25797. SamplerSound (const String& name,
  25798. AudioFormatReader& source,
  25799. const BitArray& midiNotes,
  25800. const int midiNoteForNormalPitch,
  25801. const double attackTimeSecs,
  25802. const double releaseTimeSecs,
  25803. const double maxSampleLengthSeconds);
  25804. /** Destructor. */
  25805. ~SamplerSound();
  25806. /** Returns the sample's name */
  25807. const String& getName() const throw() { return name; }
  25808. /** Returns the audio sample data.
  25809. This could be 0 if there was a problem loading it.
  25810. */
  25811. AudioSampleBuffer* getAudioData() const throw() { return data; }
  25812. bool appliesToNote (const int midiNoteNumber);
  25813. bool appliesToChannel (const int midiChannel);
  25814. juce_UseDebuggingNewOperator
  25815. private:
  25816. friend class SamplerVoice;
  25817. String name;
  25818. AudioSampleBuffer* data;
  25819. double sourceSampleRate;
  25820. BitArray midiNotes;
  25821. int length, attackSamples, releaseSamples;
  25822. int midiRootNote;
  25823. };
  25824. /**
  25825. A subclass of SynthesiserVoice that can play a SamplerSound.
  25826. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25827. give it some SampledSound objects to play.
  25828. @see SamplerSound, Synthesiser, SynthesiserVoice
  25829. */
  25830. class JUCE_API SamplerVoice : public SynthesiserVoice
  25831. {
  25832. public:
  25833. /** Creates a SamplerVoice.
  25834. */
  25835. SamplerVoice();
  25836. /** Destructor. */
  25837. ~SamplerVoice();
  25838. bool canPlaySound (SynthesiserSound* sound);
  25839. void startNote (const int midiNoteNumber,
  25840. const float velocity,
  25841. SynthesiserSound* sound,
  25842. const int currentPitchWheelPosition);
  25843. void stopNote (const bool allowTailOff);
  25844. void pitchWheelMoved (const int newValue);
  25845. void controllerMoved (const int controllerNumber,
  25846. const int newValue);
  25847. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  25848. juce_UseDebuggingNewOperator
  25849. private:
  25850. double pitchRatio;
  25851. double sourceSamplePosition;
  25852. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  25853. bool isInAttack, isInRelease;
  25854. };
  25855. #endif // __JUCE_SAMPLER_JUCEHEADER__
  25856. /********* End of inlined file: juce_Sampler.h *********/
  25857. #endif
  25858. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25859. #endif
  25860. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25861. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  25862. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25863. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25864. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  25865. /**
  25866. Implements a plugin format manager for AudioUnits.
  25867. */
  25868. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  25869. {
  25870. public:
  25871. AudioUnitPluginFormat();
  25872. ~AudioUnitPluginFormat();
  25873. const String getName() const { return "AudioUnit"; }
  25874. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25875. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25876. bool fileMightContainThisPluginType (const File& file);
  25877. const FileSearchPath getDefaultLocationsToSearch();
  25878. juce_UseDebuggingNewOperator
  25879. private:
  25880. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  25881. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  25882. };
  25883. #endif
  25884. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25885. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  25886. #endif
  25887. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25888. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  25889. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25890. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25891. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  25892. // Sorry, this file is just a placeholder at the moment!...
  25893. /**
  25894. Implements a plugin format manager for DirectX plugins.
  25895. */
  25896. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  25897. {
  25898. public:
  25899. DirectXPluginFormat();
  25900. ~DirectXPluginFormat();
  25901. const String getName() const { return "DirectX"; }
  25902. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25903. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25904. bool fileMightContainThisPluginType (const File& file);
  25905. const FileSearchPath getDefaultLocationsToSearch();
  25906. juce_UseDebuggingNewOperator
  25907. private:
  25908. DirectXPluginFormat (const DirectXPluginFormat&);
  25909. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  25910. };
  25911. #endif
  25912. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25913. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  25914. #endif
  25915. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25916. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  25917. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25918. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25919. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  25920. // Sorry, this file is just a placeholder at the moment!...
  25921. /**
  25922. Implements a plugin format manager for DirectX plugins.
  25923. */
  25924. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  25925. {
  25926. public:
  25927. LADSPAPluginFormat();
  25928. ~LADSPAPluginFormat();
  25929. const String getName() const { return "LADSPA"; }
  25930. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25931. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25932. bool fileMightContainThisPluginType (const File& file);
  25933. const FileSearchPath getDefaultLocationsToSearch();
  25934. juce_UseDebuggingNewOperator
  25935. private:
  25936. LADSPAPluginFormat (const LADSPAPluginFormat&);
  25937. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  25938. };
  25939. #endif
  25940. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25941. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  25942. #endif
  25943. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25944. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  25945. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25946. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25947. #if JUCE_PLUGINHOST_VST
  25948. /**
  25949. Implements a plugin format manager for VSTs.
  25950. */
  25951. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  25952. {
  25953. public:
  25954. VSTPluginFormat();
  25955. ~VSTPluginFormat();
  25956. const String getName() const { return "VST"; }
  25957. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const File& file);
  25958. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25959. bool fileMightContainThisPluginType (const File& file);
  25960. const FileSearchPath getDefaultLocationsToSearch();
  25961. juce_UseDebuggingNewOperator
  25962. private:
  25963. VSTPluginFormat (const VSTPluginFormat&);
  25964. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  25965. };
  25966. #endif
  25967. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  25968. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  25969. #endif
  25970. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  25971. #endif
  25972. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  25973. #endif
  25974. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  25975. #endif
  25976. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  25977. #endif
  25978. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  25979. #endif
  25980. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  25981. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  25982. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  25983. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  25984. /**
  25985. Scans a directory for plugins, and adds them to a KnownPluginList.
  25986. To use one of these, create it and call scanNextFile() repeatedly, until
  25987. it returns false.
  25988. */
  25989. class JUCE_API PluginDirectoryScanner
  25990. {
  25991. public:
  25992. /**
  25993. Creates a scanner.
  25994. @param listToAddResultsTo this will get the new types added to it.
  25995. @param formatToLookFor this is the type of format that you want to look for
  25996. @param directoriesToSearch the path to search
  25997. @param searchRecursively true to search recursively
  25998. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  25999. be used as a file to store the names of any plugins
  26000. that crash during initialisation. If there are
  26001. any plugins listed in it, then these will always
  26002. be scanned after all other possible files have
  26003. been tried - in this way, even if there's a few
  26004. dodgy plugins in your path, then a couple of rescans
  26005. will still manage to find all the proper plugins.
  26006. It's probably best to choose a file in the user's
  26007. application data directory (alongside your app's
  26008. settings file) for this. The file format it uses
  26009. is just a list of filenames of the modules that
  26010. failed.
  26011. */
  26012. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26013. AudioPluginFormat& formatToLookFor,
  26014. FileSearchPath directoriesToSearch,
  26015. const bool searchRecursively,
  26016. const File& deadMansPedalFile);
  26017. /** Destructor. */
  26018. ~PluginDirectoryScanner();
  26019. /** Tries the next likely-looking file.
  26020. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26021. re-tested if it's not already in the list, or if the file's modification
  26022. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26023. false, the file will always be reloaded and tested.
  26024. Returns false when there are no more files to try.
  26025. */
  26026. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26027. /** Returns the file that will be scanned during the next call to scanNextFile().
  26028. This is handy if you want to show the user which file is currently getting
  26029. scanned.
  26030. */
  26031. const File getNextPluginFileThatWillBeScanned() const throw();
  26032. /** Returns the estimated progress, between 0 and 1.
  26033. */
  26034. float getProgress() const { return progress; }
  26035. /** This returns a list of all the filenames of things that looked like being
  26036. a plugin file, but which failed to open for some reason.
  26037. */
  26038. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26039. juce_UseDebuggingNewOperator
  26040. private:
  26041. KnownPluginList& list;
  26042. AudioPluginFormat& format;
  26043. OwnedArray <File> filesToScan;
  26044. File deadMansPedalFile;
  26045. StringArray failedFiles;
  26046. int nextIndex;
  26047. float progress;
  26048. void recursiveFileSearch (const File& dir, const bool recursive);
  26049. const StringArray getDeadMansPedalFile() throw();
  26050. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26051. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26052. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26053. };
  26054. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26055. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26056. #endif
  26057. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26058. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26059. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26060. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26061. /********* Start of inlined file: juce_ListBox.h *********/
  26062. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26063. #define __JUCE_LISTBOX_JUCEHEADER__
  26064. class ListViewport;
  26065. /**
  26066. A subclass of this is used to drive a ListBox.
  26067. @see ListBox
  26068. */
  26069. class JUCE_API ListBoxModel
  26070. {
  26071. public:
  26072. /** Destructor. */
  26073. virtual ~ListBoxModel() {}
  26074. /** This has to return the number of items in the list.
  26075. @see ListBox::getNumRows()
  26076. */
  26077. virtual int getNumRows() = 0;
  26078. /** This method must be implemented to draw a row of the list.
  26079. */
  26080. virtual void paintListBoxItem (int rowNumber,
  26081. Graphics& g,
  26082. int width, int height,
  26083. bool rowIsSelected) = 0;
  26084. /** This is used to create or update a custom component to go in a row of the list.
  26085. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26086. and handle mouse clicks with listBoxItemClicked().
  26087. This method will be called whenever a custom component might need to be updated - e.g.
  26088. when the table is changed, or TableListBox::updateContent() is called.
  26089. If you don't need a custom component for the specified row, then return 0.
  26090. If you do want a custom component, and the existingComponentToUpdate is null, then
  26091. this method must create a suitable new component and return it.
  26092. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26093. by this method. In this case, the method must either update it to make sure it's correctly representing
  26094. the given row (which may be different from the one that the component was created for), or it can
  26095. delete this component and return a new one.
  26096. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26097. */
  26098. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26099. Component* existingComponentToUpdate);
  26100. /** This can be overridden to react to the user clicking on a row.
  26101. @see listBoxItemDoubleClicked
  26102. */
  26103. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26104. /** This can be overridden to react to the user double-clicking on a row.
  26105. @see listBoxItemClicked
  26106. */
  26107. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26108. /** This can be overridden to react to the user double-clicking on a part of the list where
  26109. there are no rows.
  26110. @see listBoxItemClicked
  26111. */
  26112. virtual void backgroundClicked();
  26113. /** Override this to be informed when rows are selected or deselected.
  26114. This will be called whenever a row is selected or deselected. If a range of
  26115. rows is selected all at once, this will just be called once for that event.
  26116. @param lastRowSelected the last row that the user selected. If no
  26117. rows are currently selected, this may be -1.
  26118. */
  26119. virtual void selectedRowsChanged (int lastRowSelected);
  26120. /** Override this to be informed when the delete key is pressed.
  26121. If no rows are selected when they press the key, this won't be called.
  26122. @param lastRowSelected the last row that had been selected when they pressed the
  26123. key - if there are multiple selections, this might not be
  26124. very useful
  26125. */
  26126. virtual void deleteKeyPressed (int lastRowSelected);
  26127. /** Override this to be informed when the return key is pressed.
  26128. If no rows are selected when they press the key, this won't be called.
  26129. @param lastRowSelected the last row that had been selected when they pressed the
  26130. key - if there are multiple selections, this might not be
  26131. very useful
  26132. */
  26133. virtual void returnKeyPressed (int lastRowSelected);
  26134. /** Override this to be informed when the list is scrolled.
  26135. This might be caused by the user moving the scrollbar, or by programmatic changes
  26136. to the list position.
  26137. */
  26138. virtual void listWasScrolled();
  26139. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26140. If this returns a non-empty name then when the user drags a row, the listbox will
  26141. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26142. a drag-and-drop operation, using this string as the source description, with the listbox
  26143. itself as the source component.
  26144. @see DragAndDropContainer::startDragging
  26145. */
  26146. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26147. };
  26148. /**
  26149. A list of items that can be scrolled vertically.
  26150. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26151. either paint each row of the list and respond to events via callbacks, or for
  26152. more specialised tasks, it can supply a custom component to fill each row.
  26153. @see ComboBox, TableListBox
  26154. */
  26155. class JUCE_API ListBox : public Component,
  26156. public SettableTooltipClient
  26157. {
  26158. public:
  26159. /** Creates a ListBox.
  26160. The model pointer passed-in can be null, in which case you can set it later
  26161. with setModel().
  26162. */
  26163. ListBox (const String& componentName,
  26164. ListBoxModel* const model);
  26165. /** Destructor. */
  26166. ~ListBox();
  26167. /** Changes the current data model to display. */
  26168. void setModel (ListBoxModel* const newModel);
  26169. /** Returns the current list model. */
  26170. ListBoxModel* getModel() const throw() { return model; }
  26171. /** Causes the list to refresh its content.
  26172. Call this when the number of rows in the list changes, or if you want it
  26173. to call refreshComponentForRow() on all the row components.
  26174. Be careful not to call it from a different thread, though, as it's not
  26175. thread-safe.
  26176. */
  26177. void updateContent();
  26178. /** Turns on multiple-selection of rows.
  26179. By default this is disabled.
  26180. When your row component gets clicked you'll need to call the
  26181. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26182. clicked and to get it to do the appropriate selection based on whether
  26183. the ctrl/shift keys are held down.
  26184. */
  26185. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26186. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26187. This function is here primarily for the ComboBox class to use, but might be
  26188. useful for some other purpose too.
  26189. */
  26190. void setMouseMoveSelectsRows (bool shouldSelect);
  26191. /** Selects a row.
  26192. If the row is already selected, this won't do anything.
  26193. @param rowNumber the row to select
  26194. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26195. the selected row is off-screen, it'll scroll to make
  26196. sure that row is on-screen
  26197. @param deselectOthersFirst if true and there are multiple selections, these will
  26198. first be deselected before this item is selected
  26199. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26200. deselectAllRows, selectRangeOfRows
  26201. */
  26202. void selectRow (const int rowNumber,
  26203. bool dontScrollToShowThisRow = false,
  26204. bool deselectOthersFirst = true);
  26205. /** Selects a set of rows.
  26206. This will add these rows to the current selection, so you might need to
  26207. clear the current selection first with deselectAllRows()
  26208. @param firstRow the first row to select (inclusive)
  26209. @param lastRow the last row to select (inclusive)
  26210. */
  26211. void selectRangeOfRows (int firstRow,
  26212. int lastRow);
  26213. /** Deselects a row.
  26214. If it's not currently selected, this will do nothing.
  26215. @see selectRow, deselectAllRows
  26216. */
  26217. void deselectRow (const int rowNumber);
  26218. /** Deselects any currently selected rows.
  26219. @see deselectRow
  26220. */
  26221. void deselectAllRows();
  26222. /** Selects or deselects a row.
  26223. If the row's currently selected, this deselects it, and vice-versa.
  26224. */
  26225. void flipRowSelection (const int rowNumber);
  26226. /** Returns a sparse set indicating the rows that are currently selected.
  26227. @see setSelectedRows
  26228. */
  26229. const SparseSet<int> getSelectedRows() const;
  26230. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26231. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26232. method will be called. If it's false, no notification will be sent to the model.
  26233. @see getSelectedRows
  26234. */
  26235. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26236. const bool sendNotificationEventToModel = true);
  26237. /** Checks whether a row is selected.
  26238. */
  26239. bool isRowSelected (const int rowNumber) const;
  26240. /** Returns the number of rows that are currently selected.
  26241. @see getSelectedRow, isRowSelected, getLastRowSelected
  26242. */
  26243. int getNumSelectedRows() const;
  26244. /** Returns the row number of a selected row.
  26245. This will return the row number of the Nth selected row. The row numbers returned will
  26246. be sorted in order from low to high.
  26247. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26248. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26249. selected
  26250. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26251. */
  26252. int getSelectedRow (const int index = 0) const;
  26253. /** Returns the last row that the user selected.
  26254. This isn't the same as the highest row number that is currently selected - if the user
  26255. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26256. If nothing is selected, it will return -1.
  26257. */
  26258. int getLastRowSelected() const;
  26259. /** Multiply-selects rows based on the modifier keys.
  26260. If no modifier keys are down, this will select the given row and
  26261. deselect any others.
  26262. If the ctrl (or command on the Mac) key is down, it'll flip the
  26263. state of the selected row.
  26264. If the shift key is down, it'll select up to the given row from the
  26265. last row selected.
  26266. @see selectRow
  26267. */
  26268. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26269. const ModifierKeys& modifiers);
  26270. /** Scrolls the list to a particular position.
  26271. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26272. 1.0 scrolls to the bottom.
  26273. If the total number of rows all fit onto the screen at once, then this
  26274. method won't do anything.
  26275. @see getVerticalPosition
  26276. */
  26277. void setVerticalPosition (const double newProportion);
  26278. /** Returns the current vertical position as a proportion of the total.
  26279. This can be used in conjunction with setVerticalPosition() to save and restore
  26280. the list's position. It returns a value in the range 0 to 1.
  26281. @see setVerticalPosition
  26282. */
  26283. double getVerticalPosition() const;
  26284. /** Scrolls if necessary to make sure that a particular row is visible.
  26285. */
  26286. void scrollToEnsureRowIsOnscreen (const int row);
  26287. /** Returns a pointer to the scrollbar.
  26288. (Unlikely to be useful for most people).
  26289. */
  26290. ScrollBar* getVerticalScrollBar() const throw();
  26291. /** Returns a pointer to the scrollbar.
  26292. (Unlikely to be useful for most people).
  26293. */
  26294. ScrollBar* getHorizontalScrollBar() const throw();
  26295. /** Finds the row index that contains a given x,y position.
  26296. The position is relative to the ListBox's top-left.
  26297. If no row exists at this position, the method will return -1.
  26298. @see getComponentForRowNumber
  26299. */
  26300. int getRowContainingPosition (const int x, const int y) const throw();
  26301. /** Finds a row index that would be the most suitable place to insert a new
  26302. item for a given position.
  26303. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26304. because it lets you easily choose the best position to insert the item that
  26305. they drop, based on where they drop it.
  26306. If the position is out of range, this will return -1. If the position is
  26307. beyond the end of the list, it will return getNumRows() to indicate the end
  26308. of the list.
  26309. @see getComponentForRowNumber
  26310. */
  26311. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26312. /** Returns the position of one of the rows, relative to the top-left of
  26313. the listbox.
  26314. This may be off-screen, and the range of the row number that is passed-in is
  26315. not checked to see if it's a valid row.
  26316. */
  26317. const Rectangle getRowPosition (const int rowNumber,
  26318. const bool relativeToComponentTopLeft) const throw();
  26319. /** Finds the row component for a given row in the list.
  26320. The component returned will have been created using createRowComponent().
  26321. If the component for this row is off-screen or if the row is out-of-range,
  26322. this will return 0.
  26323. @see getRowContainingPosition
  26324. */
  26325. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26326. /** Returns the row number that the given component represents.
  26327. If the component isn't one of the list's rows, this will return -1.
  26328. */
  26329. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26330. /** Returns the width of a row (which may be less than the width of this component
  26331. if there's a scrollbar).
  26332. */
  26333. int getVisibleRowWidth() const throw();
  26334. /** Sets the height of each row in the list.
  26335. The default height is 22 pixels.
  26336. @see getRowHeight
  26337. */
  26338. void setRowHeight (const int newHeight);
  26339. /** Returns the height of a row in the list.
  26340. @see setRowHeight
  26341. */
  26342. int getRowHeight() const throw() { return rowHeight; }
  26343. /** Returns the number of rows actually visible.
  26344. This is the number of whole rows which will fit on-screen, so the value might
  26345. be more than the actual number of rows in the list.
  26346. */
  26347. int getNumRowsOnScreen() const throw();
  26348. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26349. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26350. methods.
  26351. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26352. */
  26353. enum ColourIds
  26354. {
  26355. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26356. Make this transparent if you don't want the background to be filled. */
  26357. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26358. Make this transparent to not have an outline. */
  26359. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26360. };
  26361. /** Sets the thickness of a border that will be drawn around the box.
  26362. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26363. @see outlineColourId
  26364. */
  26365. void setOutlineThickness (const int outlineThickness);
  26366. /** Returns the thickness of outline that will be drawn around the listbox.
  26367. @see setOutlineColour
  26368. */
  26369. int getOutlineThickness() const throw() { return outlineThickness; }
  26370. /** Sets a component that the list should use as a header.
  26371. This will position the given component at the top of the list, maintaining the
  26372. height of the component passed-in, but rescaling it horizontally to match the
  26373. width of the items in the listbox.
  26374. The component will be deleted when setHeaderComponent() is called with a
  26375. different component, or when the listbox is deleted.
  26376. */
  26377. void setHeaderComponent (Component* const newHeaderComponent);
  26378. /** Changes the width of the rows in the list.
  26379. This can be used to make the list's row components wider than the list itself - the
  26380. width of the rows will be either the width of the list or this value, whichever is
  26381. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26382. appear.
  26383. The default value for this is 0, which means that the rows will always
  26384. be the same width as the list.
  26385. */
  26386. void setMinimumContentWidth (const int newMinimumWidth);
  26387. /** Returns the space currently available for the row items, taking into account
  26388. borders, scrollbars, etc.
  26389. */
  26390. int getVisibleContentWidth() const throw();
  26391. /** Repaints one of the rows.
  26392. This is a lightweight alternative to calling updateContent, and just causes a
  26393. repaint of the row's area.
  26394. */
  26395. void repaintRow (const int rowNumber) throw();
  26396. /** This fairly obscure method creates an image that just shows the currently
  26397. selected row components.
  26398. It's a handy method for doing drag-and-drop, as it can be passed to the
  26399. DragAndDropContainer for use as the drag image.
  26400. Note that it will make the row components temporarily invisible, so if you're
  26401. using custom components this could affect them if they're sensitive to that
  26402. sort of thing.
  26403. @see Component::createComponentSnapshot
  26404. */
  26405. Image* createSnapshotOfSelectedRows();
  26406. /** Returns the viewport that this ListBox uses.
  26407. You may need to use this to change parameters such as whether scrollbars
  26408. are shown, etc.
  26409. */
  26410. Viewport* getViewport() const throw();
  26411. /** @internal */
  26412. bool keyPressed (const KeyPress& key);
  26413. /** @internal */
  26414. bool keyStateChanged();
  26415. /** @internal */
  26416. void paint (Graphics& g);
  26417. /** @internal */
  26418. void paintOverChildren (Graphics& g);
  26419. /** @internal */
  26420. void resized();
  26421. /** @internal */
  26422. void visibilityChanged();
  26423. /** @internal */
  26424. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26425. /** @internal */
  26426. void mouseMove (const MouseEvent&);
  26427. /** @internal */
  26428. void mouseExit (const MouseEvent&);
  26429. /** @internal */
  26430. void mouseUp (const MouseEvent&);
  26431. /** @internal */
  26432. void colourChanged();
  26433. juce_UseDebuggingNewOperator
  26434. private:
  26435. friend class ListViewport;
  26436. friend class TableListBox;
  26437. ListBoxModel* model;
  26438. ListViewport* viewport;
  26439. Component* headerComponent;
  26440. int totalItems, rowHeight, minimumRowWidth;
  26441. int outlineThickness;
  26442. int lastMouseX, lastMouseY, lastRowSelected;
  26443. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26444. SparseSet <int> selected;
  26445. void selectRowInternal (const int rowNumber,
  26446. bool dontScrollToShowThisRow,
  26447. bool deselectOthersFirst,
  26448. bool isMouseClick);
  26449. ListBox (const ListBox&);
  26450. const ListBox& operator= (const ListBox&);
  26451. };
  26452. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26453. /********* End of inlined file: juce_ListBox.h *********/
  26454. /********* Start of inlined file: juce_TextButton.h *********/
  26455. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26456. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26457. /**
  26458. A button that uses the standard lozenge-shaped background with a line of
  26459. text on it.
  26460. @see Button, DrawableButton
  26461. */
  26462. class JUCE_API TextButton : public Button
  26463. {
  26464. public:
  26465. /** Creates a TextButton.
  26466. @param buttonName the text to put in the button (the component's name is also
  26467. initially set to this string, but these can be changed later
  26468. using the setName() and setButtonText() methods)
  26469. @param toolTip an optional string to use as a toolip
  26470. @see Button
  26471. */
  26472. TextButton (const String& buttonName,
  26473. const String& toolTip = String::empty);
  26474. /** Destructor. */
  26475. ~TextButton();
  26476. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26477. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26478. methods.
  26479. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26480. */
  26481. enum ColourIds
  26482. {
  26483. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26484. 'off'). The look-and-feel class might re-interpret this to add
  26485. effects, etc. */
  26486. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26487. 'on'). The look-and-feel class might re-interpret this to add
  26488. effects, etc. */
  26489. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26490. };
  26491. /** Resizes the button to fit neatly around its current text.
  26492. If newHeight is >= 0, the button's height will be changed to this
  26493. value. If it's less than zero, its height will be unaffected.
  26494. */
  26495. void changeWidthToFitText (const int newHeight = -1);
  26496. /** This can be overridden to use different fonts than the default one.
  26497. Note that you'll need to set the font's size appropriately, too.
  26498. */
  26499. virtual const Font getFont();
  26500. juce_UseDebuggingNewOperator
  26501. protected:
  26502. /** @internal */
  26503. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26504. /** @internal */
  26505. void colourChanged();
  26506. private:
  26507. TextButton (const TextButton&);
  26508. const TextButton& operator= (const TextButton&);
  26509. };
  26510. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26511. /********* End of inlined file: juce_TextButton.h *********/
  26512. /**
  26513. A component displaying a list of plugins, with options to scan for them,
  26514. add, remove and sort them.
  26515. */
  26516. class JUCE_API PluginListComponent : public Component,
  26517. public ListBoxModel,
  26518. public ChangeListener,
  26519. public ButtonListener,
  26520. public Timer
  26521. {
  26522. public:
  26523. /**
  26524. Creates the list component.
  26525. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26526. The properties file, if supplied, is used to store the user's last search paths.
  26527. */
  26528. PluginListComponent (KnownPluginList& listToRepresent,
  26529. const File& deadMansPedalFile,
  26530. PropertiesFile* const propertiesToUse);
  26531. /** Destructor. */
  26532. ~PluginListComponent();
  26533. /** @internal */
  26534. void resized();
  26535. /** @internal */
  26536. bool isInterestedInFileDrag (const StringArray& files);
  26537. /** @internal */
  26538. void filesDropped (const StringArray& files, int, int);
  26539. /** @internal */
  26540. int getNumRows();
  26541. /** @internal */
  26542. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26543. /** @internal */
  26544. void deleteKeyPressed (int lastRowSelected);
  26545. /** @internal */
  26546. void buttonClicked (Button* b);
  26547. /** @internal */
  26548. void changeListenerCallback (void*);
  26549. /** @internal */
  26550. void timerCallback();
  26551. juce_UseDebuggingNewOperator
  26552. private:
  26553. KnownPluginList& list;
  26554. File deadMansPedalFile;
  26555. ListBox* listBox;
  26556. TextButton* optionsButton;
  26557. PropertiesFile* propertiesToUse;
  26558. int typeToScan;
  26559. void scanFor (AudioPluginFormat* format);
  26560. PluginListComponent (const PluginListComponent&);
  26561. const PluginListComponent& operator= (const PluginListComponent&);
  26562. };
  26563. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26564. /********* End of inlined file: juce_PluginListComponent.h *********/
  26565. #endif
  26566. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26567. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  26568. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26569. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26570. /********* Start of inlined file: juce_AudioFormat.h *********/
  26571. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26572. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26573. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  26574. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26575. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26576. /**
  26577. Writes samples to an audio file stream.
  26578. A subclass that writes a specific type of audio format will be created by
  26579. an AudioFormat object.
  26580. After creating one of these with the AudioFormat::createWriterFor() method
  26581. you can call its write() method to store the samples, and then delete it.
  26582. @see AudioFormat, AudioFormatReader
  26583. */
  26584. class JUCE_API AudioFormatWriter
  26585. {
  26586. protected:
  26587. /** Creates an AudioFormatWriter object.
  26588. @param destStream the stream to write to - this will be deleted
  26589. by this object when it is no longer needed
  26590. @param formatName the description that will be returned by the getFormatName()
  26591. method
  26592. @param sampleRate the sample rate to use - the base class just stores
  26593. this value, it doesn't do anything with it
  26594. @param numberOfChannels the number of channels to write - the base class just stores
  26595. this value, it doesn't do anything with it
  26596. @param bitsPerSample the bit depth of the stream - the base class just stores
  26597. this value, it doesn't do anything with it
  26598. */
  26599. AudioFormatWriter (OutputStream* const destStream,
  26600. const String& formatName,
  26601. const double sampleRate,
  26602. const unsigned int numberOfChannels,
  26603. const unsigned int bitsPerSample);
  26604. public:
  26605. /** Destructor. */
  26606. virtual ~AudioFormatWriter();
  26607. /** Returns a description of what type of format this is.
  26608. E.g. "AIFF file"
  26609. */
  26610. const String getFormatName() const throw() { return formatName; }
  26611. /** Writes a set of samples to the audio stream.
  26612. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  26613. can use AudioSampleBuffer::writeToAudioWriter().
  26614. @param samplesToWrite an array of arrays containing the sample data for
  26615. each channel to write. This is a zero-terminated
  26616. array of arrays, and can contain a different number
  26617. of channels than the actual stream uses, and the
  26618. writer should do its best to cope with this.
  26619. If the format is fixed-point, each channel will be formatted
  26620. as an array of signed integers using the full 32-bit
  26621. range -0x80000000 to 0x7fffffff, regardless of the source's
  26622. bit-depth. If it is a floating-point format, you should treat
  26623. the arrays as arrays of floats, and just cast it to an (int**)
  26624. to pass it into the method.
  26625. @param numSamples the number of samples to write
  26626. */
  26627. virtual bool write (const int** samplesToWrite,
  26628. int numSamples) = 0;
  26629. /** Reads a section of samples from an AudioFormatReader, and writes these to
  26630. the output.
  26631. This will take care of any floating-point conversion that's required to convert
  26632. between the two formats. It won't deal with sample-rate conversion, though.
  26633. @returns false if it can't read or write properly during the operation
  26634. */
  26635. bool writeFromAudioReader (AudioFormatReader& reader,
  26636. int64 startSample,
  26637. int numSamplesToRead);
  26638. /** Reads some samples from an AudioSource, and writes these to the output.
  26639. The source must already have been initialised with the AudioSource::prepareToPlay() method
  26640. @param source the source to read from
  26641. @param numSamplesToRead total number of samples to read and write
  26642. @param samplesPerBlock the maximum number of samples to fetch from the source
  26643. @returns false if it can't read or write properly during the operation
  26644. */
  26645. bool writeFromAudioSource (AudioSource& source,
  26646. int numSamplesToRead,
  26647. const int samplesPerBlock = 2048);
  26648. /** Returns the sample rate being used. */
  26649. double getSampleRate() const throw() { return sampleRate; }
  26650. /** Returns the number of channels being written. */
  26651. int getNumChannels() const throw() { return numChannels; }
  26652. /** Returns the bit-depth of the data being written. */
  26653. int getBitsPerSample() const throw() { return bitsPerSample; }
  26654. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  26655. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  26656. juce_UseDebuggingNewOperator
  26657. protected:
  26658. /** The sample rate of the stream. */
  26659. double sampleRate;
  26660. /** The number of channels being written to the stream. */
  26661. unsigned int numChannels;
  26662. /** The bit depth of the file. */
  26663. unsigned int bitsPerSample;
  26664. /** True if it's a floating-point format, false if it's fixed-point. */
  26665. bool usesFloatingPointData;
  26666. /** The output stream for Use by subclasses. */
  26667. OutputStream* output;
  26668. private:
  26669. String formatName;
  26670. };
  26671. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26672. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  26673. /**
  26674. Subclasses of AudioFormat are used to read and write different audio
  26675. file formats.
  26676. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  26677. */
  26678. class JUCE_API AudioFormat
  26679. {
  26680. public:
  26681. /** Destructor. */
  26682. virtual ~AudioFormat();
  26683. /** Returns the name of this format.
  26684. e.g. "WAV file" or "AIFF file"
  26685. */
  26686. const String& getFormatName() const;
  26687. /** Returns all the file extensions that might apply to a file of this format.
  26688. The first item will be the one that's preferred when creating a new file.
  26689. So for a wav file this might just return ".wav"; for an AIFF file it might
  26690. return two items, ".aif" and ".aiff"
  26691. */
  26692. const StringArray& getFileExtensions() const;
  26693. /** Returns true if this the given file can be read by this format.
  26694. Subclasses shouldn't do too much work here, just check the extension or
  26695. file type. The base class implementation just checks the file's extension
  26696. against one of the ones that was registered in the constructor.
  26697. */
  26698. virtual bool canHandleFile (const File& fileToTest);
  26699. /** Returns a set of sample rates that the format can read and write. */
  26700. virtual const Array <int> getPossibleSampleRates() = 0;
  26701. /** Returns a set of bit depths that the format can read and write. */
  26702. virtual const Array <int> getPossibleBitDepths() = 0;
  26703. /** Returns true if the format can do 2-channel audio. */
  26704. virtual bool canDoStereo() = 0;
  26705. /** Returns true if the format can do 1-channel audio. */
  26706. virtual bool canDoMono() = 0;
  26707. /** Returns true if the format uses compressed data. */
  26708. virtual bool isCompressed();
  26709. /** Returns a list of different qualities that can be used when writing.
  26710. Non-compressed formats will just return an empty array, but for something
  26711. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  26712. When calling createWriterFor(), an index from this array is passed in to
  26713. tell the format which option is required.
  26714. */
  26715. virtual const StringArray getQualityOptions();
  26716. /** Tries to create an object that can read from a stream containing audio
  26717. data in this format.
  26718. The reader object that is returned can be used to read from the stream, and
  26719. should then be deleted by the caller.
  26720. @param sourceStream the stream to read from - the AudioFormatReader object
  26721. that is returned will delete this stream when it no longer
  26722. needs it.
  26723. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  26724. should delete the stream object that was passed-in. (If a valid
  26725. reader is returned, it will always be in charge of deleting the
  26726. stream, so this parameter is ignored)
  26727. @see AudioFormatReader
  26728. */
  26729. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26730. const bool deleteStreamIfOpeningFails) = 0;
  26731. /** Tries to create an object that can write to a stream with this audio format.
  26732. The writer object that is returned can be used to write to the stream, and
  26733. should then be deleted by the caller.
  26734. If the stream can't be created for some reason (e.g. the parameters passed in
  26735. here aren't suitable), this will return 0.
  26736. @param streamToWriteTo the stream that the data will go to - this will be
  26737. deleted by the AudioFormatWriter object when it's no longer
  26738. needed. If no AudioFormatWriter can be created by this method,
  26739. the stream will NOT be deleted, so that the caller can re-use it
  26740. to try to open a different format, etc
  26741. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  26742. returned by getPossibleSampleRates()
  26743. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  26744. the choice will depend on the results of canDoMono() and
  26745. canDoStereo()
  26746. @param bitsPerSample the bits per sample to use - this must be one of the values
  26747. returned by getPossibleBitDepths()
  26748. @param metadataValues a set of metadata values that the writer should try to write
  26749. to the stream. Exactly what these are depends on the format,
  26750. and the subclass doesn't actually have to do anything with
  26751. them if it doesn't want to. Have a look at the specific format
  26752. implementation classes to see possible values that can be
  26753. used
  26754. @param qualityOptionIndex the index of one of compression qualities returned by the
  26755. getQualityOptions() method. If there aren't any quality options
  26756. for this format, just pass 0 in this parameter, as it'll be
  26757. ignored
  26758. @see AudioFormatWriter
  26759. */
  26760. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26761. double sampleRateToUse,
  26762. unsigned int numberOfChannels,
  26763. int bitsPerSample,
  26764. const StringPairArray& metadataValues,
  26765. int qualityOptionIndex) = 0;
  26766. protected:
  26767. /** Creates an AudioFormat object.
  26768. @param formatName this sets the value that will be returned by getFormatName()
  26769. @param fileExtensions a zero-terminated list of file extensions - this is what will
  26770. be returned by getFileExtension()
  26771. */
  26772. AudioFormat (const String& formatName,
  26773. const tchar** const fileExtensions);
  26774. private:
  26775. String formatName;
  26776. StringArray fileExtensions;
  26777. };
  26778. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  26779. /********* End of inlined file: juce_AudioFormat.h *********/
  26780. /**
  26781. Reads and Writes AIFF format audio files.
  26782. @see AudioFormat
  26783. */
  26784. class JUCE_API AiffAudioFormat : public AudioFormat
  26785. {
  26786. public:
  26787. /** Creates an format object. */
  26788. AiffAudioFormat();
  26789. /** Destructor. */
  26790. ~AiffAudioFormat();
  26791. const Array <int> getPossibleSampleRates();
  26792. const Array <int> getPossibleBitDepths();
  26793. bool canDoStereo();
  26794. bool canDoMono();
  26795. #if JUCE_MAC
  26796. bool canHandleFile (const File& fileToTest);
  26797. #endif
  26798. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26799. const bool deleteStreamIfOpeningFails);
  26800. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26801. double sampleRateToUse,
  26802. unsigned int numberOfChannels,
  26803. int bitsPerSample,
  26804. const StringPairArray& metadataValues,
  26805. int qualityOptionIndex);
  26806. juce_UseDebuggingNewOperator
  26807. };
  26808. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26809. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  26810. #endif
  26811. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26812. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  26813. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26814. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26815. /**
  26816. */
  26817. class AudioCDBurner
  26818. {
  26819. public:
  26820. /** Returns a list of available optical drives.
  26821. Use openDevice() to open one of the items from this list.
  26822. */
  26823. static const StringArray findAvailableDevices();
  26824. /** Tries to open one of the optical drives.
  26825. The deviceIndex is an index into the array returned by findAvailableDevices().
  26826. */
  26827. static AudioCDBurner* openDevice (const int deviceIndex);
  26828. /** Destructor. */
  26829. ~AudioCDBurner();
  26830. /** Returns true if there's a writable disk in the drive.
  26831. */
  26832. bool isDiskPresent() const;
  26833. /** Returns the number of free blocks on the disk.
  26834. There are 75 blocks per second, at 44100Hz.
  26835. */
  26836. int getNumAvailableAudioBlocks() const;
  26837. /** Adds a track to be written.
  26838. The source passed-in here will be kept by this object, and it will
  26839. be used and deleted at some point in the future, either during the
  26840. burn() method or when this AudioCDBurner object is deleted. Your caller
  26841. method shouldn't keep a reference to it or use it again after passing
  26842. it in here.
  26843. */
  26844. bool addAudioTrack (AudioSource* source, int numSamples);
  26845. /**
  26846. Return true to cancel the current burn operation
  26847. */
  26848. class BurnProgressListener
  26849. {
  26850. public:
  26851. BurnProgressListener() throw() {}
  26852. virtual ~BurnProgressListener() {}
  26853. /** Called at intervals to report on the progress of the AudioCDBurner.
  26854. To cancel the burn, return true from this.
  26855. */
  26856. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  26857. };
  26858. const String burn (BurnProgressListener* listener,
  26859. const bool ejectDiscAfterwards,
  26860. const bool peformFakeBurnForTesting);
  26861. juce_UseDebuggingNewOperator
  26862. private:
  26863. AudioCDBurner (const int deviceIndex);
  26864. void* internal;
  26865. };
  26866. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26867. /********* End of inlined file: juce_AudioCDBurner.h *********/
  26868. #endif
  26869. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26870. /********* Start of inlined file: juce_AudioCDReader.h *********/
  26871. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26872. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  26873. #if JUCE_MAC
  26874. #endif
  26875. /**
  26876. A type of AudioFormatReader that reads from an audio CD.
  26877. One of these can be used to read a CD as if it's one big audio stream. Use the
  26878. getPositionOfTrackStart() method to find where the individual tracks are
  26879. within the stream.
  26880. @see AudioFormatReader
  26881. */
  26882. class JUCE_API AudioCDReader : public AudioFormatReader
  26883. {
  26884. public:
  26885. /** Returns a list of names of Audio CDs currently available for reading.
  26886. If there's a CD drive but no CD in it, this might return an empty list, or
  26887. possibly a device that can be opened but which has no tracks, depending
  26888. on the platform.
  26889. @see createReaderForCD
  26890. */
  26891. static const StringArray getAvailableCDNames();
  26892. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  26893. @param index the index of one of the available CDs - use getAvailableCDNames()
  26894. to find out how many there are.
  26895. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  26896. caller will be responsible for deleting the object returned.
  26897. */
  26898. static AudioCDReader* createReaderForCD (const int index);
  26899. /** Destructor. */
  26900. ~AudioCDReader();
  26901. /** Implementation of the AudioFormatReader method. */
  26902. bool read (int** destSamples,
  26903. int64 startSampleInFile,
  26904. int numSamples);
  26905. /** Checks whether the CD has been removed from the drive.
  26906. */
  26907. bool isCDStillPresent() const;
  26908. /** Returns the total number of tracks (audio + data).
  26909. */
  26910. int getNumTracks() const;
  26911. /** Finds the sample offset of the start of a track.
  26912. @param trackNum the track number, where 0 is the first track.
  26913. */
  26914. int getPositionOfTrackStart (int trackNum) const;
  26915. /** Returns true if a given track is an audio track.
  26916. @param trackNum the track number, where 0 is the first track.
  26917. */
  26918. bool isTrackAudio (int trackNum) const;
  26919. /** Refreshes the object's table of contents.
  26920. If the disc has been ejected and a different one put in since this
  26921. object was created, this will cause it to update its idea of how many tracks
  26922. there are, etc.
  26923. */
  26924. void refreshTrackLengths();
  26925. /** Enables scanning for indexes within tracks.
  26926. @see getLastIndex
  26927. */
  26928. void enableIndexScanning (bool enabled);
  26929. /** Returns the index number found during the last read() call.
  26930. Index scanning is turned off by default - turn it on with enableIndexScanning().
  26931. Then when the read() method is called, if it comes across an index within that
  26932. block, the index number is stored and returned by this method.
  26933. Some devices might not support indexes, of course.
  26934. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  26935. @see enableIndexScanning
  26936. */
  26937. int getLastIndex() const;
  26938. /** Scans a track to find the position of any indexes within it.
  26939. @param trackNumber the track to look in, where 0 is the first track on the disc
  26940. @returns an array of sample positions of any index points found (not including
  26941. the index that marks the start of the track)
  26942. */
  26943. const Array <int> findIndexesInTrack (const int trackNumber);
  26944. /** Returns the CDDB id number for the CD.
  26945. It's not a great way of identifying a disc, but it's traditional.
  26946. */
  26947. int getCDDBId();
  26948. /** Tries to eject the disk.
  26949. Of course this might not be possible, if some other process is using it.
  26950. */
  26951. void ejectDisk();
  26952. juce_UseDebuggingNewOperator
  26953. private:
  26954. #if JUCE_MAC
  26955. File volumeDir;
  26956. OwnedArray<File> tracks;
  26957. Array <int> trackStartSamples;
  26958. int currentReaderTrack;
  26959. AudioFormatReader* reader;
  26960. AudioCDReader (const File& volume);
  26961. public:
  26962. static int compareElements (const File* const, const File* const) throw();
  26963. private:
  26964. #elif JUCE_WIN32
  26965. int numTracks;
  26966. int trackStarts[100];
  26967. bool audioTracks [100];
  26968. void* handle;
  26969. bool indexingEnabled;
  26970. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  26971. MemoryBlock buffer;
  26972. AudioCDReader (void* handle);
  26973. int getIndexAt (int samplePos);
  26974. #elif JUCE_LINUX
  26975. AudioCDReader();
  26976. #endif
  26977. AudioCDReader (const AudioCDReader&);
  26978. const AudioCDReader& operator= (const AudioCDReader&);
  26979. };
  26980. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  26981. /********* End of inlined file: juce_AudioCDReader.h *********/
  26982. #endif
  26983. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26984. #endif
  26985. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  26986. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  26987. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  26988. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  26989. /**
  26990. A class for keeping a list of available audio formats, and for deciding which
  26991. one to use to open a given file.
  26992. You can either use this class as a singleton object, or create instances of it
  26993. yourself. Once created, use its registerFormat() method to tell it which
  26994. formats it should use.
  26995. @see AudioFormat
  26996. */
  26997. class JUCE_API AudioFormatManager
  26998. {
  26999. public:
  27000. /** Creates an empty format manager.
  27001. Before it'll be any use, you'll need to call registerFormat() with all the
  27002. formats you want it to be able to recognise.
  27003. */
  27004. AudioFormatManager();
  27005. /** Destructor. */
  27006. ~AudioFormatManager();
  27007. juce_DeclareSingleton (AudioFormatManager, false);
  27008. /** Adds a format to the manager's list of available file types.
  27009. The object passed-in will be deleted by this object, so don't keep a pointer
  27010. to it!
  27011. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27012. return this one when called.
  27013. */
  27014. void registerFormat (AudioFormat* newFormat,
  27015. const bool makeThisTheDefaultFormat);
  27016. /** Handy method to make it easy to register the formats that come with Juce.
  27017. Currently, this will add WAV and AIFF to the list.
  27018. */
  27019. void registerBasicFormats();
  27020. /** Clears the list of known formats. */
  27021. void clearFormats();
  27022. /** Returns the number of currently registered file formats. */
  27023. int getNumKnownFormats() const;
  27024. /** Returns one of the registered file formats. */
  27025. AudioFormat* getKnownFormat (const int index) const;
  27026. /** Looks for which of the known formats is listed as being for a given file
  27027. extension.
  27028. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27029. */
  27030. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27031. /** Returns the format which has been set as the default one.
  27032. You can set a format as being the default when it is registered. It's useful
  27033. when you want to write to a file, because the best format may change between
  27034. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27035. If none has been set as the default, this method will just return the first
  27036. one in the list.
  27037. */
  27038. AudioFormat* getDefaultFormat() const;
  27039. /** Returns a set of wildcards for file-matching that contains the extensions for
  27040. all known formats.
  27041. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27042. */
  27043. const String getWildcardForAllFormats() const;
  27044. /** Searches through the known formats to try to create a suitable reader for
  27045. this file.
  27046. If none of the registered formats can open the file, it'll return 0. If it
  27047. returns a reader, it's the caller's responsibility to delete the reader.
  27048. */
  27049. AudioFormatReader* createReaderFor (const File& audioFile);
  27050. /** Searches through the known formats to try to create a suitable reader for
  27051. this stream.
  27052. The stream object that is passed-in will be deleted by this method or by the
  27053. reader that is returned, so the caller should not keep any references to it.
  27054. The stream that is passed-in must be capable of being repositioned so
  27055. that all the formats can have a go at opening it.
  27056. If none of the registered formats can open the stream, it'll return 0. If it
  27057. returns a reader, it's the caller's responsibility to delete the reader.
  27058. */
  27059. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27060. juce_UseDebuggingNewOperator
  27061. private:
  27062. VoidArray knownFormats;
  27063. int defaultFormatIndex;
  27064. };
  27065. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27066. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27067. #endif
  27068. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27069. #endif
  27070. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27071. #endif
  27072. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27073. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27074. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27075. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27076. /**
  27077. This class is used to wrap an AudioFormatReader and only read from a
  27078. subsection of the file.
  27079. So if you have a reader which can read a 1000 sample file, you could wrap it
  27080. in one of these to only access, e.g. samples 100 to 200, and any samples
  27081. outside that will come back as 0. Accessing sample 0 from this reader will
  27082. actually read the first sample from the other's subsection, which might
  27083. be at a non-zero position.
  27084. @see AudioFormatReader
  27085. */
  27086. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27087. {
  27088. public:
  27089. /** Creates a AudioSubsectionReader for a given data source.
  27090. @param sourceReader the source reader from which we'll be taking data
  27091. @param subsectionStartSample the sample within the source reader which will be
  27092. mapped onto sample 0 for this reader.
  27093. @param subsectionLength the number of samples from the source that will
  27094. make up the subsection. If this reader is asked for
  27095. any samples beyond this region, it will return zero.
  27096. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27097. this object is deleted.
  27098. */
  27099. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27100. const int64 subsectionStartSample,
  27101. const int64 subsectionLength,
  27102. const bool deleteSourceWhenDeleted);
  27103. /** Destructor. */
  27104. ~AudioSubsectionReader();
  27105. bool read (int** destSamples,
  27106. int64 startSample,
  27107. int numSamples);
  27108. void readMaxLevels (int64 startSample,
  27109. int64 numSamples,
  27110. float& lowestLeft,
  27111. float& highestLeft,
  27112. float& lowestRight,
  27113. float& highestRight);
  27114. juce_UseDebuggingNewOperator
  27115. private:
  27116. AudioFormatReader* const source;
  27117. int64 startSample, length;
  27118. const bool deleteSourceWhenDeleted;
  27119. AudioSubsectionReader (const AudioSubsectionReader&);
  27120. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27121. };
  27122. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27123. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27124. #endif
  27125. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27126. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27127. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27128. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27129. class AudioThumbnailCache;
  27130. /**
  27131. Makes it easy to quickly draw scaled views of the waveform shape of an
  27132. audio file.
  27133. To use this class, just create an AudioThumbNail class for the file you want
  27134. to draw, call setSource to tell it which file or resource to use, then call
  27135. drawChannel() to draw it.
  27136. The class will asynchronously scan the wavefile to create its scaled-down view,
  27137. so you should make your UI repaint itself as this data comes in. To do this, the
  27138. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27139. listeners should repaint themselves.
  27140. The thumbnail stores an internal low-res version of the wave data, and this can
  27141. be loaded and saved to avoid having to scan the file again.
  27142. @see AudioThumbnailCache
  27143. */
  27144. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27145. public TimeSliceClient,
  27146. private Timer
  27147. {
  27148. public:
  27149. /** Creates an audio thumbnail.
  27150. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27151. of the audio data, this is the scale at which it should be done
  27152. @param formatManagerToUse the audio format manager that is used to open the file
  27153. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27154. thread and storage that is used to by the thumbnail, and the cache
  27155. object can be shared between multiple thumbnails
  27156. */
  27157. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27158. AudioFormatManager& formatManagerToUse,
  27159. AudioThumbnailCache& cacheToUse);
  27160. /** Destructor. */
  27161. ~AudioThumbnail();
  27162. /** Specifies the file or stream that contains the audio file.
  27163. For a file, just call
  27164. @code
  27165. setSource (new FileInputSource (file))
  27166. @endcode
  27167. You can pass a zero in here to clear the thumbnail.
  27168. The source that is passed in will be deleted by this object when it is no
  27169. longer needed
  27170. */
  27171. void setSource (InputSource* const newSource);
  27172. /** Reloads the low res thumbnail data from an input stream.
  27173. The thumb will automatically attempt to reload itself from its
  27174. AudioThumbnailCache.
  27175. */
  27176. void loadFrom (InputStream& input);
  27177. /** Saves the low res thumbnail data to an output stream.
  27178. The thumb will automatically attempt to save itself to its
  27179. AudioThumbnailCache after it finishes scanning the wave file.
  27180. */
  27181. void saveTo (OutputStream& output) const;
  27182. /** Returns the number of channels in the file.
  27183. */
  27184. int getNumChannels() const throw();
  27185. /** Returns the length of the audio file.
  27186. */
  27187. double getTotalLength() const throw();
  27188. /** Renders the waveform shape for a channel.
  27189. The waveform will be drawn within the specified rectangle, where startTime
  27190. and endTime specify the times within the audio file that should be positioned
  27191. at the left and right edges of the rectangle.
  27192. The waveform will be scaled vertically so that a full-volume sample will fill
  27193. the rectangle vertically, but you can also specify an extra vertical scale factor
  27194. with the verticalZoomFactor parameter.
  27195. */
  27196. void drawChannel (Graphics& g,
  27197. int x, int y, int w, int h,
  27198. double startTime,
  27199. double endTime,
  27200. int channelNum,
  27201. const float verticalZoomFactor);
  27202. /** Returns true if the low res preview is fully generated.
  27203. */
  27204. bool isFullyLoaded() const throw();
  27205. /** @internal */
  27206. bool useTimeSlice();
  27207. /** @internal */
  27208. void timerCallback();
  27209. juce_UseDebuggingNewOperator
  27210. private:
  27211. AudioFormatManager& formatManagerToUse;
  27212. AudioThumbnailCache& cache;
  27213. InputSource* source;
  27214. CriticalSection readerLock;
  27215. AudioFormatReader* reader;
  27216. MemoryBlock data, cachedLevels;
  27217. int orginalSamplesPerThumbnailSample;
  27218. int numChannelsCached, numSamplesCached;
  27219. double cachedStart, cachedTimePerPixel;
  27220. bool cacheNeedsRefilling;
  27221. void clear();
  27222. AudioFormatReader* createReader() const;
  27223. void generateSection (AudioFormatReader& reader,
  27224. int64 startSample,
  27225. int numSamples);
  27226. char* getChannelData (int channel) const;
  27227. void refillCache (const int numSamples,
  27228. double startTime,
  27229. const double timePerPixel);
  27230. friend class AudioThumbnailCache;
  27231. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27232. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27233. // returns true if more needs to be read
  27234. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27235. };
  27236. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27237. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27238. #endif
  27239. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27240. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27241. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27242. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27243. struct ThumbnailCacheEntry;
  27244. /**
  27245. An instance of this class is used to manage multiple AudioThumbnail objects.
  27246. The cache runs a single background thread that is shared by all the thumbnails
  27247. that need it, and it maintains a set of low-res previews in memory, to avoid
  27248. having to re-scan audio files too often.
  27249. @see AudioThumbnail
  27250. */
  27251. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27252. {
  27253. public:
  27254. /** Creates a cache object.
  27255. The maxNumThumbsToStore parameter lets you specify how many previews should
  27256. be kept in memory at once.
  27257. */
  27258. AudioThumbnailCache (const int maxNumThumbsToStore);
  27259. /** Destructor. */
  27260. ~AudioThumbnailCache();
  27261. /** Clears out any stored thumbnails.
  27262. */
  27263. void clear();
  27264. /** Reloads the specified thumb if this cache contains the appropriate stored
  27265. data.
  27266. This is called automatically by the AudioThumbnail class, so you shouldn't
  27267. normally need to call it directly.
  27268. */
  27269. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27270. /** Stores the cachable data from the specified thumb in this cache.
  27271. This is called automatically by the AudioThumbnail class, so you shouldn't
  27272. normally need to call it directly.
  27273. */
  27274. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27275. juce_UseDebuggingNewOperator
  27276. private:
  27277. OwnedArray <ThumbnailCacheEntry> thumbs;
  27278. int maxNumThumbsToStore;
  27279. friend class AudioThumbnail;
  27280. void addThumbnail (AudioThumbnail* const thumb);
  27281. void removeThumbnail (AudioThumbnail* const thumb);
  27282. };
  27283. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27284. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27285. #endif
  27286. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27287. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27288. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27289. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27290. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27291. /**
  27292. Reads and writes the lossless-compression FLAC audio format.
  27293. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27294. and make sure your include search path and library search path are set up to find
  27295. the FLAC header files and static libraries.
  27296. @see AudioFormat
  27297. */
  27298. class JUCE_API FlacAudioFormat : public AudioFormat
  27299. {
  27300. public:
  27301. FlacAudioFormat();
  27302. ~FlacAudioFormat();
  27303. const Array <int> getPossibleSampleRates();
  27304. const Array <int> getPossibleBitDepths();
  27305. bool canDoStereo();
  27306. bool canDoMono();
  27307. bool isCompressed();
  27308. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27309. const bool deleteStreamIfOpeningFails);
  27310. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27311. double sampleRateToUse,
  27312. unsigned int numberOfChannels,
  27313. int bitsPerSample,
  27314. const StringPairArray& metadataValues,
  27315. int qualityOptionIndex);
  27316. juce_UseDebuggingNewOperator
  27317. };
  27318. #endif
  27319. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27320. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27321. #endif
  27322. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27323. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27324. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27325. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27326. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27327. /**
  27328. Reads and writes the Ogg-Vorbis audio format.
  27329. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27330. and make sure your include search path and library search path are set up to find
  27331. the Vorbis and Ogg header files and static libraries.
  27332. @see AudioFormat,
  27333. */
  27334. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27335. {
  27336. public:
  27337. OggVorbisAudioFormat();
  27338. ~OggVorbisAudioFormat();
  27339. const Array <int> getPossibleSampleRates();
  27340. const Array <int> getPossibleBitDepths();
  27341. bool canDoStereo();
  27342. bool canDoMono();
  27343. bool isCompressed();
  27344. const StringArray getQualityOptions();
  27345. /** Tries to estimate the quality level of an ogg file based on its size.
  27346. If it can't read the file for some reason, this will just return 1 (medium quality),
  27347. otherwise it will return the approximate quality setting that would have been used
  27348. to create the file.
  27349. @see getQualityOptions
  27350. */
  27351. int estimateOggFileQuality (const File& source);
  27352. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27353. const bool deleteStreamIfOpeningFails);
  27354. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27355. double sampleRateToUse,
  27356. unsigned int numberOfChannels,
  27357. int bitsPerSample,
  27358. const StringPairArray& metadataValues,
  27359. int qualityOptionIndex);
  27360. juce_UseDebuggingNewOperator
  27361. };
  27362. #endif
  27363. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27364. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27365. #endif
  27366. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27367. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27368. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27369. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27370. #if JUCE_QUICKTIME
  27371. /**
  27372. Uses QuickTime to read the audio track a movie or media file.
  27373. As well as QuickTime movies, this should also manage to open other audio
  27374. files that quicktime can understand, like mp3, m4a, etc.
  27375. @see AudioFormat
  27376. */
  27377. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27378. {
  27379. public:
  27380. /** Creates a format object. */
  27381. QuickTimeAudioFormat();
  27382. /** Destructor. */
  27383. ~QuickTimeAudioFormat();
  27384. const Array <int> getPossibleSampleRates();
  27385. const Array <int> getPossibleBitDepths();
  27386. bool canDoStereo();
  27387. bool canDoMono();
  27388. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27389. const bool deleteStreamIfOpeningFails);
  27390. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27391. double sampleRateToUse,
  27392. unsigned int numberOfChannels,
  27393. int bitsPerSample,
  27394. const StringPairArray& metadataValues,
  27395. int qualityOptionIndex);
  27396. juce_UseDebuggingNewOperator
  27397. };
  27398. #endif
  27399. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27400. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27401. #endif
  27402. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27403. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27404. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27405. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27406. /**
  27407. Reads and Writes WAV format audio files.
  27408. @see AudioFormat
  27409. */
  27410. class JUCE_API WavAudioFormat : public AudioFormat
  27411. {
  27412. public:
  27413. /** Creates a format object. */
  27414. WavAudioFormat();
  27415. /** Destructor. */
  27416. ~WavAudioFormat();
  27417. /** Metadata property name used by wav readers and writers for adding
  27418. a BWAV chunk to the file.
  27419. @see AudioFormatReader::metadataValues, createWriterFor
  27420. */
  27421. static const tchar* const bwavDescription;
  27422. /** Metadata property name used by wav readers and writers for adding
  27423. a BWAV chunk to the file.
  27424. @see AudioFormatReader::metadataValues, createWriterFor
  27425. */
  27426. static const tchar* const bwavOriginator;
  27427. /** Metadata property name used by wav readers and writers for adding
  27428. a BWAV chunk to the file.
  27429. @see AudioFormatReader::metadataValues, createWriterFor
  27430. */
  27431. static const tchar* const bwavOriginatorRef;
  27432. /** Metadata property name used by wav readers and writers for adding
  27433. a BWAV chunk to the file.
  27434. Date format is: yyyy-mm-dd
  27435. @see AudioFormatReader::metadataValues, createWriterFor
  27436. */
  27437. static const tchar* const bwavOriginationDate;
  27438. /** Metadata property name used by wav readers and writers for adding
  27439. a BWAV chunk to the file.
  27440. Time format is: hh-mm-ss
  27441. @see AudioFormatReader::metadataValues, createWriterFor
  27442. */
  27443. static const tchar* const bwavOriginationTime;
  27444. /** Metadata property name used by wav readers and writers for adding
  27445. a BWAV chunk to the file.
  27446. This is the number of samples from the start of an edit that the
  27447. file is supposed to begin at. Seems like an obvious mistake to
  27448. only allow a file to occur in an edit once, but that's the way
  27449. it is..
  27450. @see AudioFormatReader::metadataValues, createWriterFor
  27451. */
  27452. static const tchar* const bwavTimeReference;
  27453. /** Metadata property name used by wav readers and writers for adding
  27454. a BWAV chunk to the file.
  27455. This is a
  27456. @see AudioFormatReader::metadataValues, createWriterFor
  27457. */
  27458. static const tchar* const bwavCodingHistory;
  27459. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27460. This just makes it easier than using the property names directly, and it
  27461. fills out the time and date in the right format.
  27462. */
  27463. static const StringPairArray createBWAVMetadata (const String& description,
  27464. const String& originator,
  27465. const String& originatorRef,
  27466. const Time& dateAndTime,
  27467. const int64 timeReferenceSamples,
  27468. const String& codingHistory);
  27469. const Array <int> getPossibleSampleRates();
  27470. const Array <int> getPossibleBitDepths();
  27471. bool canDoStereo();
  27472. bool canDoMono();
  27473. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27474. const bool deleteStreamIfOpeningFails);
  27475. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27476. double sampleRateToUse,
  27477. unsigned int numberOfChannels,
  27478. int bitsPerSample,
  27479. const StringPairArray& metadataValues,
  27480. int qualityOptionIndex);
  27481. juce_UseDebuggingNewOperator
  27482. };
  27483. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27484. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27485. #endif
  27486. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27487. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  27488. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27489. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27490. /********* Start of inlined file: juce_ActionListenerList.h *********/
  27491. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27492. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27493. /**
  27494. A set of ActionListeners.
  27495. Listeners can be added and removed from the list, and messages can be
  27496. broadcast to all the listeners.
  27497. @see ActionListener, ActionBroadcaster
  27498. */
  27499. class JUCE_API ActionListenerList : public MessageListener
  27500. {
  27501. public:
  27502. /** Creates an empty list. */
  27503. ActionListenerList() throw();
  27504. /** Destructor. */
  27505. ~ActionListenerList() throw();
  27506. /** Adds a listener to the list.
  27507. (Trying to add a listener that's already on the list will have no effect).
  27508. */
  27509. void addActionListener (ActionListener* const listener) throw();
  27510. /** Removes a listener from the list.
  27511. If the listener isn't on the list, this won't have any effect.
  27512. */
  27513. void removeActionListener (ActionListener* const listener) throw();
  27514. /** Removes all listeners from the list. */
  27515. void removeAllActionListeners() throw();
  27516. /** Broadcasts a message to all the registered listeners.
  27517. This sends the message asynchronously.
  27518. If a listener is on the list when this method is called but is removed from
  27519. the list before the message arrives, it won't receive the message. Similarly
  27520. listeners that are added to the list after the message is sent but before it
  27521. arrives won't get the message either.
  27522. */
  27523. void sendActionMessage (const String& message) const;
  27524. /** @internal */
  27525. void handleMessage (const Message&);
  27526. juce_UseDebuggingNewOperator
  27527. private:
  27528. SortedSet <void*> actionListeners_;
  27529. CriticalSection actionListenerLock_;
  27530. ActionListenerList (const ActionListenerList&);
  27531. const ActionListenerList& operator= (const ActionListenerList&);
  27532. };
  27533. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27534. /********* End of inlined file: juce_ActionListenerList.h *********/
  27535. /** Manages a list of ActionListeners, and can send them messages.
  27536. To quickly add methods to your class that can add/remove action
  27537. listeners and broadcast to them, you can derive from this.
  27538. @see ActionListenerList, ActionListener
  27539. */
  27540. class JUCE_API ActionBroadcaster
  27541. {
  27542. public:
  27543. /** Creates an ActionBroadcaster. */
  27544. ActionBroadcaster() throw();
  27545. /** Destructor. */
  27546. virtual ~ActionBroadcaster();
  27547. /** Adds a listener to the list.
  27548. (Trying to add a listener that's already on the list will have no effect).
  27549. */
  27550. void addActionListener (ActionListener* const listener);
  27551. /** Removes a listener from the list.
  27552. If the listener isn't on the list, this won't have any effect.
  27553. */
  27554. void removeActionListener (ActionListener* const listener);
  27555. /** Removes all listeners from the list. */
  27556. void removeAllActionListeners();
  27557. /** Broadcasts a message to all the registered listeners.
  27558. @see ActionListenerList::sendActionMessage
  27559. */
  27560. void sendActionMessage (const String& message) const;
  27561. private:
  27562. ActionListenerList actionListenerList;
  27563. ActionBroadcaster (const ActionBroadcaster&);
  27564. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  27565. };
  27566. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27567. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  27568. #endif
  27569. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  27570. #endif
  27571. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27572. #endif
  27573. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  27574. #endif
  27575. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  27576. #endif
  27577. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  27578. #endif
  27579. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  27580. #endif
  27581. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27582. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  27583. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27584. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27585. class InterprocessConnectionServer;
  27586. /**
  27587. Manages a simple two-way messaging connection to another process, using either
  27588. a socket or a named pipe as the transport medium.
  27589. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  27590. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27591. and incoming messages will result in a callback via the messageReceived()
  27592. method.
  27593. To open a pipe and wait for another client to connect to it, use the createPipe()
  27594. method.
  27595. To act as a socket server and create connections for one or more client, see the
  27596. InterprocessConnectionServer class.
  27597. @see InterprocessConnectionServer, Socket, NamedPipe
  27598. */
  27599. class JUCE_API InterprocessConnection : public Thread,
  27600. private MessageListener
  27601. {
  27602. public:
  27603. /** Creates a connection.
  27604. Connections are created manually, connecting them with the connectToSocket()
  27605. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  27606. when a client wants to connect.
  27607. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  27608. connectionLost() and messageReceived() methods will
  27609. always be made using the message thread; if false,
  27610. these will be called immediately on the connection's
  27611. own thread.
  27612. @param magicMessageHeaderNumber a magic number to use in the header to check the
  27613. validity of the data blocks being sent and received. This
  27614. can be any number, but the sender and receiver must obviously
  27615. use matching values or they won't recognise each other.
  27616. */
  27617. InterprocessConnection (const bool callbacksOnMessageThread = true,
  27618. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  27619. /** Destructor. */
  27620. ~InterprocessConnection();
  27621. /** Tries to connect this object to a socket.
  27622. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  27623. object waiting to receive client connections on this port number.
  27624. @param hostName the host computer, either a network address or name
  27625. @param portNumber the socket port number to try to connect to
  27626. @param timeOutMillisecs how long to keep trying before giving up
  27627. @returns true if the connection is established successfully
  27628. @see Socket
  27629. */
  27630. bool connectToSocket (const String& hostName,
  27631. const int portNumber,
  27632. const int timeOutMillisecs);
  27633. /** Tries to connect the object to an existing named pipe.
  27634. For this to work, another process on the same computer must already have opened
  27635. an InterprocessConnection object and used createPipe() to create a pipe for this
  27636. to connect to.
  27637. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27638. @returns true if it connects successfully.
  27639. @see createPipe, NamedPipe
  27640. */
  27641. bool connectToPipe (const String& pipeName,
  27642. const int pipeReceiveMessageTimeoutMs = -1);
  27643. /** Tries to create a new pipe for other processes to connect to.
  27644. This creates a pipe with the given name, so that other processes can use
  27645. connectToPipe() to connect to the other end.
  27646. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27647. If another process is already using this pipe, this will fail and return false.
  27648. */
  27649. bool createPipe (const String& pipeName,
  27650. const int pipeReceiveMessageTimeoutMs = -1);
  27651. /** Disconnects and closes any currently-open sockets or pipes. */
  27652. void disconnect();
  27653. /** True if a socket or pipe is currently active. */
  27654. bool isConnected() const;
  27655. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  27656. StreamingSocket* getSocket() const throw() { return socket; }
  27657. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  27658. NamedPipe* getPipe() const throw() { return pipe; }
  27659. /** Returns the name of the machine at the other end of this connection.
  27660. This will return an empty string if the other machine isn't known for
  27661. some reason.
  27662. */
  27663. const String getConnectedHostName() const;
  27664. /** Tries to send a message to the other end of this connection.
  27665. This will fail if it's not connected, or if there's some kind of write error. If
  27666. it succeeds, the connection object at the other end will receive the message by
  27667. a callback to its messageReceived() method.
  27668. @see messageReceived
  27669. */
  27670. bool sendMessage (const MemoryBlock& message);
  27671. /** Called when the connection is first connected.
  27672. If the connection was created with the callbacksOnMessageThread flag set, then
  27673. this will be called on the message thread; otherwise it will be called on a server
  27674. thread.
  27675. */
  27676. virtual void connectionMade() = 0;
  27677. /** Called when the connection is broken.
  27678. If the connection was created with the callbacksOnMessageThread flag set, then
  27679. this will be called on the message thread; otherwise it will be called on a server
  27680. thread.
  27681. */
  27682. virtual void connectionLost() = 0;
  27683. /** Called when a message arrives.
  27684. When the object at the other end of this connection sends us a message with sendMessage(),
  27685. this callback is used to deliver it to us.
  27686. If the connection was created with the callbacksOnMessageThread flag set, then
  27687. this will be called on the message thread; otherwise it will be called on a server
  27688. thread.
  27689. @see sendMessage
  27690. */
  27691. virtual void messageReceived (const MemoryBlock& message) = 0;
  27692. juce_UseDebuggingNewOperator
  27693. private:
  27694. CriticalSection pipeAndSocketLock;
  27695. StreamingSocket* socket;
  27696. NamedPipe* pipe;
  27697. bool callbackConnectionState;
  27698. const bool useMessageThread;
  27699. const uint32 magicMessageHeader;
  27700. int pipeReceiveMessageTimeout;
  27701. friend class InterprocessConnectionServer;
  27702. void initialiseWithSocket (StreamingSocket* const socket_);
  27703. void initialiseWithPipe (NamedPipe* const pipe_);
  27704. void handleMessage (const Message& message);
  27705. void connectionMadeInt();
  27706. void connectionLostInt();
  27707. void deliverDataInt (const MemoryBlock& data);
  27708. bool readNextMessageInt();
  27709. void run();
  27710. InterprocessConnection (const InterprocessConnection&);
  27711. const InterprocessConnection& operator= (const InterprocessConnection&);
  27712. };
  27713. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27714. /********* End of inlined file: juce_InterprocessConnection.h *********/
  27715. #endif
  27716. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27717. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  27718. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27719. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27720. /**
  27721. An object that waits for client sockets to connect to a port on this host, and
  27722. creates InterprocessConnection objects for each one.
  27723. To use this, create a class derived from it which implements the createConnectionObject()
  27724. method, so that it creates suitable connection objects for each client that tries
  27725. to connect.
  27726. @see InterprocessConnection
  27727. */
  27728. class JUCE_API InterprocessConnectionServer : private Thread
  27729. {
  27730. public:
  27731. /** Creates an uninitialised server object.
  27732. */
  27733. InterprocessConnectionServer();
  27734. /** Destructor. */
  27735. ~InterprocessConnectionServer();
  27736. /** Starts an internal thread which listens on the given port number.
  27737. While this is running, in another process tries to connect with the
  27738. InterprocessConnection::connectToSocket() method, this object will call
  27739. createConnectionObject() to create a connection to that client.
  27740. Use stop() to stop the thread running.
  27741. @see createConnectionObject, stop
  27742. */
  27743. bool beginWaitingForSocket (const int portNumber);
  27744. /** Terminates the listener thread, if it's active.
  27745. @see beginWaitingForSocket
  27746. */
  27747. void stop();
  27748. protected:
  27749. /** Creates a suitable connection object for a client process that wants to
  27750. connect to this one.
  27751. This will be called by the listener thread when a client process tries
  27752. to connect, and must return a new InterprocessConnection object that will
  27753. then run as this end of the connection.
  27754. @see InterprocessConnection
  27755. */
  27756. virtual InterprocessConnection* createConnectionObject() = 0;
  27757. public:
  27758. juce_UseDebuggingNewOperator
  27759. private:
  27760. StreamingSocket* volatile socket;
  27761. void run();
  27762. InterprocessConnectionServer (const InterprocessConnectionServer&);
  27763. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  27764. };
  27765. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27766. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  27767. #endif
  27768. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  27769. #endif
  27770. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  27771. #endif
  27772. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27773. /********* Start of inlined file: juce_MessageManager.h *********/
  27774. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27775. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27776. class Thread;
  27777. class Component;
  27778. class MessageManagerLock;
  27779. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  27780. */
  27781. typedef void* (MessageCallbackFunction) (void* userData);
  27782. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  27783. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  27784. */
  27785. class JUCE_API MessageManager : private DeletedAtShutdown
  27786. {
  27787. public:
  27788. /** Returns the global instance of the MessageManager. */
  27789. static MessageManager* getInstance() throw();
  27790. void runDispatchLoop();
  27791. void stopDispatchLoop();
  27792. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  27793. /** Synchronously dispatches messages until a given time has elapsed.
  27794. Returns false if a quit message has been posted, otherwise returns true.
  27795. */
  27796. bool runDispatchLoopUntil (int millisecondsToRunFor);
  27797. /*int runModalLoop (Component* componentToBeModal);
  27798. bool makeComponentModal (Component* componentToBeModal);
  27799. bool isComponentModal (const Component* component) const;
  27800. Component* getCurrentModalComponent() const;
  27801. void exitModalLoop (int returnValue);*/
  27802. /** Calls a function using the message-thread.
  27803. This can be used by any thread to cause this function to be called-back
  27804. by the message thread. If it's the message-thread that's calling this method,
  27805. then the function will just be called; if another thread is calling, a message
  27806. will be posted to the queue, and this method will block until that message
  27807. is delivered, the function is called, and the result is returned.
  27808. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  27809. thread has a critical section locked, which an unrelated message callback then tries to lock
  27810. before the message thread gets round to processing this callback.
  27811. @param callback the function to call - its signature must be @code
  27812. void* myCallbackFunction (void*) @endcode
  27813. @param userData a user-defined pointer that will be passed to the function that gets called
  27814. @returns the value that the callback function returns.
  27815. @see MessageManagerLock
  27816. */
  27817. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  27818. void* userData);
  27819. /** Returns true if the caller-thread is the message thread. */
  27820. bool isThisTheMessageThread() const throw();
  27821. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  27822. (Best to ignore this method unless you really know what you're doing..)
  27823. @see getCurrentMessageThread
  27824. */
  27825. void setCurrentMessageThread (const int64 threadId) throw();
  27826. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  27827. (Best to ignore this method unless you really know what you're doing..)
  27828. @see setCurrentMessageThread
  27829. */
  27830. int64 getCurrentMessageThread() const throw() { return messageThreadId; }
  27831. /** Returns true if the caller thread has currenltly got the message manager locked.
  27832. see the MessageManagerLock class for more info about this.
  27833. This will be true if the caller is the message thread, because that automatically
  27834. gains a lock while a message is being dispatched.
  27835. */
  27836. bool currentThreadHasLockedMessageManager() const throw();
  27837. /** Sends a message to all other JUCE applications that are running.
  27838. @param messageText the string that will be passed to the actionListenerCallback()
  27839. method of the broadcast listeners in the other app.
  27840. @see registerBroadcastListener, ActionListener
  27841. */
  27842. static void broadcastMessage (const String& messageText) throw();
  27843. /** Registers a listener to get told about broadcast messages.
  27844. The actionListenerCallback() callback's string parameter
  27845. is the message passed into broadcastMessage().
  27846. @see broadcastMessage
  27847. */
  27848. void registerBroadcastListener (ActionListener* listener) throw();
  27849. /** Deregisters a broadcast listener. */
  27850. void deregisterBroadcastListener (ActionListener* listener) throw();
  27851. /** @internal */
  27852. void deliverMessage (void*);
  27853. /** @internal */
  27854. void deliverBroadcastMessage (const String&);
  27855. juce_UseDebuggingNewOperator
  27856. private:
  27857. MessageManager() throw();
  27858. ~MessageManager() throw();
  27859. friend class MessageListener;
  27860. friend class ChangeBroadcaster;
  27861. friend class ActionBroadcaster;
  27862. static MessageManager* instance;
  27863. SortedSet<const MessageListener*> messageListeners;
  27864. ActionListenerList* broadcastListeners;
  27865. friend class JUCEApplication;
  27866. bool quitMessagePosted, quitMessageReceived;
  27867. int64 messageThreadId;
  27868. VoidArray modalComponents;
  27869. static void* exitModalLoopCallback (void*);
  27870. void postMessageToQueue (Message* const message);
  27871. static void doPlatformSpecificInitialisation();
  27872. static void doPlatformSpecificShutdown();
  27873. friend class MessageManagerLock;
  27874. CriticalSection messageDispatchLock;
  27875. int64 currentLockingThreadId;
  27876. MessageManager (const MessageManager&);
  27877. const MessageManager& operator= (const MessageManager&);
  27878. };
  27879. /** Used to make sure that the calling thread has exclusive access to the message loop.
  27880. Because it's not thread-safe to call any of the Component or other UI classes
  27881. from threads other than the message thread, one of these objects can be used to
  27882. lock the message loop and allow this to be done. The message thread will be
  27883. suspended for the lifetime of the MessageManagerLock object, so create one on
  27884. the stack like this: @code
  27885. void MyThread::run()
  27886. {
  27887. someData = 1234;
  27888. const MessageManagerLock mmLock;
  27889. // the event loop will now be locked so it's safe to make a few calls..
  27890. myComponent->setBounds (newBounds);
  27891. myComponent->repaint();
  27892. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  27893. }
  27894. @endcode
  27895. Obviously be careful not to create one of these and leave it lying around, or
  27896. your app will grind to a halt!
  27897. Another caveat is that using this in conjunction with other CriticalSections
  27898. can create lots of interesting ways of producing a deadlock! In particular, if
  27899. your message thread calls stopThread() for a thread that uses these locks,
  27900. you'll get an (occasional) deadlock..
  27901. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  27902. */
  27903. class JUCE_API MessageManagerLock
  27904. {
  27905. public:
  27906. /** Tries to acquire a lock on the message manager.
  27907. If this constructor
  27908. When this constructor returns, the message manager will have finished processing the
  27909. last message and will not send another message until this MessageManagerLock is
  27910. deleted.
  27911. If the current thread already has the lock, nothing will be done, so it's perfectly
  27912. safe to create these locks recursively.
  27913. */
  27914. MessageManagerLock() throw();
  27915. /** Releases the current thread's lock on the message manager.
  27916. Make sure this object is created and deleted by the same thread,
  27917. otherwise there are no guarantees what will happen!
  27918. */
  27919. ~MessageManagerLock() throw();
  27920. /** Tries to acquire a lock on the message manager.
  27921. This does the same thing as the normal constructor, but while it's waiting to get
  27922. the lock, it checks the specified thread to see if it has been given the
  27923. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  27924. without gaining the lock.
  27925. To find out whether the lock was successful, call lockWasGained(). If this is
  27926. false, your thread is being told to die, so you'd better get out of there.
  27927. If the current thread already has the lock, nothing will be done, so it's perfectly
  27928. safe to create these locks recursively.
  27929. E.g.
  27930. @code
  27931. void run()
  27932. {
  27933. ...
  27934. while (! threadShouldExit())
  27935. {
  27936. MessageManagerLock mml (Thread::getCurrentThread());
  27937. if (! mml.lockWasGained)
  27938. return; // another thread is trying to kill us!
  27939. ..do some locked stuff here..
  27940. }
  27941. ..and now the MM is now unlocked..
  27942. }
  27943. @endcode
  27944. */
  27945. MessageManagerLock (Thread* const threadToCheckForExitSignal) throw();
  27946. /** Returns true if the lock was successfully acquired.
  27947. (See the constructor that takes a Thread for more info).
  27948. */
  27949. bool lockWasGained() const throw() { return locked; }
  27950. private:
  27951. int64 lastLockingThreadId;
  27952. bool locked;
  27953. };
  27954. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27955. /********* End of inlined file: juce_MessageManager.h *********/
  27956. #endif
  27957. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  27958. /********* Start of inlined file: juce_MultiTimer.h *********/
  27959. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  27960. #define __JUCE_MULTITIMER_JUCEHEADER__
  27961. /**
  27962. A type of timer class that can run multiple timers with different frequencies,
  27963. all of which share a single callback.
  27964. This class is very similar to the Timer class, but allows you run multiple
  27965. separate timers, where each one has a unique ID number. The methods in this
  27966. class are exactly equivalent to those in Timer, but with the addition of
  27967. this ID number.
  27968. To use it, you need to create a subclass of MultiTimer, implementing the
  27969. timerCallback() method. Then you can start timers with startTimer(), and
  27970. each time the callback is triggered, it passes in the ID of the timer that
  27971. caused it.
  27972. @see Timer
  27973. */
  27974. class JUCE_API MultiTimer
  27975. {
  27976. protected:
  27977. /** Creates a MultiTimer.
  27978. When created, no timers are running, so use startTimer() to start things off.
  27979. */
  27980. MultiTimer() throw();
  27981. /** Creates a copy of another timer.
  27982. Note that this timer will not contain any running timers, even if the one you're
  27983. copying from was running.
  27984. */
  27985. MultiTimer (const MultiTimer& other) throw();
  27986. public:
  27987. /** Destructor. */
  27988. virtual ~MultiTimer();
  27989. /** The user-defined callback routine that actually gets called by each of the
  27990. timers that are running.
  27991. It's perfectly ok to call startTimer() or stopTimer() from within this
  27992. callback to change the subsequent intervals.
  27993. */
  27994. virtual void timerCallback (const int timerId) = 0;
  27995. /** Starts a timer and sets the length of interval required.
  27996. If the timer is already started, this will reset it, so the
  27997. time between calling this method and the next timer callback
  27998. will not be less than the interval length passed in.
  27999. @param timerId a unique Id number that identifies the timer to
  28000. start. This is the id that will be passed back
  28001. to the timerCallback() method when this timer is
  28002. triggered
  28003. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28004. rounded up to 1)
  28005. */
  28006. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28007. /** Stops a timer.
  28008. If a timer has been started with the given ID number, it will be cancelled.
  28009. No more callbacks will be made for the specified timer after this method returns.
  28010. If this is called from a different thread, any callbacks that may
  28011. be currently executing may be allowed to finish before the method
  28012. returns.
  28013. */
  28014. void stopTimer (const int timerId) throw();
  28015. /** Checks whether a timer has been started for a specified ID.
  28016. @returns true if a timer with the given ID is running.
  28017. */
  28018. bool isTimerRunning (const int timerId) const throw();
  28019. /** Returns the interval for a specified timer ID.
  28020. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28021. is running for the ID number specified.
  28022. */
  28023. int getTimerInterval (const int timerId) const throw();
  28024. private:
  28025. CriticalSection timerListLock;
  28026. VoidArray timers;
  28027. const MultiTimer& operator= (const MultiTimer&);
  28028. };
  28029. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28030. /********* End of inlined file: juce_MultiTimer.h *********/
  28031. #endif
  28032. #ifndef __JUCE_TIMER_JUCEHEADER__
  28033. #endif
  28034. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28035. #endif
  28036. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28037. /********* Start of inlined file: juce_GradientBrush.h *********/
  28038. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28039. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28040. /********* Start of inlined file: juce_ColourGradient.h *********/
  28041. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28042. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28043. /**
  28044. Structure used to define a colour gradient for painting areas.
  28045. @see GradientBrush
  28046. */
  28047. class JUCE_API ColourGradient
  28048. {
  28049. public:
  28050. /** Creates a gradient object.
  28051. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28052. colour2 should be. In between them there's a gradient.
  28053. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28054. its centre.
  28055. The alpha transparencies of the colours are used, so note that
  28056. if you blend from transparent to a solid colour, the RGB of the transparent
  28057. colour will become visible in parts of the gradient. e.g. blending
  28058. from Colour::transparentBlack to Colours::white will produce a
  28059. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28060. will be white all the way across.
  28061. @see ColourGradient
  28062. */
  28063. ColourGradient (const Colour& colour1,
  28064. const float x1,
  28065. const float y1,
  28066. const Colour& colour2,
  28067. const float x2,
  28068. const float y2,
  28069. const bool isRadial) throw();
  28070. /** Creates an uninitialised gradient.
  28071. If you use this constructor instead of the other one, be sure to set all the
  28072. object's public member variables before using it!
  28073. */
  28074. ColourGradient() throw();
  28075. /** Destructor */
  28076. ~ColourGradient() throw();
  28077. /** Removes any colours that have been added.
  28078. This will also remove any start and end colours, so the gradient won't work. You'll
  28079. need to add more colours with addColour().
  28080. */
  28081. void clearColours() throw();
  28082. /** Adds a colour at a point along the length of the gradient.
  28083. This allows the gradient to go through a spectrum of colours, instead of just a
  28084. start and end colour.
  28085. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28086. of the distance along the line between the two points
  28087. at which the colour should occur.
  28088. @param colour the colour that should be used at this point
  28089. */
  28090. void addColour (const double proportionAlongGradient,
  28091. const Colour& colour) throw();
  28092. /** Multiplies the alpha value of all the colours by the given scale factor */
  28093. void multiplyOpacity (const float multiplier) throw();
  28094. /** Returns the number of colour-stops that have been added. */
  28095. int getNumColours() const throw();
  28096. /** Returns the position along the length of the gradient of the colour with this index.
  28097. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28098. */
  28099. double getColourPosition (const int index) const throw();
  28100. /** Returns the colour that was added with a given index.
  28101. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28102. */
  28103. const Colour getColour (const int index) const throw();
  28104. /** Creates a set of interpolated premultiplied ARGB values.
  28105. The caller must delete the array that is returned using juce_free().
  28106. */
  28107. PixelARGB* createLookupTable (int& numEntries) const throw();
  28108. /** Returns true if all colours are opaque. */
  28109. bool isOpaque() const throw();
  28110. /** Returns true if all colours are completely transparent. */
  28111. bool isInvisible() const throw();
  28112. float x1;
  28113. float y1;
  28114. float x2;
  28115. float y2;
  28116. /** If true, the gradient should be filled circularly, centred around
  28117. (x1, y1), with (x2, y2) defining a point on the circumference.
  28118. If false, the gradient is linear between the two points.
  28119. */
  28120. bool isRadial;
  28121. /** A transform to apply to the resultant gradient shape */
  28122. AffineTransform transform;
  28123. juce_UseDebuggingNewOperator
  28124. private:
  28125. Array <uint32> colours;
  28126. };
  28127. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28128. /********* End of inlined file: juce_ColourGradient.h *********/
  28129. /**
  28130. A Brush that fills areas with a colour gradient.
  28131. The gradient can either be linear or circular.
  28132. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28133. */
  28134. class JUCE_API GradientBrush : public Brush
  28135. {
  28136. public:
  28137. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28138. (x1, y1) is the location relative to the origin of the Graphics context,
  28139. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28140. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28141. its centre.
  28142. The alpha transparencies of the colours are used, so the brush
  28143. need not be completely opaque. Note that this means that if you
  28144. blend from transparent to a solid colour, the RGB of the transparent
  28145. colour will become visible in parts of the gradient. e.g. blending
  28146. from Colour::transparentBlack to Colours::white will produce a
  28147. grey colour, but Colour::transparentWhite to Colours::white will be
  28148. white all the way across.
  28149. @see ColourGradient
  28150. */
  28151. GradientBrush (const Colour& colour1,
  28152. const float x1,
  28153. const float y1,
  28154. const Colour& colour2,
  28155. const float x2,
  28156. const float y2,
  28157. const bool isRadial) throw();
  28158. /** Creates a gradient brush from a ColourGradient object.
  28159. */
  28160. GradientBrush (const ColourGradient& gradient) throw();
  28161. /** Destructor. */
  28162. ~GradientBrush() throw();
  28163. Brush* createCopy() const throw();
  28164. void applyTransform (const AffineTransform& transform) throw();
  28165. void multiplyOpacity (const float multiple) throw();
  28166. bool isInvisible() const throw();
  28167. void paintPath (LowLevelGraphicsContext& context,
  28168. const Path& path, const AffineTransform& transform) throw();
  28169. void paintRectangle (LowLevelGraphicsContext& context,
  28170. int x, int y, int w, int h) throw();
  28171. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28172. const Image& alphaChannelImage, int imageX, int imageY,
  28173. int x, int y, int w, int h) throw();
  28174. juce_UseDebuggingNewOperator
  28175. protected:
  28176. ColourGradient gradient;
  28177. private:
  28178. GradientBrush (const GradientBrush&);
  28179. const GradientBrush& operator= (const GradientBrush&);
  28180. };
  28181. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28182. /********* End of inlined file: juce_GradientBrush.h *********/
  28183. #endif
  28184. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28185. /********* Start of inlined file: juce_ImageBrush.h *********/
  28186. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28187. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28188. /********* Start of inlined file: juce_Image.h *********/
  28189. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28190. #define __JUCE_IMAGE_JUCEHEADER__
  28191. /**
  28192. Holds a fixed-size bitmap.
  28193. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28194. To draw into an image, create a Graphics object for it.
  28195. e.g. @code
  28196. // create a transparent 500x500 image..
  28197. Image myImage (Image::RGB, 500, 500, true);
  28198. Graphics g (myImage);
  28199. g.setColour (Colours::red);
  28200. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28201. @endcode
  28202. Other useful ways to create an image are with the ImageCache class, or the
  28203. ImageFileFormat, which provides a way to load common image files.
  28204. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28205. */
  28206. class JUCE_API Image
  28207. {
  28208. public:
  28209. enum PixelFormat
  28210. {
  28211. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28212. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28213. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28214. };
  28215. /** Creates an in-memory image with a specified size and format.
  28216. @param format the number of colour channels in the image
  28217. @param imageWidth the desired width of the image, in pixels - this value must be
  28218. greater than zero (otherwise a width of 1 will be used)
  28219. @param imageHeight the desired width of the image, in pixels - this value must be
  28220. greater than zero (otherwise a height of 1 will be used)
  28221. @param clearImage if true, the image will initially be cleared to black or transparent
  28222. black. If false, the image may contain random data, and the
  28223. user will have to deal with this
  28224. */
  28225. Image (const PixelFormat format,
  28226. const int imageWidth,
  28227. const int imageHeight,
  28228. const bool clearImage);
  28229. /** Creates a copy of another image.
  28230. @see createCopy
  28231. */
  28232. Image (const Image& other);
  28233. /** Destructor. */
  28234. virtual ~Image();
  28235. /** Returns the image's width (in pixels). */
  28236. int getWidth() const throw() { return imageWidth; }
  28237. /** Returns the image's height (in pixels). */
  28238. int getHeight() const throw() { return imageHeight; }
  28239. /** Returns the image's pixel format. */
  28240. PixelFormat getFormat() const throw() { return format; }
  28241. /** True if the image's format is ARGB. */
  28242. bool isARGB() const throw() { return format == ARGB; }
  28243. /** True if the image's format is RGB. */
  28244. bool isRGB() const throw() { return format == RGB; }
  28245. /** True if the image contains an alpha-channel. */
  28246. bool hasAlphaChannel() const throw() { return format != RGB; }
  28247. /** Clears a section of the image with a given colour.
  28248. This won't do any alpha-blending - it just sets all pixels in the image to
  28249. the given colour (which may be non-opaque if the image has an alpha channel).
  28250. */
  28251. virtual void clear (int x, int y, int w, int h,
  28252. const Colour& colourToClearTo = Colour (0x00000000));
  28253. /** Returns a new image that's a copy of this one.
  28254. A new size for the copied image can be specified, or values less than
  28255. zero can be passed-in to use the image's existing dimensions.
  28256. It's up to the caller to delete the image when no longer needed.
  28257. */
  28258. virtual Image* createCopy (int newWidth = -1,
  28259. int newHeight = -1,
  28260. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28261. /** Returns the colour of one of the pixels in the image.
  28262. If the co-ordinates given are beyond the image's boundaries, this will
  28263. return Colours::transparentBlack.
  28264. (0, 0) is the image's top-left corner.
  28265. @see getAlphaAt, setPixelAt, blendPixelAt
  28266. */
  28267. virtual const Colour getPixelAt (const int x, const int y) const;
  28268. /** Sets the colour of one of the image's pixels.
  28269. If the co-ordinates are beyond the image's boundaries, then nothing will
  28270. happen.
  28271. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28272. just replace the existing pixel with the given one. The colour's opacity
  28273. will be ignored if this image doesn't have an alpha-channel.
  28274. (0, 0) is the image's top-left corner.
  28275. @see blendPixelAt
  28276. */
  28277. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28278. /** Changes the opacity of a pixel.
  28279. This only has an effect if the image has an alpha channel and if the
  28280. given co-ordinates are inside the image's boundary.
  28281. The multiplier must be in the range 0 to 1.0, and the current alpha
  28282. at the given co-ordinates will be multiplied by this value.
  28283. @see getAlphaAt, setPixelAt
  28284. */
  28285. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28286. /** Changes the overall opacity of the image.
  28287. This will multiply the alpha value of each pixel in the image by the given
  28288. amount (limiting the resulting alpha values between 0 and 255). This allows
  28289. you to make an image more or less transparent.
  28290. If the image doesn't have an alpha channel, this won't have any effect.
  28291. */
  28292. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28293. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28294. */
  28295. virtual void desaturate();
  28296. /** Locks some of the pixels in the image so they can be read and written to.
  28297. This returns a pointer to some memory containing the pixels in the given
  28298. rectangle. It also returns values for the line and pixel stride used within
  28299. the data. The format of the pixel data is the same as that of this image.
  28300. When you've finished reading and changing the data, you must call
  28301. releasePixelDataReadWrite() to give the pixels back to the image.
  28302. For images that are stored in memory, this method may just return a direct
  28303. pointer to the image's data, but other types of image may be stored elsewhere,
  28304. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28305. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28306. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28307. instead.
  28308. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28309. */
  28310. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28311. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28312. */
  28313. virtual void releasePixelDataReadWrite (void* sourceData);
  28314. /** Locks some of the pixels in the image so they can be read.
  28315. This returns a pointer to some memory containing the pixels in the given
  28316. rectangle. It also returns values for the line and pixel stride used within
  28317. the data. The format of the pixel data is the same as that of this image.
  28318. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28319. to let the image free the memory if necessary.
  28320. For images that are stored in memory, this method may just return a direct
  28321. pointer to the image's data, but other types of image may be stored elsewhere,
  28322. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28323. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28324. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28325. instead.
  28326. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28327. */
  28328. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28329. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28330. */
  28331. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28332. /** Copies some pixel values to a rectangle of the image.
  28333. The format of the pixel data must match that of the image itself, and the
  28334. rectangle supplied must be within the image's bounds.
  28335. */
  28336. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28337. const uint8* sourcePixelData, int sourceLineStride);
  28338. /** Copies a section of the image to somewhere else within itself.
  28339. */
  28340. virtual void moveImageSection (int destX, int destY,
  28341. int sourceX, int sourceY,
  28342. int width, int height);
  28343. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28344. of the image.
  28345. @param result the list that will have the area added to it
  28346. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28347. above this level will be considered opaque
  28348. */
  28349. void createSolidAreaMask (RectangleList& result,
  28350. const float alphaThreshold = 0.5f) const;
  28351. juce_UseDebuggingNewOperator
  28352. /** Creates a context suitable for drawing onto this image.
  28353. Don't call this method directly! It's used internally by the Graphics class.
  28354. */
  28355. virtual LowLevelGraphicsContext* createLowLevelContext();
  28356. protected:
  28357. const PixelFormat format;
  28358. const int imageWidth, imageHeight;
  28359. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28360. Image (const PixelFormat format,
  28361. const int imageWidth,
  28362. const int imageHeight);
  28363. int pixelStride, lineStride;
  28364. uint8* imageData;
  28365. private:
  28366. const Image& operator= (const Image&);
  28367. };
  28368. #endif // __JUCE_IMAGE_JUCEHEADER__
  28369. /********* End of inlined file: juce_Image.h *********/
  28370. /**
  28371. A Brush that fills areas with tiled repetitions of an image.
  28372. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28373. */
  28374. class JUCE_API ImageBrush : public Brush
  28375. {
  28376. public:
  28377. /* Creates an image brush, ready for use in Graphics::setBrush().
  28378. (x, y) is an anchor point for the top-left of the image
  28379. A reference to the image passed in will be kept, so don't delete
  28380. it within the lifetime of this object
  28381. */
  28382. ImageBrush (Image* const image,
  28383. const int anchorX,
  28384. const int anchorY,
  28385. const float opacity) throw();
  28386. /** Destructor. */
  28387. ~ImageBrush() throw();
  28388. Brush* createCopy() const throw();
  28389. void applyTransform (const AffineTransform& transform) throw();
  28390. void multiplyOpacity (const float multiple) throw();
  28391. bool isInvisible() const throw();
  28392. void paintPath (LowLevelGraphicsContext& context,
  28393. const Path& path, const AffineTransform& transform) throw();
  28394. void paintRectangle (LowLevelGraphicsContext& context,
  28395. int x, int y, int w, int h) throw();
  28396. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28397. const Image& alphaChannelImage, int imageX, int imageY,
  28398. int x, int y, int w, int h) throw();
  28399. juce_UseDebuggingNewOperator
  28400. protected:
  28401. Image* image;
  28402. int anchorX, anchorY;
  28403. float opacity;
  28404. private:
  28405. ImageBrush (const ImageBrush&);
  28406. const ImageBrush& operator= (const ImageBrush&);
  28407. void getStartXY (int& x, int& y) const throw();
  28408. };
  28409. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28410. /********* End of inlined file: juce_ImageBrush.h *********/
  28411. #endif
  28412. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28413. #endif
  28414. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28415. #endif
  28416. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28417. #endif
  28418. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28419. #endif
  28420. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28421. #endif
  28422. #ifndef __JUCE_FONT_JUCEHEADER__
  28423. #endif
  28424. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28425. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28426. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28427. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28428. /**
  28429. An glyph from a particular font, with a particular size, style,
  28430. typeface and position.
  28431. @see GlyphArrangement, Font
  28432. */
  28433. class JUCE_API PositionedGlyph
  28434. {
  28435. public:
  28436. /** Returns the character the glyph represents. */
  28437. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28438. /** Checks whether the glyph is actually empty. */
  28439. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28440. /** Returns the position of the glyph's left-hand edge. */
  28441. float getLeft() const throw() { return x; }
  28442. /** Returns the position of the glyph's right-hand edge. */
  28443. float getRight() const throw() { return x + w; }
  28444. /** Returns the y position of the glyph's baseline. */
  28445. float getBaselineY() const throw() { return y; }
  28446. /** Returns the y position of the top of the glyph. */
  28447. float getTop() const throw() { return y - fontAscent; }
  28448. /** Returns the y position of the bottom of the glyph. */
  28449. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28450. /** Shifts the glyph's position by a relative amount. */
  28451. void moveBy (const float deltaX,
  28452. const float deltaY) throw();
  28453. /** Draws the glyph into a graphics context. */
  28454. void draw (const Graphics& g) const throw();
  28455. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28456. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28457. /** Returns the path for this glyph.
  28458. @param path the glyph's outline will be appended to this path
  28459. */
  28460. void createPath (Path& path) const throw();
  28461. /** Checks to see if a point lies within this glyph. */
  28462. bool hitTest (float x, float y) const throw();
  28463. juce_UseDebuggingNewOperator
  28464. private:
  28465. friend class GlyphArrangement;
  28466. float x, y, w;
  28467. float fontHeight, fontAscent, fontHorizontalScale;
  28468. bool isUnderlined;
  28469. const TypefaceGlyphInfo* glyphInfo;
  28470. PositionedGlyph() throw();
  28471. };
  28472. /**
  28473. A set of glyphs, each with a position.
  28474. You can create a GlyphArrangement, text to it and then draw it onto a
  28475. graphics context. It's used internally by the text methods in the
  28476. Graphics class, but can be used directly if more control is needed.
  28477. @see Font, PositionedGlyph
  28478. */
  28479. class JUCE_API GlyphArrangement
  28480. {
  28481. public:
  28482. /** Creates an empty arrangement. */
  28483. GlyphArrangement() throw();
  28484. /** Takes a copy of another arrangement. */
  28485. GlyphArrangement (const GlyphArrangement& other) throw();
  28486. /** Copies another arrangement onto this one.
  28487. To add another arrangement without clearing this one, use addGlyphArrangement().
  28488. */
  28489. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28490. /** Destructor. */
  28491. ~GlyphArrangement() throw();
  28492. /** Returns the total number of glyphs in the arrangement. */
  28493. int getNumGlyphs() const throw() { return numGlyphs; }
  28494. /** Returns one of the glyphs from the arrangement.
  28495. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28496. careful not to pass an out-of-range index here, as it
  28497. doesn't do any bounds-checking.
  28498. */
  28499. PositionedGlyph& getGlyph (const int index) const throw();
  28500. /** Clears all text from the arrangement and resets it.
  28501. */
  28502. void clear() throw();
  28503. /** Appends a line of text to the arrangement.
  28504. This will add the text as a single line, where x is the left-hand edge of the
  28505. first character, and y is the position for the text's baseline.
  28506. If the text contains new-lines or carriage-returns, this will ignore them - use
  28507. addJustifiedText() to add multi-line arrangements.
  28508. */
  28509. void addLineOfText (const Font& font,
  28510. const String& text,
  28511. const float x,
  28512. const float y) throw();
  28513. /** Adds a line of text, truncating it if it's wider than a specified size.
  28514. This is the same as addLineOfText(), but if the line's width exceeds the value
  28515. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  28516. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  28517. */
  28518. void addCurtailedLineOfText (const Font& font,
  28519. const String& text,
  28520. float x,
  28521. const float y,
  28522. const float maxWidthPixels,
  28523. const bool useEllipsis) throw();
  28524. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  28525. This will add text to the arrangement, breaking it into new lines either where there
  28526. is a new-line or carriage-return character in the text, or where a line's width
  28527. exceeds the value set in maxLineWidth.
  28528. Each line that is added will be laid out using the flags set in horizontalLayout, so
  28529. the lines can be left- or right-justified, or centred horizontally in the space
  28530. between x and (x + maxLineWidth).
  28531. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  28532. lines will be placed below it, separated by a distance of font.getHeight().
  28533. */
  28534. void addJustifiedText (const Font& font,
  28535. const String& text,
  28536. float x, float y,
  28537. const float maxLineWidth,
  28538. const Justification& horizontalLayout) throw();
  28539. /** Tries to fit some text withing a given space.
  28540. This does its best to make the given text readable within the specified rectangle,
  28541. so it useful for labelling things.
  28542. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  28543. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  28544. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  28545. it's been truncated.
  28546. A Justification parameter lets you specify how the text is laid out within the rectangle,
  28547. both horizontally and vertically.
  28548. @see Graphics::drawFittedText
  28549. */
  28550. void addFittedText (const Font& font,
  28551. const String& text,
  28552. float x, float y,
  28553. float width, float height,
  28554. const Justification& layout,
  28555. int maximumLinesToUse,
  28556. const float minimumHorizontalScale = 0.7f) throw();
  28557. /** Appends another glyph arrangement to this one. */
  28558. void addGlyphArrangement (const GlyphArrangement& other) throw();
  28559. /** Draws this glyph arrangement to a graphics context.
  28560. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  28561. method, which renders the glyphs as filled vectors.
  28562. */
  28563. void draw (const Graphics& g) const throw();
  28564. /** Draws this glyph arrangement to a graphics context.
  28565. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  28566. method for non-transformed arrangements.
  28567. */
  28568. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28569. /** Converts the set of glyphs into a path.
  28570. @param path the glyphs' outlines will be appended to this path
  28571. */
  28572. void createPath (Path& path) const throw();
  28573. /** Looks for a glyph that contains the given co-ordinate.
  28574. @returns the index of the glyph, or -1 if none were found.
  28575. */
  28576. int findGlyphIndexAt (float x, float y) const throw();
  28577. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  28578. @param startIndex the first glyph to test
  28579. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  28580. startIndex will be included
  28581. @param left on return, the leftmost co-ordinate of the rectangle
  28582. @param top on return, the top co-ordinate of the rectangle
  28583. @param right on return, the rightmost co-ordinate of the rectangle
  28584. @param bottom on return, the bottom co-ordinate of the rectangle
  28585. @param includeWhitespace if true, the extent of any whitespace characters will also
  28586. be taken into account
  28587. */
  28588. void getBoundingBox (int startIndex,
  28589. int numGlyphs,
  28590. float& left,
  28591. float& top,
  28592. float& right,
  28593. float& bottom,
  28594. const bool includeWhitespace) const throw();
  28595. /** Shifts a set of glyphs by a given amount.
  28596. @param startIndex the first glyph to transform
  28597. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  28598. startIndex will be used
  28599. @param deltaX the amount to add to their x-positions
  28600. @param deltaY the amount to add to their y-positions
  28601. */
  28602. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  28603. const float deltaX,
  28604. const float deltaY) throw();
  28605. /** Removes a set of glyphs from the arrangement.
  28606. @param startIndex the first glyph to remove
  28607. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  28608. startIndex will be deleted
  28609. */
  28610. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  28611. /** Expands or compresses a set of glyphs horizontally.
  28612. @param startIndex the first glyph to transform
  28613. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  28614. startIndex will be used
  28615. @param horizontalScaleFactor how much to scale their horizontal width by
  28616. */
  28617. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  28618. const float horizontalScaleFactor) throw();
  28619. /** Justifies a set of glyphs within a given space.
  28620. This moves the glyphs as a block so that the whole thing is located within the
  28621. given rectangle with the specified layout.
  28622. If the Justification::horizontallyJustified flag is specified, each line will
  28623. be stretched out to fill the specified width.
  28624. */
  28625. void justifyGlyphs (const int startIndex, const int numGlyphs,
  28626. const float x,
  28627. const float y,
  28628. const float width,
  28629. const float height,
  28630. const Justification& justification) throw();
  28631. juce_UseDebuggingNewOperator
  28632. private:
  28633. int numGlyphs, numAllocated;
  28634. PositionedGlyph* glyphs;
  28635. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  28636. void removeLast() throw();
  28637. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  28638. void incGlyphRefCount (const int index) const throw();
  28639. void decGlyphRefCount (const int index) const throw();
  28640. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  28641. };
  28642. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28643. /********* End of inlined file: juce_GlyphArrangement.h *********/
  28644. #endif
  28645. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28646. /********* Start of inlined file: juce_TextLayout.h *********/
  28647. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28648. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  28649. class Graphics;
  28650. /**
  28651. A laid-out arrangement of text.
  28652. You can add text in different fonts to a TextLayout object, then call its
  28653. layout() method to word-wrap it into lines. The layout can then be drawn
  28654. using a graphics context.
  28655. It's handy if you've got a message to display, because you can format it,
  28656. measure the extent of the layout, and then create a suitably-sized window
  28657. to show it in.
  28658. @see Font, Graphics::drawFittedText, GlyphArrangement
  28659. */
  28660. class JUCE_API TextLayout
  28661. {
  28662. public:
  28663. /** Creates an empty text layout.
  28664. Text can then be appended using the appendText() method.
  28665. */
  28666. TextLayout() throw();
  28667. /** Creates a copy of another layout object. */
  28668. TextLayout (const TextLayout& other) throw();
  28669. /** Creates a text layout from an initial string and font. */
  28670. TextLayout (const String& text, const Font& font) throw();
  28671. /** Destructor. */
  28672. ~TextLayout() throw();
  28673. /** Copies another layout onto this one. */
  28674. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  28675. /** Clears the layout, removing all its text. */
  28676. void clear() throw();
  28677. /** Adds a string to the end of the arrangement.
  28678. The string will be broken onto new lines wherever it contains
  28679. carriage-returns or linefeeds. After adding it, you can call layout()
  28680. to wrap long lines into a paragraph and justify it.
  28681. */
  28682. void appendText (const String& textToAppend,
  28683. const Font& fontToUse) throw();
  28684. /** Replaces all the text with a new string.
  28685. This is equivalent to calling clear() followed by appendText().
  28686. */
  28687. void setText (const String& newText,
  28688. const Font& fontToUse) throw();
  28689. /** Breaks the text up to form a paragraph with the given width.
  28690. @param maximumWidth any text wider than this will be split
  28691. across multiple lines
  28692. @param justification how the lines are to be laid-out horizontally
  28693. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  28694. width that keeps all the lines of text at a
  28695. similar length - this is good when you're displaying
  28696. a short message and don't want it to get split
  28697. onto two lines with only a couple of words on
  28698. the second line, which looks untidy.
  28699. */
  28700. void layout (int maximumWidth,
  28701. const Justification& justification,
  28702. const bool attemptToBalanceLineLengths) throw();
  28703. /** Returns the overall width of the entire text layout. */
  28704. int getWidth() const throw();
  28705. /** Returns the overall height of the entire text layout. */
  28706. int getHeight() const throw();
  28707. /** Returns the total number of lines of text. */
  28708. int getNumLines() const throw() { return totalLines; }
  28709. /** Returns the width of a particular line of text.
  28710. @param lineNumber the line, from 0 to (getNumLines() - 1)
  28711. */
  28712. int getLineWidth (const int lineNumber) const throw();
  28713. /** Renders the text at a specified position using a graphics context.
  28714. */
  28715. void draw (Graphics& g,
  28716. const int topLeftX,
  28717. const int topLeftY) const throw();
  28718. /** Renders the text within a specified rectangle using a graphics context.
  28719. The justification flags dictate how the block of text should be positioned
  28720. within the rectangle.
  28721. */
  28722. void drawWithin (Graphics& g,
  28723. int x, int y, int w, int h,
  28724. const Justification& layoutFlags) const throw();
  28725. juce_UseDebuggingNewOperator
  28726. private:
  28727. VoidArray tokens;
  28728. int totalLines;
  28729. };
  28730. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  28731. /********* End of inlined file: juce_TextLayout.h *********/
  28732. #endif
  28733. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  28734. #endif
  28735. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28736. /********* Start of inlined file: juce_EdgeTable.h *********/
  28737. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28738. #define __JUCE_EDGETABLE_JUCEHEADER__
  28739. class Path;
  28740. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  28741. /**
  28742. A table of horizontal scan-line segments - used for rasterising Paths.
  28743. @see Path, Graphics
  28744. */
  28745. class JUCE_API EdgeTable
  28746. {
  28747. public:
  28748. /** Indicates the quality at which the edge table should be generated.
  28749. Higher values will have better quality anti-aliasing, but will take
  28750. longer to generate the edge table and to render it.
  28751. */
  28752. enum OversamplingLevel
  28753. {
  28754. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  28755. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  28756. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  28757. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  28758. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  28759. normal user-interface use. */
  28760. };
  28761. /** Creates an empty edge table ready to have paths added.
  28762. A table is created with a fixed vertical size, and only sections of paths
  28763. which lie within their range will be added to the table.
  28764. @param topY the lowest y co-ordinate that the table can contain
  28765. @param height the number of horizontal lines it can contain
  28766. @param verticalOversampling the amount of oversampling used for anti-aliasing
  28767. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  28768. worth changing this except for very special purposes
  28769. */
  28770. EdgeTable (const int topY,
  28771. const int height,
  28772. const OversamplingLevel verticalOversampling = Oversampling_4times,
  28773. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  28774. /** Creates a copy of another edge table. */
  28775. EdgeTable (const EdgeTable& other) throw();
  28776. /** Copies from another edge table. */
  28777. const EdgeTable& operator= (const EdgeTable& other) throw();
  28778. /** Destructor. */
  28779. ~EdgeTable() throw();
  28780. /** Adds edges to the table for a path.
  28781. This will add horizontal lines to the edge table for any parts of the path
  28782. which lie within the vertical bounds for which this table was created.
  28783. @param path the path to add
  28784. @param transform an optional transform to apply to the path while it's
  28785. being added
  28786. */
  28787. void addPath (const Path& path,
  28788. const AffineTransform& transform) throw();
  28789. /** Reduces the amount of space the table has allocated.
  28790. This will shrink the table down to use as little memory as possible - useful for
  28791. read-only tables that get stored and re-used for rendering.
  28792. */
  28793. void optimiseTable() throw();
  28794. /** Iterates the lines in the table, for rendering.
  28795. This function will iterate each line in the table, and call a user-defined class
  28796. to render each pixel or continuous line of pixels that the table contains.
  28797. @param iterationCallback this templated class must contain the following methods:
  28798. @code
  28799. inline void setEdgeTableYPos (int y);
  28800. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  28801. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  28802. @endcode
  28803. (these don't necessarily have to be 'const', but it might help it go faster)
  28804. @param clipLeft the left-hand edge of the rectangle which should be iterated
  28805. @param clipTop the top edge of the rectangle which should be iterated
  28806. @param clipRight the right-hand edge of the rectangle which should be iterated
  28807. @param clipBottom the bottom edge of the rectangle which should be iterated
  28808. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  28809. */
  28810. template <class EdgeTableIterationCallback>
  28811. void iterate (EdgeTableIterationCallback& iterationCallback,
  28812. const int clipLeft,
  28813. int clipTop,
  28814. const int clipRight,
  28815. int clipBottom,
  28816. const int subPixelXOffset) const
  28817. {
  28818. if (clipTop < top)
  28819. clipTop = top;
  28820. if (clipBottom > top + height)
  28821. clipBottom = top + height;
  28822. const int* singleLine = table + lineStrideElements
  28823. * ((clipTop - top) << (int) oversampling);
  28824. int mergedLineAllocation = 128;
  28825. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  28826. int* mergedLine = (int*) temp.getData();
  28827. const int timesOverSampling = 1 << (int) oversampling;
  28828. for (int y = clipTop; y < clipBottom; ++y)
  28829. {
  28830. int numMergedPoints = 0;
  28831. // sort all the oversampled lines into a single merged line ready to draw..
  28832. for (int over = timesOverSampling; --over >= 0;)
  28833. {
  28834. const int* l = singleLine;
  28835. singleLine += lineStrideElements;
  28836. int num = *l;
  28837. jassert (num >= 0);
  28838. if (num > 0)
  28839. {
  28840. if (numMergedPoints + num >= mergedLineAllocation)
  28841. {
  28842. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  28843. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  28844. mergedLine = (int*) temp.getData();
  28845. }
  28846. while (--num >= 0)
  28847. {
  28848. const int x = *++l;
  28849. const int winding = *++l;
  28850. int n = numMergedPoints << 1;
  28851. while (n > 0)
  28852. {
  28853. const int cx = mergedLine [n - 2];
  28854. if (cx <= x)
  28855. break;
  28856. mergedLine [n] = cx;
  28857. --n;
  28858. mergedLine [n + 2] = mergedLine [n];
  28859. --n;
  28860. }
  28861. mergedLine [n] = x;
  28862. mergedLine [n + 1] = winding;
  28863. ++numMergedPoints;
  28864. }
  28865. }
  28866. }
  28867. if (--numMergedPoints > 0)
  28868. {
  28869. const int* line = mergedLine;
  28870. int x = subPixelXOffset + *line;
  28871. int level = *++line;
  28872. int levelAccumulator = 0;
  28873. iterationCallback.setEdgeTableYPos (y);
  28874. while (--numMergedPoints >= 0)
  28875. {
  28876. const int endX = subPixelXOffset + *++line;
  28877. jassert (endX >= x);
  28878. const int absLevel = abs (level);
  28879. int endOfRun = (endX >> 8);
  28880. if (endOfRun == (x >> 8))
  28881. {
  28882. // small segment within the same pixel, so just save it for the next
  28883. // time round..
  28884. levelAccumulator += (endX - x) * absLevel;
  28885. }
  28886. else
  28887. {
  28888. // plot the fist pixel of this segment, including any accumulated
  28889. // levels from smaller segments that haven't been drawn yet
  28890. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  28891. levelAccumulator >>= 8;
  28892. if (levelAccumulator > 0xff)
  28893. levelAccumulator = 0xff;
  28894. x >>= 8;
  28895. if (x >= clipRight)
  28896. {
  28897. levelAccumulator = 0;
  28898. break;
  28899. }
  28900. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  28901. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  28902. if (++x >= clipRight)
  28903. {
  28904. levelAccumulator = 0;
  28905. break;
  28906. }
  28907. // if there's a segment of solid pixels, do it all in one go..
  28908. if (absLevel > 0 && endOfRun > x)
  28909. {
  28910. if (x < clipLeft)
  28911. x = clipLeft;
  28912. if (endOfRun > clipRight)
  28913. endOfRun = clipRight;
  28914. const int numPix = endOfRun - x;
  28915. if (numPix > 0)
  28916. iterationCallback.handleEdgeTableLine (x, numPix,
  28917. jmin (absLevel, 0xff));
  28918. }
  28919. // save the bit at the end to be drawn next time round the loop.
  28920. levelAccumulator = (endX & 0xff) * absLevel;
  28921. }
  28922. level += *++line;
  28923. x = endX;
  28924. }
  28925. if (levelAccumulator > 0)
  28926. {
  28927. levelAccumulator >>= 8;
  28928. if (levelAccumulator > 0xff)
  28929. levelAccumulator = 0xff;
  28930. x >>= 8;
  28931. if (x >= clipLeft && x < clipRight)
  28932. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  28933. }
  28934. }
  28935. }
  28936. }
  28937. juce_UseDebuggingNewOperator
  28938. private:
  28939. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  28940. int* table;
  28941. int top, height, maxEdgesPerLine, lineStrideElements;
  28942. OversamplingLevel oversampling;
  28943. // this will assume that the y co-ord is within bounds, and will avoid checking
  28944. // this for speed.
  28945. void addEdgePoint (const int x, const int y, const int winding) throw();
  28946. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  28947. };
  28948. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  28949. /********* End of inlined file: juce_EdgeTable.h *********/
  28950. #endif
  28951. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  28952. #endif
  28953. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  28954. #endif
  28955. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  28956. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  28957. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  28958. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  28959. /**
  28960. Interface class for graphics context objects, used internally by the Graphics class.
  28961. Users are not supposed to create instances of this class directly - do your drawing
  28962. via the Graphics object instead.
  28963. It's a base class for different types of graphics context, that may perform software-based
  28964. or OS-accelerated rendering.
  28965. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  28966. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  28967. context.
  28968. */
  28969. class JUCE_API LowLevelGraphicsContext
  28970. {
  28971. protected:
  28972. LowLevelGraphicsContext();
  28973. public:
  28974. virtual ~LowLevelGraphicsContext();
  28975. /** Returns true if this device is vector-based, e.g. a printer. */
  28976. virtual bool isVectorDevice() const = 0;
  28977. /** Moves the origin to a new position.
  28978. The co-ords are relative to the current origin, and indicate the new position
  28979. of (0, 0).
  28980. */
  28981. virtual void setOrigin (int x, int y) = 0;
  28982. /** Cliping co-ords are relative to the origin. */
  28983. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  28984. /** Cliping co-ords are relative to the origin. */
  28985. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  28986. /** Cliping co-ords are relative to the origin. */
  28987. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  28988. virtual void saveState() = 0;
  28989. virtual void restoreState() = 0;
  28990. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  28991. virtual const Rectangle getClipBounds() const = 0;
  28992. virtual bool isClipEmpty() const = 0;
  28993. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  28994. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  28995. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  28996. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  28997. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  28998. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  28999. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29000. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29001. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29002. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29003. virtual void blendImage (const Image& sourceImage,
  29004. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29005. float alpha) = 0;
  29006. virtual void blendImageRescaling (const Image& sourceImage,
  29007. int destX, int destY, int destW, int destH,
  29008. int sourceX, int sourceY, int sourceW, int sourceH,
  29009. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29010. virtual void blendImageWarping (const Image& sourceImage,
  29011. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29012. const AffineTransform& transform,
  29013. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29014. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29015. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29016. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29017. };
  29018. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29019. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29020. #endif
  29021. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29022. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29023. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29024. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29025. /**
  29026. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29027. into a PostScript document.
  29028. */
  29029. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29030. {
  29031. public:
  29032. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29033. const String& documentTitle,
  29034. const int totalWidth,
  29035. const int totalHeight);
  29036. ~LowLevelGraphicsPostScriptRenderer();
  29037. bool isVectorDevice() const;
  29038. void setOrigin (int x, int y);
  29039. bool reduceClipRegion (int x, int y, int w, int h);
  29040. bool reduceClipRegion (const RectangleList& clipRegion);
  29041. void excludeClipRegion (int x, int y, int w, int h);
  29042. void saveState();
  29043. void restoreState();
  29044. bool clipRegionIntersects (int x, int y, int w, int h);
  29045. const Rectangle getClipBounds() const;
  29046. bool isClipEmpty() const;
  29047. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29048. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29049. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29050. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29051. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29052. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29053. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29054. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29055. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29056. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29057. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29058. int sourceX, int sourceY, float alpha);
  29059. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29060. int sourceX, int sourceY, int sourceW, int sourceH,
  29061. float alpha, const Graphics::ResamplingQuality quality);
  29062. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29063. const AffineTransform& transform,
  29064. float alpha, const Graphics::ResamplingQuality quality);
  29065. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29066. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29067. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29068. juce_UseDebuggingNewOperator
  29069. protected:
  29070. OutputStream& out;
  29071. RectangleList* clip;
  29072. int totalWidth, totalHeight, xOffset, yOffset;
  29073. bool needToClip;
  29074. Colour lastColour;
  29075. struct SavedState
  29076. {
  29077. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29078. ~SavedState();
  29079. RectangleList* clip;
  29080. const int xOffset, yOffset;
  29081. private:
  29082. SavedState (const SavedState&);
  29083. const SavedState& operator= (const SavedState&);
  29084. };
  29085. OwnedArray <SavedState> stateStack;
  29086. void writeClip();
  29087. void writeColour (const Colour& colour);
  29088. void writePath (const Path& path) const;
  29089. void writeXY (const float x, const float y) const;
  29090. void writeTransform (const AffineTransform& trans) const;
  29091. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29092. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29093. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29094. };
  29095. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29096. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29097. #endif
  29098. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29099. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29100. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29101. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29102. /**
  29103. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29104. its rendering in memory.
  29105. User code is not supposed to create instances of this class directly - do all your
  29106. rendering via the Graphics class instead.
  29107. */
  29108. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29109. {
  29110. public:
  29111. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29112. ~LowLevelGraphicsSoftwareRenderer();
  29113. bool isVectorDevice() const;
  29114. void setOrigin (int x, int y);
  29115. bool reduceClipRegion (int x, int y, int w, int h);
  29116. bool reduceClipRegion (const RectangleList& clipRegion);
  29117. void excludeClipRegion (int x, int y, int w, int h);
  29118. void saveState();
  29119. void restoreState();
  29120. bool clipRegionIntersects (int x, int y, int w, int h);
  29121. const Rectangle getClipBounds() const;
  29122. bool isClipEmpty() const;
  29123. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29124. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29125. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29126. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29127. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29128. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29129. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29130. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29131. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29132. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29133. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29134. int sourceX, int sourceY, float alpha);
  29135. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29136. int sourceX, int sourceY, int sourceW, int sourceH,
  29137. float alpha, const Graphics::ResamplingQuality quality);
  29138. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29139. const AffineTransform& transform,
  29140. float alpha, const Graphics::ResamplingQuality quality);
  29141. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29142. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29143. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29144. RectangleList* getRawClipRegion() throw() { return clip; }
  29145. juce_UseDebuggingNewOperator
  29146. protected:
  29147. Image& image;
  29148. RectangleList* clip;
  29149. int xOffset, yOffset;
  29150. struct SavedState
  29151. {
  29152. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29153. ~SavedState();
  29154. RectangleList* clip;
  29155. const int xOffset, yOffset;
  29156. private:
  29157. SavedState (const SavedState&);
  29158. const SavedState& operator= (const SavedState&);
  29159. };
  29160. OwnedArray <SavedState> stateStack;
  29161. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29162. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29163. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29164. const Path& path, const AffineTransform& transform,
  29165. int& x, int& y, int& w, int& h) const;
  29166. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29167. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29168. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29169. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29170. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29171. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29172. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29173. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29174. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29175. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29176. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29177. float alpha);
  29178. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29179. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29180. const AffineTransform& transform,
  29181. float alpha, const Graphics::ResamplingQuality quality);
  29182. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29183. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29184. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29185. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29186. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29187. };
  29188. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29189. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29190. #endif
  29191. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29192. #endif
  29193. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29194. #endif
  29195. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29196. #endif
  29197. #ifndef __JUCE_LINE_JUCEHEADER__
  29198. #endif
  29199. #ifndef __JUCE_PATH_JUCEHEADER__
  29200. #endif
  29201. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29202. /********* Start of inlined file: juce_PathIterator.h *********/
  29203. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29204. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29205. /**
  29206. Flattens a Path object into a series of straight-line sections.
  29207. Use one of these to iterate through a Path object, and it will convert
  29208. all the curves into line sections so it's easy to render or perform
  29209. geometric operations on.
  29210. @see Path
  29211. */
  29212. class JUCE_API PathFlatteningIterator
  29213. {
  29214. public:
  29215. /** Creates a PathFlatteningIterator.
  29216. After creation, use the next() method to initialise the fields in the
  29217. object with the first line's position.
  29218. @param path the path to iterate along
  29219. @param transform a transform to apply to each point in the path being iterated
  29220. @param tolerence the amount by which the curves are allowed to deviate from the
  29221. lines into which they are being broken down - a higher tolerence
  29222. is a bit faster, but less smooth.
  29223. */
  29224. PathFlatteningIterator (const Path& path,
  29225. const AffineTransform& transform = AffineTransform::identity,
  29226. float tolerence = 9.0f) throw();
  29227. /** Destructor. */
  29228. ~PathFlatteningIterator() throw();
  29229. /** Fetches the next line segment from the path.
  29230. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29231. so that they describe the new line segment.
  29232. @returns false when there are no more lines to fetch.
  29233. */
  29234. bool next() throw();
  29235. /** The x position of the start of the current line segment. */
  29236. float x1;
  29237. /** The y position of the start of the current line segment. */
  29238. float y1;
  29239. /** The x position of the end of the current line segment. */
  29240. float x2;
  29241. /** The y position of the end of the current line segment. */
  29242. float y2;
  29243. /** Indicates whether the current line segment is closing a sub-path.
  29244. If the current line is the one that connects the end of a sub-path
  29245. back to the start again, this will be true.
  29246. */
  29247. bool closesSubPath;
  29248. /** The index of the current line within the current sub-path.
  29249. E.g. you can use this to see whether the line is the first one in the
  29250. subpath by seeing if it's 0.
  29251. */
  29252. int subPathIndex;
  29253. /** Returns true if the current segment is the last in the current sub-path. */
  29254. bool isLastInSubpath() const throw() { return stackPos == stackBase; }
  29255. juce_UseDebuggingNewOperator
  29256. private:
  29257. const Path& path;
  29258. const AffineTransform transform;
  29259. float* points;
  29260. float tolerence, subPathCloseX, subPathCloseY;
  29261. bool isIdentityTransform;
  29262. float* stackBase;
  29263. float* stackPos;
  29264. int index, stackSize;
  29265. PathFlatteningIterator (const PathFlatteningIterator&);
  29266. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29267. };
  29268. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29269. /********* End of inlined file: juce_PathIterator.h *********/
  29270. #endif
  29271. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29272. #endif
  29273. #ifndef __JUCE_POINT_JUCEHEADER__
  29274. #endif
  29275. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29276. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29277. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29278. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29279. /**
  29280. A rectangle whose co-ordinates can be defined in terms of absolute or
  29281. proportional distances.
  29282. Designed mainly for storing component positions, this gives you a lot of
  29283. control over how each co-ordinate is stored, either as an absolute position,
  29284. or as a proportion of the size of a parent rectangle.
  29285. It also allows you to define the anchor points by which the rectangle is
  29286. positioned, so for example you could specify that the top right of the
  29287. rectangle should be an absolute distance from its parent's bottom-right corner.
  29288. This object can be stored as a string, which takes the form "x y w h", including
  29289. symbols like '%' and letters to indicate the anchor point. See its toString()
  29290. method for more info.
  29291. Example usage:
  29292. @code
  29293. class MyComponent
  29294. {
  29295. void resized()
  29296. {
  29297. // this will set the child component's x to be 20% of our width, its y
  29298. // to be 30, its width to be 150, and its height to be 50% of our
  29299. // height..
  29300. const PositionedRectangle pos1 ("20% 30 150 50%");
  29301. pos1.applyToComponent (*myChildComponent1);
  29302. // this will inset the child component with a gap of 10 pixels
  29303. // around each of its edges..
  29304. const PositionedRectangle pos2 ("10 10 20M 20M");
  29305. pos2.applyToComponent (*myChildComponent2);
  29306. }
  29307. };
  29308. @endcode
  29309. */
  29310. class JUCE_API PositionedRectangle
  29311. {
  29312. public:
  29313. /** Creates an empty rectangle with all co-ordinates set to zero.
  29314. The default anchor point is top-left; the default
  29315. */
  29316. PositionedRectangle() throw();
  29317. /** Initialises a PositionedRectangle from a saved string version.
  29318. The string must be in the format generated by toString().
  29319. */
  29320. PositionedRectangle (const String& stringVersion) throw();
  29321. /** Creates a copy of another PositionedRectangle. */
  29322. PositionedRectangle (const PositionedRectangle& other) throw();
  29323. /** Copies another PositionedRectangle. */
  29324. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29325. /** Destructor. */
  29326. ~PositionedRectangle() throw();
  29327. /** Returns a string version of this position, from which it can later be
  29328. re-generated.
  29329. The format is four co-ordinates, "x y w h".
  29330. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29331. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29332. as a percentage, e.g. "80%".
  29333. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29334. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29335. the parent's right-hand edge.
  29336. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29337. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29338. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29339. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29340. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29341. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29342. has "c" appended to it. So "-50Rc" would mean that this component's
  29343. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29344. this component's centre should be placed 40% across the parent's width.
  29345. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29346. the number has "M" appended to it.
  29347. To reload a stored string, use the constructor that takes a string parameter.
  29348. */
  29349. const String toString() const throw();
  29350. /** Calculates the absolute position, given the size of the space that
  29351. it should go in.
  29352. This will work out any proportional distances and sizes relative to the
  29353. target rectangle, and will return the absolute position.
  29354. @see applyToComponent
  29355. */
  29356. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29357. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29358. */
  29359. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29360. double& x,
  29361. double& y,
  29362. double& width,
  29363. double& height) const throw();
  29364. /** This sets the bounds of the given component to this position.
  29365. This is equivalent to writing:
  29366. @code
  29367. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29368. @endcode
  29369. @see getRectangle, updateFromComponent
  29370. */
  29371. void applyToComponent (Component& comp) const throw();
  29372. /** Updates this object's co-ordinates to match the given rectangle.
  29373. This will set all co-ordinates based on the given rectangle, re-calculating
  29374. any proportional distances, and using the current anchor points.
  29375. So for example if the x co-ordinate mode is currently proportional, this will
  29376. re-calculate x based on the rectangle's relative position within the target
  29377. rectangle's width.
  29378. If the target rectangle's width or height are zero then it may not be possible
  29379. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29380. will not be changed.
  29381. */
  29382. void updateFrom (const Rectangle& newPosition,
  29383. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29384. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29385. */
  29386. void updateFromDouble (const double x, const double y,
  29387. const double width, const double height,
  29388. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29389. /** Updates this object's co-ordinates to match the bounds of this component.
  29390. This is equivalent to calling updateFrom() with the component's bounds and
  29391. it parent size.
  29392. If the component doesn't currently have a parent, then proportional co-ordinates
  29393. might not be updated because it would need to know the parent's size to do the
  29394. maths for this.
  29395. */
  29396. void updateFromComponent (const Component& comp) throw();
  29397. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29398. enum AnchorPoint
  29399. {
  29400. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29401. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29402. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29403. };
  29404. /** Specifies how an x or y co-ordinate should be interpreted. */
  29405. enum PositionMode
  29406. {
  29407. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29408. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29409. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29410. 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. */
  29411. };
  29412. /** Specifies how the width or height should be interpreted. */
  29413. enum SizeMode
  29414. {
  29415. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29416. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29417. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29418. };
  29419. /** Sets all options for all co-ordinates.
  29420. This requires a reference rectangle to be specified, because if you're changing any
  29421. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29422. the co-ordinates, and will need to know the parent size so it can calculate this.
  29423. */
  29424. void setModes (const AnchorPoint xAnchorMode,
  29425. const PositionMode xPositionMode,
  29426. const AnchorPoint yAnchorMode,
  29427. const PositionMode yPositionMode,
  29428. const SizeMode widthMode,
  29429. const SizeMode heightMode,
  29430. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29431. /** Returns the anchoring mode for the x co-ordinate.
  29432. To change any of the modes, use setModes().
  29433. */
  29434. AnchorPoint getAnchorPointX() const throw();
  29435. /** Returns the positioning mode for the x co-ordinate.
  29436. To change any of the modes, use setModes().
  29437. */
  29438. PositionMode getPositionModeX() const throw();
  29439. /** Returns the raw x co-ordinate.
  29440. If the x position mode is absolute, then this will be the absolute value. If it's
  29441. proportional, then this will be a fractional proportion, where 1.0 means the full
  29442. width of the parent space.
  29443. */
  29444. double getX() const throw() { return x; }
  29445. /** Sets the raw value of the x co-ordinate.
  29446. See getX() for the meaning of this value.
  29447. */
  29448. void setX (const double newX) throw() { x = newX; }
  29449. /** Returns the anchoring mode for the y co-ordinate.
  29450. To change any of the modes, use setModes().
  29451. */
  29452. AnchorPoint getAnchorPointY() const throw();
  29453. /** Returns the positioning mode for the y co-ordinate.
  29454. To change any of the modes, use setModes().
  29455. */
  29456. PositionMode getPositionModeY() const throw();
  29457. /** Returns the raw y co-ordinate.
  29458. If the y position mode is absolute, then this will be the absolute value. If it's
  29459. proportional, then this will be a fractional proportion, where 1.0 means the full
  29460. height of the parent space.
  29461. */
  29462. double getY() const throw() { return y; }
  29463. /** Sets the raw value of the y co-ordinate.
  29464. See getY() for the meaning of this value.
  29465. */
  29466. void setY (const double newY) throw() { y = newY; }
  29467. /** Returns the mode used to calculate the width.
  29468. To change any of the modes, use setModes().
  29469. */
  29470. SizeMode getWidthMode() const throw();
  29471. /** Returns the raw width value.
  29472. If the width mode is absolute, then this will be the absolute value. If the mode is
  29473. proportional, then this will be a fractional proportion, where 1.0 means the full
  29474. width of the parent space.
  29475. */
  29476. double getWidth() const throw() { return w; }
  29477. /** Sets the raw width value.
  29478. See getWidth() for the details about what this value means.
  29479. */
  29480. void setWidth (const double newWidth) throw() { w = newWidth; }
  29481. /** Returns the mode used to calculate the height.
  29482. To change any of the modes, use setModes().
  29483. */
  29484. SizeMode getHeightMode() const throw();
  29485. /** Returns the raw height value.
  29486. If the height mode is absolute, then this will be the absolute value. If the mode is
  29487. proportional, then this will be a fractional proportion, where 1.0 means the full
  29488. height of the parent space.
  29489. */
  29490. double getHeight() const throw() { return h; }
  29491. /** Sets the raw height value.
  29492. See getHeight() for the details about what this value means.
  29493. */
  29494. void setHeight (const double newHeight) throw() { h = newHeight; }
  29495. /** If the size and position are constance, and wouldn't be affected by changes
  29496. in the parent's size, then this will return true.
  29497. */
  29498. bool isPositionAbsolute() const throw();
  29499. /** Compares two objects. */
  29500. const bool operator== (const PositionedRectangle& other) const throw();
  29501. /** Compares two objects. */
  29502. const bool operator!= (const PositionedRectangle& other) const throw();
  29503. juce_UseDebuggingNewOperator
  29504. private:
  29505. double x, y, w, h;
  29506. uint8 xMode, yMode, wMode, hMode;
  29507. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  29508. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  29509. void decodePosString (const String& s, uint8& mode, double& value) throw();
  29510. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  29511. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  29512. const uint8 xMode, const uint8 wMode,
  29513. const int parentPos, const int parentSize) const throw();
  29514. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  29515. const uint8 xMode, const uint8 wMode,
  29516. const int parentPos, const int parentSize) const throw();
  29517. };
  29518. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29519. /********* End of inlined file: juce_PositionedRectangle.h *********/
  29520. #endif
  29521. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29522. #endif
  29523. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  29524. #endif
  29525. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29526. #endif
  29527. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29528. /********* Start of inlined file: juce_ImageCache.h *********/
  29529. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29530. #define __JUCE_IMAGECACHE_JUCEHEADER__
  29531. /**
  29532. A global cache of images that have been loaded from files or memory.
  29533. If you're loading an image and may need to use the image in more than one
  29534. place, this is used to allow the same image to be shared rather than loading
  29535. multiple copies into memory.
  29536. Another advantage is that after images are released, they will be kept in
  29537. memory for a few seconds before it is actually deleted, so if you're repeatedly
  29538. loading/deleting the same image, it'll reduce the chances of having to reload it
  29539. each time.
  29540. @see Image, ImageFileFormat
  29541. */
  29542. class JUCE_API ImageCache : private DeletedAtShutdown,
  29543. private Timer
  29544. {
  29545. public:
  29546. /** Loads an image from a file, (or just returns the image if it's already cached).
  29547. If the cache already contains an image that was loaded from this file,
  29548. that image will be returned. Otherwise, this method will try to load the
  29549. file, add it to the cache, and return it.
  29550. It's very important not to delete the image that is returned - instead use
  29551. the ImageCache::release() method.
  29552. Also, remember that the image returned is shared, so drawing into it might
  29553. affect other things that are using it!
  29554. @param file the file to try to load
  29555. @returns the image, or null if it there was an error loading it
  29556. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29557. */
  29558. static Image* getFromFile (const File& file);
  29559. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  29560. If the cache already contains an image that was loaded from this block of memory,
  29561. that image will be returned. Otherwise, this method will try to load the
  29562. file, add it to the cache, and return it.
  29563. It's very important not to delete the image that is returned - instead use
  29564. the ImageCache::release() method.
  29565. Also, remember that the image returned is shared, so drawing into it might
  29566. affect other things that are using it!
  29567. @param imageData the block of memory containing the image data
  29568. @param dataSize the data size in bytes
  29569. @returns the image, or null if it there was an error loading it
  29570. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29571. */
  29572. static Image* getFromMemory (const void* imageData,
  29573. const int dataSize);
  29574. /** Releases an image that was previously created by the ImageCache.
  29575. If an image has been returned by the getFromFile() or getFromMemory() methods,
  29576. it mustn't be deleted directly, but should be released with this method
  29577. instead.
  29578. @see getFromFile, getFromMemory
  29579. */
  29580. static void release (Image* const imageToRelease);
  29581. /** Checks whether an image is in the cache or not.
  29582. @returns true if the image is currently in the cache
  29583. */
  29584. static bool isImageInCache (Image* const imageToLookFor);
  29585. /** Increments the reference-count for a cached image.
  29586. If the image isn't in the cache, this method won't do anything.
  29587. */
  29588. static void incReferenceCount (Image* const image);
  29589. /** Checks the cache for an image with a particular hashcode.
  29590. If there's an image in the cache with this hashcode, it will be returned,
  29591. otherwise it will return zero.
  29592. If an image is returned, it must be released with the release() method
  29593. when no longer needed, to maintain the correct reference counts.
  29594. @param hashCode the hash code that would have been associated with the
  29595. image by addImageToCache()
  29596. @see addImageToCache
  29597. */
  29598. static Image* getFromHashCode (const int64 hashCode);
  29599. /** Adds an image to the cache with a user-defined hash-code.
  29600. After calling this, responsibilty for deleting the image will be taken
  29601. by the ImageCache.
  29602. The image will be initially be given a reference count of 1, so call
  29603. the release() method to delete it.
  29604. @param image the image to add
  29605. @param hashCode the hash-code to associate with it
  29606. @see getFromHashCode
  29607. */
  29608. static void addImageToCache (Image* const image,
  29609. const int64 hashCode);
  29610. /** Changes the amount of time before an unused image will be removed from the cache.
  29611. By default this is about 5 seconds.
  29612. */
  29613. static void setCacheTimeout (const int millisecs);
  29614. juce_UseDebuggingNewOperator
  29615. private:
  29616. CriticalSection lock;
  29617. VoidArray images;
  29618. ImageCache() throw();
  29619. ImageCache (const ImageCache&);
  29620. const ImageCache& operator= (const ImageCache&);
  29621. ~ImageCache();
  29622. void timerCallback();
  29623. };
  29624. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  29625. /********* End of inlined file: juce_ImageCache.h *********/
  29626. #endif
  29627. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29628. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  29629. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29630. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29631. /**
  29632. Represents a filter kernel to use in convoluting an image.
  29633. @see Image::applyConvolution
  29634. */
  29635. class JUCE_API ImageConvolutionKernel
  29636. {
  29637. public:
  29638. /** Creates an empty convulution kernel.
  29639. @param size the length of each dimension of the kernel, so e.g. if the size
  29640. is 5, it will create a 5x5 kernel
  29641. */
  29642. ImageConvolutionKernel (const int size) throw();
  29643. /** Destructor. */
  29644. ~ImageConvolutionKernel() throw();
  29645. /** Resets all values in the kernel to zero.
  29646. */
  29647. void clear() throw();
  29648. /** Sets the value of a specific cell in the kernel.
  29649. The x and y parameters must be in the range 0 < x < getKernelSize().
  29650. @see setOverallSum
  29651. */
  29652. void setKernelValue (const int x,
  29653. const int y,
  29654. const float value) throw();
  29655. /** Rescales all values in the kernel to make the total add up to a fixed value.
  29656. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  29657. */
  29658. void setOverallSum (const float desiredTotalSum) throw();
  29659. /** Multiplies all values in the kernel by a value. */
  29660. void rescaleAllValues (const float multiplier) throw();
  29661. /** Intialises the kernel for a gaussian blur.
  29662. @param blurRadius this may be larger or smaller than the kernel's actual
  29663. size but this will obviously be wasteful or clip at the
  29664. edges. Ideally the kernel should be just larger than
  29665. (blurRadius * 2).
  29666. */
  29667. void createGaussianBlur (const float blurRadius) throw();
  29668. /** Returns the size of the kernel.
  29669. E.g. if it's a 3x3 kernel, this returns 3.
  29670. */
  29671. int getKernelSize() const throw() { return size; }
  29672. /** Returns a 2-dimensional array of the kernel's values.
  29673. The size of each dimension of the array will be getKernelSize().
  29674. */
  29675. float** getValues() const throw() { return values; }
  29676. /** Applies the kernel to an image.
  29677. @param destImage the image that will receive the resultant convoluted pixels.
  29678. @param sourceImage an optional source image to read from - if this is 0, then the
  29679. destination image will be used as the source. If an image is
  29680. specified, it must be exactly the same size and type as the destination
  29681. image.
  29682. @param x the region of the image to apply the filter to
  29683. @param y the region of the image to apply the filter to
  29684. @param width the region of the image to apply the filter to
  29685. @param height the region of the image to apply the filter to
  29686. */
  29687. void applyToImage (Image& destImage,
  29688. const Image* sourceImage,
  29689. int x,
  29690. int y,
  29691. int width,
  29692. int height) const;
  29693. juce_UseDebuggingNewOperator
  29694. private:
  29695. float** values;
  29696. int size;
  29697. // no reason not to implement these one day..
  29698. ImageConvolutionKernel (const ImageConvolutionKernel&);
  29699. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  29700. };
  29701. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29702. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  29703. #endif
  29704. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29705. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  29706. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29707. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29708. /**
  29709. Base-class for codecs that can read and write image file formats such
  29710. as PNG, JPEG, etc.
  29711. This class also contains static methods to make it easy to load images
  29712. from files, streams or from memory.
  29713. @see Image, ImageCache
  29714. */
  29715. class JUCE_API ImageFileFormat
  29716. {
  29717. protected:
  29718. /** Creates an ImageFormat. */
  29719. ImageFileFormat() throw() {}
  29720. public:
  29721. /** Destructor. */
  29722. virtual ~ImageFileFormat() throw() {}
  29723. /** Returns a description of this file format.
  29724. E.g. "JPEG", "PNG"
  29725. */
  29726. virtual const String getFormatName() = 0;
  29727. /** Returns true if the given stream seems to contain data that this format
  29728. understands.
  29729. The format class should only read the first few bytes of the stream and sniff
  29730. for header bytes that it understands.
  29731. @see decodeImage
  29732. */
  29733. virtual bool canUnderstand (InputStream& input) = 0;
  29734. /** Tries to decode and return an image from the given stream.
  29735. This will be called for an image format after calling its canUnderStand() method
  29736. to see if it can handle the stream.
  29737. @param input the stream to read the data from. The stream will be positioned
  29738. at the start of the image data (but this may not necessarily
  29739. be position 0)
  29740. @returns the image that was decoded, or 0 if it fails. It's the
  29741. caller's responsibility to delete this image when no longer needed.
  29742. @see loadFrom
  29743. */
  29744. virtual Image* decodeImage (InputStream& input) = 0;
  29745. /** Attempts to write an image to a stream.
  29746. To specify extra information like encoding quality, there will be appropriate parameters
  29747. in the subclasses of the specific file types.
  29748. @returns true if it nothing went wrong.
  29749. */
  29750. virtual bool writeImageToStream (const Image& sourceImage,
  29751. OutputStream& destStream) = 0;
  29752. /** Tries the built-in decoders to see if it can find one to read this stream.
  29753. There are currently built-in decoders for PNG, JPEG and GIF formats.
  29754. The object that is returned should not be deleted by the caller.
  29755. @see canUnderstand, decodeImage, loadFrom
  29756. */
  29757. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  29758. /** Tries to load an image from a stream.
  29759. This will use the findImageFormatForStream() method to locate a suitable
  29760. codec, and use that to load the image.
  29761. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29762. caller's responsibility to delete this image when no longer needed.
  29763. */
  29764. static Image* loadFrom (InputStream& input);
  29765. /** Tries to load an image from a file.
  29766. This will use the findImageFormatForStream() method to locate a suitable
  29767. codec, and use that to load the image.
  29768. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29769. caller's responsibility to delete this image when no longer needed.
  29770. */
  29771. static Image* loadFrom (const File& file);
  29772. /** Tries to load an image from a block of raw image data.
  29773. This will use the findImageFormatForStream() method to locate a suitable
  29774. codec, and use that to load the image.
  29775. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29776. caller's responsibility to delete this image when no longer needed.
  29777. */
  29778. static Image* loadFrom (const void* rawData,
  29779. const int numBytesOfData);
  29780. };
  29781. /**
  29782. A type of ImageFileFormat for reading and writing PNG files.
  29783. @see ImageFileFormat, JPEGImageFormat
  29784. */
  29785. class PNGImageFormat : public ImageFileFormat
  29786. {
  29787. public:
  29788. PNGImageFormat() throw();
  29789. ~PNGImageFormat() throw();
  29790. const String getFormatName();
  29791. bool canUnderstand (InputStream& input);
  29792. Image* decodeImage (InputStream& input);
  29793. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29794. };
  29795. /**
  29796. A type of ImageFileFormat for reading and writing JPEG files.
  29797. @see ImageFileFormat, PNGImageFormat
  29798. */
  29799. class JPEGImageFormat : public ImageFileFormat
  29800. {
  29801. public:
  29802. JPEGImageFormat() throw();
  29803. ~JPEGImageFormat() throw();
  29804. /** Specifies the quality to be used when writing a JPEG file.
  29805. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  29806. any negative value is "default" quality
  29807. */
  29808. void setQuality (const float newQuality);
  29809. const String getFormatName();
  29810. bool canUnderstand (InputStream& input);
  29811. Image* decodeImage (InputStream& input);
  29812. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29813. private:
  29814. float quality;
  29815. };
  29816. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29817. /********* End of inlined file: juce_ImageFileFormat.h *********/
  29818. #endif
  29819. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29820. /********* Start of inlined file: juce_Drawable.h *********/
  29821. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29822. #define __JUCE_DRAWABLE_JUCEHEADER__
  29823. /**
  29824. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  29825. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29826. */
  29827. class JUCE_API Drawable
  29828. {
  29829. protected:
  29830. /** The base class can't be instantiated directly.
  29831. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29832. */
  29833. Drawable();
  29834. public:
  29835. /** Destructor. */
  29836. virtual ~Drawable();
  29837. /** Creates a deep copy of this Drawable object.
  29838. Use this to create a new copy of this and any sub-objects in the tree.
  29839. */
  29840. virtual Drawable* createCopy() const = 0;
  29841. /** Renders this Drawable object.
  29842. This is the main rendering method you should call to render a Drawable.
  29843. @see drawWithin
  29844. */
  29845. virtual void draw (Graphics& g,
  29846. const AffineTransform& transform = AffineTransform::identity) const = 0;
  29847. /** Renders the Drawable at a given offset within the Graphics context.
  29848. The co-ordinates passed-in are used to translate the object relative to its own
  29849. origin before drawing it - this is basically a quick way of saying:
  29850. @code
  29851. draw (g, AffineTransform::translation (x, y)).
  29852. @endcode
  29853. */
  29854. void drawAt (Graphics& g,
  29855. const float x,
  29856. const float y) const;
  29857. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  29858. changing its aspect-ratio.
  29859. The object can placed arbitrarily within the rectangle based on a Justification type,
  29860. and can either be made as big as possible, or just reduced to fit.
  29861. @param g the graphics context to render onto
  29862. @param destX top-left of the target rectangle to fit it into
  29863. @param destY top-left of the target rectangle to fit it into
  29864. @param destWidth size of the target rectangle to fit the image into
  29865. @param destHeight size of the target rectangle to fit the image into
  29866. @param placement defines the alignment and rescaling to use to fit
  29867. this object within the target rectangle.
  29868. */
  29869. void drawWithin (Graphics& g,
  29870. const int destX,
  29871. const int destY,
  29872. const int destWidth,
  29873. const int destHeight,
  29874. const RectanglePlacement& placement) const;
  29875. /** Returns the smallest rectangle that can contain this Drawable object.
  29876. Co-ordinates are relative to the object's own origin.
  29877. */
  29878. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  29879. /** Returns true if the given point is somewhere inside this Drawable.
  29880. Co-ordinates are relative to the object's own origin.
  29881. */
  29882. virtual bool hitTest (float x, float y) const = 0;
  29883. /** Returns the name given to this drawable.
  29884. @see setName
  29885. */
  29886. const String& getName() const throw() { return name; }
  29887. /** Assigns a name to this drawable. */
  29888. void setName (const String& newName) throw() { name = newName; }
  29889. /** Tries to turn some kind of image file into a drawable.
  29890. The data could be an image that the ImageFileFormat class understands, or it
  29891. could be SVG.
  29892. */
  29893. static Drawable* createFromImageData (const void* data, const int numBytes);
  29894. /** Tries to turn a stream containing some kind of image data into a drawable.
  29895. The data could be an image that the ImageFileFormat class understands, or it
  29896. could be SVG.
  29897. */
  29898. static Drawable* createFromImageDataStream (InputStream& dataSource);
  29899. /** Tries to turn a file containing some kind of image data into a drawable.
  29900. The data could be an image that the ImageFileFormat class understands, or it
  29901. could be SVG.
  29902. */
  29903. static Drawable* createFromImageFile (const File& file);
  29904. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  29905. into a Drawable tree.
  29906. The object returned must be deleted by the caller. If something goes wrong
  29907. while parsing, it may return 0.
  29908. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  29909. implementation, but it can return the basic vector objects.
  29910. */
  29911. static Drawable* createFromSVG (const XmlElement& svgDocument);
  29912. juce_UseDebuggingNewOperator
  29913. private:
  29914. Drawable (const Drawable&);
  29915. const Drawable& operator= (const Drawable&);
  29916. String name;
  29917. };
  29918. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  29919. /********* End of inlined file: juce_Drawable.h *********/
  29920. #endif
  29921. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29922. /********* Start of inlined file: juce_DrawableComposite.h *********/
  29923. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29924. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  29925. /**
  29926. A drawable object which acts as a container for a set of other Drawables.
  29927. @see Drawable
  29928. */
  29929. class JUCE_API DrawableComposite : public Drawable
  29930. {
  29931. public:
  29932. /** Creates a composite Drawable.
  29933. */
  29934. DrawableComposite();
  29935. /** Destructor. */
  29936. virtual ~DrawableComposite();
  29937. /** Adds a new sub-drawable to this one.
  29938. This passes in a Drawable pointer for this object to look after. To add a copy
  29939. of a drawable, use the form of this method that takes a Drawable reference instead.
  29940. @param drawable the object to add - this will be deleted automatically
  29941. when no longer needed, so the caller mustn't keep any
  29942. pointers to it.
  29943. @param transform the transform to apply to this drawable when it's being
  29944. drawn
  29945. @param index where to insert it in the list of drawables. 0 is the back,
  29946. -1 is the front, or any value from 0 and getNumDrawables()
  29947. can be used
  29948. @see removeDrawable
  29949. */
  29950. void insertDrawable (Drawable* drawable,
  29951. const AffineTransform& transform = AffineTransform::identity,
  29952. const int index = -1);
  29953. /** Adds a new sub-drawable to this one.
  29954. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  29955. for this object to look after, use the form of this method that takes a Drawable
  29956. pointer instead.
  29957. @param drawable the object to add - an internal copy will be made of this object
  29958. @param transform the transform to apply to this drawable when it's being
  29959. drawn
  29960. @param index where to insert it in the list of drawables. 0 is the back,
  29961. -1 is the front, or any value from 0 and getNumDrawables()
  29962. can be used
  29963. @see removeDrawable
  29964. */
  29965. void insertDrawable (const Drawable& drawable,
  29966. const AffineTransform& transform = AffineTransform::identity,
  29967. const int index = -1);
  29968. /** Deletes one of the Drawable objects.
  29969. @param index the index of the drawable to delete, between 0
  29970. and (getNumDrawables() - 1).
  29971. @see insertDrawable, getNumDrawables
  29972. */
  29973. void removeDrawable (const int index);
  29974. /** Returns the number of drawables contained inside this one.
  29975. @see getDrawable
  29976. */
  29977. int getNumDrawables() const throw() { return drawables.size(); }
  29978. /** Returns one of the drawables that are contained in this one.
  29979. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  29980. to find it.
  29981. The pointer returned is managed by this object and will be deleted when no longer
  29982. needed, so be careful what you do with it.
  29983. @see getNumDrawables
  29984. */
  29985. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  29986. /** Returns the transform that applies to one of the drawables that are contained in this one.
  29987. The pointer returned is managed by this object and will be deleted when no longer
  29988. needed, so be careful what you do with it.
  29989. @see getNumDrawables
  29990. */
  29991. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  29992. /** Brings one of the Drawables to the front.
  29993. @param index the index of the drawable to move, between 0
  29994. and (getNumDrawables() - 1).
  29995. @see insertDrawable, getNumDrawables
  29996. */
  29997. void bringToFront (const int index);
  29998. /** @internal */
  29999. void draw (Graphics& g, const AffineTransform& transform) const;
  30000. /** @internal */
  30001. void getBounds (float& x, float& y, float& width, float& height) const;
  30002. /** @internal */
  30003. bool hitTest (float x, float y) const;
  30004. /** @internal */
  30005. Drawable* createCopy() const;
  30006. juce_UseDebuggingNewOperator
  30007. private:
  30008. OwnedArray <Drawable> drawables;
  30009. OwnedArray <AffineTransform> transforms;
  30010. DrawableComposite (const DrawableComposite&);
  30011. const DrawableComposite& operator= (const DrawableComposite&);
  30012. };
  30013. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30014. /********* End of inlined file: juce_DrawableComposite.h *********/
  30015. #endif
  30016. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30017. /********* Start of inlined file: juce_DrawableImage.h *********/
  30018. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30019. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30020. /**
  30021. A drawable object which is a bitmap image.
  30022. @see Drawable
  30023. */
  30024. class JUCE_API DrawableImage : public Drawable
  30025. {
  30026. public:
  30027. DrawableImage();
  30028. /** Destructor. */
  30029. virtual ~DrawableImage();
  30030. /** Sets the image that this drawable will render.
  30031. An internal copy is made of the image passed-in. If you want to provide an
  30032. image that this object can take charge of without needing to create a copy,
  30033. use the other setImage() method.
  30034. */
  30035. void setImage (const Image& imageToCopy);
  30036. /** Sets the image that this drawable will render.
  30037. An internal copy of this will not be made, so the caller mustn't delete
  30038. the image while it's still being used by this object.
  30039. A good way to use this is with the ImageCache - if you create an image
  30040. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30041. it'll be released neatly with its reference count being decreased.
  30042. @param imageToUse the image to render
  30043. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30044. then the image will be deleted when this object no longer
  30045. needs it - unless the image was created by the ImageCache,
  30046. in which case it will be released with ImageCache::release().
  30047. */
  30048. void setImage (Image* imageToUse,
  30049. const bool releaseWhenNotNeeded);
  30050. /** Returns the current image. */
  30051. Image* getImage() const throw() { return image; }
  30052. /** Clears (and possibly deletes) the currently set image. */
  30053. void clearImage();
  30054. /** Sets the opacity to use when drawing the image. */
  30055. void setOpacity (const float newOpacity);
  30056. /** Returns the image's opacity. */
  30057. float getOpacity() const throw() { return opacity; }
  30058. /** Sets a colour to draw over the image's alpha channel.
  30059. By default this is transparent so isn't drawn, but if you set a non-transparent
  30060. colour here, then it will be overlaid on the image, using the image's alpha
  30061. channel as a mask.
  30062. This is handy for doing things like darkening or lightening an image by overlaying
  30063. it with semi-transparent black or white.
  30064. */
  30065. void setOverlayColour (const Colour& newOverlayColour);
  30066. /** Returns the overlay colour. */
  30067. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30068. /** @internal */
  30069. void draw (Graphics& g, const AffineTransform& transform) const;
  30070. /** @internal */
  30071. void getBounds (float& x, float& y, float& width, float& height) const;
  30072. /** @internal */
  30073. bool hitTest (float x, float y) const;
  30074. /** @internal */
  30075. Drawable* createCopy() const;
  30076. juce_UseDebuggingNewOperator
  30077. private:
  30078. Image* image;
  30079. bool canDeleteImage;
  30080. float opacity;
  30081. Colour overlayColour;
  30082. DrawableImage (const DrawableImage&);
  30083. const DrawableImage& operator= (const DrawableImage&);
  30084. };
  30085. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30086. /********* End of inlined file: juce_DrawableImage.h *********/
  30087. #endif
  30088. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30089. /********* Start of inlined file: juce_DrawablePath.h *********/
  30090. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30091. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30092. /**
  30093. A drawable object which renders a filled or outlined shape.
  30094. @see Drawable
  30095. */
  30096. class JUCE_API DrawablePath : public Drawable
  30097. {
  30098. public:
  30099. /** Creates a DrawablePath.
  30100. */
  30101. DrawablePath();
  30102. /** Destructor. */
  30103. virtual ~DrawablePath();
  30104. /** Changes the path that will be drawn.
  30105. @see setSolidFill, setOutline
  30106. */
  30107. void setPath (const Path& newPath);
  30108. /** Returns the current path. */
  30109. const Path& getPath() const throw() { return path; }
  30110. /** Sets a colour to fill the path with.
  30111. This colour is used to fill the path - if you don't want the path to be
  30112. filled (e.g. if you're just drawing an outline), set this colour to be
  30113. transparent.
  30114. @see setPath, setOutline
  30115. */
  30116. void setSolidFill (const Colour& newColour);
  30117. /** Sets a custom brush to use to fill the path.
  30118. @see setSolidFill
  30119. */
  30120. void setFillBrush (const Brush& newBrush);
  30121. /** Returns the brush currently being used to fill the shape. */
  30122. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30123. /** Changes the properties of the outline that will be drawn around the path.
  30124. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30125. colour passed-in here will be used for it.
  30126. @see setPath, setSolidFill
  30127. */
  30128. void setOutline (const float thickness,
  30129. const Colour& outlineColour);
  30130. /** Changes the properties of the outline that will be drawn around the path.
  30131. If the stroke type has 0 thickness, no outline will be drawn.
  30132. @see setPath, setSolidFill
  30133. */
  30134. void setOutline (const PathStrokeType& strokeType,
  30135. const Brush& strokeBrush);
  30136. /** Returns the current outline style. */
  30137. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30138. /** Returns the brush currently being used to draw the outline. */
  30139. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30140. /** @internal */
  30141. void draw (Graphics& g, const AffineTransform& transform) const;
  30142. /** @internal */
  30143. void getBounds (float& x, float& y, float& width, float& height) const;
  30144. /** @internal */
  30145. bool hitTest (float x, float y) const;
  30146. /** @internal */
  30147. Drawable* createCopy() const;
  30148. juce_UseDebuggingNewOperator
  30149. private:
  30150. Path path, outline;
  30151. Brush* fillBrush;
  30152. Brush* strokeBrush;
  30153. PathStrokeType strokeType;
  30154. void updateOutline();
  30155. DrawablePath (const DrawablePath&);
  30156. const DrawablePath& operator= (const DrawablePath&);
  30157. };
  30158. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30159. /********* End of inlined file: juce_DrawablePath.h *********/
  30160. #endif
  30161. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30162. /********* Start of inlined file: juce_DrawableText.h *********/
  30163. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30164. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30165. /**
  30166. A drawable object which renders a line of text.
  30167. @see Drawable
  30168. */
  30169. class JUCE_API DrawableText : public Drawable
  30170. {
  30171. public:
  30172. /** Creates a DrawableText object. */
  30173. DrawableText();
  30174. /** Destructor. */
  30175. virtual ~DrawableText();
  30176. /** Sets the block of text to render */
  30177. void setText (const GlyphArrangement& newText);
  30178. /** Sets a single line of text to render.
  30179. This is a convenient method of adding a single line - for
  30180. more complex text, use the setText() that takes a
  30181. GlyphArrangement instead.
  30182. */
  30183. void setText (const String& newText, const Font& fontToUse);
  30184. /** Returns the text arrangement that was set with setText(). */
  30185. const GlyphArrangement& getText() const throw() { return text; }
  30186. /** Sets the colour of the text. */
  30187. void setColour (const Colour& newColour);
  30188. /** Returns the current text colour. */
  30189. const Colour& getColour() const throw() { return colour; }
  30190. /** @internal */
  30191. void draw (Graphics& g, const AffineTransform& transform) const;
  30192. /** @internal */
  30193. void getBounds (float& x, float& y, float& width, float& height) const;
  30194. /** @internal */
  30195. bool hitTest (float x, float y) const;
  30196. /** @internal */
  30197. Drawable* createCopy() const;
  30198. juce_UseDebuggingNewOperator
  30199. private:
  30200. GlyphArrangement text;
  30201. Colour colour;
  30202. DrawableText (const DrawableText&);
  30203. const DrawableText& operator= (const DrawableText&);
  30204. };
  30205. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30206. /********* End of inlined file: juce_DrawableText.h *********/
  30207. #endif
  30208. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30209. #endif
  30210. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30211. #endif
  30212. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30213. #endif
  30214. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30215. #endif
  30216. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30217. /********* Start of inlined file: juce_ArrowButton.h *********/
  30218. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30219. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30220. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30221. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30222. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30223. /**
  30224. An effect filter that adds a drop-shadow behind the image's content.
  30225. (This will only work on images/components that aren't opaque, of course).
  30226. When added to a component, this effect will draw a soft-edged
  30227. shadow based on what gets drawn inside it. The shadow will also
  30228. be applied to the component's children.
  30229. For speed, this doesn't use a proper gaussian blur, but cheats by
  30230. using a simple bilinear filter. If you need a really high-quality
  30231. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30232. @see Component::setComponentEffect
  30233. */
  30234. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30235. {
  30236. public:
  30237. /** Creates a default drop-shadow effect.
  30238. To customise the shadow's appearance, use the setShadowProperties()
  30239. method.
  30240. */
  30241. DropShadowEffect();
  30242. /** Destructor. */
  30243. ~DropShadowEffect();
  30244. /** Sets up parameters affecting the shadow's appearance.
  30245. @param newRadius the (approximate) radius of the blur used
  30246. @param newOpacity the opacity with which the shadow is rendered
  30247. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30248. component's contents
  30249. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30250. component's contents
  30251. */
  30252. void setShadowProperties (const float newRadius,
  30253. const float newOpacity,
  30254. const int newShadowOffsetX,
  30255. const int newShadowOffsetY);
  30256. /** @internal */
  30257. void applyEffect (Image& sourceImage, Graphics& destContext);
  30258. juce_UseDebuggingNewOperator
  30259. private:
  30260. int offsetX, offsetY;
  30261. float radius, opacity;
  30262. };
  30263. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30264. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30265. /**
  30266. A button with an arrow in it.
  30267. @see Button
  30268. */
  30269. class JUCE_API ArrowButton : public Button
  30270. {
  30271. public:
  30272. /** Creates an ArrowButton.
  30273. @param buttonName the name to give the button
  30274. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30275. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30276. @param arrowColour the colour to use for the arrow
  30277. */
  30278. ArrowButton (const String& buttonName,
  30279. float arrowDirection,
  30280. const Colour& arrowColour);
  30281. /** Destructor. */
  30282. ~ArrowButton();
  30283. juce_UseDebuggingNewOperator
  30284. protected:
  30285. /** @internal */
  30286. void paintButton (Graphics& g,
  30287. bool isMouseOverButton,
  30288. bool isButtonDown);
  30289. /** @internal */
  30290. void buttonStateChanged();
  30291. private:
  30292. Colour colour;
  30293. DropShadowEffect shadow;
  30294. Path path;
  30295. int offset;
  30296. ArrowButton (const ArrowButton&);
  30297. const ArrowButton& operator= (const ArrowButton&);
  30298. };
  30299. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30300. /********* End of inlined file: juce_ArrowButton.h *********/
  30301. #endif
  30302. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30303. #endif
  30304. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30305. /********* Start of inlined file: juce_DrawableButton.h *********/
  30306. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30307. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30308. /**
  30309. A button that displays a Drawable.
  30310. Up to three Drawable objects can be given to this button, to represent the
  30311. 'normal', 'over' and 'down' states.
  30312. @see Button
  30313. */
  30314. class JUCE_API DrawableButton : public Button
  30315. {
  30316. public:
  30317. enum ButtonStyle
  30318. {
  30319. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30320. ImageRaw, /**< The button will just display the images in their normal size and position.
  30321. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30322. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30323. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30324. };
  30325. /** Creates a DrawableButton.
  30326. After creating one of these, use setImages() to specify the drawables to use.
  30327. @param buttonName the name to give the component
  30328. @param buttonStyle the layout to use
  30329. @see ButtonStyle, setButtonStyle, setImages
  30330. */
  30331. DrawableButton (const String& buttonName,
  30332. const ButtonStyle buttonStyle);
  30333. /** Destructor. */
  30334. ~DrawableButton();
  30335. /** Sets up the images to draw for the various button states.
  30336. The button will keep its own internal copies of these drawables.
  30337. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30338. will be made of the object passed-in if it is non-zero.
  30339. @param overImage the thing to draw for the button's 'over' state - if this is
  30340. zero, the button's normal image will be used when the mouse is
  30341. over it. An internal copy will be made of the object passed-in
  30342. if it is non-zero.
  30343. @param downImage the thing to draw for the button's 'down' state - if this is
  30344. zero, the 'over' image will be used instead (or the normal image
  30345. as a last resort). An internal copy will be made of the object
  30346. passed-in if it is non-zero.
  30347. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30348. the normal image will be drawn with a reduced opacity instead.
  30349. An internal copy will be made of the object passed-in if it is
  30350. non-zero.
  30351. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30352. state is 'on'. If this is 0, the normal image is used instead
  30353. @param overImageOn same as the overImage, but this is used when the button's toggle
  30354. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30355. @param downImageOn same as the downImage, but this is used when the button's toggle
  30356. state is 'on'. If this is 0, the overImageOn is drawn instead
  30357. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30358. state is 'on'. If this is 0, the normal image will be drawn instead
  30359. with a reduced opacity
  30360. */
  30361. void setImages (const Drawable* normalImage,
  30362. const Drawable* overImage = 0,
  30363. const Drawable* downImage = 0,
  30364. const Drawable* disabledImage = 0,
  30365. const Drawable* normalImageOn = 0,
  30366. const Drawable* overImageOn = 0,
  30367. const Drawable* downImageOn = 0,
  30368. const Drawable* disabledImageOn = 0);
  30369. /** Changes the button's style.
  30370. @see ButtonStyle
  30371. */
  30372. void setButtonStyle (const ButtonStyle newStyle);
  30373. /** Changes the button's background colours.
  30374. The toggledOffColour is the colour to use when the button's toggle state
  30375. is off, and toggledOnColour when it's on.
  30376. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30377. used to fill the background of the component.
  30378. For an ImageOnButtonBackground style, the colour is used to draw the
  30379. button's lozenge shape and exactly how the colour's used will depend
  30380. on the LookAndFeel.
  30381. */
  30382. void setBackgroundColours (const Colour& toggledOffColour,
  30383. const Colour& toggledOnColour);
  30384. /** Returns the current background colour being used.
  30385. @see setBackgroundColour
  30386. */
  30387. const Colour& getBackgroundColour() const throw();
  30388. /** Gives the button an optional amount of space around the edge of the drawable.
  30389. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30390. ones on a button background. If the button is too small for the given gap, a
  30391. smaller gap will be used.
  30392. By default there's a gap of about 3 pixels.
  30393. */
  30394. void setEdgeIndent (const int numPixelsIndent);
  30395. /** Returns the image that the button is currently displaying. */
  30396. const Drawable* getCurrentImage() const throw();
  30397. const Drawable* getNormalImage() const throw();
  30398. const Drawable* getOverImage() const throw();
  30399. const Drawable* getDownImage() const throw();
  30400. juce_UseDebuggingNewOperator
  30401. protected:
  30402. /** @internal */
  30403. void paintButton (Graphics& g,
  30404. bool isMouseOverButton,
  30405. bool isButtonDown);
  30406. private:
  30407. ButtonStyle style;
  30408. Drawable* normalImage;
  30409. Drawable* overImage;
  30410. Drawable* downImage;
  30411. Drawable* disabledImage;
  30412. Drawable* normalImageOn;
  30413. Drawable* overImageOn;
  30414. Drawable* downImageOn;
  30415. Drawable* disabledImageOn;
  30416. Colour backgroundOff, backgroundOn;
  30417. int edgeIndent;
  30418. void deleteImages();
  30419. DrawableButton (const DrawableButton&);
  30420. const DrawableButton& operator= (const DrawableButton&);
  30421. };
  30422. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30423. /********* End of inlined file: juce_DrawableButton.h *********/
  30424. #endif
  30425. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30426. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30427. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30428. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30429. /**
  30430. A button showing an underlined weblink, that will launch the link
  30431. when it's clicked.
  30432. @see Button
  30433. */
  30434. class JUCE_API HyperlinkButton : public Button
  30435. {
  30436. public:
  30437. /** Creates a HyperlinkButton.
  30438. @param linkText the text that will be displayed in the button - this is
  30439. also set as the Component's name, but the text can be
  30440. changed later with the Button::getButtonText() method
  30441. @param linkURL the URL to launch when the user clicks the button
  30442. */
  30443. HyperlinkButton (const String& linkText,
  30444. const URL& linkURL);
  30445. /** Destructor. */
  30446. ~HyperlinkButton();
  30447. /** Changes the font to use for the text.
  30448. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30449. to match the size of the component.
  30450. */
  30451. void setFont (const Font& newFont,
  30452. const bool resizeToMatchComponentHeight,
  30453. const Justification& justificationType = Justification::horizontallyCentred);
  30454. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30455. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30456. methods.
  30457. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30458. */
  30459. enum ColourIds
  30460. {
  30461. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30462. };
  30463. /** Changes the URL that the button will trigger. */
  30464. void setURL (const URL& newURL) throw();
  30465. /** Returns the URL that the button will trigger. */
  30466. const URL& getURL() const throw() { return url; }
  30467. /** Resizes the button horizontally to fit snugly around the text.
  30468. This won't affect the button's height.
  30469. */
  30470. void changeWidthToFitText();
  30471. juce_UseDebuggingNewOperator
  30472. protected:
  30473. /** @internal */
  30474. void clicked();
  30475. /** @internal */
  30476. void colourChanged();
  30477. /** @internal */
  30478. void paintButton (Graphics& g,
  30479. bool isMouseOverButton,
  30480. bool isButtonDown);
  30481. private:
  30482. URL url;
  30483. Font font;
  30484. bool resizeFont;
  30485. Justification justification;
  30486. const Font getFontToUse() const;
  30487. HyperlinkButton (const HyperlinkButton&);
  30488. const HyperlinkButton& operator= (const HyperlinkButton&);
  30489. };
  30490. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30491. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30492. #endif
  30493. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30494. /********* Start of inlined file: juce_ImageButton.h *********/
  30495. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30496. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30497. /**
  30498. As the title suggests, this is a button containing an image.
  30499. The colour and transparency of the image can be set to vary when the
  30500. button state changes.
  30501. @see Button, ShapeButton, TextButton
  30502. */
  30503. class JUCE_API ImageButton : public Button
  30504. {
  30505. public:
  30506. /** Creates an ImageButton.
  30507. Use setImage() to specify the image to use. The colours and opacities that
  30508. are specified here can be changed later using setDrawingOptions().
  30509. @param name the name to give the component
  30510. */
  30511. ImageButton (const String& name);
  30512. /** Destructor. */
  30513. ~ImageButton();
  30514. /** Sets up the images to draw in various states.
  30515. Important! Bear in mind that if you pass the same image in for more than one of
  30516. these parameters, this button will delete it (or release from the ImageCache)
  30517. multiple times!
  30518. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30519. resized to the same dimensions as the normal image
  30520. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30521. button when the button's size changes
  30522. @param preserveImageProportions if true then any rescaling of the image to fit
  30523. the button will keep the image's x and y proportions
  30524. correct - i.e. it won't distort its shape, although
  30525. this might create gaps around the edges
  30526. @param normalImage the image to use when the button is in its normal state. The
  30527. image passed in will be deleted (or released if it
  30528. was created by the ImageCache class) when the
  30529. button no longer needs it.
  30530. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30531. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30532. normal image - if this colour is transparent, no overlay
  30533. will be drawn. The overlay will be drawn over the top of the
  30534. image, so you can basically add a solid or semi-transparent
  30535. colour to the image to brighten or darken it
  30536. @param overImage the image to use when the mouse is over the button. If
  30537. you want to use the same image as was set in the normalImage
  30538. parameter, this value can be 0. As for normalImage, it
  30539. will be deleted or released by the button when no longer
  30540. needed
  30541. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30542. is over the button
  30543. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30544. image when the mouse is over - if this colour is transparent,
  30545. no overlay will be drawn
  30546. @param downImage an image to use when the button is pressed down. If set
  30547. to zero, the 'over' image will be drawn instead (or the
  30548. normal image if there isn't an 'over' image either). This
  30549. image will be deleted or released by the button when no
  30550. longer needed
  30551. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30552. is pressed
  30553. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30554. image when the button is pressed down - if this colour is
  30555. transparent, no overlay will be drawn
  30556. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30557. whenever it's inside the button's bounding rectangle. If
  30558. set to values higher than 0, the mouse will only be
  30559. considered to be over the image when the value of the
  30560. image's alpha channel at that position is greater than
  30561. this level.
  30562. */
  30563. void setImages (const bool resizeButtonNowToFitThisImage,
  30564. const bool rescaleImagesWhenButtonSizeChanges,
  30565. const bool preserveImageProportions,
  30566. Image* const normalImage,
  30567. const float imageOpacityWhenNormal,
  30568. const Colour& overlayColourWhenNormal,
  30569. Image* const overImage,
  30570. const float imageOpacityWhenOver,
  30571. const Colour& overlayColourWhenOver,
  30572. Image* const downImage,
  30573. const float imageOpacityWhenDown,
  30574. const Colour& overlayColourWhenDown,
  30575. const float hitTestAlphaThreshold = 0.0f);
  30576. /** Returns the currently set 'normal' image. */
  30577. Image* getNormalImage() const throw();
  30578. /** Returns the image that's drawn when the mouse is over the button.
  30579. If an 'over' image has been set, this will return it; otherwise it'll
  30580. just return the normal image.
  30581. */
  30582. Image* getOverImage() const throw();
  30583. /** Returns the image that's drawn when the button is held down.
  30584. If a 'down' image has been set, this will return it; otherwise it'll
  30585. return the 'over' image or normal image, depending on what's available.
  30586. */
  30587. Image* getDownImage() const throw();
  30588. juce_UseDebuggingNewOperator
  30589. protected:
  30590. /** @internal */
  30591. bool hitTest (int x, int y);
  30592. /** @internal */
  30593. void paintButton (Graphics& g,
  30594. bool isMouseOverButton,
  30595. bool isButtonDown);
  30596. private:
  30597. bool scaleImageToFit, preserveProportions;
  30598. unsigned char alphaThreshold;
  30599. int imageX, imageY, imageW, imageH;
  30600. Image* normalImage;
  30601. Image* overImage;
  30602. Image* downImage;
  30603. float normalOpacity, overOpacity, downOpacity;
  30604. Colour normalOverlay, overOverlay, downOverlay;
  30605. Image* getCurrentImage() const;
  30606. void deleteImages();
  30607. ImageButton (const ImageButton&);
  30608. const ImageButton& operator= (const ImageButton&);
  30609. };
  30610. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30611. /********* End of inlined file: juce_ImageButton.h *********/
  30612. #endif
  30613. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30614. /********* Start of inlined file: juce_ShapeButton.h *********/
  30615. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30616. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30617. /**
  30618. A button that contains a filled shape.
  30619. @see Button, ImageButton, TextButton, ArrowButton
  30620. */
  30621. class JUCE_API ShapeButton : public Button
  30622. {
  30623. public:
  30624. /** Creates a ShapeButton.
  30625. @param name a name to give the component - see Component::setName()
  30626. @param normalColour the colour to fill the shape with when the mouse isn't over
  30627. @param overColour the colour to use when the mouse is over the shape
  30628. @param downColour the colour to use when the button is in the pressed-down state
  30629. */
  30630. ShapeButton (const String& name,
  30631. const Colour& normalColour,
  30632. const Colour& overColour,
  30633. const Colour& downColour);
  30634. /** Destructor. */
  30635. ~ShapeButton();
  30636. /** Sets the shape to use.
  30637. @param newShape the shape to use
  30638. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30639. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30640. the button is resized
  30641. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30642. */
  30643. void setShape (const Path& newShape,
  30644. const bool resizeNowToFitThisShape,
  30645. const bool maintainShapeProportions,
  30646. const bool hasDropShadow);
  30647. /** Set the colours to use for drawing the shape.
  30648. @param normalColour the colour to fill the shape with when the mouse isn't over
  30649. @param overColour the colour to use when the mouse is over the shape
  30650. @param downColour the colour to use when the button is in the pressed-down state
  30651. */
  30652. void setColours (const Colour& normalColour,
  30653. const Colour& overColour,
  30654. const Colour& downColour);
  30655. /** Sets up an outline to draw around the shape.
  30656. @param outlineColour the colour to use
  30657. @param outlineStrokeWidth the thickness of line to draw
  30658. */
  30659. void setOutline (const Colour& outlineColour,
  30660. const float outlineStrokeWidth);
  30661. juce_UseDebuggingNewOperator
  30662. protected:
  30663. /** @internal */
  30664. void paintButton (Graphics& g,
  30665. bool isMouseOverButton,
  30666. bool isButtonDown);
  30667. private:
  30668. Colour normalColour, overColour, downColour, outlineColour;
  30669. DropShadowEffect shadow;
  30670. Path shape;
  30671. bool maintainShapeProportions;
  30672. float outlineWidth;
  30673. ShapeButton (const ShapeButton&);
  30674. const ShapeButton& operator= (const ShapeButton&);
  30675. };
  30676. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  30677. /********* End of inlined file: juce_ShapeButton.h *********/
  30678. #endif
  30679. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30680. #endif
  30681. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30682. /********* Start of inlined file: juce_ToggleButton.h *********/
  30683. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30684. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30685. /**
  30686. A button that can be toggled on/off.
  30687. All buttons can be toggle buttons, but this lets you create one of the
  30688. standard ones which has a tick-box and a text label next to it.
  30689. @see Button, DrawableButton, TextButton
  30690. */
  30691. class JUCE_API ToggleButton : public Button
  30692. {
  30693. public:
  30694. /** Creates a ToggleButton.
  30695. @param buttonText the text to put in the button (the component's name is also
  30696. initially set to this string, but these can be changed later
  30697. using the setName() and setButtonText() methods)
  30698. */
  30699. ToggleButton (const String& buttonText);
  30700. /** Destructor. */
  30701. ~ToggleButton();
  30702. /** Resizes the button to fit neatly around its current text.
  30703. The button's height won't be affected, only its width.
  30704. */
  30705. void changeWidthToFitText();
  30706. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30707. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30708. methods.
  30709. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30710. */
  30711. enum ColourIds
  30712. {
  30713. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  30714. };
  30715. juce_UseDebuggingNewOperator
  30716. protected:
  30717. /** @internal */
  30718. void paintButton (Graphics& g,
  30719. bool isMouseOverButton,
  30720. bool isButtonDown);
  30721. /** @internal */
  30722. void colourChanged();
  30723. private:
  30724. ToggleButton (const ToggleButton&);
  30725. const ToggleButton& operator= (const ToggleButton&);
  30726. };
  30727. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30728. /********* End of inlined file: juce_ToggleButton.h *********/
  30729. #endif
  30730. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30731. /********* Start of inlined file: juce_ToolbarButton.h *********/
  30732. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30733. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30734. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  30735. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30736. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30737. /********* Start of inlined file: juce_Toolbar.h *********/
  30738. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  30739. #define __JUCE_TOOLBAR_JUCEHEADER__
  30740. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  30741. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30742. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30743. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  30744. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30745. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30746. /**
  30747. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  30748. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  30749. derive your component from this class, and make sure that it is somewhere inside a
  30750. DragAndDropContainer component.
  30751. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30752. the operating system onto your component, you don't need any of these classes: instead
  30753. see the FileDragAndDropTarget class.
  30754. @see DragAndDropContainer, FileDragAndDropTarget
  30755. */
  30756. class JUCE_API DragAndDropTarget
  30757. {
  30758. public:
  30759. /** Destructor. */
  30760. virtual ~DragAndDropTarget() {}
  30761. /** Callback to check whether this target is interested in the type of object being
  30762. dragged.
  30763. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30764. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30765. @returns true if this component wants to receive the other callbacks regarging this
  30766. type of object; if it returns false, no other callbacks will be made.
  30767. */
  30768. virtual bool isInterestedInDragSource (const String& sourceDescription,
  30769. Component* sourceComponent) = 0;
  30770. /** Callback to indicate that something is being dragged over this component.
  30771. This gets called when the user moves the mouse into this component while dragging
  30772. something.
  30773. Use this callback as a trigger to make your component repaint itself to give the
  30774. user feedback about whether the item can be dropped here or not.
  30775. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30776. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30777. @param x the mouse x position, relative to this component
  30778. @param y the mouse y position, relative to this component
  30779. @see itemDragExit
  30780. */
  30781. virtual void itemDragEnter (const String& sourceDescription,
  30782. Component* sourceComponent,
  30783. int x,
  30784. int y);
  30785. /** Callback to indicate that the user is dragging something over this component.
  30786. This gets called when the user moves the mouse over this component while dragging
  30787. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  30788. this lets you know what happens in-between.
  30789. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30790. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30791. @param x the mouse x position, relative to this component
  30792. @param y the mouse y position, relative to this component
  30793. */
  30794. virtual void itemDragMove (const String& sourceDescription,
  30795. Component* sourceComponent,
  30796. int x,
  30797. int y);
  30798. /** Callback to indicate that something has been dragged off the edge of this component.
  30799. This gets called when the user moves the mouse out of this component while dragging
  30800. something.
  30801. If you've used itemDragEnter() to repaint your component and give feedback, use this
  30802. as a signal to repaint it in its normal state.
  30803. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30804. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30805. @see itemDragEnter
  30806. */
  30807. virtual void itemDragExit (const String& sourceDescription,
  30808. Component* sourceComponent);
  30809. /** Callback to indicate that the user has dropped something onto this component.
  30810. When the user drops an item this get called, and you can use the description to
  30811. work out whether your object wants to deal with it or not.
  30812. Note that after this is called, the itemDragExit method may not be called, so you should
  30813. clean up in here if there's anything you need to do when the drag finishes.
  30814. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30815. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30816. @param x the mouse x position, relative to this component
  30817. @param y the mouse y position, relative to this component
  30818. */
  30819. virtual void itemDropped (const String& sourceDescription,
  30820. Component* sourceComponent,
  30821. int x,
  30822. int y) = 0;
  30823. /** Overriding this allows the target to tell the drag container whether to
  30824. draw the drag image while the cursor is over it.
  30825. By default it returns true, but if you return false, then the normal drag
  30826. image will not be shown when the cursor is over this target.
  30827. */
  30828. virtual bool shouldDrawDragImageWhenOver();
  30829. };
  30830. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30831. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  30832. /**
  30833. Enables drag-and-drop behaviour for a component and all its sub-components.
  30834. For a component to be able to make or receive drag-and-drop events, one of its parent
  30835. components must derive from this class. It's probably best for the top-level
  30836. component to implement it.
  30837. Then to start a drag operation, any sub-component can just call the startDragging()
  30838. method, and this object will take over, tracking the mouse and sending appropriate
  30839. callbacks to any child components derived from DragAndDropTarget which the mouse
  30840. moves over.
  30841. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30842. the operating system onto your component, you don't need any of these classes: you can do this
  30843. simply by overriding Component::filesDropped().
  30844. @see DragAndDropTarget
  30845. */
  30846. class JUCE_API DragAndDropContainer
  30847. {
  30848. public:
  30849. /** Creates a DragAndDropContainer.
  30850. The object that derives from this class must also be a Component.
  30851. */
  30852. DragAndDropContainer();
  30853. /** Destructor. */
  30854. virtual ~DragAndDropContainer();
  30855. /** Begins a drag-and-drop operation.
  30856. This starts a drag-and-drop operation - call it when the user drags the
  30857. mouse in your drag-source component, and this object will track mouse
  30858. movements until the user lets go of the mouse button, and will send
  30859. appropriate messages to DragAndDropTarget objects that the mouse moves
  30860. over.
  30861. findParentDragContainerFor() is a handy method to call to find the
  30862. drag container to use for a component.
  30863. @param sourceDescription a string to use as the description of the thing being
  30864. dragged - this will be passed to the objects that might be
  30865. dropped-onto so they can decide if they want to handle it or
  30866. not
  30867. @param sourceComponent the component that is being dragged
  30868. @param dragImage the image to drag around underneath the mouse. If this is
  30869. zero, a snapshot of the sourceComponent will be used instead. An
  30870. image passed-in will be deleted by this object when no longer
  30871. needed.
  30872. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  30873. window, and can be dragged to DragAndDropTargets that are the
  30874. children of components other than this one.
  30875. */
  30876. void startDragging (const String& sourceDescription,
  30877. Component* sourceComponent,
  30878. Image* dragImage = 0,
  30879. const bool allowDraggingToOtherJuceWindows = false);
  30880. /** Returns true if something is currently being dragged. */
  30881. bool isDragAndDropActive() const;
  30882. /** Returns the description of the thing that's currently being dragged.
  30883. If nothing's being dragged, this will return an empty string, otherwise it's the
  30884. string that was passed into startDragging().
  30885. @see startDragging
  30886. */
  30887. const String getCurrentDragDescription() const;
  30888. /** Utility to find the DragAndDropContainer for a given Component.
  30889. This will search up this component's parent hierarchy looking for the first
  30890. parent component which is a DragAndDropContainer.
  30891. It's useful when a component wants to call startDragging but doesn't know
  30892. the DragAndDropContainer it should to use.
  30893. Obviously this may return 0 if it doesn't find a suitable component.
  30894. */
  30895. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  30896. /** This performs a synchronous drag-and-drop of a set of files to some external
  30897. application.
  30898. You can call this function in response to a mouseDrag callback, and it will
  30899. block, running its own internal message loop and tracking the mouse, while it
  30900. uses a native operating system drag-and-drop operation to move or copy some
  30901. files to another application.
  30902. @param files a list of filenames to drag
  30903. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  30904. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  30905. @returns true if the files were successfully dropped somewhere, or false if it
  30906. was interrupted
  30907. @see performExternalDragDropOfText
  30908. */
  30909. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  30910. /** This performs a synchronous drag-and-drop of a block of text to some external
  30911. application.
  30912. You can call this function in response to a mouseDrag callback, and it will
  30913. block, running its own internal message loop and tracking the mouse, while it
  30914. uses a native operating system drag-and-drop operation to move or copy some
  30915. text to another application.
  30916. @param text the text to copy
  30917. @returns true if the text was successfully dropped somewhere, or false if it
  30918. was interrupted
  30919. @see performExternalDragDropOfFiles
  30920. */
  30921. static bool performExternalDragDropOfText (const String& text);
  30922. juce_UseDebuggingNewOperator
  30923. protected:
  30924. /** Override this if you want to be able to perform an external drag a set of files
  30925. when the user drags outside of this container component.
  30926. This method will be called when a drag operation moves outside the Juce-based window,
  30927. and if you want it to then perform a file drag-and-drop, add the filenames you want
  30928. to the array passed in, and return true.
  30929. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  30930. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  30931. @param files on return, the filenames you want to drag
  30932. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  30933. it must make a copy of them (see the performExternalDragDropOfFiles()
  30934. method)
  30935. @see performExternalDragDropOfFiles
  30936. */
  30937. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  30938. Component* dragSourceComponent,
  30939. StringArray& files,
  30940. bool& canMoveFiles);
  30941. private:
  30942. friend class DragImageComponent;
  30943. Component* dragImageComponent;
  30944. String currentDragDesc;
  30945. };
  30946. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30947. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  30948. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  30949. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30950. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30951. /**
  30952. Animates a set of components, moving it to a new position.
  30953. To use this, create a ComponentAnimator, and use its animateComponent() method
  30954. to tell it to move components to destination positions. Any number of
  30955. components can be animated by one ComponentAnimator object (if you've got a
  30956. lot of components to move, it's much more efficient to share a single animator
  30957. than to have many animators running at once).
  30958. You'll need to make sure the animator object isn't deleted before it finishes
  30959. moving the components.
  30960. */
  30961. class JUCE_API ComponentAnimator : private Timer
  30962. {
  30963. public:
  30964. /** Creates a ComponentAnimator. */
  30965. ComponentAnimator();
  30966. /** Destructor. */
  30967. ~ComponentAnimator();
  30968. /** Starts a component moving from its current position to a specified position.
  30969. If the component is already in the middle of an animation, that will be abandoned,
  30970. and a new animation will begin, moving the component from its current location.
  30971. The start and end speed parameters let you apply some acceleration to the component's
  30972. movement.
  30973. @param component the component to move
  30974. @param finalPosition the destination position and size to move it to
  30975. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  30976. to arrive at its destination
  30977. @param startSpeed a value to indicate the relative start speed of the
  30978. animation. If this is 0, the component will start
  30979. by accelerating from rest; higher values mean that it
  30980. will have an initial speed greater than zero. If the
  30981. value if greater than 1, it will decelerate towards the
  30982. middle of its journey. To move the component at a constant
  30983. rate for its entire animation, set both the start and
  30984. end speeds to 1.0
  30985. @param endSpeed a relative speed at which the component should be moving
  30986. when the animation finishes. If this is 0, the component
  30987. will decelerate to a standstill at its final position; higher
  30988. values mean the component will still be moving when it stops.
  30989. To move the component at a constant rate for its entire
  30990. animation, set both the start and end speeds to 1.0
  30991. */
  30992. void animateComponent (Component* const component,
  30993. const Rectangle& finalPosition,
  30994. const int millisecondsToSpendMoving,
  30995. const double startSpeed = 1.0,
  30996. const double endSpeed = 1.0);
  30997. /** Stops a component if it's currently being animated.
  30998. If moveComponentToItsFinalPosition is true, then the component will
  30999. be immediately moved to its destination position and size. If false, it will be
  31000. left in whatever location it currently occupies.
  31001. */
  31002. void cancelAnimation (Component* const component,
  31003. const bool moveComponentToItsFinalPosition);
  31004. /** Clears all of the active animations.
  31005. If moveComponentsToTheirFinalPositions is true, all the components will
  31006. be immediately set to their final positions. If false, they will be
  31007. left in whatever locations they currently occupy.
  31008. */
  31009. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31010. /** Returns the destination position for a component.
  31011. If the component is being animated, this will return the target position that
  31012. was specified when animateComponent() was called.
  31013. If the specified component isn't currently being animated, this method will just
  31014. return its current position.
  31015. */
  31016. const Rectangle getComponentDestination (Component* const component);
  31017. juce_UseDebuggingNewOperator
  31018. private:
  31019. VoidArray tasks;
  31020. uint32 lastTime;
  31021. void* findTaskFor (Component* const component) const;
  31022. void timerCallback();
  31023. };
  31024. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31025. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31026. class ToolbarItemComponent;
  31027. class ToolbarItemFactory;
  31028. class MissingItemsComponent;
  31029. /**
  31030. A toolbar component.
  31031. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31032. and looks after their order and layout.
  31033. Items (icon buttons or other custom components) are added to a toolbar using a
  31034. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31035. toolbar might contain more than one instance of a particular item type.
  31036. Toolbars can be interactively customised, allowing the user to drag the items
  31037. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31038. component as a source of new items.
  31039. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31040. */
  31041. class JUCE_API Toolbar : public Component,
  31042. public DragAndDropContainer,
  31043. public DragAndDropTarget,
  31044. private ButtonListener
  31045. {
  31046. public:
  31047. /** Creates an empty toolbar component.
  31048. To add some icons or other components to your toolbar, you'll need to
  31049. create a ToolbarItemFactory class that can create a suitable set of
  31050. ToolbarItemComponents.
  31051. @see ToolbarItemFactory, ToolbarItemComponents
  31052. */
  31053. Toolbar();
  31054. /** Destructor.
  31055. Any items on the bar will be deleted when the toolbar is deleted.
  31056. */
  31057. ~Toolbar();
  31058. /** Changes the bar's orientation.
  31059. @see isVertical
  31060. */
  31061. void setVertical (const bool shouldBeVertical);
  31062. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31063. You can change the bar's orientation with setVertical().
  31064. */
  31065. bool isVertical() const throw() { return vertical; }
  31066. /** Returns the depth of the bar.
  31067. If the bar is horizontal, this will return its height; if it's vertical, it
  31068. will return its width.
  31069. @see getLength
  31070. */
  31071. int getThickness() const throw();
  31072. /** Returns the length of the bar.
  31073. If the bar is horizontal, this will return its width; if it's vertical, it
  31074. will return its height.
  31075. @see getThickness
  31076. */
  31077. int getLength() const throw();
  31078. /** Deletes all items from the bar.
  31079. */
  31080. void clear();
  31081. /** Adds an item to the toolbar.
  31082. The factory's ToolbarItemFactory::createItem() will be called by this method
  31083. to create the component that will actually be added to the bar.
  31084. The new item will be inserted at the specified index (if the index is -1, it
  31085. will be added to the right-hand or bottom end of the bar).
  31086. Once added, the component will be automatically deleted by this object when it
  31087. is no longer needed.
  31088. @see ToolbarItemFactory
  31089. */
  31090. void addItem (ToolbarItemFactory& factory,
  31091. const int itemId,
  31092. const int insertIndex = -1);
  31093. /** Deletes one of the items from the bar.
  31094. */
  31095. void removeToolbarItem (const int itemIndex);
  31096. /** Returns the number of items currently on the toolbar.
  31097. @see getItemId, getItemComponent
  31098. */
  31099. int getNumItems() const throw();
  31100. /** Returns the ID of the item with the given index.
  31101. If the index is less than zero or greater than the number of items,
  31102. this will return 0.
  31103. @see getNumItems
  31104. */
  31105. int getItemId (const int itemIndex) const throw();
  31106. /** Returns the component being used for the item with the given index.
  31107. If the index is less than zero or greater than the number of items,
  31108. this will return 0.
  31109. @see getNumItems
  31110. */
  31111. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31112. /** Clears this toolbar and adds to it the default set of items that the specified
  31113. factory creates.
  31114. @see ToolbarItemFactory::getDefaultItemSet
  31115. */
  31116. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31117. /** Options for the way items should be displayed.
  31118. @see setStyle, getStyle
  31119. */
  31120. enum ToolbarItemStyle
  31121. {
  31122. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31123. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31124. textOnly /**< Means that the toolbar only display text labels for each item. */
  31125. };
  31126. /** Returns the toolbar's current style.
  31127. @see ToolbarItemStyle, setStyle
  31128. */
  31129. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31130. /** Changes the toolbar's current style.
  31131. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31132. */
  31133. void setStyle (const ToolbarItemStyle& newStyle);
  31134. /** Flags used by the showCustomisationDialog() method. */
  31135. enum CustomisationFlags
  31136. {
  31137. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31138. show the "icons only" option on its choice of toolbar styles. */
  31139. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31140. show the "icons with text" option on its choice of toolbar styles. */
  31141. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31142. show the "text only" option on its choice of toolbar styles. */
  31143. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31144. show a button to reset the toolbar to its default set of items. */
  31145. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31146. };
  31147. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31148. The dialog contains a ToolbarItemPalette and various controls for editing other
  31149. aspects of the toolbar. This method will block and run the dialog box modally,
  31150. returning when the user closes it.
  31151. The factory is used to determine the set of items that will be shown on the
  31152. palette.
  31153. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31154. enum.
  31155. @see ToolbarItemPalette
  31156. */
  31157. void showCustomisationDialog (ToolbarItemFactory& factory,
  31158. const int optionFlags = allCustomisationOptionsEnabled);
  31159. /** Turns on or off the toolbar's editing mode, in which its items can be
  31160. rearranged by the user.
  31161. (In most cases it's easier just to use showCustomisationDialog() instead of
  31162. trying to enable editing directly).
  31163. @see ToolbarItemPalette
  31164. */
  31165. void setEditingActive (const bool editingEnabled);
  31166. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31167. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31168. methods.
  31169. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31170. */
  31171. enum ColourIds
  31172. {
  31173. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31174. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31175. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31176. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31177. over them. */
  31178. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31179. held down on them. */
  31180. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31181. when the style is set to iconsWithText or textOnly. */
  31182. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31183. the customisation dialog is active and the mouse moves over them. */
  31184. };
  31185. /** Returns a string that represents the toolbar's current set of items.
  31186. This lets you later restore the same item layout using restoreFromString().
  31187. @see restoreFromString
  31188. */
  31189. const String toString() const;
  31190. /** Restores a set of items that was previously stored in a string by the toString()
  31191. method.
  31192. The factory object is used to create any item components that are needed.
  31193. @see toString
  31194. */
  31195. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31196. const String& savedVersion);
  31197. /** @internal */
  31198. void paint (Graphics& g);
  31199. /** @internal */
  31200. void resized();
  31201. /** @internal */
  31202. void buttonClicked (Button*);
  31203. /** @internal */
  31204. void mouseDown (const MouseEvent&);
  31205. /** @internal */
  31206. bool isInterestedInDragSource (const String&, Component*);
  31207. /** @internal */
  31208. void itemDragMove (const String&, Component*, int, int);
  31209. /** @internal */
  31210. void itemDragExit (const String&, Component*);
  31211. /** @internal */
  31212. void itemDropped (const String&, Component*, int, int);
  31213. /** @internal */
  31214. void updateAllItemPositions (const bool animate);
  31215. /** @internal */
  31216. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31217. juce_UseDebuggingNewOperator
  31218. private:
  31219. Button* missingItemsButton;
  31220. bool vertical, isEditingActive;
  31221. ToolbarItemStyle toolbarStyle;
  31222. ComponentAnimator animator;
  31223. friend class MissingItemsComponent;
  31224. Array <ToolbarItemComponent*> items;
  31225. friend class ItemDragAndDropOverlayComponent;
  31226. static const tchar* const toolbarDragDescriptor;
  31227. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31228. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31229. Toolbar (const Toolbar&);
  31230. const Toolbar& operator= (const Toolbar&);
  31231. };
  31232. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31233. /********* End of inlined file: juce_Toolbar.h *********/
  31234. class ItemDragAndDropOverlayComponent;
  31235. /**
  31236. A component that can be used as one of the items in a Toolbar.
  31237. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31238. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31239. class for further info about creating them.
  31240. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31241. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31242. calling the constructor, and override contentAreaChanged(), in which you can position
  31243. any sub-components you need to add.
  31244. To add basic buttons without writing a special subclass, have a look at the
  31245. ToolbarButton class.
  31246. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31247. */
  31248. class JUCE_API ToolbarItemComponent : public Button
  31249. {
  31250. public:
  31251. /** Constructor.
  31252. @param itemId the ID of the type of toolbar item which this represents
  31253. @param labelText the text to display if the toolbar's style is set to
  31254. Toolbar::iconsWithText or Toolbar::textOnly
  31255. @param isBeingUsedAsAButton set this to false if you don't want the button
  31256. to draw itself with button over/down states when the mouse
  31257. moves over it or clicks
  31258. */
  31259. ToolbarItemComponent (const int itemId,
  31260. const String& labelText,
  31261. const bool isBeingUsedAsAButton);
  31262. /** Destructor. */
  31263. ~ToolbarItemComponent();
  31264. /** Returns the item type ID that this component represents.
  31265. This value is in the constructor.
  31266. */
  31267. int getItemId() const throw() { return itemId; }
  31268. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31269. inside one.
  31270. */
  31271. Toolbar* getToolbar() const;
  31272. /** Returns true if this component is currently inside a toolbar which is vertical.
  31273. @see Toolbar::isVertical
  31274. */
  31275. bool isToolbarVertical() const;
  31276. /** Returns the current style setting of this item.
  31277. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31278. @see setStyle, Toolbar::getStyle
  31279. */
  31280. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31281. /** Changes the current style setting of this item.
  31282. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31283. by the toolbar that holds this item.
  31284. @see setStyle, Toolbar::setStyle
  31285. */
  31286. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31287. /** Returns the area of the component that should be used to display the button image or
  31288. other contents of the item.
  31289. This content area may change when the item's style changes, and may leave a space around the
  31290. edge of the component where the text label can be shown.
  31291. @see contentAreaChanged
  31292. */
  31293. const Rectangle getContentArea() const throw() { return contentArea; }
  31294. /** This method must return the size criteria for this item, based on a given toolbar
  31295. size and orientation.
  31296. The preferredSize, minSize and maxSize values must all be set by your implementation
  31297. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31298. toolbar, they refer to the item's height.
  31299. The preferredSize is the size that the component would like to be, and this must be
  31300. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31301. the same value.
  31302. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31303. Toolbar::getThickness().
  31304. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31305. vertically.
  31306. */
  31307. virtual bool getToolbarItemSizes (int toolbarThickness,
  31308. bool isToolbarVertical,
  31309. int& preferredSize,
  31310. int& minSize,
  31311. int& maxSize) = 0;
  31312. /** Your subclass should use this method to draw its content area.
  31313. The graphics object that is passed-in will have been clipped and had its origin
  31314. moved to fit the content area as specified get getContentArea(). The width and height
  31315. parameters are the width and height of the content area.
  31316. If the component you're writing isn't a button, you can just do nothing in this method.
  31317. */
  31318. virtual void paintButtonArea (Graphics& g,
  31319. int width, int height,
  31320. bool isMouseOver, bool isMouseDown) = 0;
  31321. /** Callback to indicate that the content area of this item has changed.
  31322. This might be because the component was resized, or because the style changed and
  31323. the space needed for the text label is different.
  31324. See getContentArea() for a description of what the area is.
  31325. */
  31326. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31327. /** Editing modes.
  31328. These are used by setEditingMode(), but will be rarely needed in user code.
  31329. */
  31330. enum ToolbarEditingMode
  31331. {
  31332. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31333. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31334. customisation mode, and the items can be dragged around. */
  31335. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31336. dragged onto a toolbar to add it to that bar.*/
  31337. };
  31338. /** Changes the editing mode of this component.
  31339. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31340. and is unlikely to be of much use in end-user-code.
  31341. */
  31342. void setEditingMode (const ToolbarEditingMode newMode);
  31343. /** Returns the current editing mode of this component.
  31344. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31345. and is unlikely to be of much use in end-user-code.
  31346. */
  31347. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31348. /** @internal */
  31349. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31350. /** @internal */
  31351. void resized();
  31352. juce_UseDebuggingNewOperator
  31353. private:
  31354. friend class Toolbar;
  31355. friend class ItemDragAndDropOverlayComponent;
  31356. const int itemId;
  31357. ToolbarEditingMode mode;
  31358. Toolbar::ToolbarItemStyle toolbarStyle;
  31359. Component* overlayComp;
  31360. int dragOffsetX, dragOffsetY;
  31361. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31362. Rectangle contentArea;
  31363. ToolbarItemComponent (const ToolbarItemComponent&);
  31364. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31365. };
  31366. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31367. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31368. /**
  31369. A type of button designed to go on a toolbar.
  31370. This simple button can have two Drawable objects specified - one for normal
  31371. use and another one (optionally) for the button's "on" state if it's a
  31372. toggle button.
  31373. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31374. */
  31375. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31376. {
  31377. public:
  31378. /** Creates a ToolbarButton.
  31379. @param itemId the ID for this toolbar item type. This is passed through to the
  31380. ToolbarItemComponent constructor
  31381. @param labelText the text to display on the button (if the toolbar is using a style
  31382. that shows text labels). This is passed through to the
  31383. ToolbarItemComponent constructor
  31384. @param normalImage a drawable object that the button should use as its icon. The object
  31385. that is passed-in here will be kept by this object and will be
  31386. deleted when no longer needed or when this button is deleted.
  31387. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31388. is in a toggled-on state (see the Button::getToggleState() method). If
  31389. 0 is passed-in here, then the normal image will be used instead, regardless
  31390. of the toggle state. The object that is passed-in here will be kept by
  31391. this object and will be deleted when no longer needed or when this button
  31392. is deleted.
  31393. */
  31394. ToolbarButton (const int itemId,
  31395. const String& labelText,
  31396. Drawable* const normalImage,
  31397. Drawable* const toggledOnImage);
  31398. /** Destructor. */
  31399. ~ToolbarButton();
  31400. /** @internal */
  31401. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31402. int& minSize, int& maxSize);
  31403. /** @internal */
  31404. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31405. /** @internal */
  31406. void contentAreaChanged (const Rectangle& newBounds);
  31407. juce_UseDebuggingNewOperator
  31408. private:
  31409. Drawable* const normalImage;
  31410. Drawable* const toggledOnImage;
  31411. ToolbarButton (const ToolbarButton&);
  31412. const ToolbarButton& operator= (const ToolbarButton&);
  31413. };
  31414. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31415. /********* End of inlined file: juce_ToolbarButton.h *********/
  31416. #endif
  31417. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31418. #endif
  31419. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31420. /********* Start of inlined file: juce_GlowEffect.h *********/
  31421. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31422. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31423. /**
  31424. A component effect that adds a coloured blur around the component's contents.
  31425. (This will only work on non-opaque components).
  31426. @see Component::setComponentEffect, DropShadowEffect
  31427. */
  31428. class JUCE_API GlowEffect : public ImageEffectFilter
  31429. {
  31430. public:
  31431. /** Creates a default 'glow' effect.
  31432. To customise its appearance, use the setGlowProperties() method.
  31433. */
  31434. GlowEffect();
  31435. /** Destructor. */
  31436. ~GlowEffect();
  31437. /** Sets the glow's radius and colour.
  31438. The radius is how large the blur should be, and the colour is
  31439. used to render it (for a less intense glow, lower the colour's
  31440. opacity).
  31441. */
  31442. void setGlowProperties (const float newRadius,
  31443. const Colour& newColour);
  31444. /** @internal */
  31445. void applyEffect (Image& sourceImage, Graphics& destContext);
  31446. juce_UseDebuggingNewOperator
  31447. private:
  31448. float radius;
  31449. Colour colour;
  31450. };
  31451. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31452. /********* End of inlined file: juce_GlowEffect.h *********/
  31453. #endif
  31454. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31455. #endif
  31456. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31457. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31458. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31459. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31460. /**
  31461. An effect filter that reduces the image's opacity.
  31462. This can be used to make a component (and its child components) more
  31463. transparent.
  31464. @see Component::setComponentEffect
  31465. */
  31466. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31467. {
  31468. public:
  31469. /** Creates the effect object.
  31470. The opacity of the component to which the effect is applied will be
  31471. scaled by the given factor (in the range 0 to 1.0f).
  31472. */
  31473. ReduceOpacityEffect (const float opacity = 1.0f);
  31474. /** Destructor. */
  31475. ~ReduceOpacityEffect();
  31476. /** Sets how much to scale the component's opacity.
  31477. @param newOpacity should be between 0 and 1.0f
  31478. */
  31479. void setOpacity (const float newOpacity);
  31480. /** @internal */
  31481. void applyEffect (Image& sourceImage, Graphics& destContext);
  31482. juce_UseDebuggingNewOperator
  31483. private:
  31484. float opacity;
  31485. };
  31486. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31487. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31488. #endif
  31489. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31490. #endif
  31491. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31492. #endif
  31493. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31494. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31495. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31496. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31497. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31498. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31499. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31500. /**
  31501. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31502. command in a ApplicationCommandManager.
  31503. Normally, you won't actually create a KeyPressMappingSet directly, because
  31504. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  31505. you'd create yourself an ApplicationCommandManager, and call its
  31506. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  31507. KeyPressMappingSet.
  31508. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  31509. to the top-level component for which you want to handle keystrokes. So for example:
  31510. @code
  31511. class MyMainWindow : public Component
  31512. {
  31513. ApplicationCommandManager* myCommandManager;
  31514. public:
  31515. MyMainWindow()
  31516. {
  31517. myCommandManager = new ApplicationCommandManager();
  31518. // first, make sure the command manager has registered all the commands that its
  31519. // targets can perform..
  31520. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  31521. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  31522. // this will use the command manager to initialise the KeyPressMappingSet with
  31523. // the default keypresses that were specified when the targets added their commands
  31524. // to the manager.
  31525. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  31526. // having set up the default key-mappings, you might now want to load the last set
  31527. // of mappings that the user configured.
  31528. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  31529. // Now tell our top-level window to send any keypresses that arrive to the
  31530. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  31531. addKeyListener (myCommandManager->getKeyMappings());
  31532. }
  31533. ...
  31534. }
  31535. @endcode
  31536. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  31537. register to be told when a command or mapping is added, removed, etc.
  31538. There's also a UI component called KeyMappingEditorComponent that can be used
  31539. to easily edit the key mappings.
  31540. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  31541. */
  31542. class JUCE_API KeyPressMappingSet : public KeyListener,
  31543. public ChangeBroadcaster,
  31544. public FocusChangeListener
  31545. {
  31546. public:
  31547. /** Creates a KeyPressMappingSet for a given command manager.
  31548. Normally, you won't actually create a KeyPressMappingSet directly, because
  31549. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  31550. best thing to do is to create your ApplicationCommandManager, and use the
  31551. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  31552. When a suitable keypress happens, the manager's invoke() method will be
  31553. used to invoke the appropriate command.
  31554. @see ApplicationCommandManager
  31555. */
  31556. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  31557. /** Creates an copy of a KeyPressMappingSet. */
  31558. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  31559. /** Destructor. */
  31560. ~KeyPressMappingSet();
  31561. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  31562. /** Returns a list of keypresses that are assigned to a particular command.
  31563. @param commandID the command's ID
  31564. */
  31565. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  31566. /** Assigns a keypress to a command.
  31567. If the keypress is already assigned to a different command, it will first be
  31568. removed from that command, to avoid it triggering multiple functions.
  31569. @param commandID the ID of the command that you want to add a keypress to. If
  31570. this is 0, the keypress will be removed from anything that it
  31571. was previously assigned to, but not re-assigned
  31572. @param newKeyPress the new key-press
  31573. @param insertIndex if this is less than zero, the key will be appended to the
  31574. end of the list of keypresses; otherwise the new keypress will
  31575. be inserted into the existing list at this index
  31576. */
  31577. void addKeyPress (const CommandID commandID,
  31578. const KeyPress& newKeyPress,
  31579. int insertIndex = -1) throw();
  31580. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  31581. @see resetToDefaultMapping
  31582. */
  31583. void resetToDefaultMappings() throw();
  31584. /** Resets all key-mappings to the defaults for a particular command.
  31585. @see resetToDefaultMappings
  31586. */
  31587. void resetToDefaultMapping (const CommandID commandID) throw();
  31588. /** Removes all keypresses that are assigned to any commands. */
  31589. void clearAllKeyPresses() throw();
  31590. /** Removes all keypresses that are assigned to a particular command. */
  31591. void clearAllKeyPresses (const CommandID commandID) throw();
  31592. /** Removes one of the keypresses that are assigned to a command.
  31593. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  31594. which the keyPressIndex refers.
  31595. */
  31596. void removeKeyPress (const CommandID commandID,
  31597. const int keyPressIndex) throw();
  31598. /** Removes a keypress from any command that it may be assigned to.
  31599. */
  31600. void removeKeyPress (const KeyPress& keypress) throw();
  31601. /** Returns true if the given command is linked to this key. */
  31602. bool containsMapping (const CommandID commandID,
  31603. const KeyPress& keyPress) const throw();
  31604. /** Looks for a command that corresponds to a keypress.
  31605. @returns the UID of the command or 0 if none was found
  31606. */
  31607. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  31608. /** Tries to recreate the mappings from a previously stored state.
  31609. The XML passed in must have been created by the createXml() method.
  31610. If the stored state makes any reference to commands that aren't
  31611. currently available, these will be ignored.
  31612. If the set of mappings being loaded was a set of differences (using createXml (true)),
  31613. then this will call resetToDefaultMappings() and then merge the saved mappings
  31614. on top. If the saved set was created with createXml (false), then this method
  31615. will first clear all existing mappings and load the saved ones as a complete set.
  31616. @returns true if it manages to load the XML correctly
  31617. @see createXml
  31618. */
  31619. bool restoreFromXml (const XmlElement& xmlVersion);
  31620. /** Creates an XML representation of the current mappings.
  31621. This will produce a lump of XML that can be later reloaded using
  31622. restoreFromXml() to recreate the current mapping state.
  31623. The object that is returned must be deleted by the caller.
  31624. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  31625. will be saved into the XML. If it's true, then the XML will
  31626. only store the differences between the current mappings and
  31627. the default mappings you'd get from calling resetToDefaultMappings().
  31628. The advantage of saving a set of differences from the default is that
  31629. if you change the default mappings (in a new version of your app, for
  31630. example), then these will be merged into a user's saved preferences.
  31631. @see restoreFromXml
  31632. */
  31633. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  31634. /** @internal */
  31635. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31636. /** @internal */
  31637. bool keyStateChanged (Component* originatingComponent);
  31638. /** @internal */
  31639. void globalFocusChanged (Component* focusedComponent);
  31640. juce_UseDebuggingNewOperator
  31641. private:
  31642. ApplicationCommandManager* commandManager;
  31643. struct CommandMapping
  31644. {
  31645. CommandID commandID;
  31646. Array <KeyPress> keypresses;
  31647. bool wantsKeyUpDownCallbacks;
  31648. };
  31649. OwnedArray <CommandMapping> mappings;
  31650. struct KeyPressTime
  31651. {
  31652. KeyPress key;
  31653. uint32 timeWhenPressed;
  31654. };
  31655. OwnedArray <KeyPressTime> keysDown;
  31656. void handleMessage (const Message& message);
  31657. void invokeCommand (const CommandID commandID,
  31658. const KeyPress& keyPress,
  31659. const bool isKeyDown,
  31660. const int millisecsSinceKeyPressed,
  31661. Component* const originatingComponent) const;
  31662. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  31663. };
  31664. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31665. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  31666. /********* Start of inlined file: juce_TreeView.h *********/
  31667. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  31668. #define __JUCE_TREEVIEW_JUCEHEADER__
  31669. class TreeView;
  31670. /**
  31671. An item in a treeview.
  31672. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  31673. own sub-items.
  31674. To implement an item that contains sub-items, override the itemOpennessChanged()
  31675. method so that when it is opened, it adds the new sub-items to itself using the
  31676. addSubItem method. Depending on the nature of the item it might choose to only
  31677. do this the first time it's opened, or it might want to refresh itself each time.
  31678. It also has the option of deleting its sub-items when it is closed, or leaving them
  31679. in place.
  31680. */
  31681. class JUCE_API TreeViewItem
  31682. {
  31683. public:
  31684. /** Constructor. */
  31685. TreeViewItem();
  31686. /** Destructor. */
  31687. virtual ~TreeViewItem();
  31688. /** Returns the number of sub-items that have been added to this item.
  31689. Note that this doesn't mean much if the node isn't open.
  31690. @see getSubItem, mightContainSubItems, addSubItem
  31691. */
  31692. int getNumSubItems() const throw();
  31693. /** Returns one of the item's sub-items.
  31694. Remember that the object returned might get deleted at any time when its parent
  31695. item is closed or refreshed, depending on the nature of the items you're using.
  31696. @see getNumSubItems
  31697. */
  31698. TreeViewItem* getSubItem (const int index) const throw();
  31699. /** Removes any sub-items. */
  31700. void clearSubItems();
  31701. /** Adds a sub-item.
  31702. @param newItem the object to add to the item's sub-item list. Once added, these can be
  31703. found using getSubItem(). When the items are later removed with
  31704. removeSubItem() (or when this item is deleted), they will be deleted.
  31705. @param insertPosition the index which the new item should have when it's added. If this
  31706. value is less than 0, the item will be added to the end of the list.
  31707. */
  31708. void addSubItem (TreeViewItem* const newItem,
  31709. const int insertPosition = -1);
  31710. /** Removes one of the sub-items.
  31711. @param index the item to remove
  31712. @param deleteItem if true, the item that is removed will also be deleted.
  31713. */
  31714. void removeSubItem (const int index,
  31715. const bool deleteItem = true);
  31716. /** Returns the TreeView to which this item belongs. */
  31717. TreeView* getOwnerView() const throw() { return ownerView; }
  31718. /** Returns the item within which this item is contained. */
  31719. TreeViewItem* getParentItem() const throw() { return parentItem; }
  31720. /** True if this item is currently open in the treeview. */
  31721. bool isOpen() const throw();
  31722. /** Opens or closes the item.
  31723. When opened or closed, the item's itemOpennessChanged() method will be called,
  31724. and a subclass should use this callback to create and add any sub-items that
  31725. it needs to.
  31726. @see itemOpennessChanged, mightContainSubItems
  31727. */
  31728. void setOpen (const bool shouldBeOpen);
  31729. /** True if this item is currently selected.
  31730. Use this when painting the node, to decide whether to draw it as selected or not.
  31731. */
  31732. bool isSelected() const throw();
  31733. /** Selects or deselects the item.
  31734. This will cause a callback to itemSelectionChanged()
  31735. */
  31736. void setSelected (const bool shouldBeSelected,
  31737. const bool deselectOtherItemsFirst);
  31738. /** Returns the rectangle that this item occupies.
  31739. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  31740. top-left of the TreeView comp, so this will depend on the scroll-position of
  31741. the tree. If false, it is relative to the top-left of the topmost item in the
  31742. tree (so this would be unaffected by scrolling the view).
  31743. */
  31744. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  31745. /** Sends a signal to the treeview to make it refresh itself.
  31746. Call this if your items have changed and you want the tree to update to reflect
  31747. this.
  31748. */
  31749. void treeHasChanged() const throw();
  31750. /** Returns the row number of this item in the tree.
  31751. The row number of an item will change according to which items are open.
  31752. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  31753. */
  31754. int getRowNumberInTree() const throw();
  31755. /** Changes whether lines are drawn to connect any sub-items to this item.
  31756. By default, line-drawing is turned on.
  31757. */
  31758. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  31759. /** Tells the tree whether this item can potentially be opened.
  31760. If your item could contain sub-items, this should return true; if it returns
  31761. false then the tree will not try to open the item. This determines whether or
  31762. not the item will be drawn with a 'plus' button next to it.
  31763. */
  31764. virtual bool mightContainSubItems() = 0;
  31765. /** Returns a string to uniquely identify this item.
  31766. If you're planning on using the TreeView::getOpennessState() method, then
  31767. these strings will be used to identify which nodes are open. The string
  31768. should be unique amongst the item's sibling items, but it's ok for there
  31769. to be duplicates at other levels of the tree.
  31770. If you're not going to store the state, then it's ok not to bother implementing
  31771. this method.
  31772. */
  31773. virtual const String getUniqueName() const;
  31774. /** Called when an item is opened or closed.
  31775. When setOpen() is called and the item has specified that it might
  31776. have sub-items with the mightContainSubItems() method, this method
  31777. is called to let the item create or manage its sub-items.
  31778. So when this is called with isNowOpen set to true (i.e. when the item is being
  31779. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  31780. refresh its sub-item list.
  31781. When this is called with isNowOpen set to false, the subclass might want
  31782. to use clearSubItems() to save on space, or it might choose to leave them,
  31783. depending on the nature of the tree.
  31784. You could also use this callback as a trigger to start a background process
  31785. which asynchronously creates sub-items and adds them, if that's more
  31786. appropriate for the task in hand.
  31787. @see mightContainSubItems
  31788. */
  31789. virtual void itemOpennessChanged (bool isNowOpen);
  31790. /** Must return the width required by this item.
  31791. If your item needs to have a particular width in pixels, return that value; if
  31792. you'd rather have it just fill whatever space is available in the treeview,
  31793. return -1.
  31794. If all your items return -1, no horizontal scrollbar will be shown, but if any
  31795. items have fixed widths and extend beyond the width of the treeview, a
  31796. scrollbar will appear.
  31797. Each item can be a different width, but if they change width, you should call
  31798. treeHasChanged() to update the tree.
  31799. */
  31800. virtual int getItemWidth() const { return -1; }
  31801. /** Must return the height required by this item.
  31802. This is the height in pixels that the item will take up. Items in the tree
  31803. can be different heights, but if they change height, you should call
  31804. treeHasChanged() to update the tree.
  31805. */
  31806. virtual int getItemHeight() const { return 20; }
  31807. /** Creates a component that will be used to represent this item.
  31808. You don't have to implement this method - if it returns 0 then no component
  31809. will be used for the item, and you can just draw it using the paintItem()
  31810. callback. But if you do return a component, it will be positioned in the
  31811. treeview so that it can be used to represent this item.
  31812. The component returned will be managed by the treeview, so always return
  31813. a new component, and don't keep a reference to it, as the treeview will
  31814. delete it later when it goes off the screen or is no longer needed. Also
  31815. bear in mind that if the component keeps a reference to the item that
  31816. created it, that item could be deleted before the component. Its position
  31817. and size will be completely managed by the tree, so don't attempt to move it
  31818. around.
  31819. Something you may want to do with your component is to give it a pointer to
  31820. the TreeView that created it. This is perfectly safe, and there's no danger
  31821. of it becoming a dangling pointer because the TreeView will always delete
  31822. the component before it is itself deleted.
  31823. As long as you stick to these rules you can return whatever kind of
  31824. component you like. It's most useful if you're doing things like drag-and-drop
  31825. of items, or want to use a Label component to edit item names, etc.
  31826. */
  31827. virtual Component* createItemComponent() { return 0; }
  31828. /** Draws the item's contents.
  31829. You can choose to either implement this method and draw each item, or you
  31830. can use createItemComponent() to create a component that will represent the
  31831. item.
  31832. If all you need in your tree is to be able to draw the items and detect when
  31833. the user selects or double-clicks one of them, it's probably enough to
  31834. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  31835. complicated interactions, you may need to use createItemComponent() instead.
  31836. @param g the graphics context to draw into
  31837. @param width the width of the area available for drawing
  31838. @param height the height of the area available for drawing
  31839. */
  31840. virtual void paintItem (Graphics& g, int width, int height);
  31841. /** Called when the user clicks on this item.
  31842. If you're using createItemComponent() to create a custom component for the
  31843. item, the mouse-clicks might not make it through to the treeview, but this
  31844. is how you find out about clicks when just drawing each item individually.
  31845. The associated mouse-event details are passed in, so you can find out about
  31846. which button, where it was, etc.
  31847. @see itemDoubleClicked
  31848. */
  31849. virtual void itemClicked (const MouseEvent& e);
  31850. /** Called when the user double-clicks on this item.
  31851. If you're using createItemComponent() to create a custom component for the
  31852. item, the mouse-clicks might not make it through to the treeview, but this
  31853. is how you find out about clicks when just drawing each item individually.
  31854. The associated mouse-event details are passed in, so you can find out about
  31855. which button, where it was, etc.
  31856. If not overridden, the base class method here will open or close the item as
  31857. if the 'plus' button had been clicked.
  31858. @see itemClicked
  31859. */
  31860. virtual void itemDoubleClicked (const MouseEvent& e);
  31861. /** Called when the item is selected or deselected.
  31862. Use this if you want to do something special when the item's selectedness
  31863. changes. By default it'll get repainted when this happens.
  31864. */
  31865. virtual void itemSelectionChanged (bool isNowSelected);
  31866. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  31867. If this returns a non-empty name then when the user drags an item, the treeview will
  31868. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  31869. a drag-and-drop operation, using this string as the source description, with the treeview
  31870. itself as the source component.
  31871. If you need more complex drag-and-drop behaviour, you can use custom components for
  31872. the items, and use those to trigger the drag.
  31873. @see DragAndDropContainer::startDragging
  31874. */
  31875. virtual const String getDragSourceDescription();
  31876. juce_UseDebuggingNewOperator
  31877. private:
  31878. TreeView* ownerView;
  31879. TreeViewItem* parentItem;
  31880. OwnedArray <TreeViewItem> subItems;
  31881. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  31882. int uid;
  31883. bool selected : 1;
  31884. bool redrawNeeded : 1;
  31885. bool drawLinesInside : 1;
  31886. unsigned int openness : 2;
  31887. friend class TreeView;
  31888. friend class TreeViewContentComponent;
  31889. void updatePositions (int newY);
  31890. int getIndentX() const throw();
  31891. void setOwnerView (TreeView* const newOwner) throw();
  31892. void paintRecursively (Graphics& g, int width);
  31893. TreeViewItem* findItemRecursively (int y) throw();
  31894. TreeViewItem* getDeepestOpenParentItem() throw();
  31895. void restoreFromXml (const XmlElement& e);
  31896. XmlElement* createXmlOpenness() const;
  31897. bool isLastOfSiblings() const throw();
  31898. TreeViewItem* getTopLevelItem() throw();
  31899. int getNumRows() const throw();
  31900. TreeViewItem* getItemOnRow (int index) throw();
  31901. void deselectAllRecursively();
  31902. int countSelectedItemsRecursively() const throw();
  31903. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  31904. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  31905. TreeViewItem (const TreeViewItem&);
  31906. const TreeViewItem& operator= (const TreeViewItem&);
  31907. };
  31908. /**
  31909. A tree-view component.
  31910. Use one of these to hold and display a structure of TreeViewItem objects.
  31911. */
  31912. class JUCE_API TreeView : public Component,
  31913. public SettableTooltipClient,
  31914. private AsyncUpdater
  31915. {
  31916. public:
  31917. /** Creates an empty treeview.
  31918. Once you've got a treeview component, you'll need to give it something to
  31919. display, using the setRootItem() method.
  31920. */
  31921. TreeView (const String& componentName = String::empty);
  31922. /** Destructor. */
  31923. ~TreeView();
  31924. /** Sets the item that is displayed in the treeview.
  31925. A tree has a single root item which contains as many sub-items as it needs. If
  31926. you want the tree to contain a number of root items, you should still use a single
  31927. root item above these, but hide it using setRootItemVisible().
  31928. You can pass in 0 to this method to clear the tree and remove its current root item.
  31929. The object passed in will not be deleted by the treeview, it's up to the caller
  31930. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  31931. this item until you've removed it from the tree, either by calling setRootItem (0),
  31932. or by deleting the tree first.
  31933. */
  31934. void setRootItem (TreeViewItem* const newRootItem);
  31935. /** Returns the tree's root item.
  31936. This will be the last object passed to setRootItem(), or 0 if none has been set.
  31937. */
  31938. TreeViewItem* getRootItem() const throw() { return rootItem; }
  31939. /** Changes whether the tree's root item is shown or not.
  31940. If the root item is hidden, only its sub-items will be shown in the treeview - this
  31941. lets you make the tree look as if it's got many root items. If it's hidden, this call
  31942. will also make sure the root item is open (otherwise the treeview would look empty).
  31943. */
  31944. void setRootItemVisible (const bool shouldBeVisible);
  31945. /** Returns true if the root item is visible.
  31946. @see setRootItemVisible
  31947. */
  31948. bool isRootItemVisible() const throw() { return rootItemVisible; }
  31949. /** Sets whether items are open or closed by default.
  31950. Normally, items are closed until the user opens them, but you can use this
  31951. to make them default to being open until explicitly closed.
  31952. @see areItemsOpenByDefault
  31953. */
  31954. void setDefaultOpenness (const bool isOpenByDefault);
  31955. /** Returns true if the tree's items default to being open.
  31956. @see setDefaultOpenness
  31957. */
  31958. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  31959. /** This sets a flag to indicate that the tree can be used for multi-selection.
  31960. You can always select multiple items internally by calling the
  31961. TreeViewItem::setSelected() method, but this flag indicates whether the user
  31962. is allowed to multi-select by clicking on the tree.
  31963. By default it is disabled.
  31964. @see isMultiSelectEnabled
  31965. */
  31966. void setMultiSelectEnabled (const bool canMultiSelect);
  31967. /** Returns whether multi-select has been enabled for the tree.
  31968. @see setMultiSelectEnabled
  31969. */
  31970. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  31971. /** Deselects any items that are currently selected. */
  31972. void clearSelectedItems();
  31973. /** Returns the number of items that are currently selected.
  31974. @see getSelectedItem, clearSelectedItems
  31975. */
  31976. int getNumSelectedItems() const throw();
  31977. /** Returns one of the selected items in the tree.
  31978. @param index the index, 0 to (getNumSelectedItems() - 1)
  31979. */
  31980. TreeViewItem* getSelectedItem (const int index) const throw();
  31981. /** Returns the number of rows the tree is using.
  31982. This will depend on which items are open.
  31983. @see TreeViewItem::getRowNumberInTree()
  31984. */
  31985. int getNumRowsInTree() const;
  31986. /** Returns the item on a particular row of the tree.
  31987. If the index is out of range, this will return 0.
  31988. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  31989. */
  31990. TreeViewItem* getItemOnRow (int index) const;
  31991. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  31992. void scrollToKeepItemVisible (TreeViewItem* item);
  31993. /** Returns the treeview's Viewport object. */
  31994. Viewport* getViewport() const throw() { return viewport; }
  31995. /** Returns the number of pixels by which each nested level of the tree is indented.
  31996. @see setIndentSize
  31997. */
  31998. int getIndentSize() const throw() { return indentSize; }
  31999. /** Changes the distance by which each nested level of the tree is indented.
  32000. @see getIndentSize
  32001. */
  32002. void setIndentSize (const int newIndentSize);
  32003. /** Saves the current state of open/closed nodes so it can be restored later.
  32004. This takes a snapshot of which nodes have been explicitly opened or closed,
  32005. and records it as XML. To identify node objects it uses the
  32006. TreeViewItem::getUniqueName() method to create named paths. This
  32007. means that the same state of open/closed nodes can be restored to a
  32008. completely different instance of the tree, as long as it contains nodes
  32009. whose unique names are the same.
  32010. The caller is responsible for deleting the object that is returned.
  32011. @param alsoIncludeScrollPosition if this is true, the state will also
  32012. include information about where the
  32013. tree has been scrolled to vertically,
  32014. so this can also be restored
  32015. @see restoreOpennessState
  32016. */
  32017. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32018. /** Restores a previously saved arrangement of open/closed nodes.
  32019. This will try to restore a snapshot of the tree's state that was created by
  32020. the getOpennessState() method. If any of the nodes named in the original
  32021. XML aren't present in this tree, they will be ignored.
  32022. @see getOpennessState
  32023. */
  32024. void restoreOpennessState (const XmlElement& newState);
  32025. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32026. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32027. methods.
  32028. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32029. */
  32030. enum ColourIds
  32031. {
  32032. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32033. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32034. };
  32035. /** @internal */
  32036. void paint (Graphics& g);
  32037. /** @internal */
  32038. void resized();
  32039. /** @internal */
  32040. bool keyPressed (const KeyPress& key);
  32041. /** @internal */
  32042. void colourChanged();
  32043. juce_UseDebuggingNewOperator
  32044. private:
  32045. friend class TreeViewItem;
  32046. friend class TreeViewContentComponent;
  32047. Viewport* viewport;
  32048. CriticalSection nodeAlterationLock;
  32049. TreeViewItem* rootItem;
  32050. int indentSize;
  32051. bool defaultOpenness : 1;
  32052. bool needsRecalculating : 1;
  32053. bool rootItemVisible : 1;
  32054. bool multiSelectEnabled : 1;
  32055. void itemsChanged() throw();
  32056. void handleAsyncUpdate();
  32057. void moveSelectedRow (int delta);
  32058. TreeView (const TreeView&);
  32059. const TreeView& operator= (const TreeView&);
  32060. };
  32061. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32062. /********* End of inlined file: juce_TreeView.h *********/
  32063. /**
  32064. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32065. object.
  32066. @see KeyPressMappingSet
  32067. */
  32068. class JUCE_API KeyMappingEditorComponent : public Component,
  32069. public TreeViewItem,
  32070. public ChangeListener,
  32071. private ButtonListener
  32072. {
  32073. public:
  32074. /** Creates a KeyMappingEditorComponent.
  32075. @param mappingSet this is the set of mappings to display and
  32076. edit. Make sure the mappings object is not
  32077. deleted before this component!
  32078. @param showResetToDefaultButton if true, then at the bottom of the
  32079. list, the component will include a 'reset to
  32080. defaults' button.
  32081. */
  32082. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32083. const bool showResetToDefaultButton);
  32084. /** Destructor. */
  32085. virtual ~KeyMappingEditorComponent();
  32086. /** Sets up the colours to use for parts of the component.
  32087. @param mainBackground colour to use for most of the background
  32088. @param textColour colour to use for the text
  32089. */
  32090. void setColours (const Colour& mainBackground,
  32091. const Colour& textColour);
  32092. /** Returns the KeyPressMappingSet that this component is acting upon.
  32093. */
  32094. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32095. /** Can be overridden if some commands need to be excluded from the list.
  32096. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32097. method to decide what to return, but you can override it to handle special cases.
  32098. */
  32099. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32100. /** Can be overridden to indicate that some commands are shown as read-only.
  32101. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32102. method to decide what to return, but you can override it to handle special cases.
  32103. */
  32104. virtual bool isCommandReadOnly (const CommandID commandID);
  32105. /** This can be overridden to let you change the format of the string used
  32106. to describe a keypress.
  32107. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32108. keys that are triggered by something else externally. If you override the
  32109. method, be sure to let the base class's method handle keys you're not
  32110. interested in.
  32111. */
  32112. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32113. /** @internal */
  32114. void parentHierarchyChanged();
  32115. /** @internal */
  32116. void resized();
  32117. /** @internal */
  32118. void changeListenerCallback (void*);
  32119. /** @internal */
  32120. bool mightContainSubItems();
  32121. /** @internal */
  32122. const String getUniqueName() const;
  32123. /** @internal */
  32124. void buttonClicked (Button* button);
  32125. juce_UseDebuggingNewOperator
  32126. private:
  32127. KeyPressMappingSet* mappings;
  32128. TreeView* tree;
  32129. friend class KeyMappingTreeViewItem;
  32130. friend class KeyCategoryTreeViewItem;
  32131. friend class KeyMappingItemComponent;
  32132. friend class KeyMappingChangeButton;
  32133. Colour backgroundColour, textColour;
  32134. TextButton* resetButton;
  32135. void assignNewKey (const CommandID commandID, int index);
  32136. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32137. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32138. };
  32139. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32140. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32141. #endif
  32142. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32143. #endif
  32144. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32145. #endif
  32146. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32147. #endif
  32148. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32149. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32150. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32151. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32152. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32153. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32154. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32155. class MenuBarModel;
  32156. /**
  32157. A class to receive callbacks when a MenuBarModel changes.
  32158. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32159. */
  32160. class JUCE_API MenuBarModelListener
  32161. {
  32162. public:
  32163. /** Destructor. */
  32164. virtual ~MenuBarModelListener() {}
  32165. /** This callback is made when items are changed in the menu bar model.
  32166. */
  32167. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32168. /** This callback is made when an application command is invoked that
  32169. is represented by one of the items in the menu bar model.
  32170. */
  32171. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32172. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32173. };
  32174. /**
  32175. A class for controlling MenuBar components.
  32176. This class is used to tell a MenuBar what menus to show, and to respond
  32177. to a menu being selected.
  32178. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32179. */
  32180. class JUCE_API MenuBarModel : private AsyncUpdater,
  32181. private ApplicationCommandManagerListener
  32182. {
  32183. public:
  32184. MenuBarModel() throw();
  32185. /** Destructor. */
  32186. virtual ~MenuBarModel();
  32187. /** Call this when some of your menu items have changed.
  32188. This method will cause a callback to any MenuBarListener objects that
  32189. are registered with this model.
  32190. If this model is displaying items from an ApplicationCommandManager, you
  32191. can use the setApplicationCommandManagerToWatch() method to cause
  32192. change messages to be sent automatically when the ApplicationCommandManager
  32193. is changed.
  32194. @see addListener, removeListener, MenuBarListener
  32195. */
  32196. void menuItemsChanged();
  32197. /** Tells the menu bar to listen to the specified command manager, and to update
  32198. itself when the commands change.
  32199. This will also allow it to flash a menu name when a command from that menu
  32200. is invoked using a keystroke.
  32201. */
  32202. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32203. /** Registers a listener for callbacks when the menu items in this model change.
  32204. The listener object will get callbacks when this object's menuItemsChanged()
  32205. method is called.
  32206. @see removeListener
  32207. */
  32208. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32209. /** Removes a listener.
  32210. @see addListener
  32211. */
  32212. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32213. /** This method must return a list of the names of the menus. */
  32214. virtual const StringArray getMenuBarNames() = 0;
  32215. /** This should return the popup menu to display for a given top-level menu.
  32216. @param topLevelMenuIndex the index of the top-level menu to show
  32217. @param menuName the name of the top-level menu item to show
  32218. */
  32219. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32220. const String& menuName) = 0;
  32221. /** This is called when a menu item has been clicked on.
  32222. @param menuItemID the item ID of the PopupMenu item that was selected
  32223. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32224. chosen (just in case you've used duplicate ID numbers
  32225. on more than one of the popup menus)
  32226. */
  32227. virtual void menuItemSelected (int menuItemID,
  32228. int topLevelMenuIndex) = 0;
  32229. #if JUCE_MAC || DOXYGEN
  32230. /** MAC ONLY - Sets the model that is currently being shown as the main
  32231. menu bar at the top of the screen on the Mac.
  32232. You can pass 0 to stop the current model being displayed. Be careful
  32233. not to delete a model while it is being used.
  32234. An optional extra menu can be specified, containing items to add to the top of
  32235. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  32236. an apple, it's the one next to it, with your application's name at the top
  32237. and the services menu etc on it). When one of these items is selected, the
  32238. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  32239. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  32240. object then newMenuBarModel must be non-null.
  32241. */
  32242. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  32243. const PopupMenu* extraAppleMenuItems = 0) throw();
  32244. /** MAC ONLY - Returns the menu model that is currently being shown as
  32245. the main menu bar.
  32246. */
  32247. static MenuBarModel* getMacMainMenu() throw();
  32248. #endif
  32249. /** @internal */
  32250. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32251. /** @internal */
  32252. void applicationCommandListChanged();
  32253. /** @internal */
  32254. void handleAsyncUpdate();
  32255. juce_UseDebuggingNewOperator
  32256. private:
  32257. ApplicationCommandManager* manager;
  32258. SortedSet <void*> listeners;
  32259. MenuBarModel (const MenuBarModel&);
  32260. const MenuBarModel& operator= (const MenuBarModel&);
  32261. };
  32262. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32263. /********* End of inlined file: juce_MenuBarModel.h *********/
  32264. /**
  32265. A menu bar component.
  32266. @see MenuBarModel
  32267. */
  32268. class JUCE_API MenuBarComponent : public Component,
  32269. private MenuBarModelListener,
  32270. private Timer
  32271. {
  32272. public:
  32273. /** Creates a menu bar.
  32274. @param model the model object to use to control this bar. You can
  32275. pass 0 into this if you like, and set the model later
  32276. using the setModel() method
  32277. */
  32278. MenuBarComponent (MenuBarModel* const model);
  32279. /** Destructor. */
  32280. ~MenuBarComponent();
  32281. /** Changes the model object to use to control the bar.
  32282. This can be 0, in which case the bar will be empty. Don't delete the object
  32283. that is passed-in while it's still being used by this MenuBar.
  32284. */
  32285. void setModel (MenuBarModel* const newModel);
  32286. /** Pops up one of the menu items.
  32287. This lets you manually open one of the menus - it could be triggered by a
  32288. key shortcut, for example.
  32289. */
  32290. void showMenu (const int menuIndex);
  32291. /** @internal */
  32292. void paint (Graphics& g);
  32293. /** @internal */
  32294. void resized();
  32295. /** @internal */
  32296. void mouseEnter (const MouseEvent& e);
  32297. /** @internal */
  32298. void mouseExit (const MouseEvent& e);
  32299. /** @internal */
  32300. void mouseDown (const MouseEvent& e);
  32301. /** @internal */
  32302. void mouseDrag (const MouseEvent& e);
  32303. /** @internal */
  32304. void mouseUp (const MouseEvent& e);
  32305. /** @internal */
  32306. void mouseMove (const MouseEvent& e);
  32307. /** @internal */
  32308. void inputAttemptWhenModal();
  32309. /** @internal */
  32310. void handleCommandMessage (int commandId);
  32311. /** @internal */
  32312. bool keyPressed (const KeyPress& key);
  32313. /** @internal */
  32314. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32315. /** @internal */
  32316. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32317. const ApplicationCommandTarget::InvocationInfo& info);
  32318. juce_UseDebuggingNewOperator
  32319. private:
  32320. MenuBarModel* model;
  32321. StringArray menuNames;
  32322. Array <int> xPositions;
  32323. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32324. int lastMouseX, lastMouseY;
  32325. bool inModalState;
  32326. Component* currentPopup;
  32327. int getItemAt (int x, int y);
  32328. void updateItemUnderMouse (const int x, const int y);
  32329. void hideCurrentMenu();
  32330. void timerCallback();
  32331. void repaintMenuItem (int index);
  32332. MenuBarComponent (const MenuBarComponent&);
  32333. const MenuBarComponent& operator= (const MenuBarComponent&);
  32334. };
  32335. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32336. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32337. #endif
  32338. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32339. #endif
  32340. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32341. #endif
  32342. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32343. #endif
  32344. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32345. /********* Start of inlined file: juce_ComponentDragger.h *********/
  32346. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32347. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32348. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32349. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32350. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32351. /**
  32352. A class that imposes restrictions on a Component's size or position.
  32353. This is used by classes such as ResizableCornerComponent,
  32354. ResizableBorderComponent and ResizableWindow.
  32355. The base class can impose some basic size and position limits, but you can
  32356. also subclass this for custom uses.
  32357. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  32358. */
  32359. class JUCE_API ComponentBoundsConstrainer
  32360. {
  32361. public:
  32362. /** When first created, the object will not impose any restrictions on the components. */
  32363. ComponentBoundsConstrainer() throw();
  32364. /** Destructor. */
  32365. virtual ~ComponentBoundsConstrainer();
  32366. /** Imposes a minimum width limit. */
  32367. void setMinimumWidth (const int minimumWidth) throw();
  32368. /** Returns the current minimum width. */
  32369. int getMinimumWidth() const throw() { return minW; }
  32370. /** Imposes a maximum width limit. */
  32371. void setMaximumWidth (const int maximumWidth) throw();
  32372. /** Returns the current maximum width. */
  32373. int getMaximumWidth() const throw() { return maxW; }
  32374. /** Imposes a minimum height limit. */
  32375. void setMinimumHeight (const int minimumHeight) throw();
  32376. /** Returns the current minimum height. */
  32377. int getMinimumHeight() const throw() { return minH; }
  32378. /** Imposes a maximum height limit. */
  32379. void setMaximumHeight (const int maximumHeight) throw();
  32380. /** Returns the current maximum height. */
  32381. int getMaximumHeight() const throw() { return maxH; }
  32382. /** Imposes a minimum width and height limit. */
  32383. void setMinimumSize (const int minimumWidth,
  32384. const int minimumHeight) throw();
  32385. /** Imposes a maximum width and height limit. */
  32386. void setMaximumSize (const int maximumWidth,
  32387. const int maximumHeight) throw();
  32388. /** Set all the maximum and minimum dimensions. */
  32389. void setSizeLimits (const int minimumWidth,
  32390. const int minimumHeight,
  32391. const int maximumWidth,
  32392. const int maximumHeight) throw();
  32393. /** Sets the amount by which the component is allowed to go off-screen.
  32394. The values indicate how many pixels must remain on-screen when dragged off
  32395. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  32396. when the component goes off the top of the screen, its y-position will be
  32397. clipped so that there are always at least 10 pixels on-screen. In other words,
  32398. the lowest y-position it can take would be (10 - the component's height).
  32399. If you pass 0 or less for one of these amounts, the component is allowed
  32400. to move beyond that edge completely, with no restrictions at all.
  32401. If you pass a very large number (i.e. larger that the dimensions of the
  32402. component itself), then the component won't be allowed to overlap that
  32403. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  32404. the component will bump into the left side of the screen and go no further.
  32405. */
  32406. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  32407. const int minimumWhenOffTheLeft,
  32408. const int minimumWhenOffTheBottom,
  32409. const int minimumWhenOffTheRight) throw();
  32410. /** Specifies a width-to-height ratio that the resizer should always maintain.
  32411. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  32412. will always be maintained as this multiple of the height.
  32413. @see setResizeLimits
  32414. */
  32415. void setFixedAspectRatio (const double widthOverHeight) throw();
  32416. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  32417. If no aspect ratio is being enforced, this will return 0.
  32418. */
  32419. double getFixedAspectRatio() const throw();
  32420. /** This callback changes the given co-ordinates to impose whatever the current
  32421. constraints are set to be.
  32422. @param x the x position that should be examined and adjusted
  32423. @param y the y position that should be examined and adjusted
  32424. @param w the width that should be examined and adjusted
  32425. @param h the height that should be examined and adjusted
  32426. @param previousBounds the component's current size
  32427. @param limits the region in which the component can be positioned
  32428. @param isStretchingTop whether the top edge of the component is being resized
  32429. @param isStretchingLeft whether the left edge of the component is being resized
  32430. @param isStretchingBottom whether the bottom edge of the component is being resized
  32431. @param isStretchingRight whether the right edge of the component is being resized
  32432. */
  32433. virtual void checkBounds (int& x, int& y, int& w, int& h,
  32434. const Rectangle& previousBounds,
  32435. const Rectangle& limits,
  32436. const bool isStretchingTop,
  32437. const bool isStretchingLeft,
  32438. const bool isStretchingBottom,
  32439. const bool isStretchingRight);
  32440. /** This callback happens when the resizer is about to start dragging. */
  32441. virtual void resizeStart();
  32442. /** This callback happens when the resizer has finished dragging. */
  32443. virtual void resizeEnd();
  32444. /** Checks the given bounds, and then sets the component to the corrected size. */
  32445. void setBoundsForComponent (Component* const component,
  32446. int x, int y, int w, int h,
  32447. const bool isStretchingTop,
  32448. const bool isStretchingLeft,
  32449. const bool isStretchingBottom,
  32450. const bool isStretchingRight);
  32451. /** Called by setBoundsForComponent() to apply a new constrained size to a
  32452. component.
  32453. By default this just calls setBounds(), but it virtual in case it's needed for
  32454. extremely cunning purposes.
  32455. */
  32456. virtual void applyBoundsToComponent (Component* component,
  32457. int x, int y, int w, int h);
  32458. juce_UseDebuggingNewOperator
  32459. private:
  32460. int minW, maxW, minH, maxH;
  32461. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  32462. double aspectRatio;
  32463. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  32464. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  32465. };
  32466. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32467. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32468. /**
  32469. An object to take care of the logic for dragging components around with the mouse.
  32470. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  32471. then in your mouseDrag() callback, call dragComponent().
  32472. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  32473. to limit the component's position and keep it on-screen.
  32474. e.g. @code
  32475. class MyDraggableComp
  32476. {
  32477. ComponentDragger myDragger;
  32478. void mouseDown (const MouseEvent& e)
  32479. {
  32480. myDragger.startDraggingComponent (this, 0);
  32481. }
  32482. void mouseDrag (const MouseEvent& e)
  32483. {
  32484. myDragger.dragComponent (this, e);
  32485. }
  32486. };
  32487. @endcode
  32488. */
  32489. class JUCE_API ComponentDragger
  32490. {
  32491. public:
  32492. /** Creates a ComponentDragger. */
  32493. ComponentDragger();
  32494. /** Destructor. */
  32495. virtual ~ComponentDragger();
  32496. /** Call this from your component's mouseDown() method, to prepare for dragging.
  32497. @param componentToDrag the component that you want to drag
  32498. @param constrainer a constrainer object to use to keep the component
  32499. from going offscreen
  32500. @see dragComponent
  32501. */
  32502. void startDraggingComponent (Component* const componentToDrag,
  32503. ComponentBoundsConstrainer* constrainer);
  32504. /** Call this from your mouseDrag() callback to move the component.
  32505. This will move the component, but will first check the validity of the
  32506. component's new position using the checkPosition() method, which you
  32507. can override if you need to enforce special positioning limits on the
  32508. component.
  32509. @param componentToDrag the component that you want to drag
  32510. @param e the current mouse-drag event
  32511. @see dragComponent
  32512. */
  32513. void dragComponent (Component* const componentToDrag,
  32514. const MouseEvent& e);
  32515. juce_UseDebuggingNewOperator
  32516. private:
  32517. ComponentBoundsConstrainer* constrainer;
  32518. int originalX, originalY;
  32519. };
  32520. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32521. /********* End of inlined file: juce_ComponentDragger.h *********/
  32522. #endif
  32523. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32524. #endif
  32525. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32526. #endif
  32527. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32528. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32529. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32530. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32531. /**
  32532. Components derived from this class can have files dropped onto them by an external application.
  32533. @see DragAndDropContainer
  32534. */
  32535. class JUCE_API FileDragAndDropTarget
  32536. {
  32537. public:
  32538. /** Destructor. */
  32539. virtual ~FileDragAndDropTarget() {}
  32540. /** Callback to check whether this target is interested in the set of files being offered.
  32541. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32542. component, so don't do anything time-consuming in here, like opening the files to have a look
  32543. inside them!
  32544. @param files the set of (absolute) pathnames of the files that the user is dragging
  32545. @returns true if this component wants to receive the other callbacks regarging this
  32546. type of object; if it returns false, no other callbacks will be made.
  32547. */
  32548. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32549. /** Callback to indicate that some files are being dragged over this component.
  32550. This gets called when the user moves the mouse into this component while dragging.
  32551. Use this callback as a trigger to make your component repaint itself to give the
  32552. user feedback about whether the files can be dropped here or not.
  32553. @param files the set of (absolute) pathnames of the files that the user is dragging
  32554. @param x the mouse x position, relative to this component
  32555. @param y the mouse y position, relative to this component
  32556. */
  32557. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32558. /** Callback to indicate that the user is dragging some files over this component.
  32559. This gets called when the user moves the mouse over this component while dragging.
  32560. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32561. this lets you know what happens in-between.
  32562. @param files the set of (absolute) pathnames of the files that the user is dragging
  32563. @param x the mouse x position, relative to this component
  32564. @param y the mouse y position, relative to this component
  32565. */
  32566. virtual void fileDragMove (const StringArray& files, int x, int y);
  32567. /** Callback to indicate that the mouse has moved away from this component.
  32568. This gets called when the user moves the mouse out of this component while dragging
  32569. the files.
  32570. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32571. as a signal to repaint it in its normal state.
  32572. @param files the set of (absolute) pathnames of the files that the user is dragging
  32573. */
  32574. virtual void fileDragExit (const StringArray& files);
  32575. /** Callback to indicate that the user has dropped the files onto this component.
  32576. When the user drops the files, this get called, and you can use the files in whatever
  32577. way is appropriate.
  32578. Note that after this is called, the fileDragExit method may not be called, so you should
  32579. clean up in here if there's anything you need to do when the drag finishes.
  32580. @param files the set of (absolute) pathnames of the files that the user is dragging
  32581. @param x the mouse x position, relative to this component
  32582. @param y the mouse y position, relative to this component
  32583. */
  32584. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32585. };
  32586. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32587. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32588. #endif
  32589. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32590. /********* Start of inlined file: juce_LassoComponent.h *********/
  32591. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32592. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32593. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  32594. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32595. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32596. /** Manages a list of selectable items.
  32597. Use one of these to keep a track of things that the user has highlighted, like
  32598. icons or things in a list.
  32599. The class is templated so that you can use it to hold either a set of pointers
  32600. to objects, or a set of ID numbers or handles, for cases where each item may
  32601. not always have a corresponding object.
  32602. To be informed when items are selected/deselected, register a ChangeListener with
  32603. this object.
  32604. @see SelectableObject
  32605. */
  32606. template <class SelectableItemType>
  32607. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  32608. {
  32609. public:
  32610. /** Creates an empty set. */
  32611. SelectedItemSet()
  32612. {
  32613. }
  32614. /** Creates a set based on an array of items. */
  32615. SelectedItemSet (const Array <SelectableItemType>& items)
  32616. : selectedItems (items)
  32617. {
  32618. }
  32619. /** Creates a copy of another set. */
  32620. SelectedItemSet (const SelectedItemSet& other)
  32621. : selectedItems (other.selectedItems)
  32622. {
  32623. }
  32624. /** Creates a copy of another set. */
  32625. const SelectedItemSet& operator= (const SelectedItemSet& other)
  32626. {
  32627. if (selectedItems != other.selectedItems)
  32628. {
  32629. selectedItems = other.selectedItems;
  32630. changed();
  32631. }
  32632. return *this;
  32633. }
  32634. /** Destructor. */
  32635. ~SelectedItemSet()
  32636. {
  32637. }
  32638. /** Clears any other currently selected items, and selects this item.
  32639. If this item is already the only thing selected, no change notification
  32640. will be sent out.
  32641. @see addToSelection, addToSelectionBasedOnModifiers
  32642. */
  32643. void selectOnly (SelectableItemType item)
  32644. {
  32645. if (isSelected (item))
  32646. {
  32647. for (int i = selectedItems.size(); --i >= 0;)
  32648. {
  32649. if (selectedItems.getUnchecked(i) != item)
  32650. {
  32651. deselect (selectedItems.getUnchecked(i));
  32652. i = jmin (i, selectedItems.size());
  32653. }
  32654. }
  32655. }
  32656. else
  32657. {
  32658. deselectAll();
  32659. changed();
  32660. selectedItems.add (item);
  32661. itemSelected (item);
  32662. }
  32663. }
  32664. /** Selects an item.
  32665. If the item is already selected, no change notification will be sent out.
  32666. @see selectOnly, addToSelectionBasedOnModifiers
  32667. */
  32668. void addToSelection (SelectableItemType item)
  32669. {
  32670. if (! isSelected (item))
  32671. {
  32672. changed();
  32673. selectedItems.add (item);
  32674. itemSelected (item);
  32675. }
  32676. }
  32677. /** Selects or deselects an item.
  32678. This will use the modifier keys to decide whether to deselect other items
  32679. first.
  32680. So if the shift key is held down, the item will be added without deselecting
  32681. anything (same as calling addToSelection() )
  32682. If no modifiers are down, the current selection will be cleared first (same
  32683. as calling selectOnly() )
  32684. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  32685. so it'll be added to the set unless it's already there, in which case it'll be
  32686. deselected.
  32687. If the items that you're selecting can also be dragged, you may need to use the
  32688. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  32689. subtleties of this kind of usage.
  32690. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  32691. */
  32692. void addToSelectionBasedOnModifiers (SelectableItemType item,
  32693. const ModifierKeys& modifiers)
  32694. {
  32695. if (modifiers.isShiftDown())
  32696. {
  32697. addToSelection (item);
  32698. }
  32699. else if (modifiers.isCommandDown())
  32700. {
  32701. if (isSelected (item))
  32702. deselect (item);
  32703. else
  32704. addToSelection (item);
  32705. }
  32706. else
  32707. {
  32708. selectOnly (item);
  32709. }
  32710. }
  32711. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  32712. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  32713. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  32714. makes it easy to handle multiple-selection of sets of objects that can also
  32715. be dragged.
  32716. For example, if you have several items already selected, and you click on
  32717. one of them (without dragging), then you'd expect this to deselect the other, and
  32718. just select the item you clicked on. But if you had clicked on this item and
  32719. dragged it, you'd have expected them all to stay selected.
  32720. When you call this method, you'll need to store the boolean result, because the
  32721. addToSelectionOnMouseUp() method will need to be know this value.
  32722. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  32723. */
  32724. bool addToSelectionOnMouseDown (SelectableItemType item,
  32725. const ModifierKeys& modifiers)
  32726. {
  32727. if (isSelected (item))
  32728. {
  32729. return ! modifiers.isPopupMenu();
  32730. }
  32731. else
  32732. {
  32733. addToSelectionBasedOnModifiers (item, modifiers);
  32734. return false;
  32735. }
  32736. }
  32737. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  32738. Call this during a mouseUp callback, when you have previously called the
  32739. addToSelectionOnMouseDown() method during your mouseDown event.
  32740. See addToSelectionOnMouseDown() for more info
  32741. @param item the item to select (or deselect)
  32742. @param modifiers the modifiers from the mouse-up event
  32743. @param wasItemDragged true if your item was dragged during the mouse click
  32744. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  32745. back from the addToSelectionOnMouseDown() call that you
  32746. should have made during the matching mouseDown event
  32747. */
  32748. void addToSelectionOnMouseUp (SelectableItemType item,
  32749. const ModifierKeys& modifiers,
  32750. const bool wasItemDragged,
  32751. const bool resultOfMouseDownSelectMethod)
  32752. {
  32753. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  32754. addToSelectionBasedOnModifiers (item, modifiers);
  32755. }
  32756. /** Deselects an item. */
  32757. void deselect (SelectableItemType item)
  32758. {
  32759. const int i = selectedItems.indexOf (item);
  32760. if (i >= 0)
  32761. {
  32762. changed();
  32763. itemDeselected (selectedItems.remove (i));
  32764. }
  32765. }
  32766. /** Deselects all items. */
  32767. void deselectAll()
  32768. {
  32769. if (selectedItems.size() > 0)
  32770. {
  32771. changed();
  32772. for (int i = selectedItems.size(); --i >= 0;)
  32773. {
  32774. itemDeselected (selectedItems.remove (i));
  32775. i = jmin (i, selectedItems.size());
  32776. }
  32777. }
  32778. }
  32779. /** Returns the number of currently selected items.
  32780. @see getSelectedItem
  32781. */
  32782. int getNumSelected() const throw()
  32783. {
  32784. return selectedItems.size();
  32785. }
  32786. /** Returns one of the currently selected items.
  32787. Returns 0 if the index is out-of-range.
  32788. @see getNumSelected
  32789. */
  32790. SelectableItemType getSelectedItem (const int index) const throw()
  32791. {
  32792. return selectedItems [index];
  32793. }
  32794. /** True if this item is currently selected. */
  32795. bool isSelected (const SelectableItemType item) const throw()
  32796. {
  32797. return selectedItems.contains (item);
  32798. }
  32799. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  32800. /** Can be overridden to do special handling when an item is selected.
  32801. For example, if the item is an object, you might want to call it and tell
  32802. it that it's being selected.
  32803. */
  32804. virtual void itemSelected (SelectableItemType item) {}
  32805. /** Can be overridden to do special handling when an item is deselected.
  32806. For example, if the item is an object, you might want to call it and tell
  32807. it that it's being deselected.
  32808. */
  32809. virtual void itemDeselected (SelectableItemType item) {}
  32810. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  32811. */
  32812. void changed (const bool synchronous = false)
  32813. {
  32814. if (synchronous)
  32815. sendSynchronousChangeMessage (this);
  32816. else
  32817. sendChangeMessage (this);
  32818. }
  32819. juce_UseDebuggingNewOperator
  32820. private:
  32821. Array <SelectableItemType> selectedItems;
  32822. };
  32823. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32824. /********* End of inlined file: juce_SelectedItemSet.h *********/
  32825. /**
  32826. A class used by the LassoComponent to manage the things that it selects.
  32827. This allows the LassoComponent to find out which items are within the lasso,
  32828. and to change the list of selected items.
  32829. @see LassoComponent, SelectedItemSet
  32830. */
  32831. template <class SelectableItemType>
  32832. class LassoSource
  32833. {
  32834. public:
  32835. /** Destructor. */
  32836. virtual ~LassoSource() {}
  32837. /** Returns the set of items that lie within a given lassoable region.
  32838. Your implementation of this method must find all the relevent items that lie
  32839. within the given rectangle. and add them to the itemsFound array.
  32840. The co-ordinates are relative to the top-left of the lasso component's parent
  32841. component. (i.e. they are the same as the size and position of the lasso
  32842. component itself).
  32843. */
  32844. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  32845. int x, int y, int width, int height) = 0;
  32846. /** Returns the SelectedItemSet that the lasso should update.
  32847. This set will be continuously updated by the LassoComponent as it gets
  32848. dragged around, so make sure that you've got a ChangeListener attached to
  32849. the set so that your UI objects will know when the selection changes and
  32850. be able to update themselves appropriately.
  32851. */
  32852. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  32853. };
  32854. /**
  32855. A component that acts as a rectangular selection region, which you drag with
  32856. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  32857. To use one of these:
  32858. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  32859. component, and call its beginLasso() method, giving it a
  32860. suitable LassoSource object that it can use to find out which items are in
  32861. the active area.
  32862. - Each time your parent component gets a mouseDrag event, call dragLasso()
  32863. to update the lasso's position - it will use its LassoSource to calculate and
  32864. update the current selection.
  32865. - After the drag has finished and you get a mouseUp callback, you should call
  32866. endLasso() to clean up. This will make the lasso component invisible, and you
  32867. can remove it from the parent component, or delete it.
  32868. The class takes into account the modifier keys that are being held down while
  32869. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  32870. be added to the original selection; if ctrl or command is pressed, they will be
  32871. xor'ed with any previously selected items.
  32872. @see LassoSource, SelectedItemSet
  32873. */
  32874. template <class SelectableItemType>
  32875. class LassoComponent : public Component
  32876. {
  32877. public:
  32878. /** Creates a Lasso component.
  32879. The fill colour is used to fill the lasso'ed rectangle, and the outline
  32880. colour is used to draw a line around its edge.
  32881. */
  32882. LassoComponent (const int outlineThickness_ = 1)
  32883. : source (0),
  32884. outlineThickness (outlineThickness_)
  32885. {
  32886. }
  32887. /** Destructor. */
  32888. ~LassoComponent()
  32889. {
  32890. }
  32891. /** Call this in your mouseDown event, to initialise a drag.
  32892. Pass in a suitable LassoSource object which the lasso will use to find
  32893. the items and change the selection.
  32894. After using this method to initialise the lasso, repeatedly call dragLasso()
  32895. in your component's mouseDrag callback.
  32896. @see dragLasso, endLasso, LassoSource
  32897. */
  32898. void beginLasso (const MouseEvent& e,
  32899. LassoSource <SelectableItemType>* const lassoSource)
  32900. {
  32901. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  32902. jassert (lassoSource != 0); // the source can't be null!
  32903. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  32904. source = lassoSource;
  32905. if (lassoSource != 0)
  32906. originalSelection = lassoSource->getLassoSelection().getItemArray();
  32907. setSize (0, 0);
  32908. }
  32909. /** Call this in your mouseDrag event, to update the lasso's position.
  32910. This must be repeatedly calling when the mouse is dragged, after you've
  32911. first initialised the lasso with beginLasso().
  32912. This method takes into account the modifier keys that are being held down, so
  32913. if shift is pressed, then the lassoed items will be added to any that were
  32914. previously selected; if ctrl or command is pressed, then they will be xor'ed
  32915. with previously selected items.
  32916. @see beginLasso, endLasso
  32917. */
  32918. void dragLasso (const MouseEvent& e)
  32919. {
  32920. if (source != 0)
  32921. {
  32922. const int x1 = e.getMouseDownX();
  32923. const int y1 = e.getMouseDownY();
  32924. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  32925. setVisible (true);
  32926. Array <SelectableItemType> itemsInLasso;
  32927. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  32928. if (e.mods.isShiftDown())
  32929. {
  32930. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  32931. itemsInLasso.addArray (originalSelection);
  32932. }
  32933. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  32934. {
  32935. Array <SelectableItemType> originalMinusNew (originalSelection);
  32936. originalMinusNew.removeValuesIn (itemsInLasso);
  32937. itemsInLasso.removeValuesIn (originalSelection);
  32938. itemsInLasso.addArray (originalMinusNew);
  32939. }
  32940. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  32941. }
  32942. }
  32943. /** Call this in your mouseUp event, after the lasso has been dragged.
  32944. @see beginLasso, dragLasso
  32945. */
  32946. void endLasso()
  32947. {
  32948. source = 0;
  32949. originalSelection.clear();
  32950. setVisible (false);
  32951. }
  32952. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32953. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32954. methods.
  32955. Note that you can also use the constants from TextEditor::ColourIds to change the
  32956. colour of the text editor that is opened when a label is editable.
  32957. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32958. */
  32959. enum ColourIds
  32960. {
  32961. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  32962. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  32963. };
  32964. /** @internal */
  32965. void paint (Graphics& g)
  32966. {
  32967. g.fillAll (findColour (lassoFillColourId));
  32968. g.setColour (findColour (lassoOutlineColourId));
  32969. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  32970. // this suggests that you've left a lasso comp lying around after the
  32971. // mouse drag has finished.. Be careful to call endLasso() when you get a
  32972. // mouse-up event.
  32973. jassert (isMouseButtonDownAnywhere());
  32974. }
  32975. /** @internal */
  32976. bool hitTest (int x, int y) { return false; }
  32977. juce_UseDebuggingNewOperator
  32978. private:
  32979. Array <SelectableItemType> originalSelection;
  32980. LassoSource <SelectableItemType>* source;
  32981. int outlineThickness;
  32982. };
  32983. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32984. /********* End of inlined file: juce_LassoComponent.h *********/
  32985. #endif
  32986. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  32987. #endif
  32988. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  32989. #endif
  32990. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  32991. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  32992. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  32993. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  32994. /**
  32995. Monitors a component for mouse activity, and triggers a callback
  32996. when the mouse hovers in one place for a specified length of time.
  32997. To use a hover-detector, just create one and call its setHoverComponent()
  32998. method to start it watching a component. You can call setHoverComponent (0)
  32999. to make it inactive.
  33000. (Be careful not to delete a component that's being monitored without first
  33001. stopping or deleting the hover detector).
  33002. */
  33003. class JUCE_API MouseHoverDetector
  33004. {
  33005. public:
  33006. /** Creates a hover detector.
  33007. Initially the object is inactive, and you need to tell it which component
  33008. to monitor, using the setHoverComponent() method.
  33009. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  33010. needs to stay still before the mouseHovered() method
  33011. is invoked. You can change this setting later with
  33012. the setHoverTimeMillisecs() method
  33013. */
  33014. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  33015. /** Destructor. */
  33016. virtual ~MouseHoverDetector();
  33017. /** Changes the time for which the mouse has to stay still before it's considered
  33018. to be hovering.
  33019. */
  33020. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  33021. /** Changes the component that's being monitored for hovering.
  33022. Be careful not to delete a component that's being monitored without first
  33023. stopping or deleting the hover detector.
  33024. */
  33025. void setHoverComponent (Component* const newSourceComponent);
  33026. protected:
  33027. /** Called back when the mouse hovers.
  33028. After the mouse has stayed still over the component for the length of time
  33029. specified by setHoverTimeMillisecs(), this method will be invoked.
  33030. When the mouse is first moved after this callback has occurred, the
  33031. mouseMovedAfterHover() method will be called.
  33032. @param mouseX the mouse's X position relative to the component being monitored
  33033. @param mouseY the mouse's Y position relative to the component being monitored
  33034. */
  33035. virtual void mouseHovered (int mouseX,
  33036. int mouseY) = 0;
  33037. /** Called when the mouse is moved away after just having hovered. */
  33038. virtual void mouseMovedAfterHover() = 0;
  33039. private:
  33040. class JUCE_API HoverDetectorInternal : public MouseListener,
  33041. public Timer
  33042. {
  33043. public:
  33044. MouseHoverDetector* owner;
  33045. int lastX, lastY;
  33046. void timerCallback();
  33047. void mouseEnter (const MouseEvent&);
  33048. void mouseExit (const MouseEvent&);
  33049. void mouseDown (const MouseEvent&);
  33050. void mouseUp (const MouseEvent&);
  33051. void mouseMove (const MouseEvent&);
  33052. void mouseWheelMove (const MouseEvent&, float, float);
  33053. } internalTimer;
  33054. friend class HoverDetectorInternal;
  33055. Component* source;
  33056. int hoverTimeMillisecs;
  33057. bool hasJustHovered;
  33058. void hoverTimerCallback();
  33059. void checkJustHoveredCallback();
  33060. };
  33061. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33062. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33063. #endif
  33064. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33065. #endif
  33066. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33067. #endif
  33068. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33069. #endif
  33070. #ifndef __JUCE_LABEL_JUCEHEADER__
  33071. #endif
  33072. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33073. #endif
  33074. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33075. /********* Start of inlined file: juce_ProgressBar.h *********/
  33076. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33077. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33078. /**
  33079. A progress bar component.
  33080. To use this, just create one and make it visible. It'll run its own timer
  33081. to keep an eye on a variable that you give it, and will automatically
  33082. redraw itself when the variable changes.
  33083. For an easy way of running a background task with a dialog box showing its
  33084. progress, see the ThreadWithProgressWindow class.
  33085. @see ThreadWithProgressWindow
  33086. */
  33087. class JUCE_API ProgressBar : public Component,
  33088. public SettableTooltipClient,
  33089. private Timer
  33090. {
  33091. public:
  33092. /** Creates a ProgressBar.
  33093. @param progress pass in a reference to a double that you're going to
  33094. update with your task's progress. The ProgressBar will
  33095. monitor the value of this variable and will redraw itself
  33096. when the value changes. The range is from 0 to 1.0. Obviously
  33097. you'd better be careful not to delete this variable while the
  33098. ProgressBar still exists!
  33099. */
  33100. ProgressBar (double& progress);
  33101. /** Destructor. */
  33102. ~ProgressBar();
  33103. /** Turns the percentage display on or off.
  33104. By default this is on, and the progress bar will display a text string showing
  33105. its current percentage.
  33106. */
  33107. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33108. /** Gives the progress bar a string to display inside it.
  33109. If you call this, it will turn off the percentage display.
  33110. @see setPercentageDisplay
  33111. */
  33112. void setTextToDisplay (const String& text);
  33113. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33114. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33115. methods.
  33116. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33117. */
  33118. enum ColourIds
  33119. {
  33120. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33121. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33122. classes will probably use variations on this colour. */
  33123. };
  33124. juce_UseDebuggingNewOperator
  33125. protected:
  33126. /** @internal */
  33127. void paint (Graphics& g);
  33128. /** @internal */
  33129. void lookAndFeelChanged();
  33130. /** @internal */
  33131. void visibilityChanged();
  33132. /** @internal */
  33133. void colourChanged();
  33134. private:
  33135. double& progress;
  33136. double currentValue;
  33137. bool displayPercentage;
  33138. String displayedMessage, currentMessage;
  33139. void timerCallback();
  33140. ProgressBar (const ProgressBar&);
  33141. const ProgressBar& operator= (const ProgressBar&);
  33142. };
  33143. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33144. /********* End of inlined file: juce_ProgressBar.h *********/
  33145. #endif
  33146. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33147. /********* Start of inlined file: juce_Slider.h *********/
  33148. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33149. #define __JUCE_SLIDER_JUCEHEADER__
  33150. /********* Start of inlined file: juce_SliderListener.h *********/
  33151. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33152. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33153. class Slider;
  33154. /**
  33155. A class for receiving callbacks from a Slider.
  33156. To be told when a slider's value changes, you can register a SliderListener
  33157. object using Slider::addListener().
  33158. @see Slider::addListener, Slider::removeListener
  33159. */
  33160. class JUCE_API SliderListener
  33161. {
  33162. public:
  33163. /** Destructor. */
  33164. virtual ~SliderListener() {}
  33165. /** Called when the slider's value is changed.
  33166. This may be caused by dragging it, or by typing in its text entry box,
  33167. or by a call to Slider::setValue().
  33168. You can find out the new value using Slider::getValue().
  33169. @see Slider::valueChanged
  33170. */
  33171. virtual void sliderValueChanged (Slider* slider) = 0;
  33172. /** Called when the slider is about to be dragged.
  33173. This is called when a drag begins, then it's followed by multiple calls
  33174. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33175. user lets go.
  33176. @see sliderDragEnded, Slider::startedDragging
  33177. */
  33178. virtual void sliderDragStarted (Slider* slider);
  33179. /** Called after a drag operation has finished.
  33180. @see sliderDragStarted, Slider::stoppedDragging
  33181. */
  33182. virtual void sliderDragEnded (Slider* slider);
  33183. };
  33184. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33185. /********* End of inlined file: juce_SliderListener.h *********/
  33186. /**
  33187. A slider control for changing a value.
  33188. The slider can be horizontal, vertical, or rotary, and can optionally have
  33189. a text-box inside it to show an editable display of the current value.
  33190. To use it, create a Slider object and use the setSliderStyle() method
  33191. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33192. To define the values that it can be set to, see the setRange() and setValue() methods.
  33193. There are also lots of custom tweaks you can do by subclassing and overriding
  33194. some of the virtual methods, such as changing the scaling, changing the format of
  33195. the text display, custom ways of limiting the values, etc.
  33196. You can register SliderListeners with a slider, which will be informed when the value
  33197. changes, or a subclass can override valueChanged() to be informed synchronously.
  33198. @see SliderListener
  33199. */
  33200. class JUCE_API Slider : public Component,
  33201. public SettableTooltipClient,
  33202. private AsyncUpdater,
  33203. private ButtonListener,
  33204. private LabelListener
  33205. {
  33206. public:
  33207. /** Creates a slider.
  33208. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33209. setRange(), etc.
  33210. */
  33211. Slider (const String& componentName);
  33212. /** Destructor. */
  33213. ~Slider();
  33214. /** The types of slider available.
  33215. @see setSliderStyle, setRotaryParameters
  33216. */
  33217. enum SliderStyle
  33218. {
  33219. LinearHorizontal, /**< A traditional horizontal slider. */
  33220. LinearVertical, /**< A traditional vertical slider. */
  33221. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33222. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33223. @see setRotaryParameters */
  33224. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33225. @see setRotaryParameters */
  33226. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33227. @see setRotaryParameters */
  33228. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33229. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33230. @see setMinValue, setMaxValue */
  33231. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33232. @see setMinValue, setMaxValue */
  33233. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33234. value, with the current value being somewhere between them.
  33235. @see setMinValue, setMaxValue */
  33236. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33237. value, with the current value being somewhere between them.
  33238. @see setMinValue, setMaxValue */
  33239. };
  33240. /** Changes the type of slider interface being used.
  33241. @param newStyle the type of interface
  33242. @see setRotaryParameters, setVelocityBasedMode,
  33243. */
  33244. void setSliderStyle (const SliderStyle newStyle);
  33245. /** Returns the slider's current style.
  33246. @see setSliderStyle
  33247. */
  33248. SliderStyle getSliderStyle() const throw() { return style; }
  33249. /** Changes the properties of a rotary slider.
  33250. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33251. the slider's minimum value is represented
  33252. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33253. the slider's maximum value is represented. This must be
  33254. greater than startAngleRadians
  33255. @param stopAtEnd if true, then when the slider is dragged around past the
  33256. minimum or maximum, it'll stop there; if false, it'll wrap
  33257. back to the opposite value
  33258. */
  33259. void setRotaryParameters (const float startAngleRadians,
  33260. const float endAngleRadians,
  33261. const bool stopAtEnd);
  33262. /** Sets the distance the mouse has to move to drag the slider across
  33263. the full extent of its range.
  33264. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33265. relative mouse movements to adjust the slider.
  33266. */
  33267. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33268. /** Changes the way the the mouse is used when dragging the slider.
  33269. If true, this will turn on velocity-sensitive dragging, so that
  33270. the faster the mouse moves, the bigger the movement to the slider. This
  33271. helps when making accurate adjustments if the slider's range is quite large.
  33272. If false, the slider will just try to snap to wherever the mouse is.
  33273. */
  33274. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33275. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33276. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33277. or if you're holding down ctrl.
  33278. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33279. @param threshold the minimum number of pixels that the mouse needs to move for it
  33280. to be treated as a movement
  33281. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33282. the threshold is reached
  33283. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33284. key to toggle velocity-sensitive mode
  33285. */
  33286. void setVelocityModeParameters (const double sensitivity = 1.0,
  33287. const int threshold = 1,
  33288. const double offset = 0.0,
  33289. const bool userCanPressKeyToSwapMode = true) throw();
  33290. /** Sets up a skew factor to alter the way values are distributed.
  33291. You may want to use a range of values on the slider where more accuracy
  33292. is required towards one end of the range, so this will logarithmically
  33293. spread the values across the length of the slider.
  33294. If the factor is < 1.0, the lower end of the range will fill more of the
  33295. slider's length; if the factor is > 1.0, the upper end of the range
  33296. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33297. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33298. method instead.
  33299. @see getSkewFactor, setSkewFactorFromMidPoint
  33300. */
  33301. void setSkewFactor (const double factor) throw();
  33302. /** Sets up a skew factor to alter the way values are distributed.
  33303. This allows you to specify the slider value that should appear in the
  33304. centre of the slider's visible range.
  33305. @see setSkewFactor, getSkewFactor
  33306. */
  33307. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33308. /** Returns the current skew factor.
  33309. See setSkewFactor for more info.
  33310. @see setSkewFactor, setSkewFactorFromMidPoint
  33311. */
  33312. double getSkewFactor() const throw() { return skewFactor; }
  33313. /** Used by setIncDecButtonsMode().
  33314. */
  33315. enum IncDecButtonMode
  33316. {
  33317. incDecButtonsNotDraggable,
  33318. incDecButtonsDraggable_AutoDirection,
  33319. incDecButtonsDraggable_Horizontal,
  33320. incDecButtonsDraggable_Vertical
  33321. };
  33322. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33323. can be dragged on the buttons to drag the values.
  33324. By default this is turned off. When enabled, clicking on the buttons still works
  33325. them as normal, but by holding down the mouse on a button and dragging it a little
  33326. distance, it flips into a mode where the value can be dragged. The drag direction can
  33327. either be set explicitly to be vertical or horizontal, or can be set to
  33328. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33329. are side-by-side or above each other.
  33330. */
  33331. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33332. /** The position of the slider's text-entry box.
  33333. @see setTextBoxStyle
  33334. */
  33335. enum TextEntryBoxPosition
  33336. {
  33337. NoTextBox, /**< Doesn't display a text box. */
  33338. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33339. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33340. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33341. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33342. };
  33343. /** Changes the location and properties of the text-entry box.
  33344. @param newPosition where it should go (or NoTextBox to not have one at all)
  33345. @param isReadOnly if true, it's a read-only display
  33346. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33347. room for the slider as well!
  33348. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33349. room for the slider as well!
  33350. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33351. */
  33352. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33353. const bool isReadOnly,
  33354. const int textEntryBoxWidth,
  33355. const int textEntryBoxHeight);
  33356. /** Returns the status of the text-box.
  33357. @see setTextBoxStyle
  33358. */
  33359. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33360. /** Returns the width used for the text-box.
  33361. @see setTextBoxStyle
  33362. */
  33363. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33364. /** Returns the height used for the text-box.
  33365. @see setTextBoxStyle
  33366. */
  33367. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33368. /** Makes the text-box editable.
  33369. By default this is true, and the user can enter values into the textbox,
  33370. but it can be turned off if that's not suitable.
  33371. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33372. */
  33373. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33374. /** Returns true if the text-box is read-only.
  33375. @see setTextBoxStyle
  33376. */
  33377. bool isTextBoxEditable() const throw() { return editableText; }
  33378. /** If the text-box is editable, this will give it the focus so that the user can
  33379. type directly into it.
  33380. This is basically the effect as the user clicking on it.
  33381. */
  33382. void showTextBox();
  33383. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33384. focus away from it.
  33385. @param discardCurrentEditorContents if true, the slider's value will be left
  33386. unchanged; if false, the current contents of the
  33387. text editor will be used to set the slider position
  33388. before it is hidden.
  33389. */
  33390. void hideTextBox (const bool discardCurrentEditorContents);
  33391. /** Changes the slider's current value.
  33392. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33393. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33394. want to handle it.
  33395. @param newValue the new value to set - this will be restricted by the
  33396. minimum and maximum range, and will be snapped to the
  33397. nearest interval if one has been set
  33398. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33399. any SliderListeners or the valueChanged() method
  33400. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33401. synchronously; if false, it will be asynchronous
  33402. */
  33403. void setValue (double newValue,
  33404. const bool sendUpdateMessage = true,
  33405. const bool sendMessageSynchronously = false);
  33406. /** Returns the slider's current value. */
  33407. double getValue() const throw();
  33408. /** Sets the limits that the slider's value can take.
  33409. @param newMinimum the lowest value allowed
  33410. @param newMaximum the highest value allowed
  33411. @param newInterval the steps in which the value is allowed to increase - if this
  33412. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33413. */
  33414. void setRange (const double newMinimum,
  33415. const double newMaximum,
  33416. const double newInterval = 0);
  33417. /** Returns the current maximum value.
  33418. @see setRange
  33419. */
  33420. double getMaximum() const throw() { return maximum; }
  33421. /** Returns the current minimum value.
  33422. @see setRange
  33423. */
  33424. double getMinimum() const throw() { return minimum; }
  33425. /** Returns the current step-size for values.
  33426. @see setRange
  33427. */
  33428. double getInterval() const throw() { return interval; }
  33429. /** For a slider with two or three thumbs, this returns the lower of its values.
  33430. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33431. A slider with three values also uses the normal getValue() and setValue() methods to
  33432. control the middle value.
  33433. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33434. */
  33435. double getMinValue() const throw();
  33436. /** For a slider with two or three thumbs, this sets the lower of its values.
  33437. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33438. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33439. want to handle it.
  33440. @param newValue the new value to set - this will be restricted by the
  33441. minimum and maximum range, and the max value (in a two-value
  33442. slider) or the mid value (in a three-value slider), and
  33443. will be snapped to the nearest interval if one has been set.
  33444. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33445. any SliderListeners or the valueChanged() method
  33446. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33447. synchronously; if false, it will be asynchronous
  33448. @see getMinValue, setMaxValue, setValue
  33449. */
  33450. void setMinValue (double newValue,
  33451. const bool sendUpdateMessage = true,
  33452. const bool sendMessageSynchronously = false);
  33453. /** For a slider with two or three thumbs, this returns the higher of its values.
  33454. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33455. A slider with three values also uses the normal getValue() and setValue() methods to
  33456. control the middle value.
  33457. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33458. */
  33459. double getMaxValue() const throw();
  33460. /** For a slider with two or three thumbs, this sets the lower of its values.
  33461. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33462. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33463. want to handle it.
  33464. @param newValue the new value to set - this will be restricted by the
  33465. minimum and maximum range, and the max value (in a two-value
  33466. slider) or the mid value (in a three-value slider), and
  33467. will be snapped to the nearest interval if one has been set.
  33468. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33469. any SliderListeners or the valueChanged() method
  33470. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33471. synchronously; if false, it will be asynchronous
  33472. @see getMaxValue, setMinValue, setValue
  33473. */
  33474. void setMaxValue (double newValue,
  33475. const bool sendUpdateMessage = true,
  33476. const bool sendMessageSynchronously = false);
  33477. /** Adds a listener to be called when this slider's value changes. */
  33478. void addListener (SliderListener* const listener) throw();
  33479. /** Removes a previously-registered listener. */
  33480. void removeListener (SliderListener* const listener) throw();
  33481. /** This lets you choose whether double-clicking moves the slider to a given position.
  33482. By default this is turned off, but it's handy if you want a double-click to act
  33483. as a quick way of resetting a slider. Just pass in the value you want it to
  33484. go to when double-clicked.
  33485. @see getDoubleClickReturnValue
  33486. */
  33487. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  33488. const double valueToSetOnDoubleClick) throw();
  33489. /** Returns the values last set by setDoubleClickReturnValue() method.
  33490. Sets isEnabled to true if double-click is enabled, and returns the value
  33491. that was set.
  33492. @see setDoubleClickReturnValue
  33493. */
  33494. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  33495. /** Tells the slider whether to keep sending change messages while the user
  33496. is dragging the slider.
  33497. If set to true, a change message will only be sent when the user has
  33498. dragged the slider and let go. If set to false (the default), then messages
  33499. will be continuously sent as they drag it while the mouse button is still
  33500. held down.
  33501. */
  33502. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  33503. /** This lets you change whether the slider thumb jumps to the mouse position
  33504. when you click.
  33505. By default, this is true. If it's false, then the slider moves with relative
  33506. motion when you drag it.
  33507. This only applies to linear bars, and won't affect two- or three- value
  33508. sliders.
  33509. */
  33510. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  33511. /** If enabled, this gives the slider a pop-up bubble which appears while the
  33512. slider is being dragged.
  33513. This can be handy if your slider doesn't have a text-box, so that users can
  33514. see the value just when they're changing it.
  33515. If you pass a component as the parentComponentToUse parameter, the pop-up
  33516. bubble will be added as a child of that component when it's needed. If you
  33517. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  33518. transparent window, so if you're using an OS that can't do transparent windows
  33519. you'll have to add it to a parent component instead).
  33520. */
  33521. void setPopupDisplayEnabled (const bool isEnabled,
  33522. Component* const parentComponentToUse) throw();
  33523. /** If this is set to true, then right-clicking on the slider will pop-up
  33524. a menu to let the user change the way it works.
  33525. By default this is turned off, but when turned on, the menu will include
  33526. things like velocity sensitivity, and for rotary sliders, whether they
  33527. use a linear or rotary mouse-drag to move them.
  33528. */
  33529. void setPopupMenuEnabled (const bool menuEnabled) throw();
  33530. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  33531. By default it's enabled.
  33532. */
  33533. void setScrollWheelEnabled (const bool enabled) throw();
  33534. /** Returns a number to indicate which thumb is currently being dragged by the
  33535. mouse.
  33536. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  33537. the maximum-value thumb, or -1 if none is currently down.
  33538. */
  33539. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  33540. /** Callback to indicate that the user is about to start dragging the slider.
  33541. @see SliderListener::sliderDragStarted
  33542. */
  33543. virtual void startedDragging();
  33544. /** Callback to indicate that the user has just stopped dragging the slider.
  33545. @see SliderListener::sliderDragEnded
  33546. */
  33547. virtual void stoppedDragging();
  33548. /** Callback to indicate that the user has just moved the slider.
  33549. @see SliderListener::sliderValueChanged
  33550. */
  33551. virtual void valueChanged();
  33552. /** Callback to indicate that the user has just moved the slider.
  33553. Note - the valueChanged() method has changed its format and now no longer has
  33554. any parameters. Update your code to use the new version.
  33555. This version has been left here with an int as its return value to cause
  33556. a syntax error if you've got existing code that uses the old version.
  33557. */
  33558. virtual int valueChanged (double) { jassertfalse; return 0; }
  33559. /** Subclasses can override this to convert a text string to a value.
  33560. When the user enters something into the text-entry box, this method is
  33561. called to convert it to a value.
  33562. The default routine just tries to convert it to a double.
  33563. @see getTextFromValue
  33564. */
  33565. virtual double getValueFromText (const String& text);
  33566. /** Turns the slider's current value into a text string.
  33567. Subclasses can override this to customise the formatting of the text-entry box.
  33568. The default implementation just turns the value into a string, using
  33569. a number of decimal places based on the range interval. If a suffix string
  33570. has been set using setTextValueSuffix(), this will be appended to the text.
  33571. @see getValueFromText
  33572. */
  33573. virtual const String getTextFromValue (double value);
  33574. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  33575. a string.
  33576. This is used by the default implementation of getTextFromValue(), and is just
  33577. appended to the numeric value. For more advanced formatting, you can override
  33578. getTextFromValue() and do something else.
  33579. */
  33580. void setTextValueSuffix (const String& suffix);
  33581. /** Allows a user-defined mapping of distance along the slider to its value.
  33582. The default implementation for this performs the skewing operation that
  33583. can be set up in the setSkewFactor() method. Override it if you need
  33584. some kind of custom mapping instead, but make sure you also implement the
  33585. inverse function in valueToProportionOfLength().
  33586. @param proportion a value 0 to 1.0, indicating a distance along the slider
  33587. @returns the slider value that is represented by this position
  33588. @see valueToProportionOfLength
  33589. */
  33590. virtual double proportionOfLengthToValue (double proportion);
  33591. /** Allows a user-defined mapping of value to the position of the slider along its length.
  33592. The default implementation for this performs the skewing operation that
  33593. can be set up in the setSkewFactor() method. Override it if you need
  33594. some kind of custom mapping instead, but make sure you also implement the
  33595. inverse function in proportionOfLengthToValue().
  33596. @param value a valid slider value, between the range of values specified in
  33597. setRange()
  33598. @returns a value 0 to 1.0 indicating the distance along the slider that
  33599. represents this value
  33600. @see proportionOfLengthToValue
  33601. */
  33602. virtual double valueToProportionOfLength (double value);
  33603. /** Returns the X or Y coordinate of a value along the slider's length.
  33604. If the slider is horizontal, this will be the X coordinate of the given
  33605. value, relative to the left of the slider. If it's vertical, then this will
  33606. be the Y coordinate, relative to the top of the slider.
  33607. If the slider is rotary, this will throw an assertion and return 0. If the
  33608. value is out-of-range, it will be constrained to the length of the slider.
  33609. */
  33610. float getPositionOfValue (const double value);
  33611. /** This can be overridden to allow the slider to snap to user-definable values.
  33612. If overridden, it will be called when the user tries to move the slider to
  33613. a given position, and allows a subclass to sanity-check this value, possibly
  33614. returning a different value to use instead.
  33615. @param attemptedValue the value the user is trying to enter
  33616. @param userIsDragging true if the user is dragging with the mouse; false if
  33617. they are entering the value using the text box
  33618. @returns the value to use instead
  33619. */
  33620. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  33621. /** This can be called to force the text box to update its contents.
  33622. (Not normally needed, as this is done automatically).
  33623. */
  33624. void updateText();
  33625. /** True if the slider moves horizontally. */
  33626. bool isHorizontal() const throw();
  33627. /** True if the slider moves vertically. */
  33628. bool isVertical() const throw();
  33629. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  33630. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33631. methods.
  33632. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33633. */
  33634. enum ColourIds
  33635. {
  33636. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  33637. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  33638. and feel class how this is used. */
  33639. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  33640. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  33641. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  33642. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  33643. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  33644. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  33645. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  33646. };
  33647. juce_UseDebuggingNewOperator
  33648. protected:
  33649. /** @internal */
  33650. void labelTextChanged (Label*);
  33651. /** @internal */
  33652. void paint (Graphics& g);
  33653. /** @internal */
  33654. void resized();
  33655. /** @internal */
  33656. void mouseDown (const MouseEvent& e);
  33657. /** @internal */
  33658. void mouseUp (const MouseEvent& e);
  33659. /** @internal */
  33660. void mouseDrag (const MouseEvent& e);
  33661. /** @internal */
  33662. void mouseDoubleClick (const MouseEvent& e);
  33663. /** @internal */
  33664. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33665. /** @internal */
  33666. void modifierKeysChanged (const ModifierKeys& modifiers);
  33667. /** @internal */
  33668. void buttonClicked (Button* button);
  33669. /** @internal */
  33670. void lookAndFeelChanged();
  33671. /** @internal */
  33672. void enablementChanged();
  33673. /** @internal */
  33674. void focusOfChildComponentChanged (FocusChangeType cause);
  33675. /** @internal */
  33676. void handleAsyncUpdate();
  33677. /** @internal */
  33678. void colourChanged();
  33679. private:
  33680. SortedSet <void*> listeners;
  33681. double currentValue, valueMin, valueMax;
  33682. double minimum, maximum, interval, doubleClickReturnValue;
  33683. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  33684. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  33685. int velocityModeThreshold;
  33686. float rotaryStart, rotaryEnd;
  33687. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  33688. int sliderRegionStart, sliderRegionSize;
  33689. int sliderBeingDragged;
  33690. int pixelsForFullDragExtent;
  33691. Rectangle sliderRect;
  33692. String textSuffix;
  33693. SliderStyle style;
  33694. TextEntryBoxPosition textBoxPos;
  33695. int textBoxWidth, textBoxHeight;
  33696. IncDecButtonMode incDecButtonMode;
  33697. bool editableText : 1, doubleClickToValue : 1;
  33698. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  33699. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  33700. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  33701. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  33702. Font font;
  33703. Label* valueBox;
  33704. Button* incButton;
  33705. Button* decButton;
  33706. Component* popupDisplay;
  33707. Component* parentForPopupDisplay;
  33708. float getLinearSliderPos (const double value);
  33709. void restoreMouseIfHidden();
  33710. void sendDragStart();
  33711. void sendDragEnd();
  33712. double constrainedValue (double value) const throw();
  33713. void triggerChangeMessage (const bool synchronous);
  33714. bool incDecDragDirectionIsHorizontal() const throw();
  33715. Slider (const Slider&);
  33716. const Slider& operator= (const Slider&);
  33717. };
  33718. #endif // __JUCE_SLIDER_JUCEHEADER__
  33719. /********* End of inlined file: juce_Slider.h *********/
  33720. #endif
  33721. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33722. #endif
  33723. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33724. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  33725. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33726. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33727. class TableHeaderComponent;
  33728. /**
  33729. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  33730. You can register one of these objects for table events using TableHeaderComponent::addListener()
  33731. and TableHeaderComponent::removeListener().
  33732. @see TableHeaderComponent
  33733. */
  33734. class JUCE_API TableHeaderListener
  33735. {
  33736. public:
  33737. TableHeaderListener() {}
  33738. /** Destructor. */
  33739. virtual ~TableHeaderListener() {}
  33740. /** This is called when some of the table's columns are added, removed, hidden,
  33741. or rearranged.
  33742. */
  33743. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  33744. /** This is called when one or more of the table's columns are resized.
  33745. */
  33746. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  33747. /** This is called when the column by which the table should be sorted is changed.
  33748. */
  33749. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  33750. /** This is called when the user begins or ends dragging one of the columns around.
  33751. When the user starts dragging a column, this is called with the ID of that
  33752. column. When they finish dragging, it is called again with 0 as the ID.
  33753. */
  33754. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  33755. int columnIdNowBeingDragged);
  33756. };
  33757. /**
  33758. A component that displays a strip of column headings for a table, and allows these
  33759. to be resized, dragged around, etc.
  33760. This is just the component that goes at the top of a table. You can use it
  33761. directly for custom components, or to create a simple table, use the
  33762. TableListBox class.
  33763. To use one of these, create it and use addColumn() to add all the columns that you need.
  33764. Each column must be given a unique ID number that's used to refer to it.
  33765. @see TableListBox, TableHeaderListener
  33766. */
  33767. class JUCE_API TableHeaderComponent : public Component,
  33768. private AsyncUpdater
  33769. {
  33770. public:
  33771. /** Creates an empty table header.
  33772. */
  33773. TableHeaderComponent();
  33774. /** Destructor. */
  33775. ~TableHeaderComponent();
  33776. /** A combination of these flags are passed into the addColumn() method to specify
  33777. the properties of a column.
  33778. */
  33779. enum ColumnPropertyFlags
  33780. {
  33781. 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. */
  33782. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  33783. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  33784. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  33785. 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. */
  33786. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  33787. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  33788. /** This set of default flags is used as the default parameter value in addColumn(). */
  33789. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  33790. /** A quick way of combining flags for a column that's not resizable. */
  33791. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  33792. /** A quick way of combining flags for a column that's not resizable or sortable. */
  33793. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  33794. /** A quick way of combining flags for a column that's not sortable. */
  33795. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  33796. };
  33797. /** Adds a column to the table.
  33798. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  33799. registered listeners.
  33800. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  33801. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  33802. a unique ID. This is used to identify the column later on, after the user may have
  33803. changed the order that they appear in
  33804. @param width the initial width of the column, in pixels
  33805. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  33806. if the 'resizable' flag is specified for this column
  33807. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  33808. if the 'resizable' flag is specified for this column
  33809. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  33810. properties of this column
  33811. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  33812. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  33813. all columns, not just the index amongst those that are currently visible
  33814. */
  33815. void addColumn (const String& columnName,
  33816. const int columnId,
  33817. const int width,
  33818. const int minimumWidth = 30,
  33819. const int maximumWidth = -1,
  33820. const int propertyFlags = defaultFlags,
  33821. const int insertIndex = -1);
  33822. /** Removes a column with the given ID.
  33823. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  33824. registered listeners.
  33825. */
  33826. void removeColumn (const int columnIdToRemove);
  33827. /** Deletes all columns from the table.
  33828. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  33829. registered listeners.
  33830. */
  33831. void removeAllColumns();
  33832. /** Returns the number of columns in the table.
  33833. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  33834. return the total number of columns, including hidden ones.
  33835. @see isColumnVisible
  33836. */
  33837. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  33838. /** Returns the name for a column.
  33839. @see setColumnName
  33840. */
  33841. const String getColumnName (const int columnId) const throw();
  33842. /** Changes the name of a column. */
  33843. void setColumnName (const int columnId, const String& newName);
  33844. /** Moves a column to a different index in the table.
  33845. @param columnId the column to move
  33846. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  33847. */
  33848. void moveColumn (const int columnId, int newVisibleIndex);
  33849. /** Changes the width of a column.
  33850. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  33851. */
  33852. void setColumnWidth (const int columnId, const int newWidth);
  33853. /** Shows or hides a column.
  33854. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  33855. @see isColumnVisible
  33856. */
  33857. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  33858. /** Returns true if this column is currently visible.
  33859. @see setColumnVisible
  33860. */
  33861. bool isColumnVisible (const int columnId) const;
  33862. /** Changes the column which is the sort column.
  33863. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  33864. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  33865. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  33866. @see getSortColumnId, isSortedForwards, reSortTable
  33867. */
  33868. void setSortColumnId (const int columnId, const bool sortForwards);
  33869. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  33870. @see setSortColumnId, isSortedForwards
  33871. */
  33872. int getSortColumnId() const throw();
  33873. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  33874. @see setSortColumnId
  33875. */
  33876. bool isSortedForwards() const throw();
  33877. /** Triggers a re-sort of the table according to the current sort-column.
  33878. If you modifiy the table's contents, you can call this to signal that the table needs
  33879. to be re-sorted.
  33880. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  33881. tableSortOrderChanged() method of any listeners).
  33882. */
  33883. void reSortTable();
  33884. /** Returns the total width of all the visible columns in the table.
  33885. */
  33886. int getTotalWidth() const throw();
  33887. /** Returns the index of a given column.
  33888. If there's no such column ID, this will return -1.
  33889. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  33890. otherwise it'll return the index amongst all the columns, including any hidden ones.
  33891. */
  33892. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  33893. /** Returns the ID of the column at a given index.
  33894. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  33895. otherwise it'll count it amongst all the columns, including any hidden ones.
  33896. If the index is out-of-range, it'll return 0.
  33897. */
  33898. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  33899. /** Returns the rectangle containing of one of the columns.
  33900. The index is an index from 0 to the number of columns that are currently visible (hidden
  33901. ones are not counted). It returns a rectangle showing the position of the column relative
  33902. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  33903. */
  33904. const Rectangle getColumnPosition (const int index) const throw();
  33905. /** Finds the column ID at a given x-position in the component.
  33906. If there is a column at this point this returns its ID, or if not, it will return 0.
  33907. */
  33908. int getColumnIdAtX (const int xToFind) const throw();
  33909. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  33910. entire width of the component.
  33911. By default this is disabled. Turning it on also means that when resizing a column, those
  33912. on the right will be squashed to fit.
  33913. */
  33914. void setStretchToFitActive (const bool shouldStretchToFit);
  33915. /** Returns true if stretch-to-fit has been enabled.
  33916. @see setStretchToFitActive
  33917. */
  33918. bool isStretchToFitActive() const throw();
  33919. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  33920. specified width, keeping their relative proportions the same.
  33921. If the minimum widths of the columns are too wide to fit into this space, it may
  33922. actually end up wider.
  33923. */
  33924. void resizeAllColumnsToFit (int targetTotalWidth);
  33925. /** Enables or disables the pop-up menu.
  33926. The default menu allows the user to show or hide columns. You can add custom
  33927. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  33928. By default the menu is enabled.
  33929. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  33930. */
  33931. void setPopupMenuActive (const bool hasMenu);
  33932. /** Returns true if the pop-up menu is enabled.
  33933. @see setPopupMenuActive
  33934. */
  33935. bool isPopupMenuActive() const throw();
  33936. /** Returns a string that encapsulates the table's current layout.
  33937. This can be restored later using restoreFromString(). It saves the order of
  33938. the columns, the currently-sorted column, and the widths.
  33939. @see restoreFromString
  33940. */
  33941. const String toString() const;
  33942. /** Restores the state of the table, based on a string previously created with
  33943. toString().
  33944. @see toString
  33945. */
  33946. void restoreFromString (const String& storedVersion);
  33947. /** Adds a listener to be informed about things that happen to the header. */
  33948. void addListener (TableHeaderListener* const newListener) throw();
  33949. /** Removes a previously-registered listener. */
  33950. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  33951. /** This can be overridden to handle a mouse-click on one of the column headers.
  33952. The default implementation will use this click to call getSortColumnId() and
  33953. change the sort order.
  33954. */
  33955. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  33956. /** This can be overridden to add custom items to the pop-up menu.
  33957. If you override this, you should call the superclass's method to add its
  33958. column show/hide items, if you want them on the menu as well.
  33959. Then to handle the result, override reactToMenuItem().
  33960. @see reactToMenuItem
  33961. */
  33962. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  33963. /** Override this to handle any custom items that you have added to the
  33964. pop-up menu with an addMenuItems() override.
  33965. If the menuReturnId isn't one of your own custom menu items, you'll need to
  33966. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  33967. handle the items that it had added.
  33968. @see addMenuItems
  33969. */
  33970. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  33971. /** @internal */
  33972. void paint (Graphics& g);
  33973. /** @internal */
  33974. void resized();
  33975. /** @internal */
  33976. void mouseMove (const MouseEvent&);
  33977. /** @internal */
  33978. void mouseEnter (const MouseEvent&);
  33979. /** @internal */
  33980. void mouseExit (const MouseEvent&);
  33981. /** @internal */
  33982. void mouseDown (const MouseEvent&);
  33983. /** @internal */
  33984. void mouseDrag (const MouseEvent&);
  33985. /** @internal */
  33986. void mouseUp (const MouseEvent&);
  33987. /** @internal */
  33988. const MouseCursor getMouseCursor();
  33989. juce_UseDebuggingNewOperator
  33990. private:
  33991. struct ColumnInfo
  33992. {
  33993. String name;
  33994. int id, propertyFlags, width, minimumWidth, maximumWidth;
  33995. double lastDeliberateWidth;
  33996. bool isVisible() const throw();
  33997. };
  33998. OwnedArray <ColumnInfo> columns;
  33999. Array <TableHeaderListener*> listeners;
  34000. Component* dragOverlayComp;
  34001. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34002. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34003. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34004. ColumnInfo* getInfoForId (const int columnId) const throw();
  34005. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  34006. void sendColumnsChanged();
  34007. void handleAsyncUpdate();
  34008. void beginDrag (const MouseEvent&);
  34009. void endDrag (const int finalIndex);
  34010. int getResizeDraggerAt (const int mouseX) const throw();
  34011. void updateColumnUnderMouse (int x, int y);
  34012. void showColumnChooserMenu (const int);
  34013. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34014. TableHeaderComponent (const TableHeaderComponent&);
  34015. const TableHeaderComponent operator= (const TableHeaderComponent&);
  34016. };
  34017. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34018. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  34019. #endif
  34020. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34021. /********* Start of inlined file: juce_TableListBox.h *********/
  34022. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34023. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34024. /**
  34025. One of these is used by a TableListBox as the data model for the table's contents.
  34026. The virtual methods that you override in this class take care of drawing the
  34027. table cells, and reacting to events.
  34028. @see TableListBox
  34029. */
  34030. class JUCE_API TableListBoxModel
  34031. {
  34032. public:
  34033. TableListBoxModel() {}
  34034. /** Destructor. */
  34035. virtual ~TableListBoxModel() {}
  34036. /** This must return the number of rows currently in the table.
  34037. If the number of rows changes, you must call TableListBox::updateContent() to
  34038. cause it to refresh the list.
  34039. */
  34040. virtual int getNumRows() = 0;
  34041. /** This must draw the background behind one of the rows in the table.
  34042. The graphics context has its origin at the row's top-left, and your method
  34043. should fill the area specified by the width and height parameters.
  34044. */
  34045. virtual void paintRowBackground (Graphics& g,
  34046. int rowNumber,
  34047. int width, int height,
  34048. bool rowIsSelected) = 0;
  34049. /** This must draw one of the cells.
  34050. The graphics context's origin will already be set to the top-left of the cell,
  34051. whose size is specified by (width, height).
  34052. */
  34053. virtual void paintCell (Graphics& g,
  34054. int rowNumber,
  34055. int columnId,
  34056. int width, int height,
  34057. bool rowIsSelected) = 0;
  34058. /** This is used to create or update a custom component to go in a cell.
  34059. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34060. and handle mouse clicks with cellClicked().
  34061. This method will be called whenever a custom component might need to be updated - e.g.
  34062. when the table is changed, or TableListBox::updateContent() is called.
  34063. If you don't need a custom component for the specified cell, then return 0.
  34064. If you do want a custom component, and the existingComponentToUpdate is null, then
  34065. this method must create a new component suitable for the cell, and return it.
  34066. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34067. by this method. In this case, the method must either update it to make sure it's correctly representing
  34068. the given cell (which may be different from the one that the component was created for), or it can
  34069. delete this component and return a new one.
  34070. */
  34071. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34072. Component* existingComponentToUpdate);
  34073. /** This callback is made when the user clicks on one of the cells in the table.
  34074. The mouse event's coordinates will be relative to the entire table row.
  34075. @see cellDoubleClicked, backgroundClicked
  34076. */
  34077. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34078. /** This callback is made when the user clicks on one of the cells in the table.
  34079. The mouse event's coordinates will be relative to the entire table row.
  34080. @see cellClicked, backgroundClicked
  34081. */
  34082. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34083. /** This can be overridden to react to the user double-clicking on a part of the list where
  34084. there are no rows.
  34085. @see cellClicked
  34086. */
  34087. virtual void backgroundClicked();
  34088. /** This callback is made when the table's sort order is changed.
  34089. This could be because the user has clicked a column header, or because the
  34090. TableHeaderComponent::setSortColumnId() method was called.
  34091. If you implement this, your method should re-sort the table using the given
  34092. column as the key.
  34093. */
  34094. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34095. /** Returns the best width for one of the columns.
  34096. If you implement this method, you should measure the width of all the items
  34097. in this column, and return the best size.
  34098. Returning 0 means that the column shouldn't be changed.
  34099. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34100. */
  34101. virtual int getColumnAutoSizeWidth (int columnId);
  34102. /** Override this to be informed when rows are selected or deselected.
  34103. @see ListBox::selectedRowsChanged()
  34104. */
  34105. virtual void selectedRowsChanged (int lastRowSelected);
  34106. /** Override this to be informed when the delete key is pressed.
  34107. @see ListBox::deleteKeyPressed()
  34108. */
  34109. virtual void deleteKeyPressed (int lastRowSelected);
  34110. /** Override this to be informed when the return key is pressed.
  34111. @see ListBox::returnKeyPressed()
  34112. */
  34113. virtual void returnKeyPressed (int lastRowSelected);
  34114. /** Override this to be informed when the list is scrolled.
  34115. This might be caused by the user moving the scrollbar, or by programmatic changes
  34116. to the list position.
  34117. */
  34118. virtual void listWasScrolled();
  34119. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34120. If this returns a non-empty name then when the user drags a row, the table will try to
  34121. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34122. drag-and-drop operation, using this string as the source description, and the listbox
  34123. itself as the source component.
  34124. @see DragAndDropContainer::startDragging
  34125. */
  34126. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34127. };
  34128. /**
  34129. A table of cells, using a TableHeaderComponent as its header.
  34130. This component makes it easy to create a table by providing a TableListBoxModel as
  34131. the data source.
  34132. @see TableListBoxModel, TableHeaderComponent
  34133. */
  34134. class JUCE_API TableListBox : public ListBox,
  34135. private ListBoxModel,
  34136. private TableHeaderListener
  34137. {
  34138. public:
  34139. /** Creates a TableListBox.
  34140. The model pointer passed-in can be null, in which case you can set it later
  34141. with setModel().
  34142. */
  34143. TableListBox (const String& componentName,
  34144. TableListBoxModel* const model);
  34145. /** Destructor. */
  34146. ~TableListBox();
  34147. /** Changes the TableListBoxModel that is being used for this table.
  34148. */
  34149. void setModel (TableListBoxModel* const newModel);
  34150. /** Returns the model currently in use. */
  34151. TableListBoxModel* getModel() const throw() { return model; }
  34152. /** Returns the header component being used in this table. */
  34153. TableHeaderComponent* getHeader() const throw() { return header; }
  34154. /** Changes the height of the table header component.
  34155. @see getHeaderHeight
  34156. */
  34157. void setHeaderHeight (const int newHeight);
  34158. /** Returns the height of the table header.
  34159. @see setHeaderHeight
  34160. */
  34161. int getHeaderHeight() const throw();
  34162. /** Resizes a column to fit its contents.
  34163. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34164. and applies that to the column.
  34165. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34166. */
  34167. void autoSizeColumn (const int columnId);
  34168. /** Calls autoSizeColumn() for all columns in the table. */
  34169. void autoSizeAllColumns();
  34170. /** Enables or disables the auto size options on the popup menu.
  34171. By default, these are enabled.
  34172. */
  34173. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34174. /** True if the auto-size options should be shown on the menu.
  34175. @see setAutoSizeMenuOptionsShown
  34176. */
  34177. bool isAutoSizeMenuOptionShown() const throw();
  34178. /** Returns the position of one of the cells in the table.
  34179. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34180. the table component's top-left. The row number isn't checked to see if it's
  34181. in-range, but the column ID must exist or this will return an empty rectangle.
  34182. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34183. top-left of the table's top-left cell.
  34184. */
  34185. const Rectangle getCellPosition (const int columnId,
  34186. const int rowNumber,
  34187. const bool relativeToComponentTopLeft) const;
  34188. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34189. @see ListBox::scrollToEnsureRowIsOnscreen
  34190. */
  34191. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34192. /** @internal */
  34193. int getNumRows();
  34194. /** @internal */
  34195. void paintListBoxItem (int, Graphics&, int, int, bool);
  34196. /** @internal */
  34197. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34198. /** @internal */
  34199. void selectedRowsChanged (int lastRowSelected);
  34200. /** @internal */
  34201. void deleteKeyPressed (int currentSelectedRow);
  34202. /** @internal */
  34203. void returnKeyPressed (int currentSelectedRow);
  34204. /** @internal */
  34205. void backgroundClicked();
  34206. /** @internal */
  34207. void listWasScrolled();
  34208. /** @internal */
  34209. void tableColumnsChanged (TableHeaderComponent*);
  34210. /** @internal */
  34211. void tableColumnsResized (TableHeaderComponent*);
  34212. /** @internal */
  34213. void tableSortOrderChanged (TableHeaderComponent*);
  34214. /** @internal */
  34215. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34216. /** @internal */
  34217. void resized();
  34218. juce_UseDebuggingNewOperator
  34219. private:
  34220. TableHeaderComponent* header;
  34221. TableListBoxModel* model;
  34222. int columnIdNowBeingDragged;
  34223. bool autoSizeOptionsShown;
  34224. void updateColumnComponents() const;
  34225. TableListBox (const TableListBox&);
  34226. const TableListBox& operator= (const TableListBox&);
  34227. };
  34228. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34229. /********* End of inlined file: juce_TableListBox.h *********/
  34230. #endif
  34231. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34232. #endif
  34233. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34234. #endif
  34235. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34236. #endif
  34237. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34238. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  34239. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34240. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34241. /**
  34242. A factory object which can create ToolbarItemComponent objects.
  34243. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34244. that it can create.
  34245. Each type of item is identified by a unique ID, and multiple instances of an
  34246. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34247. bars).
  34248. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34249. */
  34250. class JUCE_API ToolbarItemFactory
  34251. {
  34252. public:
  34253. ToolbarItemFactory();
  34254. /** Destructor. */
  34255. virtual ~ToolbarItemFactory();
  34256. /** A set of reserved item ID values, used for the built-in item types.
  34257. */
  34258. enum SpecialItemIds
  34259. {
  34260. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34261. can be placed between sets of items to break them into groups. */
  34262. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34263. items.*/
  34264. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34265. either side of it, filling any available space. */
  34266. };
  34267. /** Must return a list of the IDs for all the item types that this factory can create.
  34268. The ids should be added to the array that is passed-in.
  34269. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34270. and the predefined IDs in the SpecialItemIds enum.
  34271. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34272. to this list if you want your toolbar to be able to contain those items.
  34273. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34274. of available items, and their order on the palette will reflect the order in which
  34275. they appear on this list.
  34276. @see ToolbarItemPalette
  34277. */
  34278. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34279. /** Must return the set of items that should be added to a toolbar as its default set.
  34280. This method is used by Toolbar::addDefaultItems() to determine which items to
  34281. create.
  34282. The items that your method adds to the array that is passed-in will be added to the
  34283. toolbar in the same order. Items can appear in the list more than once.
  34284. */
  34285. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34286. /** Must create an instance of one of the items that the factory lists in its
  34287. getAllToolbarItemIds() method.
  34288. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34289. method, except for the built-in item types from the SpecialItemIds enum, which
  34290. are created internally by the toolbar code.
  34291. Try not to keep a pointer to the object that is returned, as it will be deleted
  34292. automatically by the toolbar, and remember that multiple instances of the same
  34293. item type are likely to exist at the same time.
  34294. */
  34295. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  34296. };
  34297. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34298. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  34299. #endif
  34300. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34301. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  34302. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34303. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34304. /**
  34305. A component containing a list of toolbar items, which the user can drag onto
  34306. a toolbar to add them.
  34307. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34308. which automatically shows one of these in a dialog box with lots of extra controls.
  34309. @see Toolbar
  34310. */
  34311. class JUCE_API ToolbarItemPalette : public Component,
  34312. public DragAndDropContainer
  34313. {
  34314. public:
  34315. /** Creates a palette of items for a given factory, with the aim of adding them
  34316. to the specified toolbar.
  34317. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34318. set of items that are shown in this palette.
  34319. The toolbar and factory must not be deleted while this object exists.
  34320. */
  34321. ToolbarItemPalette (ToolbarItemFactory& factory,
  34322. Toolbar* const toolbar);
  34323. /** Destructor. */
  34324. ~ToolbarItemPalette();
  34325. /** @internal */
  34326. void resized();
  34327. juce_UseDebuggingNewOperator
  34328. private:
  34329. ToolbarItemFactory& factory;
  34330. Toolbar* toolbar;
  34331. Viewport* viewport;
  34332. friend class Toolbar;
  34333. void replaceComponent (ToolbarItemComponent* const comp);
  34334. ToolbarItemPalette (const ToolbarItemPalette&);
  34335. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34336. };
  34337. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34338. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  34339. #endif
  34340. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34341. #endif
  34342. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34343. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34344. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34345. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34346. /**
  34347. A PropertyComponent that contains an on/off toggle button.
  34348. This type of property component can be used if you have a boolean value to
  34349. toggle on/off.
  34350. @see PropertyComponent
  34351. */
  34352. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  34353. private ButtonListener
  34354. {
  34355. public:
  34356. /** Creates a button component.
  34357. @param propertyName the property name to be passed to the PropertyComponent
  34358. @param buttonTextWhenTrue the text shown in the button when the value is true
  34359. @param buttonTextWhenFalse the text shown in the button when the value is false
  34360. */
  34361. BooleanPropertyComponent (const String& propertyName,
  34362. const String& buttonTextWhenTrue,
  34363. const String& buttonTextWhenFalse);
  34364. /** Destructor. */
  34365. ~BooleanPropertyComponent();
  34366. /** Called to change the state of the boolean value. */
  34367. virtual void setState (const bool newState) = 0;
  34368. /** Must return the current value of the property. */
  34369. virtual bool getState() const = 0;
  34370. /** @internal */
  34371. void paint (Graphics& g);
  34372. /** @internal */
  34373. void refresh();
  34374. /** @internal */
  34375. void buttonClicked (Button*);
  34376. juce_UseDebuggingNewOperator
  34377. private:
  34378. ToggleButton* button;
  34379. String onText, offText;
  34380. };
  34381. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34382. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  34383. #endif
  34384. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34385. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  34386. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34387. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34388. /**
  34389. A PropertyComponent that contains a button.
  34390. This type of property component can be used if you need a button to trigger some
  34391. kind of action.
  34392. @see PropertyComponent
  34393. */
  34394. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  34395. private ButtonListener
  34396. {
  34397. public:
  34398. /** Creates a button component.
  34399. @param propertyName the property name to be passed to the PropertyComponent
  34400. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  34401. */
  34402. ButtonPropertyComponent (const String& propertyName,
  34403. const bool triggerOnMouseDown);
  34404. /** Destructor. */
  34405. ~ButtonPropertyComponent();
  34406. /** Called when the user clicks the button.
  34407. */
  34408. virtual void buttonClicked() = 0;
  34409. /** Returns the string that should be displayed in the button.
  34410. If you need to change this string, call refresh() to update the component.
  34411. */
  34412. virtual const String getButtonText() const = 0;
  34413. /** @internal */
  34414. void refresh();
  34415. /** @internal */
  34416. void buttonClicked (Button*);
  34417. juce_UseDebuggingNewOperator
  34418. private:
  34419. TextButton* button;
  34420. };
  34421. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34422. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  34423. #endif
  34424. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34425. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  34426. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34427. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34428. /**
  34429. A PropertyComponent that shows its value as a combo box.
  34430. This type of property component contains a list of options and has a
  34431. combo box to choose one.
  34432. Your subclass's constructor must add some strings to the choices StringArray
  34433. and these are shown in the list.
  34434. The getIndex() method will be called to find out which option is the currently
  34435. selected one. If you call refresh() it will call getIndex() to check whether
  34436. the value has changed, and will update the combo box if needed.
  34437. If the user selects a different item from the list, setIndex() will be
  34438. called to let your class process this.
  34439. @see PropertyComponent, PropertyPanel
  34440. */
  34441. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  34442. private ComboBoxListener
  34443. {
  34444. public:
  34445. /** Creates the component.
  34446. Your subclass's constructor must add a list of options to the choices
  34447. member variable.
  34448. */
  34449. ChoicePropertyComponent (const String& propertyName);
  34450. /** Destructor. */
  34451. ~ChoicePropertyComponent();
  34452. /** Called when the user selects an item from the combo box.
  34453. Your subclass must use this callback to update the value that this component
  34454. represents. The index is the index of the chosen item in the choices
  34455. StringArray.
  34456. */
  34457. virtual void setIndex (const int newIndex) = 0;
  34458. /** Returns the index of the item that should currently be shown.
  34459. This is the index of the item in the choices StringArray that will be
  34460. shown.
  34461. */
  34462. virtual int getIndex() const = 0;
  34463. /** Returns the list of options. */
  34464. const StringArray& getChoices() const throw();
  34465. /** @internal */
  34466. void refresh();
  34467. /** @internal */
  34468. void comboBoxChanged (ComboBox*);
  34469. juce_UseDebuggingNewOperator
  34470. protected:
  34471. /** The list of options that will be shown in the combo box.
  34472. Your subclass must populate this array in its constructor. If any empty
  34473. strings are added, these will be replaced with horizontal separators (see
  34474. ComboBox::addSeparator() for more info).
  34475. */
  34476. StringArray choices;
  34477. private:
  34478. ComboBox* comboBox;
  34479. };
  34480. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34481. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  34482. #endif
  34483. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  34484. #endif
  34485. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  34486. #endif
  34487. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34488. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34489. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34490. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34491. /**
  34492. A PropertyComponent that shows its value as a slider.
  34493. @see PropertyComponent, Slider
  34494. */
  34495. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  34496. private SliderListener
  34497. {
  34498. public:
  34499. /** Creates the property component.
  34500. The ranges, interval and skew factor are passed to the Slider component.
  34501. If you need to customise the slider in other ways, your constructor can
  34502. access the slider member variable and change it directly.
  34503. */
  34504. SliderPropertyComponent (const String& propertyName,
  34505. const double rangeMin,
  34506. const double rangeMax,
  34507. const double interval,
  34508. const double skewFactor = 1.0);
  34509. /** Destructor. */
  34510. ~SliderPropertyComponent();
  34511. /** Called when the user moves the slider to change its value.
  34512. Your subclass must use this method to update whatever item this property
  34513. represents.
  34514. */
  34515. virtual void setValue (const double newValue) = 0;
  34516. /** Returns the value that the slider should show. */
  34517. virtual const double getValue() const = 0;
  34518. /** @internal */
  34519. void refresh();
  34520. /** @internal */
  34521. void changeListenerCallback (void*);
  34522. /** @internal */
  34523. void sliderValueChanged (Slider*);
  34524. juce_UseDebuggingNewOperator
  34525. protected:
  34526. /** The slider component being used in this component.
  34527. Your subclass has access to this in case it needs to customise it in some way.
  34528. */
  34529. Slider* slider;
  34530. };
  34531. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34532. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  34533. #endif
  34534. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34535. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  34536. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34537. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34538. /**
  34539. A PropertyComponent that shows its value as editable text.
  34540. @see PropertyComponent
  34541. */
  34542. class JUCE_API TextPropertyComponent : public PropertyComponent
  34543. {
  34544. public:
  34545. /** Creates a text property component.
  34546. The maxNumChars is used to set the length of string allowable, and isMultiLine
  34547. sets whether the text editor allows carriage returns.
  34548. @see TextEditor
  34549. */
  34550. TextPropertyComponent (const String& propertyName,
  34551. const int maxNumChars,
  34552. const bool isMultiLine);
  34553. /** Destructor. */
  34554. ~TextPropertyComponent();
  34555. /** Called when the user edits the text.
  34556. Your subclass must use this callback to change the value of whatever item
  34557. this property component represents.
  34558. */
  34559. virtual void setText (const String& newText) = 0;
  34560. /** Returns the text that should be shown in the text editor.
  34561. */
  34562. virtual const String getText() const = 0;
  34563. /** @internal */
  34564. void refresh();
  34565. /** @internal */
  34566. void textWasEdited();
  34567. juce_UseDebuggingNewOperator
  34568. private:
  34569. Label* textEditor;
  34570. };
  34571. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34572. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  34573. #endif
  34574. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  34575. #endif
  34576. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34577. #endif
  34578. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34579. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  34580. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34581. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34582. /** An object that watches for any movement of a component or any of its parent components.
  34583. This makes it easy to check when a component is moved relative to its top-level
  34584. peer window. The normal Component::moved() method is only called when a component
  34585. moves relative to its immediate parent, and sometimes you want to know if any of
  34586. components higher up the tree have moved (which of course will affect the overall
  34587. position of all their sub-components).
  34588. It also includes a callback that lets you know when the top-level peer is changed.
  34589. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  34590. because they need to keep their custom windows in the right place and respond to
  34591. changes in the peer.
  34592. */
  34593. class JUCE_API ComponentMovementWatcher : public ComponentListener
  34594. {
  34595. public:
  34596. /** Creates a ComponentMovementWatcher to watch a given target component. */
  34597. ComponentMovementWatcher (Component* const component);
  34598. /** Destructor. */
  34599. ~ComponentMovementWatcher();
  34600. /** This callback happens when the component that is being watched is moved
  34601. relative to its top-level peer window, or when it is resized.
  34602. */
  34603. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  34604. /** This callback happens when the component's top-level peer is changed.
  34605. */
  34606. virtual void componentPeerChanged() = 0;
  34607. juce_UseDebuggingNewOperator
  34608. /** @internal */
  34609. void componentParentHierarchyChanged (Component& component);
  34610. /** @internal */
  34611. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34612. private:
  34613. Component* const component;
  34614. ComponentPeer* lastPeer;
  34615. VoidArray registeredParentComps;
  34616. bool reentrant;
  34617. int lastX, lastY, lastWidth, lastHeight;
  34618. #ifdef JUCE_DEBUG
  34619. ComponentDeletionWatcher* deletionWatcher;
  34620. #endif
  34621. void unregister() throw();
  34622. void registerWithParentComps() throw();
  34623. ComponentMovementWatcher (const ComponentMovementWatcher&);
  34624. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  34625. };
  34626. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34627. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  34628. #endif
  34629. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34630. /********* Start of inlined file: juce_GroupComponent.h *********/
  34631. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34632. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34633. /**
  34634. A component that draws an outline around itself and has an optional title at
  34635. the top, for drawing an outline around a group of controls.
  34636. */
  34637. class JUCE_API GroupComponent : public Component
  34638. {
  34639. public:
  34640. /** Creates a GroupComponent.
  34641. @param componentName the name to give the component
  34642. @param labelText the text to show at the top of the outline
  34643. */
  34644. GroupComponent (const String& componentName,
  34645. const String& labelText);
  34646. /** Destructor. */
  34647. ~GroupComponent();
  34648. /** Changes the text that's shown at the top of the component. */
  34649. void setText (const String& newText) throw();
  34650. /** Returns the currently displayed text label. */
  34651. const String getText() const throw();
  34652. /** Sets the positioning of the text label.
  34653. (The default is Justification::left)
  34654. @see getTextLabelPosition
  34655. */
  34656. void setTextLabelPosition (const Justification& justification);
  34657. /** Returns the current text label position.
  34658. @see setTextLabelPosition
  34659. */
  34660. const Justification getTextLabelPosition() const throw() { return justification; }
  34661. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34662. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34663. methods.
  34664. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34665. */
  34666. enum ColourIds
  34667. {
  34668. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  34669. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  34670. };
  34671. /** @internal */
  34672. void paint (Graphics& g);
  34673. /** @internal */
  34674. void enablementChanged();
  34675. /** @internal */
  34676. void colourChanged();
  34677. private:
  34678. String text;
  34679. Justification justification;
  34680. GroupComponent (const GroupComponent&);
  34681. const GroupComponent& operator= (const GroupComponent&);
  34682. };
  34683. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34684. /********* End of inlined file: juce_GroupComponent.h *********/
  34685. #endif
  34686. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34687. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  34688. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34689. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34690. /********* Start of inlined file: juce_TabbedComponent.h *********/
  34691. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34692. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34693. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  34694. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34695. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34696. class TabbedButtonBar;
  34697. /** In a TabbedButtonBar, this component is used for each of the buttons.
  34698. If you want to create a TabbedButtonBar with custom tab components, derive
  34699. your component from this class, and override the TabbedButtonBar::createTabButton()
  34700. method to create it instead of the default one.
  34701. @see TabbedButtonBar
  34702. */
  34703. class JUCE_API TabBarButton : public Button
  34704. {
  34705. public:
  34706. /** Creates the tab button. */
  34707. TabBarButton (const String& name,
  34708. TabbedButtonBar* const ownerBar,
  34709. const int tabIndex);
  34710. /** Destructor. */
  34711. ~TabBarButton();
  34712. /** Chooses the best length for the tab, given the specified depth.
  34713. If the tab is horizontal, this should return its width, and the depth
  34714. specifies its height. If it's vertical, it should return the height, and
  34715. the depth is actually its width.
  34716. */
  34717. virtual int getBestTabLength (const int depth);
  34718. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  34719. void clicked (const ModifierKeys& mods);
  34720. bool hitTest (int x, int y);
  34721. juce_UseDebuggingNewOperator
  34722. protected:
  34723. friend class TabbedButtonBar;
  34724. TabbedButtonBar* const owner;
  34725. int tabIndex, overlapPixels;
  34726. DropShadowEffect shadow;
  34727. /** Returns an area of the component that's safe to draw in.
  34728. This deals with the orientation of the tabs, which affects which side is
  34729. touching the tabbed box's content component.
  34730. */
  34731. void getActiveArea (int& x, int& y, int& w, int& h);
  34732. private:
  34733. TabBarButton (const TabBarButton&);
  34734. const TabBarButton& operator= (const TabBarButton&);
  34735. };
  34736. /**
  34737. A vertical or horizontal bar containing tabs that you can select.
  34738. You can use one of these to generate things like a dialog box that has
  34739. tabbed pages you can flip between. Attach a ChangeListener to the
  34740. button bar to be told when the user changes the page.
  34741. An easier method than doing this is to use a TabbedComponent, which
  34742. contains its own TabbedButtonBar and which takes care of the layout
  34743. and other housekeeping.
  34744. @see TabbedComponent
  34745. */
  34746. class JUCE_API TabbedButtonBar : public Component,
  34747. public ChangeBroadcaster,
  34748. public ButtonListener
  34749. {
  34750. public:
  34751. /** The placement of the tab-bar
  34752. @see setOrientation, getOrientation
  34753. */
  34754. enum Orientation
  34755. {
  34756. TabsAtTop,
  34757. TabsAtBottom,
  34758. TabsAtLeft,
  34759. TabsAtRight
  34760. };
  34761. /** Creates a TabbedButtonBar with a given placement.
  34762. You can change the orientation later if you need to.
  34763. */
  34764. TabbedButtonBar (const Orientation orientation);
  34765. /** Destructor. */
  34766. ~TabbedButtonBar();
  34767. /** Changes the bar's orientation.
  34768. This won't change the bar's actual size - you'll need to do that yourself,
  34769. but this determines which direction the tabs go in, and which side they're
  34770. stuck to.
  34771. */
  34772. void setOrientation (const Orientation orientation);
  34773. /** Returns the current orientation.
  34774. @see setOrientation
  34775. */
  34776. Orientation getOrientation() const throw() { return orientation; }
  34777. /** Deletes all the tabs from the bar.
  34778. @see addTab
  34779. */
  34780. void clearTabs();
  34781. /** Adds a tab to the bar.
  34782. Tabs are added in left-to-right reading order.
  34783. If this is the first tab added, it'll also be automatically selected.
  34784. */
  34785. void addTab (const String& tabName,
  34786. const Colour& tabBackgroundColour,
  34787. int insertIndex = -1);
  34788. /** Changes the name of one of the tabs. */
  34789. void setTabName (const int tabIndex,
  34790. const String& newName);
  34791. /** Gets rid of one of the tabs. */
  34792. void removeTab (const int tabIndex);
  34793. /** Moves a tab to a new index in the list.
  34794. Pass -1 as the index to move it to the end of the list.
  34795. */
  34796. void moveTab (const int currentIndex,
  34797. const int newIndex);
  34798. /** Returns the number of tabs in the bar. */
  34799. int getNumTabs() const;
  34800. /** Returns a list of all the tab names in the bar. */
  34801. const StringArray getTabNames() const;
  34802. /** Changes the currently selected tab.
  34803. This will send a change message and cause a synchronous callback to
  34804. the currentTabChanged() method. (But if the given tab is already selected,
  34805. nothing will be done).
  34806. To deselect all the tabs, use an index of -1.
  34807. */
  34808. void setCurrentTabIndex (int newTabIndex);
  34809. /** Returns the name of the currently selected tab.
  34810. This could be an empty string if none are selected.
  34811. */
  34812. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  34813. /** Returns the index of the currently selected tab.
  34814. This could return -1 if none are selected.
  34815. */
  34816. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  34817. /** Callback method to indicate the selected tab has been changed.
  34818. @see setCurrentTabIndex
  34819. */
  34820. virtual void currentTabChanged (const int newCurrentTabIndex,
  34821. const String& newCurrentTabName);
  34822. /** Callback method to indicate that the user has right-clicked on a tab.
  34823. (Or ctrl-clicked on the Mac)
  34824. */
  34825. virtual void popupMenuClickOnTab (const int tabIndex,
  34826. const String& tabName);
  34827. /** Returns the colour of a tab.
  34828. This is the colour that was specified in addTab().
  34829. */
  34830. const Colour getTabBackgroundColour (const int tabIndex);
  34831. /** Changes the background colour of a tab.
  34832. @see addTab, getTabBackgroundColour
  34833. */
  34834. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  34835. /** @internal */
  34836. void resized();
  34837. /** @internal */
  34838. void buttonClicked (Button* button);
  34839. /** @internal */
  34840. void lookAndFeelChanged();
  34841. juce_UseDebuggingNewOperator
  34842. protected:
  34843. /** This creates one of the tabs.
  34844. If you need to use custom tab components, you can override this method and
  34845. return your own class instead of the default.
  34846. */
  34847. virtual TabBarButton* createTabButton (const String& tabName,
  34848. const int tabIndex);
  34849. private:
  34850. Orientation orientation;
  34851. StringArray tabs;
  34852. Array <Colour> tabColours;
  34853. int currentTabIndex;
  34854. Component* behindFrontTab;
  34855. Button* extraTabsButton;
  34856. TabBarButton* getTabButton (const int index) const;
  34857. TabbedButtonBar (const TabbedButtonBar&);
  34858. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  34859. };
  34860. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34861. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  34862. /**
  34863. A component with a TabbedButtonBar along one of its sides.
  34864. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  34865. with addTab(), and this will take care of showing the pages for you when the
  34866. user clicks on a different tab.
  34867. @see TabbedButtonBar
  34868. */
  34869. class JUCE_API TabbedComponent : public Component
  34870. {
  34871. public:
  34872. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  34873. Once created, add some tabs with the addTab() method.
  34874. */
  34875. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  34876. /** Destructor. */
  34877. ~TabbedComponent();
  34878. /** Changes the placement of the tabs.
  34879. This will rearrange the layout to place the tabs along the appropriate
  34880. side of this component, and will shift the content component accordingly.
  34881. @see TabbedButtonBar::setOrientation
  34882. */
  34883. void setOrientation (const TabbedButtonBar::Orientation orientation);
  34884. /** Returns the current tab placement.
  34885. @see setOrientation, TabbedButtonBar::getOrientation
  34886. */
  34887. TabbedButtonBar::Orientation getOrientation() const throw();
  34888. /** Specifies how many pixels wide or high the tab-bar should be.
  34889. If the tabs are placed along the top or bottom, this specified the height
  34890. of the bar; if they're along the left or right edges, it'll be the width
  34891. of the bar.
  34892. */
  34893. void setTabBarDepth (const int newDepth);
  34894. /** Returns the current thickness of the tab bar.
  34895. @see setTabBarDepth
  34896. */
  34897. int getTabBarDepth() const throw() { return tabDepth; }
  34898. /** Specifies an outline that should be drawn around the entire content component.
  34899. If this thickness is > 0, a line of the specified colour will be drawn around
  34900. the three sides of the content component which don't touch the tab-bar, and
  34901. the content component will be inset by this amount.
  34902. */
  34903. void setOutline (const Colour& newOutlineColour,
  34904. const int newThickness);
  34905. /** Specifies a gap to leave around the edge of the content component.
  34906. Each edge of the content component will be indented by the given number of pixels.
  34907. */
  34908. void setIndent (const int indentThickness);
  34909. /** Removes all the tabs from the bar.
  34910. @see TabbedButtonBar::clearTabs
  34911. */
  34912. void clearTabs();
  34913. /** Adds a tab to the tab-bar.
  34914. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  34915. is true, it will be deleted when the tab is removed or when this object is
  34916. deleted.
  34917. @see TabbedButtonBar::addTab
  34918. */
  34919. void addTab (const String& tabName,
  34920. const Colour& tabBackgroundColour,
  34921. Component* const contentComponent,
  34922. const bool deleteComponentWhenNotNeeded,
  34923. const int insertIndex = -1);
  34924. /** Changes the name of one of the tabs. */
  34925. void setTabName (const int tabIndex,
  34926. const String& newName);
  34927. /** Gets rid of one of the tabs. */
  34928. void removeTab (const int tabIndex);
  34929. /** Returns the number of tabs in the bar. */
  34930. int getNumTabs() const;
  34931. /** Returns a list of all the tab names in the bar. */
  34932. const StringArray getTabNames() const;
  34933. /** Returns the content component that was added for the given index.
  34934. Be sure not to use or delete the components that are returned, as this may interfere
  34935. with the TabbedComponent's use of them.
  34936. */
  34937. Component* getTabContentComponent (const int tabIndex) const throw();
  34938. /** Returns the colour of one of the tabs. */
  34939. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  34940. /** Changes the background colour of one of the tabs. */
  34941. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  34942. /** Changes the currently-selected tab.
  34943. To deselect all the tabs, pass -1 as the index.
  34944. @see TabbedButtonBar::setCurrentTabIndex
  34945. */
  34946. void setCurrentTabIndex (const int newTabIndex);
  34947. /** Returns the index of the currently selected tab.
  34948. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  34949. */
  34950. int getCurrentTabIndex() const;
  34951. /** Returns the name of the currently selected tab.
  34952. @see addTab, TabbedButtonBar::getCurrentTabName()
  34953. */
  34954. const String& getCurrentTabName() const;
  34955. /** Returns the current component that's filling the panel.
  34956. This will return 0 if there isn't one.
  34957. */
  34958. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  34959. /** Callback method to indicate the selected tab has been changed.
  34960. @see setCurrentTabIndex
  34961. */
  34962. virtual void currentTabChanged (const int newCurrentTabIndex,
  34963. const String& newCurrentTabName);
  34964. /** Callback method to indicate that the user has right-clicked on a tab.
  34965. (Or ctrl-clicked on the Mac)
  34966. */
  34967. virtual void popupMenuClickOnTab (const int tabIndex,
  34968. const String& tabName);
  34969. /** Returns the tab button bar component that is being used.
  34970. */
  34971. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  34972. /** @internal */
  34973. void paint (Graphics& g);
  34974. /** @internal */
  34975. void resized();
  34976. /** @internal */
  34977. void lookAndFeelChanged();
  34978. juce_UseDebuggingNewOperator
  34979. protected:
  34980. TabbedButtonBar* tabs;
  34981. /** This creates one of the tab buttons.
  34982. If you need to use custom tab components, you can override this method and
  34983. return your own class instead of the default.
  34984. */
  34985. virtual TabBarButton* createTabButton (const String& tabName,
  34986. const int tabIndex);
  34987. private:
  34988. Array <Component*> contentComponents;
  34989. Component* panelComponent;
  34990. int tabDepth;
  34991. Colour outlineColour;
  34992. int outlineThickness, edgeIndent;
  34993. friend class TabCompButtonBar;
  34994. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  34995. TabbedComponent (const TabbedComponent&);
  34996. const TabbedComponent& operator= (const TabbedComponent&);
  34997. };
  34998. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34999. /********* End of inlined file: juce_TabbedComponent.h *********/
  35000. /********* Start of inlined file: juce_DocumentWindow.h *********/
  35001. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35002. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35003. /********* Start of inlined file: juce_ResizableWindow.h *********/
  35004. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35005. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35006. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  35007. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35008. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35009. /********* Start of inlined file: juce_DropShadower.h *********/
  35010. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  35011. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  35012. /**
  35013. Adds a drop-shadow to a component.
  35014. This object creates and manages a set of components which sit around a
  35015. component, creating a gaussian shadow around it. The components will track
  35016. the position of the component and if it's brought to the front they'll also
  35017. follow this.
  35018. For desktop windows you don't need to use this class directly - just
  35019. set the Component::windowHasDropShadow flag when calling
  35020. Component::addToDesktop(), and the system will create one of these if it's
  35021. needed (which it obviously isn't on the Mac, for example).
  35022. */
  35023. class JUCE_API DropShadower : public ComponentListener
  35024. {
  35025. public:
  35026. /** Creates a DropShadower.
  35027. @param alpha the opacity of the shadows, from 0 to 1.0
  35028. @param xOffset the horizontal displacement of the shadow, in pixels
  35029. @param yOffset the vertical displacement of the shadow, in pixels
  35030. @param blurRadius the radius of the blur to use for creating the shadow
  35031. */
  35032. DropShadower (const float alpha = 0.5f,
  35033. const int xOffset = 1,
  35034. const int yOffset = 5,
  35035. const float blurRadius = 10.0f);
  35036. /** Destructor. */
  35037. virtual ~DropShadower();
  35038. /** Attaches the DropShadower to the component you want to shadow. */
  35039. void setOwner (Component* componentToFollow);
  35040. /** @internal */
  35041. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35042. /** @internal */
  35043. void componentBroughtToFront (Component& component);
  35044. /** @internal */
  35045. void componentChildrenChanged (Component& component);
  35046. /** @internal */
  35047. void componentParentHierarchyChanged (Component& component);
  35048. /** @internal */
  35049. void componentVisibilityChanged (Component& component);
  35050. juce_UseDebuggingNewOperator
  35051. private:
  35052. Component* owner;
  35053. int numShadows;
  35054. Component* shadowWindows[4];
  35055. Image* shadowImageSections[12];
  35056. const int shadowEdge, xOffset, yOffset;
  35057. const float alpha, blurRadius;
  35058. bool inDestructor, reentrant;
  35059. void updateShadows();
  35060. void setShadowImage (Image* const src,
  35061. const int num,
  35062. const int w, const int h,
  35063. const int sx, const int sy) throw();
  35064. void bringShadowWindowsToFront();
  35065. void deleteShadowWindows();
  35066. DropShadower (const DropShadower&);
  35067. const DropShadower& operator= (const DropShadower&);
  35068. };
  35069. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35070. /********* End of inlined file: juce_DropShadower.h *********/
  35071. /**
  35072. A base class for top-level windows.
  35073. This class is used for components that are considered a major part of your
  35074. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35075. etc. Things like menus that pop up briefly aren't derived from it.
  35076. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35077. could itself be the child of another component.
  35078. The class manages a list of all instances of top-level windows that are in use,
  35079. and each one is also given the concept of being "active". The active window is
  35080. one that is actively being used by the user. This isn't quite the same as the
  35081. component with the keyboard focus, because there may be a popup menu or other
  35082. temporary window which gets keyboard focus while the active top level window is
  35083. unchanged.
  35084. A top-level window also has an optional drop-shadow.
  35085. @see ResizableWindow, DocumentWindow, DialogWindow
  35086. */
  35087. class JUCE_API TopLevelWindow : public Component
  35088. {
  35089. public:
  35090. /** Creates a TopLevelWindow.
  35091. @param name the name to give the component
  35092. @param addToDesktop if true, the window will be automatically added to the
  35093. desktop; if false, you can use it as a child component
  35094. */
  35095. TopLevelWindow (const String& name,
  35096. const bool addToDesktop);
  35097. /** Destructor. */
  35098. ~TopLevelWindow();
  35099. /** True if this is currently the TopLevelWindow that is actively being used.
  35100. This isn't quite the same as having keyboard focus, because the focus may be
  35101. on a child component or a temporary pop-up menu, etc, while this window is
  35102. still considered to be active.
  35103. @see activeWindowStatusChanged
  35104. */
  35105. bool isActiveWindow() const throw() { return windowIsActive_; }
  35106. /** This will set the bounds of the window so that it's centred in front of another
  35107. window.
  35108. If your app has a few windows open and want to pop up a dialog box for one of
  35109. them, you can use this to show it in front of the relevent parent window, which
  35110. is a bit neater than just having it appear in the middle of the screen.
  35111. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35112. be used instead. If no window is focused, it'll just default to the middle of the
  35113. screen.
  35114. */
  35115. void centreAroundComponent (Component* componentToCentreAround,
  35116. const int width, const int height);
  35117. /** Turns the drop-shadow on and off. */
  35118. void setDropShadowEnabled (const bool useShadow);
  35119. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35120. @see isUsingNativeTitleBar
  35121. */
  35122. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35123. /** Returns true if the window is currently using an OS-native title bar.
  35124. @see setUsingNativeTitleBar
  35125. */
  35126. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35127. /** Returns the number of TopLevelWindow objects currently in use.
  35128. @see getTopLevelWindow
  35129. */
  35130. static int getNumTopLevelWindows() throw();
  35131. /** Returns one of the TopLevelWindow objects currently in use.
  35132. The index is 0 to (getNumTopLevelWindows() - 1).
  35133. */
  35134. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35135. /** Returns the currently-active top level window.
  35136. There might not be one, of course, so this can return 0.
  35137. */
  35138. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35139. juce_UseDebuggingNewOperator
  35140. /** @internal */
  35141. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35142. protected:
  35143. /** This callback happens when this window becomes active or inactive.
  35144. @see isActiveWindow
  35145. */
  35146. virtual void activeWindowStatusChanged();
  35147. /** @internal */
  35148. void focusOfChildComponentChanged (FocusChangeType cause);
  35149. /** @internal */
  35150. void parentHierarchyChanged();
  35151. /** @internal */
  35152. void visibilityChanged();
  35153. /** @internal */
  35154. virtual int getDesktopWindowStyleFlags() const;
  35155. /** @internal */
  35156. void recreateDesktopWindow();
  35157. private:
  35158. friend class TopLevelWindowManager;
  35159. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35160. DropShadower* shadower;
  35161. void setWindowActive (const bool isNowActive) throw();
  35162. TopLevelWindow (const TopLevelWindow&);
  35163. const TopLevelWindow& operator= (const TopLevelWindow&);
  35164. };
  35165. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35166. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35167. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35168. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35169. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35170. /**
  35171. A component that resizes its parent window when dragged.
  35172. This component forms a frame around the edge of a component, allowing it to
  35173. be dragged by the edges or corners to resize it - like the way windows are
  35174. resized in MSWindows or Linux.
  35175. To use it, just add it to your component, making it fill the entire parent component
  35176. (there's a mouse hit-test that only traps mouse-events which land around the
  35177. edge of the component, so it's even ok to put it on top of any other components
  35178. you're using). Make sure you rescale the resizer component to fill the parent
  35179. each time the parent's size changes.
  35180. @see ResizableCornerComponent
  35181. */
  35182. class JUCE_API ResizableBorderComponent : public Component
  35183. {
  35184. public:
  35185. /** Creates a resizer.
  35186. Pass in the target component which you want to be resized when this one is
  35187. dragged.
  35188. The target component will usually be a parent of the resizer component, but this
  35189. isn't mandatory.
  35190. Remember that when the target component is resized, it'll need to move and
  35191. resize this component to keep it in place, as this won't happen automatically.
  35192. If the constrainer parameter is non-zero, then this object will be used to enforce
  35193. limits on the size and position that the component can be stretched to. Make sure
  35194. that the constrainer isn't deleted while still in use by this object.
  35195. @see ComponentBoundsConstrainer
  35196. */
  35197. ResizableBorderComponent (Component* const componentToResize,
  35198. ComponentBoundsConstrainer* const constrainer);
  35199. /** Destructor. */
  35200. ~ResizableBorderComponent();
  35201. /** Specifies how many pixels wide the draggable edges of this component are.
  35202. @see getBorderThickness
  35203. */
  35204. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35205. /** Returns the number of pixels wide that the draggable edges of this component are.
  35206. @see setBorderThickness
  35207. */
  35208. const BorderSize getBorderThickness() const throw();
  35209. juce_UseDebuggingNewOperator
  35210. protected:
  35211. /** @internal */
  35212. void paint (Graphics& g);
  35213. /** @internal */
  35214. void mouseEnter (const MouseEvent& e);
  35215. /** @internal */
  35216. void mouseMove (const MouseEvent& e);
  35217. /** @internal */
  35218. void mouseDown (const MouseEvent& e);
  35219. /** @internal */
  35220. void mouseDrag (const MouseEvent& e);
  35221. /** @internal */
  35222. void mouseUp (const MouseEvent& e);
  35223. /** @internal */
  35224. bool hitTest (int x, int y);
  35225. private:
  35226. Component* const component;
  35227. ComponentBoundsConstrainer* constrainer;
  35228. BorderSize borderSize;
  35229. int originalX, originalY, originalW, originalH;
  35230. int mouseZone;
  35231. void updateMouseZone (const MouseEvent& e) throw();
  35232. ResizableBorderComponent (const ResizableBorderComponent&);
  35233. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35234. };
  35235. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35236. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35237. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35238. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35239. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35240. /** A component that resizes a parent window when dragged.
  35241. This is the small triangular stripey resizer component you get in the bottom-right
  35242. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35243. a larger component and it will automatically resize its parent when it gets dragged
  35244. around.
  35245. @see ResizableFrameComponent
  35246. */
  35247. class JUCE_API ResizableCornerComponent : public Component
  35248. {
  35249. public:
  35250. /** Creates a resizer.
  35251. Pass in the target component which you want to be resized when this one is
  35252. dragged.
  35253. The target component will usually be a parent of the resizer component, but this
  35254. isn't mandatory.
  35255. Remember that when the target component is resized, it'll need to move and
  35256. resize this component to keep it in place, as this won't happen automatically.
  35257. If the constrainer parameter is non-zero, then this object will be used to enforce
  35258. limits on the size and position that the component can be stretched to. Make sure
  35259. that the constrainer isn't deleted while still in use by this object. If you
  35260. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35261. @see ComponentBoundsConstrainer
  35262. */
  35263. ResizableCornerComponent (Component* const componentToResize,
  35264. ComponentBoundsConstrainer* const constrainer);
  35265. /** Destructor. */
  35266. ~ResizableCornerComponent();
  35267. juce_UseDebuggingNewOperator
  35268. protected:
  35269. /** @internal */
  35270. void paint (Graphics& g);
  35271. /** @internal */
  35272. void mouseDown (const MouseEvent& e);
  35273. /** @internal */
  35274. void mouseDrag (const MouseEvent& e);
  35275. /** @internal */
  35276. void mouseUp (const MouseEvent& e);
  35277. /** @internal */
  35278. bool hitTest (int x, int y);
  35279. private:
  35280. Component* const component;
  35281. ComponentBoundsConstrainer* constrainer;
  35282. int originalX, originalY, originalW, originalH;
  35283. ResizableCornerComponent (const ResizableCornerComponent&);
  35284. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35285. };
  35286. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35287. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35288. /**
  35289. A base class for top-level windows that can be dragged around and resized.
  35290. To add content to the window, use its setContentComponent() method to
  35291. give it a component that will remain positioned inside it (leaving a gap around
  35292. the edges for a border).
  35293. It's not advisable to add child components directly to a ResizableWindow: put them
  35294. inside your content component instead. And overriding methods like resized(), moved(), etc
  35295. is also not recommended - instead override these methods for your content component.
  35296. (If for some obscure reason you do need to override these methods, always remember to
  35297. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35298. decorations correctly).
  35299. By default resizing isn't enabled - use the setResizable() method to enable it and
  35300. to choose the style of resizing to use.
  35301. @see TopLevelWindow
  35302. */
  35303. class JUCE_API ResizableWindow : public TopLevelWindow
  35304. {
  35305. public:
  35306. /** Creates a ResizableWindow.
  35307. @param name the name to give the component
  35308. @param backgroundColour the colour to use for filling the window's background.
  35309. @param addToDesktop if true, the window will be automatically added to the
  35310. desktop; if false, you can use it as a child component
  35311. */
  35312. ResizableWindow (const String& name,
  35313. const Colour& backgroundColour,
  35314. const bool addToDesktop);
  35315. /** Destructor.
  35316. If a content component has been set with setContentComponent(), it
  35317. will be deleted.
  35318. */
  35319. ~ResizableWindow();
  35320. /** Returns the colour currently being used for the window's background.
  35321. As a convenience the window will fill itself with this colour, but you
  35322. can override the paint() method if you need more customised behaviour.
  35323. @see setBackgroundColour
  35324. */
  35325. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35326. /** Changes the colour currently being used for the window's background.
  35327. As a convenience the window will fill itself with this colour, but you
  35328. can override the paint() method if you need more customised behaviour.
  35329. Note that the opaque state of this window is altered by this call to reflect
  35330. the opacity of the colour passed-in. On window systems which can't support
  35331. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35332. be using this class as a base for a semi-transparent component anyway).
  35333. @see getBackgroundColour
  35334. */
  35335. void setBackgroundColour (const Colour& newColour);
  35336. /** Make the window resizable or fixed.
  35337. @param shouldBeResizable whether it's resizable at all
  35338. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35339. bottom-right; if false, it'll use a ResizableBorderComponent
  35340. around the edge
  35341. @see setResizeLimits, isResizable
  35342. */
  35343. void setResizable (const bool shouldBeResizable,
  35344. const bool useBottomRightCornerResizer);
  35345. /** True if resizing is enabled.
  35346. @see setResizable
  35347. */
  35348. bool isResizable() const throw();
  35349. /** This sets the maximum and minimum sizes for the window.
  35350. If the window's current size is outside these limits, it will be resized to
  35351. make sure it's within them.
  35352. Calling setBounds() on the component will bypass any size checking - it's only when
  35353. the window is being resized by the user that these values are enforced.
  35354. @see setResizable, setFixedAspectRatio
  35355. */
  35356. void setResizeLimits (const int newMinimumWidth,
  35357. const int newMinimumHeight,
  35358. const int newMaximumWidth,
  35359. const int newMaximumHeight) throw();
  35360. /** Returns the bounds constrainer object that this window is using.
  35361. You can access this to change its properties.
  35362. */
  35363. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35364. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35365. A pointer to the object you pass in will be kept, but it won't be deleted
  35366. by this object, so it's the caller's responsiblity to manage it.
  35367. If you pass 0, then no contraints will be placed on the positioning of the window.
  35368. */
  35369. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35370. /** Calls the window's setBounds method, after first checking these bounds
  35371. with the current constrainer.
  35372. @see setConstrainer
  35373. */
  35374. void setBoundsConstrained (int x, int y, int width, int height);
  35375. /** Returns true if the window is currently in full-screen mode.
  35376. @see setFullScreen
  35377. */
  35378. bool isFullScreen() const;
  35379. /** Puts the window into full-screen mode, or restores it to its normal size.
  35380. If true, the window will become full-screen; if false, it will return to the
  35381. last size it was before being made full-screen.
  35382. @see isFullScreen
  35383. */
  35384. void setFullScreen (const bool shouldBeFullScreen);
  35385. /** Returns true if the window is currently minimised.
  35386. @see setMinimised
  35387. */
  35388. bool isMinimised() const;
  35389. /** Minimises the window, or restores it to its previous position and size.
  35390. When being un-minimised, it'll return to the last position and size it
  35391. was in before being minimised.
  35392. @see isMinimised
  35393. */
  35394. void setMinimised (const bool shouldMinimise);
  35395. /** Returns a string which encodes the window's current size and position.
  35396. This string will encapsulate the window's size, position, and whether it's
  35397. in full-screen mode. It's intended for letting your application save and
  35398. restore a window's position.
  35399. Use the restoreWindowStateFromString() to restore from a saved state.
  35400. @see restoreWindowStateFromString
  35401. */
  35402. const String getWindowStateAsString();
  35403. /** Restores the window to a previously-saved size and position.
  35404. This restores the window's size, positon and full-screen status from an
  35405. string that was previously created with the getWindowStateAsString()
  35406. method.
  35407. @returns false if the string wasn't a valid window state
  35408. @see getWindowStateAsString
  35409. */
  35410. bool restoreWindowStateFromString (const String& previousState);
  35411. /** Returns the current content component.
  35412. This will be the component set by setContentComponent(), or 0 if none
  35413. has yet been specified.
  35414. @see setContentComponent
  35415. */
  35416. Component* getContentComponent() const throw() { return contentComponent; }
  35417. /** Changes the current content component.
  35418. This sets a component that will be placed in the centre of the ResizableWindow,
  35419. (leaving a space around the edge for the border).
  35420. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35421. with addChildComponent(). Instead, add them to the content component.
  35422. @param newContentComponent the new component to use (or null to not use one) - this
  35423. component will be deleted either when replaced by another call
  35424. to this method, or when the ResizableWindow is deleted.
  35425. To remove a content component without deleting it, use
  35426. setContentComponent (0, false).
  35427. @param deleteOldOne if true, the previous content component will be deleted; if
  35428. false, the previous component will just be removed without
  35429. deleting it.
  35430. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35431. it always fits around the size of the content component. If false, the
  35432. new content will be resized to fit the current space available.
  35433. */
  35434. void setContentComponent (Component* const newContentComponent,
  35435. const bool deleteOldOne = true,
  35436. const bool resizeToFit = false);
  35437. /** Changes the window so that the content component ends up with the specified size.
  35438. This is basically a setSize call on the window, but which adds on the borders,
  35439. so you can specify the content component's target size.
  35440. */
  35441. void setContentComponentSize (int width, int height);
  35442. juce_UseDebuggingNewOperator
  35443. protected:
  35444. /** @internal */
  35445. void paint (Graphics& g);
  35446. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35447. void moved();
  35448. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35449. void resized();
  35450. /** @internal */
  35451. void mouseDown (const MouseEvent& e);
  35452. /** @internal */
  35453. void mouseDrag (const MouseEvent& e);
  35454. /** @internal */
  35455. void lookAndFeelChanged();
  35456. /** @internal */
  35457. void childBoundsChanged (Component* child);
  35458. /** @internal */
  35459. void parentSizeChanged();
  35460. /** @internal */
  35461. void visibilityChanged();
  35462. /** @internal */
  35463. void activeWindowStatusChanged();
  35464. /** @internal */
  35465. int getDesktopWindowStyleFlags() const;
  35466. /** Returns the width of the border to use around the window.
  35467. @see getContentComponentBorder
  35468. */
  35469. virtual const BorderSize getBorderThickness();
  35470. /** Returns the insets to use when positioning the content component.
  35471. @see getBorderThickness
  35472. */
  35473. virtual const BorderSize getContentComponentBorder();
  35474. #ifdef JUCE_DEBUG
  35475. /** Overridden to warn people about adding components directly to this component
  35476. instead of using setContentComponent().
  35477. If you know what you're doing and are sure you really want to add a component, specify
  35478. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35479. */
  35480. void addChildComponent (Component* const child, int zOrder = -1);
  35481. /** Overridden to warn people about adding components directly to this component
  35482. instead of using setContentComponent().
  35483. If you know what you're doing and are sure you really want to add a component, specify
  35484. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35485. */
  35486. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35487. #endif
  35488. ResizableCornerComponent* resizableCorner;
  35489. ResizableBorderComponent* resizableBorder;
  35490. private:
  35491. Component* contentComponent;
  35492. bool resizeToFitContent, fullscreen;
  35493. Colour backgroundColour;
  35494. ComponentDragger dragger;
  35495. Rectangle lastNonFullScreenPos;
  35496. ComponentBoundsConstrainer defaultConstrainer;
  35497. ComponentBoundsConstrainer* constrainer;
  35498. #ifdef JUCE_DEBUG
  35499. bool hasBeenResized;
  35500. #endif
  35501. void updateLastPos();
  35502. ResizableWindow (const ResizableWindow&);
  35503. const ResizableWindow& operator= (const ResizableWindow&);
  35504. // (xxx remove these eventually)
  35505. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35506. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35507. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35508. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35509. };
  35510. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35511. /********* End of inlined file: juce_ResizableWindow.h *********/
  35512. /**
  35513. A resizable window with a title bar and maximise, minimise and close buttons.
  35514. This subclass of ResizableWindow creates a fairly standard type of window with
  35515. a title bar and various buttons. The name of the component is shown in the
  35516. title bar, and an icon can optionally be specified with setIcon().
  35517. All the methods available to a ResizableWindow are also available to this,
  35518. so it can easily be made resizable, minimised, maximised, etc.
  35519. It's not advisable to add child components directly to a DocumentWindow: put them
  35520. inside your content component instead. And overriding methods like resized(), moved(), etc
  35521. is also not recommended - instead override these methods for your content component.
  35522. (If for some obscure reason you do need to override these methods, always remember to
  35523. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35524. decorations correctly).
  35525. You can also automatically add a menu bar to the window, using the setMenuBar()
  35526. method.
  35527. @see ResizableWindow, DialogWindow
  35528. */
  35529. class JUCE_API DocumentWindow : public ResizableWindow
  35530. {
  35531. public:
  35532. /** The set of available button-types that can be put on the title bar.
  35533. @see setTitleBarButtonsRequired
  35534. */
  35535. enum TitleBarButtons
  35536. {
  35537. minimiseButton = 1,
  35538. maximiseButton = 2,
  35539. closeButton = 4,
  35540. /** A combination of all the buttons above. */
  35541. allButtons = 7
  35542. };
  35543. /** Creates a DocumentWindow.
  35544. @param name the name to give the component - this is also
  35545. the title shown at the top of the window. To change
  35546. this later, use setName()
  35547. @param backgroundColour the colour to use for filling the window's background.
  35548. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35549. should be shown on the title bar. This value is a bitwise
  35550. combination of values from the TitleBarButtons enum. Note
  35551. that it can be "allButtons" to get them all. You
  35552. can change this later with the setTitleBarButtonsRequired()
  35553. method, which can also specify where they are positioned.
  35554. @param addToDesktop if true, the window will be automatically added to the
  35555. desktop; if false, you can use it as a child component
  35556. @see TitleBarButtons
  35557. */
  35558. DocumentWindow (const String& name,
  35559. const Colour& backgroundColour,
  35560. const int requiredButtons,
  35561. const bool addToDesktop = true);
  35562. /** Destructor.
  35563. If a content component has been set with setContentComponent(), it
  35564. will be deleted.
  35565. */
  35566. ~DocumentWindow();
  35567. /** Changes the component's name.
  35568. (This is overridden from Component::setName() to cause a repaint, as
  35569. the name is what gets drawn across the window's title bar).
  35570. */
  35571. void setName (const String& newName);
  35572. /** Sets an icon to show in the title bar, next to the title.
  35573. A copy is made internally of the image, so the caller can delete the
  35574. image after calling this. If 0 is passed-in, any existing icon will be
  35575. removed.
  35576. */
  35577. void setIcon (const Image* imageToUse);
  35578. /** Changes the height of the title-bar. */
  35579. void setTitleBarHeight (const int newHeight);
  35580. /** Returns the current title bar height. */
  35581. int getTitleBarHeight() const;
  35582. /** Changes the set of title-bar buttons being shown.
  35583. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35584. should be shown on the title bar. This value is a bitwise
  35585. combination of values from the TitleBarButtons enum. Note
  35586. that it can be "allButtons" to get them all.
  35587. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  35588. left side of the bar; if false, they'll be placed at the right
  35589. */
  35590. void setTitleBarButtonsRequired (const int requiredButtons,
  35591. const bool positionTitleBarButtonsOnLeft);
  35592. /** Sets whether the title should be centred within the window.
  35593. If true, the title text is shown in the middle of the title-bar; if false,
  35594. it'll be shown at the left of the bar.
  35595. */
  35596. void setTitleBarTextCentred (const bool textShouldBeCentred);
  35597. /** Creates a menu inside this window.
  35598. @param menuBarModel this specifies a MenuBarModel that should be used to
  35599. generate the contents of a menu bar that will be placed
  35600. just below the title bar, and just above any content
  35601. component. If this value is zero, any existing menu bar
  35602. will be removed from the component; if non-zero, one will
  35603. be added if it's required.
  35604. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  35605. or less to use the look-and-feel's default size.
  35606. */
  35607. void setMenuBar (MenuBarModel* menuBarModel,
  35608. const int menuBarHeight = 0);
  35609. /** This method is called when the user tries to close the window.
  35610. This is triggered by the user clicking the close button, or using some other
  35611. OS-specific key shortcut or OS menu for getting rid of a window.
  35612. If the window is just a pop-up, you should override this closeButtonPressed()
  35613. method and make it delete the window in whatever way is appropriate for your
  35614. app. E.g. you might just want to call "delete this".
  35615. If your app is centred around this window such that the whole app should quit when
  35616. the window is closed, then you will probably want to use this method as an opportunity
  35617. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  35618. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  35619. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  35620. or closing it via the taskbar icon on Windows).
  35621. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  35622. redirects it to call this method, so any methods of closing the window that are
  35623. caught by userTriedToCloseWindow() will also end up here).
  35624. */
  35625. virtual void closeButtonPressed();
  35626. /** Callback that is triggered when the minimise button is pressed.
  35627. The default implementation of this calls ResizableWindow::setMinimised(), but
  35628. you can override it to do more customised behaviour.
  35629. */
  35630. virtual void minimiseButtonPressed();
  35631. /** Callback that is triggered when the maximise button is pressed, or when the
  35632. title-bar is double-clicked.
  35633. The default implementation of this calls ResizableWindow::setFullScreen(), but
  35634. you can override it to do more customised behaviour.
  35635. */
  35636. virtual void maximiseButtonPressed();
  35637. /** Returns the close button, (or 0 if there isn't one). */
  35638. Button* getCloseButton() const throw();
  35639. /** Returns the minimise button, (or 0 if there isn't one). */
  35640. Button* getMinimiseButton() const throw();
  35641. /** Returns the maximise button, (or 0 if there isn't one). */
  35642. Button* getMaximiseButton() const throw();
  35643. /** @internal */
  35644. void paint (Graphics& g);
  35645. /** @internal */
  35646. void resized();
  35647. /** @internal */
  35648. void lookAndFeelChanged();
  35649. /** @internal */
  35650. const BorderSize getBorderThickness();
  35651. /** @internal */
  35652. const BorderSize getContentComponentBorder();
  35653. /** @internal */
  35654. void mouseDoubleClick (const MouseEvent& e);
  35655. /** @internal */
  35656. void userTriedToCloseWindow();
  35657. /** @internal */
  35658. void activeWindowStatusChanged();
  35659. /** @internal */
  35660. int getDesktopWindowStyleFlags() const;
  35661. /** @internal */
  35662. void parentHierarchyChanged();
  35663. juce_UseDebuggingNewOperator
  35664. private:
  35665. int titleBarHeight, menuBarHeight, requiredButtons;
  35666. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  35667. Button* titleBarButtons [3];
  35668. Image* titleBarIcon;
  35669. MenuBarComponent* menuBar;
  35670. MenuBarModel* menuBarModel;
  35671. class ButtonListenerProxy : public ButtonListener
  35672. {
  35673. public:
  35674. ButtonListenerProxy();
  35675. void buttonClicked (Button* button);
  35676. DocumentWindow* owner;
  35677. } buttonListener;
  35678. int getBorderSize() const;
  35679. void repaintTitleBar();
  35680. DocumentWindow (const DocumentWindow&);
  35681. const DocumentWindow& operator= (const DocumentWindow&);
  35682. };
  35683. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35684. /********* End of inlined file: juce_DocumentWindow.h *********/
  35685. class MultiDocumentPanel;
  35686. class MDITabbedComponentInternal;
  35687. /**
  35688. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  35689. component.
  35690. It's like a normal DocumentWindow but has some extra functionality to make sure
  35691. everything works nicely inside a MultiDocumentPanel.
  35692. @see MultiDocumentPanel
  35693. */
  35694. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  35695. {
  35696. public:
  35697. /**
  35698. */
  35699. MultiDocumentPanelWindow (const Colour& backgroundColour);
  35700. /** Destructor. */
  35701. ~MultiDocumentPanelWindow();
  35702. /** @internal */
  35703. void maximiseButtonPressed();
  35704. /** @internal */
  35705. void closeButtonPressed();
  35706. /** @internal */
  35707. void activeWindowStatusChanged();
  35708. /** @internal */
  35709. void broughtToFront();
  35710. juce_UseDebuggingNewOperator
  35711. private:
  35712. void updateOrder();
  35713. MultiDocumentPanel* getOwner() const throw();
  35714. };
  35715. /**
  35716. A component that contains a set of other components either in floating windows
  35717. or tabs.
  35718. This acts as a panel that can be used to hold a set of open document windows, with
  35719. different layout modes.
  35720. Use addDocument() and closeDocument() to add or remove components from the
  35721. panel - never use any of the Component methods to access the panel's child
  35722. components directly, as these are managed internally.
  35723. */
  35724. class JUCE_API MultiDocumentPanel : public Component,
  35725. private ComponentListener
  35726. {
  35727. public:
  35728. /** Creates an empty panel.
  35729. Use addDocument() and closeDocument() to add or remove components from the
  35730. panel - never use any of the Component methods to access the panel's child
  35731. components directly, as these are managed internally.
  35732. */
  35733. MultiDocumentPanel();
  35734. /** Destructor.
  35735. When deleted, this will call closeAllDocuments (false) to make sure all its
  35736. components are deleted. If you need to make sure all documents are saved
  35737. before closing, then you should call closeAllDocuments (true) and check that
  35738. it returns true before deleting the panel.
  35739. */
  35740. ~MultiDocumentPanel();
  35741. /** Tries to close all the documents.
  35742. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35743. be called for each open document, and any of these calls fails, this method
  35744. will stop and return false, leaving some documents still open.
  35745. If checkItsOkToCloseFirst is false, then all documents will be closed
  35746. unconditionally.
  35747. @see closeDocument
  35748. */
  35749. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  35750. /** Adds a document component to the panel.
  35751. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  35752. this will fail and return false. (If it does fail, the component passed-in will not be
  35753. deleted, even if deleteWhenRemoved was set to true).
  35754. The MultiDocumentPanel will deal with creating a window border to go around your component,
  35755. so just pass in the bare content component here, no need to give it a ResizableWindow
  35756. or DocumentWindow.
  35757. @param component the component to add
  35758. @param backgroundColour the background colour to use to fill the component's
  35759. window or tab
  35760. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  35761. or closeAllDocuments(), then it will be deleted. If false, then
  35762. the caller must handle the component's deletion
  35763. */
  35764. bool addDocument (Component* const component,
  35765. const Colour& backgroundColour,
  35766. const bool deleteWhenRemoved);
  35767. /** Closes one of the documents.
  35768. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35769. be called, and if it fails, this method will return false without closing the
  35770. document.
  35771. If checkItsOkToCloseFirst is false, then the documents will be closed
  35772. unconditionally.
  35773. The component will be deleted if the deleteWhenRemoved parameter was set to
  35774. true when it was added with addDocument.
  35775. @see addDocument, closeAllDocuments
  35776. */
  35777. bool closeDocument (Component* component,
  35778. const bool checkItsOkToCloseFirst);
  35779. /** Returns the number of open document windows.
  35780. @see getDocument
  35781. */
  35782. int getNumDocuments() const throw();
  35783. /** Returns one of the open documents.
  35784. The order of the documents in this array may change when they are added, removed
  35785. or moved around.
  35786. @see getNumDocuments
  35787. */
  35788. Component* getDocument (const int index) const throw();
  35789. /** Returns the document component that is currently focused or on top.
  35790. If currently using floating windows, then this will be the component in the currently
  35791. active window, or the top component if none are active.
  35792. If it's currently in tabbed mode, then it'll return the component in the active tab.
  35793. @see setActiveDocument
  35794. */
  35795. Component* getActiveDocument() const throw();
  35796. /** Makes one of the components active and brings it to the top.
  35797. @see getActiveDocument
  35798. */
  35799. void setActiveDocument (Component* component);
  35800. /** Callback which gets invoked when the currently-active document changes. */
  35801. virtual void activeDocumentChanged();
  35802. /** Sets a limit on how many windows can be open at once.
  35803. If this is zero or less there's no limit (the default). addDocument() will fail
  35804. if this number is exceeded.
  35805. */
  35806. void setMaximumNumDocuments (const int maximumNumDocuments);
  35807. /** Sets an option to make the document fullscreen if there's only one document open.
  35808. If set to true, then if there's only one document, it'll fill the whole of this
  35809. component without tabs or a window border. If false, then tabs or a window
  35810. will always be shown, even if there's only one document. If there's more than
  35811. one document open, then this option makes no difference.
  35812. */
  35813. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  35814. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  35815. */
  35816. bool isFullscreenWhenOneDocument() const throw();
  35817. /** The different layout modes available. */
  35818. enum LayoutMode
  35819. {
  35820. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  35821. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  35822. };
  35823. /** Changes the panel's mode.
  35824. @see LayoutMode, getLayoutMode
  35825. */
  35826. void setLayoutMode (const LayoutMode newLayoutMode);
  35827. /** Returns the current layout mode. */
  35828. LayoutMode getLayoutMode() const throw() { return mode; }
  35829. /** Sets the background colour for the whole panel.
  35830. Each document has its own background colour, but this is the one used to fill the areas
  35831. behind them.
  35832. */
  35833. void setBackgroundColour (const Colour& newBackgroundColour);
  35834. /** Returns the current background colour.
  35835. @see setBackgroundColour
  35836. */
  35837. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35838. /** A subclass must override this to say whether its currently ok for a document
  35839. to be closed.
  35840. This method is called by closeDocument() and closeAllDocuments() to indicate that
  35841. a document should be saved if possible, ready for it to be closed.
  35842. If this method returns true, then it means the document is ok and can be closed.
  35843. If it returns false, then it means that the closeDocument() method should stop
  35844. and not close.
  35845. Normally, you'd use this method to ask the user if they want to save any changes,
  35846. then return true if the save operation went ok. If the user cancelled the save
  35847. operation you could return false here to abort the close operation.
  35848. If your component is based on the FileBasedDocument class, then you'd probably want
  35849. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  35850. FileBasedDocument::savedOk
  35851. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  35852. */
  35853. virtual bool tryToCloseDocument (Component* component) = 0;
  35854. /** Creates a new window to be used for a document.
  35855. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  35856. but you might want to override it to return a custom component.
  35857. */
  35858. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  35859. /** @internal */
  35860. void paint (Graphics& g);
  35861. /** @internal */
  35862. void resized();
  35863. /** @internal */
  35864. void componentNameChanged (Component&);
  35865. juce_UseDebuggingNewOperator
  35866. private:
  35867. LayoutMode mode;
  35868. Array <Component*> components;
  35869. TabbedComponent* tabComponent;
  35870. Colour backgroundColour;
  35871. int maximumNumDocuments, numDocsBeforeTabsUsed;
  35872. friend class MultiDocumentPanelWindow;
  35873. friend class MDITabbedComponentInternal;
  35874. Component* getContainerComp (Component* c) const;
  35875. void updateOrder();
  35876. void addWindow (Component* component);
  35877. };
  35878. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35879. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  35880. #endif
  35881. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35882. #endif
  35883. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35884. #endif
  35885. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  35886. #endif
  35887. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35888. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  35889. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35890. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35891. /**
  35892. For laying out a set of components, where the components have preferred sizes
  35893. and size limits, but where they are allowed to stretch to fill the available
  35894. space.
  35895. For example, if you have a component containing several other components, and
  35896. each one should be given a share of the total size, you could use one of these
  35897. to resize the child components when the parent component is resized. Then
  35898. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  35899. A StretchableLayoutManager operates only in one dimension, so if you have a set
  35900. of components stacked vertically on top of each other, you'd use one to manage their
  35901. heights. To build up complex arrangements of components, e.g. for applications
  35902. with multiple nested panels, you would use more than one StretchableLayoutManager.
  35903. E.g. by using two (one vertical, one horizontal), you could create a resizable
  35904. spreadsheet-style table.
  35905. E.g.
  35906. @code
  35907. class MyComp : public Component
  35908. {
  35909. StretchableLayoutManager myLayout;
  35910. MyComp()
  35911. {
  35912. myLayout.setItemLayout (0, // for item 0
  35913. 50, 100, // must be between 50 and 100 pixels in size
  35914. -0.6); // and its preferred size is 60% of the total available space
  35915. myLayout.setItemLayout (1, // for item 1
  35916. -0.2, -0.6, // size must be between 20% and 60% of the available space
  35917. 50); // and its preferred size is 50 pixels
  35918. }
  35919. void resized()
  35920. {
  35921. // make a list of two of our child components that we want to reposition
  35922. Component* comps[] = { myComp1, myComp2 };
  35923. // this will position the 2 components, one above the other, to fit
  35924. // vertically into the rectangle provided.
  35925. myLayout.layOutComponents (comps, 2,
  35926. 0, 0, getWidth(), getHeight(),
  35927. true);
  35928. }
  35929. };
  35930. @endcode
  35931. @see StretchableLayoutResizerBar
  35932. */
  35933. class JUCE_API StretchableLayoutManager
  35934. {
  35935. public:
  35936. /** Creates an empty layout.
  35937. You'll need to add some item properties to the layout before it can be used
  35938. to resize things - see setItemLayout().
  35939. */
  35940. StretchableLayoutManager();
  35941. /** Destructor. */
  35942. ~StretchableLayoutManager();
  35943. /** For a numbered item, this sets its size limits and preferred size.
  35944. @param itemIndex the index of the item to change.
  35945. @param minimumSize the minimum size that this item is allowed to be - a positive number
  35946. indicates an absolute size in pixels. A negative number indicates a
  35947. proportion of the available space (e.g -0.5 is 50%)
  35948. @param maximumSize the maximum size that this item is allowed to be - a positive number
  35949. indicates an absolute size in pixels. A negative number indicates a
  35950. proportion of the available space
  35951. @param preferredSize the size that this item would like to be, if there's enough room. A
  35952. positive number indicates an absolute size in pixels. A negative number
  35953. indicates a proportion of the available space
  35954. @see getItemLayout
  35955. */
  35956. void setItemLayout (const int itemIndex,
  35957. const double minimumSize,
  35958. const double maximumSize,
  35959. const double preferredSize);
  35960. /** For a numbered item, this returns its size limits and preferred size.
  35961. @param itemIndex the index of the item.
  35962. @param minimumSize the minimum size that this item is allowed to be - a positive number
  35963. indicates an absolute size in pixels. A negative number indicates a
  35964. proportion of the available space (e.g -0.5 is 50%)
  35965. @param maximumSize the maximum size that this item is allowed to be - a positive number
  35966. indicates an absolute size in pixels. A negative number indicates a
  35967. proportion of the available space
  35968. @param preferredSize the size that this item would like to be, if there's enough room. A
  35969. positive number indicates an absolute size in pixels. A negative number
  35970. indicates a proportion of the available space
  35971. @returns false if the item's properties hadn't been set
  35972. @see setItemLayout
  35973. */
  35974. bool getItemLayout (const int itemIndex,
  35975. double& minimumSize,
  35976. double& maximumSize,
  35977. double& preferredSize) const;
  35978. /** Clears all the properties that have been set with setItemLayout() and resets
  35979. this object to its initial state.
  35980. */
  35981. void clearAllItems();
  35982. /** Takes a set of components that correspond to the layout's items, and positions
  35983. them to fill a space.
  35984. This will try to give each item its preferred size, whether that's a relative size
  35985. or an absolute one.
  35986. @param components an array of components that correspond to each of the
  35987. numbered items that the StretchableLayoutManager object
  35988. has been told about with setItemLayout()
  35989. @param numComponents the number of components in the array that is passed-in. This
  35990. should be the same as the number of items this object has been
  35991. told about.
  35992. @param x the left of the rectangle in which the components should
  35993. be laid out
  35994. @param y the top of the rectangle in which the components should
  35995. be laid out
  35996. @param width the width of the rectangle in which the components should
  35997. be laid out
  35998. @param height the height of the rectangle in which the components should
  35999. be laid out
  36000. @param vertically if true, the components will be positioned in a vertical stack,
  36001. so that they fill the height of the rectangle. If false, they
  36002. will be placed side-by-side in a horizontal line, filling the
  36003. available width
  36004. @param resizeOtherDimension if true, this means that the components will have their
  36005. other dimension resized to fit the space - i.e. if the 'vertically'
  36006. parameter is true, their x-positions and widths are adjusted to fit
  36007. the x and width parameters; if 'vertically' is false, their y-positions
  36008. and heights are adjusted to fit the y and height parameters.
  36009. */
  36010. void layOutComponents (Component** const components,
  36011. int numComponents,
  36012. int x, int y, int width, int height,
  36013. const bool vertically,
  36014. const bool resizeOtherDimension);
  36015. /** Returns the current position of one of the items.
  36016. This is only a valid call after layOutComponents() has been called, as it
  36017. returns the last position that this item was placed at. If the layout was
  36018. vertical, the value returned will be the y position of the top of the item,
  36019. relative to the top of the rectangle in which the items were placed (so for
  36020. example, item 0 will always have position of 0, even in the rectangle passed
  36021. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  36022. the position returned is the item's left-hand position, again relative to the
  36023. x position of the rectangle used.
  36024. @see getItemCurrentSize, setItemPosition
  36025. */
  36026. int getItemCurrentPosition (const int itemIndex) const;
  36027. /** Returns the current size of one of the items.
  36028. This is only meaningful after layOutComponents() has been called, as it
  36029. returns the last size that this item was given. If the layout was done
  36030. vertically, it'll return the item's height in pixels; if it was horizontal,
  36031. it'll return its width.
  36032. @see getItemCurrentRelativeSize
  36033. */
  36034. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36035. /** Returns the current size of one of the items.
  36036. This is only meaningful after layOutComponents() has been called, as it
  36037. returns the last size that this item was given. If the layout was done
  36038. vertically, it'll return a negative value representing the item's height relative
  36039. to the last size used for laying the components out; if the layout was done
  36040. horizontally it'll be the proportion of its width.
  36041. @see getItemCurrentAbsoluteSize
  36042. */
  36043. double getItemCurrentRelativeSize (const int itemIndex) const;
  36044. /** Moves one of the items, shifting along any other items as necessary in
  36045. order to get it to the desired position.
  36046. Calling this method will also update the preferred sizes of the items it
  36047. shuffles along, so that they reflect their new positions.
  36048. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36049. about when it's dragged).
  36050. @param itemIndex the item to move
  36051. @param newPosition the absolute position that you'd like this item to move
  36052. to. The item might not be able to always reach exactly this position,
  36053. because other items may have minimum sizes that constrain how
  36054. far it can go
  36055. */
  36056. void setItemPosition (const int itemIndex,
  36057. int newPosition);
  36058. juce_UseDebuggingNewOperator
  36059. private:
  36060. struct ItemLayoutProperties
  36061. {
  36062. int itemIndex;
  36063. int currentSize;
  36064. double minSize, maxSize, preferredSize;
  36065. };
  36066. OwnedArray <ItemLayoutProperties> items;
  36067. int totalSize;
  36068. static int sizeToRealSize (double size, int totalSpace);
  36069. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36070. void setTotalSize (const int newTotalSize);
  36071. int fitComponentsIntoSpace (const int startIndex,
  36072. const int endIndex,
  36073. const int availableSpace,
  36074. int startPos);
  36075. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36076. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36077. void updatePrefSizesToMatchCurrentPositions();
  36078. StretchableLayoutManager (const StretchableLayoutManager&);
  36079. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36080. };
  36081. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36082. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36083. #endif
  36084. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36085. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36086. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36087. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36088. /**
  36089. A component that acts as one of the vertical or horizontal bars you see being
  36090. used to resize panels in a window.
  36091. One of these acts with a StretchableLayoutManager to resize the other components.
  36092. @see StretchableLayoutManager
  36093. */
  36094. class JUCE_API StretchableLayoutResizerBar : public Component
  36095. {
  36096. public:
  36097. /** Creates a resizer bar for use on a specified layout.
  36098. @param layoutToUse the layout that will be affected when this bar
  36099. is dragged
  36100. @param itemIndexInLayout the item index in the layout that corresponds to
  36101. this bar component. You'll need to set up the item
  36102. properties in a suitable way for a divider bar, e.g.
  36103. for an 8-pixel wide bar which, you could call
  36104. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36105. @param isBarVertical true if it's an upright bar that you drag left and
  36106. right; false for a horizontal one that you drag up and
  36107. down
  36108. */
  36109. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36110. const int itemIndexInLayout,
  36111. const bool isBarVertical);
  36112. /** Destructor. */
  36113. ~StretchableLayoutResizerBar();
  36114. /** This is called when the bar is dragged.
  36115. This method must update the positions of any components whose position is
  36116. determined by the StretchableLayoutManager, because they might have just
  36117. moved.
  36118. The default implementation calls the resized() method of this component's
  36119. parent component, because that's often where you're likely to apply the
  36120. layout, but it can be overridden for more specific needs.
  36121. */
  36122. virtual void hasBeenMoved();
  36123. /** @internal */
  36124. void paint (Graphics& g);
  36125. /** @internal */
  36126. void mouseDown (const MouseEvent& e);
  36127. /** @internal */
  36128. void mouseDrag (const MouseEvent& e);
  36129. juce_UseDebuggingNewOperator
  36130. private:
  36131. StretchableLayoutManager* layout;
  36132. int itemIndex, mouseDownPos;
  36133. bool isVertical;
  36134. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36135. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36136. };
  36137. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36138. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36139. #endif
  36140. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36141. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36142. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36143. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36144. /**
  36145. A utility class for fitting a set of objects whose sizes can vary between
  36146. a minimum and maximum size, into a space.
  36147. This is a trickier algorithm than it would first seem, so I've put it in this
  36148. class to allow it to be shared by various bits of code.
  36149. To use it, create one of these objects, call addItem() to add the list of items
  36150. you need, then call resizeToFit(), which will change all their sizes. You can
  36151. then retrieve the new sizes with getItemSize() and getNumItems().
  36152. It's currently used by the TableHeaderComponent for stretching out the table
  36153. headings to fill the table's width.
  36154. */
  36155. class StretchableObjectResizer
  36156. {
  36157. public:
  36158. /** Creates an empty object resizer. */
  36159. StretchableObjectResizer();
  36160. /** Destructor. */
  36161. ~StretchableObjectResizer();
  36162. /** Adds an item to the list.
  36163. The order parameter lets you specify groups of items that are resized first when some
  36164. space needs to be found. Those items with an order of 0 will be the first ones to be
  36165. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36166. will then try resizing the items with an order of 1, then 2, and so on.
  36167. */
  36168. void addItem (const double currentSize,
  36169. const double minSize,
  36170. const double maxSize,
  36171. const int order = 0);
  36172. /** Resizes all the items to fit this amount of space.
  36173. This will attempt to fit them in without exceeding each item's miniumum and
  36174. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36175. further, the final size may be greater or less than the size passed in.
  36176. After calling this method, you can retrieve the new sizes with the getItemSize()
  36177. method.
  36178. */
  36179. void resizeToFit (const double targetSize);
  36180. /** Returns the number of items that have been added. */
  36181. int getNumItems() const throw() { return items.size(); }
  36182. /** Returns the size of one of the items. */
  36183. double getItemSize (const int index) const throw();
  36184. juce_UseDebuggingNewOperator
  36185. private:
  36186. struct Item
  36187. {
  36188. double size;
  36189. double minSize;
  36190. double maxSize;
  36191. int order;
  36192. };
  36193. OwnedArray <Item> items;
  36194. StretchableObjectResizer (const StretchableObjectResizer&);
  36195. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36196. };
  36197. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36198. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36199. #endif
  36200. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36201. #endif
  36202. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36203. #endif
  36204. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36205. #endif
  36206. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36207. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36208. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36209. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36210. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  36211. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36212. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36213. /********* Start of inlined file: juce_FileFilter.h *********/
  36214. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36215. #define __JUCE_FILEFILTER_JUCEHEADER__
  36216. /**
  36217. Interface for deciding which files are suitable for something.
  36218. For example, this is used by DirectoryContentsList to select which files
  36219. go into the list.
  36220. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36221. */
  36222. class JUCE_API FileFilter
  36223. {
  36224. public:
  36225. /** Creates a filter with the given description.
  36226. The description can be returned later with the getDescription() method.
  36227. */
  36228. FileFilter (const String& filterDescription);
  36229. /** Destructor. */
  36230. virtual ~FileFilter();
  36231. /** Returns the description that the filter was created with. */
  36232. const String& getDescription() const throw();
  36233. /** Should return true if this file is suitable for inclusion in whatever context
  36234. the object is being used.
  36235. */
  36236. virtual bool isFileSuitable (const File& file) const = 0;
  36237. /** Should return true if this directory is suitable for inclusion in whatever context
  36238. the object is being used.
  36239. */
  36240. virtual bool isDirectorySuitable (const File& file) const = 0;
  36241. protected:
  36242. String description;
  36243. };
  36244. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36245. /********* End of inlined file: juce_FileFilter.h *********/
  36246. /**
  36247. A class to asynchronously scan for details about the files in a directory.
  36248. This keeps a list of files and some information about them, using a background
  36249. thread to scan for more files. As files are found, it broadcasts change messages
  36250. to tell any listeners.
  36251. @see FileListComponent, FileBrowserComponent
  36252. */
  36253. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36254. public TimeSliceClient
  36255. {
  36256. public:
  36257. /** Creates a directory list.
  36258. To set the directory it should point to, use setDirectory(), which will
  36259. also start it scanning for files on the background thread.
  36260. When the background thread finds and adds new files to this list, the
  36261. ChangeBroadcaster class will send a change message, so you can register
  36262. listeners and update them when the list changes.
  36263. @param fileFilter an optional filter to select which files are
  36264. included in the list. If this is 0, then all files
  36265. and directories are included. Make sure that the
  36266. filter doesn't get deleted during the lifetime of this
  36267. object
  36268. @param threadToUse a thread object that this list can use
  36269. to scan for files as a background task. Make sure
  36270. that the thread you give it has been started, or you
  36271. won't get any files!
  36272. */
  36273. DirectoryContentsList (const FileFilter* const fileFilter,
  36274. TimeSliceThread& threadToUse);
  36275. /** Destructor. */
  36276. ~DirectoryContentsList();
  36277. /** Sets the directory to look in for files.
  36278. If the directory that's passed in is different to the current one, this will
  36279. also start the background thread scanning it for files.
  36280. */
  36281. void setDirectory (const File& directory,
  36282. const bool includeDirectories,
  36283. const bool includeFiles);
  36284. /** Returns the directory that's currently being used. */
  36285. const File& getDirectory() const throw();
  36286. /** Clears the list, and stops the thread scanning for files. */
  36287. void clear();
  36288. /** Clears the list and restarts scanning the directory for files. */
  36289. void refresh();
  36290. /** True if the background thread hasn't yet finished scanning for files. */
  36291. bool isStillLoading() const;
  36292. /** Tells the list whether or not to ignore hidden files.
  36293. By default these are ignored.
  36294. */
  36295. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  36296. /** Contains cached information about one of the files in a DirectoryContentsList.
  36297. */
  36298. struct FileInfo
  36299. {
  36300. /** The filename.
  36301. This isn't a full pathname, it's just the last part of the path, same as you'd
  36302. get from File::getFileName().
  36303. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36304. */
  36305. String filename;
  36306. /** File size in bytes. */
  36307. int64 fileSize;
  36308. /** File modification time.
  36309. As supplied by File::getLastModificationTime().
  36310. */
  36311. Time modificationTime;
  36312. /** File creation time.
  36313. As supplied by File::getCreationTime().
  36314. */
  36315. Time creationTime;
  36316. /** True if the file is a directory. */
  36317. bool isDirectory;
  36318. /** True if the file is read-only. */
  36319. bool isReadOnly;
  36320. };
  36321. /** Returns the number of files currently available in the list.
  36322. The info about one of these files can be retrieved with getFileInfo() or
  36323. getFile().
  36324. Obviously as the background thread runs and scans the directory for files, this
  36325. number will change.
  36326. @see getFileInfo, getFile
  36327. */
  36328. int getNumFiles() const;
  36329. /** Returns the cached information about one of the files in the list.
  36330. If the index is in-range, this will return true and will copy the file's details
  36331. to the structure that is passed-in.
  36332. If it returns false, then the index wasn't in range, and the structure won't
  36333. be affected.
  36334. @see getNumFiles, getFile
  36335. */
  36336. bool getFileInfo (const int index,
  36337. FileInfo& resultInfo) const;
  36338. /** Returns one of the files in the list.
  36339. @param index should be less than getNumFiles(). If this is out-of-range, the
  36340. return value will be File::nonexistent
  36341. @see getNumFiles, getFileInfo
  36342. */
  36343. const File getFile (const int index) const;
  36344. /** Returns the file filter being used.
  36345. The filter is specified in the constructor.
  36346. */
  36347. const FileFilter* getFilter() const throw() { return fileFilter; }
  36348. /** @internal */
  36349. bool useTimeSlice();
  36350. /** @internal */
  36351. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  36352. /** @internal */
  36353. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  36354. const DirectoryContentsList::FileInfo* const second) throw();
  36355. juce_UseDebuggingNewOperator
  36356. private:
  36357. File root;
  36358. const FileFilter* fileFilter;
  36359. TimeSliceThread& thread;
  36360. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  36361. CriticalSection fileListLock;
  36362. OwnedArray <FileInfo> files;
  36363. void* volatile fileFindHandle;
  36364. bool volatile shouldStop;
  36365. void changed();
  36366. bool checkNextFile (bool& hasChanged);
  36367. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  36368. const int64 fileSize, const Time& modTime,
  36369. const Time& creationTime, const bool isReadOnly);
  36370. DirectoryContentsList (const DirectoryContentsList&);
  36371. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  36372. };
  36373. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36374. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  36375. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  36376. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36377. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36378. /**
  36379. A listener for user selection events in a file browser.
  36380. This is used by a FileBrowserComponent or FileListComponent.
  36381. */
  36382. class JUCE_API FileBrowserListener
  36383. {
  36384. public:
  36385. /** Destructor. */
  36386. virtual ~FileBrowserListener();
  36387. /** Callback when the user selects a different file in the browser. */
  36388. virtual void selectionChanged() = 0;
  36389. /** Callback when the user clicks on a file in the browser. */
  36390. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36391. /** Callback when the user double-clicks on a file in the browser. */
  36392. virtual void fileDoubleClicked (const File& file) = 0;
  36393. };
  36394. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36395. /********* End of inlined file: juce_FileBrowserListener.h *********/
  36396. /**
  36397. A base class for components that display a list of the files in a directory.
  36398. @see DirectoryContentsList
  36399. */
  36400. class JUCE_API DirectoryContentsDisplayComponent
  36401. {
  36402. public:
  36403. /**
  36404. */
  36405. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36406. /** Destructor. */
  36407. virtual ~DirectoryContentsDisplayComponent();
  36408. /** Returns the file that the user has currently selected.
  36409. Returns File::nonexistent if none is selected.
  36410. */
  36411. virtual const File getSelectedFile() const = 0;
  36412. /** Scrolls this view to the top. */
  36413. virtual void scrollToTop() = 0;
  36414. /** Adds a listener to be told when files are selected or clicked.
  36415. @see removeListener
  36416. */
  36417. void addListener (FileBrowserListener* const listener) throw();
  36418. /** Removes a listener.
  36419. @see addListener
  36420. */
  36421. void removeListener (FileBrowserListener* const listener) throw();
  36422. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36423. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36424. methods.
  36425. Note that you can also use the constants from TextEditor::ColourIds to change the
  36426. colour of the text editor that is opened when a label is editable.
  36427. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36428. */
  36429. enum ColourIds
  36430. {
  36431. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36432. textColourId = 0x1000541, /**< The colour for the text. */
  36433. };
  36434. /** @internal */
  36435. void sendSelectionChangeMessage();
  36436. /** @internal */
  36437. void sendDoubleClickMessage (const File& file);
  36438. /** @internal */
  36439. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36440. juce_UseDebuggingNewOperator
  36441. protected:
  36442. DirectoryContentsList& fileList;
  36443. SortedSet <void*> listeners;
  36444. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36445. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36446. };
  36447. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36448. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36449. #endif
  36450. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36451. #endif
  36452. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36453. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  36454. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36455. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36456. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  36457. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36458. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36459. /**
  36460. Base class for components that live inside a file chooser dialog box and
  36461. show previews of the files that get selected.
  36462. One of these allows special extra information to be displayed for files
  36463. in a dialog box as the user selects them. Each time the current file or
  36464. directory is changed, the selectedFileChanged() method will be called
  36465. to allow it to update itself appropriately.
  36466. @see FileChooser, ImagePreviewComponent
  36467. */
  36468. class JUCE_API FilePreviewComponent : public Component
  36469. {
  36470. public:
  36471. /** Creates a FilePreviewComponent. */
  36472. FilePreviewComponent();
  36473. /** Destructor. */
  36474. ~FilePreviewComponent();
  36475. /** Called to indicate that the user's currently selected file has changed.
  36476. @param newSelectedFile the newly selected file or directory, which may be
  36477. File::nonexistent if none is selected.
  36478. */
  36479. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36480. juce_UseDebuggingNewOperator
  36481. private:
  36482. FilePreviewComponent (const FilePreviewComponent&);
  36483. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  36484. };
  36485. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36486. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  36487. /**
  36488. A component for browsing and selecting a file or directory to open or save.
  36489. This contains a FileListComponent and adds various boxes and controls for
  36490. navigating and selecting a file. It can work in different modes so that it can
  36491. be used for loading or saving a file, or for choosing a directory.
  36492. @see FileChooserDialogBox, FileChooser, FileListComponent
  36493. */
  36494. class JUCE_API FileBrowserComponent : public Component,
  36495. public ChangeBroadcaster,
  36496. private FileBrowserListener,
  36497. private TextEditorListener,
  36498. private ButtonListener,
  36499. private ComboBoxListener
  36500. {
  36501. public:
  36502. /** Various modes that the browser can be used in.
  36503. One of these is passed into the constructor.
  36504. */
  36505. enum FileChooserMode
  36506. {
  36507. loadFileMode, /**< the component should allow the user to choose an existing
  36508. file with the intention of opening it. */
  36509. saveFileMode, /**< the component should allow the user to specify the name of
  36510. a file that will be used to save something. */
  36511. chooseDirectoryMode /**< the component should allow the user to select an existing
  36512. directory. */
  36513. };
  36514. /** Creates a FileBrowserComponent.
  36515. @param browserMode The intended purpose for the browser - see the
  36516. FileChooserMode enum for the various options
  36517. @param initialFileOrDirectory The file or directory that should be selected when
  36518. the component begins. If this is File::nonexistent,
  36519. a default directory will be chosen.
  36520. @param fileFilter an optional filter to use to determine which files
  36521. are shown. If this is 0 then all files are displayed. Note
  36522. that a pointer is kept internally to this object, so
  36523. make sure that it is not deleted before the browser object
  36524. is deleted.
  36525. @param previewComp an optional preview component that will be used to
  36526. show previews of files that the user selects
  36527. @param useTreeView if this is false, the files are shown in a list; if true,
  36528. they are shown in a treeview
  36529. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  36530. text into the filename box.
  36531. */
  36532. FileBrowserComponent (FileChooserMode browserMode,
  36533. const File& initialFileOrDirectory,
  36534. const FileFilter* fileFilter,
  36535. FilePreviewComponent* previewComp,
  36536. const bool useTreeView = false,
  36537. const bool filenameTextBoxIsReadOnly = false);
  36538. /** Destructor. */
  36539. ~FileBrowserComponent();
  36540. /**
  36541. */
  36542. const File getCurrentFile() const throw();
  36543. /** Returns true if the current file is usable.
  36544. This can be used to decide whether the user can press "ok" for the
  36545. current file. What it does depends on the mode, so for example in an "open"
  36546. mode, the current file is only valid if one has been selected and if the file
  36547. exists. In a "save" mode, a non-existent file would also be valid.
  36548. */
  36549. bool currentFileIsValid() const;
  36550. /** Returns the directory whose contents are currently being shown in the listbox. */
  36551. const File getRoot() const;
  36552. /** Changes the directory that's being shown in the listbox. */
  36553. void setRoot (const File& newRootDirectory);
  36554. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36555. void goUp();
  36556. /** Refreshes the directory that's currently being listed. */
  36557. void refresh();
  36558. /** Returns the browser's current mode. */
  36559. FileChooserMode getMode() const throw() { return mode; }
  36560. /** Returns a verb to describe what should happen when the file is accepted.
  36561. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36562. mode, it'll be "Save", etc.
  36563. */
  36564. virtual const String getActionVerb() const;
  36565. /** Adds a listener to be told when the user selects and clicks on files.
  36566. @see removeListener
  36567. */
  36568. void addListener (FileBrowserListener* const listener) throw();
  36569. /** Removes a listener.
  36570. @see addListener
  36571. */
  36572. void removeListener (FileBrowserListener* const listener) throw();
  36573. /** @internal */
  36574. void resized();
  36575. /** @internal */
  36576. void buttonClicked (Button* b);
  36577. /** @internal */
  36578. void comboBoxChanged (ComboBox*);
  36579. /** @internal */
  36580. void textEditorTextChanged (TextEditor& editor);
  36581. /** @internal */
  36582. void textEditorReturnKeyPressed (TextEditor& editor);
  36583. /** @internal */
  36584. void textEditorEscapeKeyPressed (TextEditor& editor);
  36585. /** @internal */
  36586. void textEditorFocusLost (TextEditor& editor);
  36587. /** @internal */
  36588. void selectionChanged();
  36589. /** @internal */
  36590. void fileClicked (const File& f, const MouseEvent& e);
  36591. /** @internal */
  36592. void fileDoubleClicked (const File& f);
  36593. /** @internal */
  36594. FilePreviewComponent* getPreviewComponent() const throw();
  36595. juce_UseDebuggingNewOperator
  36596. protected:
  36597. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  36598. private:
  36599. DirectoryContentsList* fileList;
  36600. FileFilter* directoriesOnlyFilter;
  36601. FileChooserMode mode;
  36602. File currentRoot;
  36603. SortedSet <void*> listeners;
  36604. DirectoryContentsDisplayComponent* fileListComponent;
  36605. FilePreviewComponent* previewComp;
  36606. ComboBox* currentPathBox;
  36607. TextEditor* filenameBox;
  36608. Button* goUpButton;
  36609. TimeSliceThread thread;
  36610. void sendListenerChangeMessage();
  36611. FileBrowserComponent (const FileBrowserComponent&);
  36612. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  36613. };
  36614. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36615. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  36616. #endif
  36617. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36618. #endif
  36619. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36620. /********* Start of inlined file: juce_FileChooser.h *********/
  36621. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36622. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36623. /**
  36624. Creates a dialog box to choose a file or directory to load or save.
  36625. To use a FileChooser:
  36626. - create one (as a local stack variable is the neatest way)
  36627. - call one of its browseFor.. methods
  36628. - if this returns true, the user has selected a file, so you can retrieve it
  36629. with the getResult() method.
  36630. e.g. @code
  36631. void loadMooseFile()
  36632. {
  36633. FileChooser myChooser ("Please select the moose you want to load...",
  36634. File::getSpecialLocation (File::userHomeDirectory),
  36635. "*.moose");
  36636. if (myChooser.browseForFileToOpen())
  36637. {
  36638. File mooseFile (myChooser.getResult());
  36639. loadMoose (mooseFile);
  36640. }
  36641. }
  36642. @endcode
  36643. */
  36644. class JUCE_API FileChooser
  36645. {
  36646. public:
  36647. /** Creates a FileChooser.
  36648. After creating one of these, use one of the browseFor... methods to display it.
  36649. @param dialogBoxTitle a text string to display in the dialog box to
  36650. tell the user what's going on
  36651. @param initialFileOrDirectory the file or directory that should be selected when
  36652. the dialog box opens. If this parameter is set to
  36653. File::nonexistent, a sensible default directory
  36654. will be used instead.
  36655. @param filePatternsAllowed a set of file patterns to specify which files can be
  36656. selected - each pattern should be separated by a
  36657. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36658. empty string means that all files are allowed
  36659. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36660. possible; if false, then a Juce-based browser dialog
  36661. box will always be used
  36662. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36663. */
  36664. FileChooser (const String& dialogBoxTitle,
  36665. const File& initialFileOrDirectory = File::nonexistent,
  36666. const String& filePatternsAllowed = String::empty,
  36667. const bool useOSNativeDialogBox = true);
  36668. /** Destructor. */
  36669. ~FileChooser();
  36670. /** Shows a dialog box to choose a file to open.
  36671. This will display the dialog box modally, using an "open file" mode, so that
  36672. it won't allow non-existent files or directories to be chosen.
  36673. @param previewComponent an optional component to display inside the dialog
  36674. box to show special info about the files that the user
  36675. is browsing. The component will not be deleted by this
  36676. object, so the caller must take care of it.
  36677. @returns true if the user selected a file, in which case, use the getResult()
  36678. method to find out what it was. Returns false if they cancelled instead.
  36679. @see browseForFileToSave, browseForDirectory
  36680. */
  36681. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36682. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36683. The files that are returned can be obtained by calling getResults(). See
  36684. browseForFileToOpen() for more info about the behaviour of this method.
  36685. */
  36686. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36687. /** Shows a dialog box to choose a file to save.
  36688. This will display the dialog box modally, using an "save file" mode, so it
  36689. will allow non-existent files to be chosen, but not directories.
  36690. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36691. the user if they're sure they want to overwrite a file that already
  36692. exists
  36693. @returns true if the user chose a file and pressed 'ok', in which case, use
  36694. the getResult() method to find out what the file was. Returns false
  36695. if they cancelled instead.
  36696. @see browseForFileToOpen, browseForDirectory
  36697. */
  36698. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  36699. /** Shows a dialog box to choose a directory.
  36700. This will display the dialog box modally, using an "open directory" mode, so it
  36701. will only allow directories to be returned, not files.
  36702. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36703. the getResult() method to find out what they chose. Returns false
  36704. if they cancelled instead.
  36705. @see browseForFileToOpen, browseForFileToSave
  36706. */
  36707. bool browseForDirectory();
  36708. /** Returns the last file that was chosen by one of the browseFor methods.
  36709. After calling the appropriate browseFor... method, this method lets you
  36710. find out what file or directory they chose.
  36711. Note that the file returned is only valid if the browse method returned true (i.e.
  36712. if the user pressed 'ok' rather than cancelling).
  36713. If you're using a multiple-file select, then use the getResults() method instead,
  36714. to obtain the list of all files chosen.
  36715. @see getResults
  36716. */
  36717. const File getResult() const;
  36718. /** Returns a list of all the files that were chosen during the last call to a
  36719. browse method.
  36720. This array may be empty if no files were chosen, or can contain multiple entries
  36721. if multiple files were chosen.
  36722. @see getResult
  36723. */
  36724. const OwnedArray <File>& getResults() const;
  36725. juce_UseDebuggingNewOperator
  36726. private:
  36727. String title, filters;
  36728. File startingFile;
  36729. OwnedArray <File> results;
  36730. bool useNativeDialogBox;
  36731. bool showDialog (const bool isDirectory,
  36732. const bool isSave,
  36733. const bool warnAboutOverwritingExistingFiles,
  36734. const bool selectMultipleFiles,
  36735. FilePreviewComponent* const previewComponent);
  36736. static void showPlatformDialog (OwnedArray<File>& results,
  36737. const String& title,
  36738. const File& file,
  36739. const String& filters,
  36740. bool isDirectory,
  36741. bool isSave,
  36742. bool warnAboutOverwritingExistingFiles,
  36743. bool selectMultipleFiles,
  36744. FilePreviewComponent* previewComponent);
  36745. };
  36746. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36747. /********* End of inlined file: juce_FileChooser.h *********/
  36748. #endif
  36749. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36750. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  36751. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36752. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36753. /**
  36754. A file open/save dialog box.
  36755. This is a Juce-based file dialog box; to use a native file chooser, see the
  36756. FileChooser class.
  36757. To use one of these, create it and call its show() method. e.g.
  36758. @code
  36759. {
  36760. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  36761. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  36762. File::nonexistent,
  36763. &wildcardFilter,
  36764. 0);
  36765. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  36766. T("Please choose some kind of file that you want to open..."),
  36767. browser,
  36768. getLookAndFeel().alertWindowBackground);
  36769. if (dialogBox.show())
  36770. {
  36771. File selectedFile = browser.getCurrentFile();
  36772. ...
  36773. }
  36774. }
  36775. @endcode
  36776. @see FileChooser
  36777. */
  36778. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  36779. public ButtonListener,
  36780. public FileBrowserListener
  36781. {
  36782. public:
  36783. /** Creates a file chooser box.
  36784. @param title the main title to show at the top of the box
  36785. @param instructions an optional longer piece of text to show below the title in
  36786. a smaller font, describing in more detail what's required.
  36787. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  36788. box. Make sure you delete this after (but not before!) the
  36789. dialog box has been deleted.
  36790. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  36791. if they try to select a file that already exists. (This
  36792. flag is only used when saving files)
  36793. @param backgroundColour the background colour for the top level window
  36794. @see FileBrowserComponent, FilePreviewComponent
  36795. */
  36796. FileChooserDialogBox (const String& title,
  36797. const String& instructions,
  36798. FileBrowserComponent& browserComponent,
  36799. const bool warnAboutOverwritingExistingFiles,
  36800. const Colour& backgroundColour);
  36801. /** Destructor. */
  36802. ~FileChooserDialogBox();
  36803. /** Displays and runs the dialog box modally.
  36804. This will show the box with the specified size, returning true if the user
  36805. pressed 'ok', or false if they cancelled.
  36806. Leave the width or height as 0 to use the default size
  36807. */
  36808. bool show (int width = 0,int height = 0);
  36809. /** @internal */
  36810. void buttonClicked (Button* button);
  36811. /** @internal */
  36812. void closeButtonPressed();
  36813. /** @internal */
  36814. void selectionChanged();
  36815. /** @internal */
  36816. void fileClicked (const File& file, const MouseEvent& e);
  36817. /** @internal */
  36818. void fileDoubleClicked (const File& file);
  36819. juce_UseDebuggingNewOperator
  36820. private:
  36821. class ContentComponent : public Component
  36822. {
  36823. public:
  36824. ContentComponent();
  36825. ~ContentComponent();
  36826. void paint (Graphics& g);
  36827. void resized();
  36828. String instructions;
  36829. GlyphArrangement text;
  36830. FileBrowserComponent* chooserComponent;
  36831. FilePreviewComponent* previewComponent;
  36832. TextButton* okButton;
  36833. TextButton* cancelButton;
  36834. };
  36835. ContentComponent* content;
  36836. const bool warnAboutOverwritingExistingFiles;
  36837. FileChooserDialogBox (const FileChooserDialogBox&);
  36838. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  36839. };
  36840. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36841. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  36842. #endif
  36843. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36844. #endif
  36845. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36846. /********* Start of inlined file: juce_FileListComponent.h *********/
  36847. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36848. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36849. /**
  36850. A component that displays the files in a directory as a listbox.
  36851. This implements the DirectoryContentsDisplayComponent base class so that
  36852. it can be used in a FileBrowserComponent.
  36853. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  36854. class and the FileBrowserListener class.
  36855. @see DirectoryContentsList, FileTreeComponent
  36856. */
  36857. class JUCE_API FileListComponent : public ListBox,
  36858. public DirectoryContentsDisplayComponent,
  36859. private ListBoxModel,
  36860. private ChangeListener
  36861. {
  36862. public:
  36863. /** Creates a listbox to show the contents of a specified directory.
  36864. */
  36865. FileListComponent (DirectoryContentsList& listToShow);
  36866. /** Destructor. */
  36867. ~FileListComponent();
  36868. /** Returns the file that the user has currently selected.
  36869. Returns File::nonexistent if none is selected.
  36870. */
  36871. const File getSelectedFile() const;
  36872. /** Scrolls to the top of the list. */
  36873. void scrollToTop();
  36874. /** @internal */
  36875. void changeListenerCallback (void*);
  36876. /** @internal */
  36877. int getNumRows();
  36878. /** @internal */
  36879. void paintListBoxItem (int, Graphics&, int, int, bool);
  36880. /** @internal */
  36881. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  36882. /** @internal */
  36883. void selectedRowsChanged (int lastRowSelected);
  36884. /** @internal */
  36885. void deleteKeyPressed (int currentSelectedRow);
  36886. /** @internal */
  36887. void returnKeyPressed (int currentSelectedRow);
  36888. juce_UseDebuggingNewOperator
  36889. private:
  36890. FileListComponent (const FileListComponent&);
  36891. const FileListComponent& operator= (const FileListComponent&);
  36892. File lastDirectory;
  36893. };
  36894. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36895. /********* End of inlined file: juce_FileListComponent.h *********/
  36896. #endif
  36897. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36898. /********* Start of inlined file: juce_FilenameComponent.h *********/
  36899. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36900. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36901. class FilenameComponent;
  36902. /**
  36903. Listens for events happening to a FilenameComponent.
  36904. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  36905. register one of these objects for event callbacks when the filename is changed.
  36906. @See FilenameComponent
  36907. */
  36908. class JUCE_API FilenameComponentListener
  36909. {
  36910. public:
  36911. /** Destructor. */
  36912. virtual ~FilenameComponentListener() {}
  36913. /** This method is called after the FilenameComponent's file has been changed. */
  36914. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  36915. };
  36916. /**
  36917. Shows a filename as an editable text box, with a 'browse' button and a
  36918. drop-down list for recently selected files.
  36919. A handy component for dialogue boxes where you want the user to be able to
  36920. select a file or directory.
  36921. Attach an FilenameComponentListener using the addListener() method, and it will
  36922. get called each time the user changes the filename, either by browsing for a file
  36923. and clicking 'ok', or by typing a new filename into the box and pressing return.
  36924. @see FileChooser, ComboBox
  36925. */
  36926. class JUCE_API FilenameComponent : public Component,
  36927. public SettableTooltipClient,
  36928. public FileDragAndDropTarget,
  36929. private AsyncUpdater,
  36930. private ButtonListener,
  36931. private ComboBoxListener
  36932. {
  36933. public:
  36934. /** Creates a FilenameComponent.
  36935. @param name the name for this component.
  36936. @param currentFile the file to initially show in the box
  36937. @param canEditFilename if true, the user can manually edit the filename; if false,
  36938. they can only change it by browsing for a new file
  36939. @param isDirectory if true, the file will be treated as a directory, and
  36940. an appropriate directory browser used
  36941. @param isForSaving if true, the file browser will allow non-existent files to
  36942. be picked, as the file is assumed to be used for saving rather
  36943. than loading
  36944. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  36945. If an empty string is passed in, then the pattern is assumed to be "*"
  36946. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  36947. to any filenames that are entered or chosen
  36948. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  36949. will only appear if the initial file isn't valid)
  36950. */
  36951. FilenameComponent (const String& name,
  36952. const File& currentFile,
  36953. const bool canEditFilename,
  36954. const bool isDirectory,
  36955. const bool isForSaving,
  36956. const String& fileBrowserWildcard,
  36957. const String& enforcedSuffix,
  36958. const String& textWhenNothingSelected);
  36959. /** Destructor. */
  36960. ~FilenameComponent();
  36961. /** Returns the currently displayed filename. */
  36962. const File getCurrentFile() const;
  36963. /** Changes the current filename.
  36964. If addToRecentlyUsedList is true, the filename will also be added to the
  36965. drop-down list of recent files.
  36966. If sendChangeNotification is false, then the listeners won't be told of the
  36967. change.
  36968. */
  36969. void setCurrentFile (File newFile,
  36970. const bool addToRecentlyUsedList,
  36971. const bool sendChangeNotification = true);
  36972. /** Changes whether the use can type into the filename box.
  36973. */
  36974. void setFilenameIsEditable (const bool shouldBeEditable);
  36975. /** Sets a file or directory to be the default starting point for the browser to show.
  36976. This is only used if the current file hasn't been set.
  36977. */
  36978. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  36979. /** Returns all the entries on the recent files list.
  36980. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  36981. state of this list.
  36982. @see setRecentlyUsedFilenames
  36983. */
  36984. const StringArray getRecentlyUsedFilenames() const;
  36985. /** Sets all the entries on the recent files list.
  36986. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  36987. state of this list.
  36988. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  36989. */
  36990. void setRecentlyUsedFilenames (const StringArray& filenames);
  36991. /** Adds an entry to the recently-used files dropdown list.
  36992. If the file is already in the list, it will be moved to the top. A limit
  36993. is also placed on the number of items that are kept in the list.
  36994. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  36995. */
  36996. void addRecentlyUsedFile (const File& file);
  36997. /** Changes the limit for the number of files that will be stored in the recent-file list.
  36998. */
  36999. void setMaxNumberOfRecentFiles (const int newMaximum);
  37000. /** Changes the text shown on the 'browse' button.
  37001. By default this button just says "..." but you can change it. The button itself
  37002. can be changed using the look-and-feel classes, so it might not actually have any
  37003. text on it.
  37004. */
  37005. void setBrowseButtonText (const String& browseButtonText);
  37006. /** Adds a listener that will be called when the selected file is changed. */
  37007. void addListener (FilenameComponentListener* const listener) throw();
  37008. /** Removes a previously-registered listener. */
  37009. void removeListener (FilenameComponentListener* const listener) throw();
  37010. /** Gives the component a tooltip. */
  37011. void setTooltip (const String& newTooltip);
  37012. /** @internal */
  37013. void paintOverChildren (Graphics& g);
  37014. /** @internal */
  37015. void resized();
  37016. /** @internal */
  37017. void lookAndFeelChanged();
  37018. /** @internal */
  37019. bool isInterestedInFileDrag (const StringArray& files);
  37020. /** @internal */
  37021. void filesDropped (const StringArray& files, int, int);
  37022. /** @internal */
  37023. void fileDragEnter (const StringArray& files, int, int);
  37024. /** @internal */
  37025. void fileDragExit (const StringArray& files);
  37026. juce_UseDebuggingNewOperator
  37027. private:
  37028. ComboBox* filenameBox;
  37029. String lastFilename;
  37030. Button* browseButton;
  37031. int maxRecentFiles;
  37032. bool isDir, isSaving, isFileDragOver;
  37033. String wildcard, enforcedSuffix, browseButtonText;
  37034. SortedSet <void*> listeners;
  37035. File defaultBrowseFile;
  37036. void comboBoxChanged (ComboBox*);
  37037. void buttonClicked (Button* button);
  37038. void handleAsyncUpdate();
  37039. FilenameComponent (const FilenameComponent&);
  37040. const FilenameComponent& operator= (const FilenameComponent&);
  37041. };
  37042. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37043. /********* End of inlined file: juce_FilenameComponent.h *********/
  37044. #endif
  37045. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37046. #endif
  37047. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37048. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37049. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37050. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37051. /**
  37052. Shows a set of file paths in a list, allowing them to be added, removed or
  37053. re-ordered.
  37054. @see FileSearchPath
  37055. */
  37056. class JUCE_API FileSearchPathListComponent : public Component,
  37057. public SettableTooltipClient,
  37058. public FileDragAndDropTarget,
  37059. private ButtonListener,
  37060. private ListBoxModel
  37061. {
  37062. public:
  37063. /** Creates an empty FileSearchPathListComponent.
  37064. */
  37065. FileSearchPathListComponent();
  37066. /** Destructor. */
  37067. ~FileSearchPathListComponent();
  37068. /** Returns the path as it is currently shown. */
  37069. const FileSearchPath& getPath() const throw() { return path; }
  37070. /** Changes the current path. */
  37071. void setPath (const FileSearchPath& newPath);
  37072. /** Sets a file or directory to be the default starting point for the browser to show.
  37073. This is only used if the current file hasn't been set.
  37074. */
  37075. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37076. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37077. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37078. methods.
  37079. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37080. */
  37081. enum ColourIds
  37082. {
  37083. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37084. Make this transparent if you don't want the background to be filled. */
  37085. };
  37086. /** @internal */
  37087. int getNumRows();
  37088. /** @internal */
  37089. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37090. /** @internal */
  37091. void deleteKeyPressed (int lastRowSelected);
  37092. /** @internal */
  37093. void returnKeyPressed (int lastRowSelected);
  37094. /** @internal */
  37095. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37096. /** @internal */
  37097. void selectedRowsChanged (int lastRowSelected);
  37098. /** @internal */
  37099. void resized();
  37100. /** @internal */
  37101. void paint (Graphics& g);
  37102. /** @internal */
  37103. bool isInterestedInFileDrag (const StringArray& files);
  37104. /** @internal */
  37105. void filesDropped (const StringArray& files, int, int);
  37106. /** @internal */
  37107. void buttonClicked (Button* button);
  37108. juce_UseDebuggingNewOperator
  37109. private:
  37110. FileSearchPath path;
  37111. File defaultBrowseTarget;
  37112. ListBox* listBox;
  37113. Button* addButton;
  37114. Button* removeButton;
  37115. Button* changeButton;
  37116. Button* upButton;
  37117. Button* downButton;
  37118. void changed() throw();
  37119. void updateButtons() throw();
  37120. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37121. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37122. };
  37123. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37124. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37125. #endif
  37126. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37127. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37128. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37129. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37130. /**
  37131. A component that displays the files in a directory as a treeview.
  37132. This implements the DirectoryContentsDisplayComponent base class so that
  37133. it can be used in a FileBrowserComponent.
  37134. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37135. class and the FileBrowserListener class.
  37136. @see DirectoryContentsList, FileListComponent
  37137. */
  37138. class JUCE_API FileTreeComponent : public TreeView,
  37139. public DirectoryContentsDisplayComponent
  37140. {
  37141. public:
  37142. /** Creates a listbox to show the contents of a specified directory.
  37143. */
  37144. FileTreeComponent (DirectoryContentsList& listToShow);
  37145. /** Destructor. */
  37146. ~FileTreeComponent();
  37147. /** Returns the number of selected files in the tree.
  37148. */
  37149. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37150. /** Returns one of the files that the user has currently selected.
  37151. Returns File::nonexistent if none is selected.
  37152. */
  37153. const File getSelectedFile (int index) const throw();
  37154. /** Returns the first of the files that the user has currently selected.
  37155. Returns File::nonexistent if none is selected.
  37156. */
  37157. const File getSelectedFile() const;
  37158. /** Scrolls the list to the top. */
  37159. void scrollToTop();
  37160. /** Setting a name for this allows tree items to be dragged.
  37161. The string that you pass in here will be returned by the getDragSourceDescription()
  37162. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37163. */
  37164. void setDragAndDropDescription (const String& description) throw();
  37165. /** Returns the last value that was set by setDragAndDropDescription().
  37166. */
  37167. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37168. juce_UseDebuggingNewOperator
  37169. private:
  37170. String dragAndDropDescription;
  37171. FileTreeComponent (const FileTreeComponent&);
  37172. const FileTreeComponent& operator= (const FileTreeComponent&);
  37173. };
  37174. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37175. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37176. #endif
  37177. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37178. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37179. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37180. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37181. /**
  37182. A simple preview component that shows thumbnails of image files.
  37183. @see FileChooserDialogBox, FilePreviewComponent
  37184. */
  37185. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37186. private Timer
  37187. {
  37188. public:
  37189. /** Creates an ImagePreviewComponent. */
  37190. ImagePreviewComponent();
  37191. /** Destructor. */
  37192. ~ImagePreviewComponent();
  37193. /** @internal */
  37194. void selectedFileChanged (const File& newSelectedFile);
  37195. /** @internal */
  37196. void paint (Graphics& g);
  37197. /** @internal */
  37198. void timerCallback();
  37199. juce_UseDebuggingNewOperator
  37200. private:
  37201. File fileToLoad;
  37202. Image* currentThumbnail;
  37203. String currentDetails;
  37204. void getThumbSize (int& w, int& h) const;
  37205. ImagePreviewComponent (const ImagePreviewComponent&);
  37206. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37207. };
  37208. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37209. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37210. #endif
  37211. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37212. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37213. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37214. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37215. /**
  37216. A type of FileFilter that works by wildcard pattern matching.
  37217. This filter only allows files that match one of the specified patterns, but
  37218. allows all directories through.
  37219. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37220. */
  37221. class JUCE_API WildcardFileFilter : public FileFilter
  37222. {
  37223. public:
  37224. /**
  37225. Creates a wildcard filter for one or more patterns.
  37226. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37227. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37228. or .aiff.
  37229. The description is a name to show the user in a list of possible patterns, so
  37230. for the wav/aiff example, your description might be "audio files".
  37231. */
  37232. WildcardFileFilter (const String& wildcardPatterns,
  37233. const String& description);
  37234. /** Destructor. */
  37235. ~WildcardFileFilter();
  37236. /** Returns true if the filename matches one of the patterns specified. */
  37237. bool isFileSuitable (const File& file) const;
  37238. /** This always returns true. */
  37239. bool isDirectorySuitable (const File& file) const;
  37240. juce_UseDebuggingNewOperator
  37241. private:
  37242. StringArray wildcards;
  37243. };
  37244. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37245. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37246. #endif
  37247. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37248. /********* Start of inlined file: juce_AlertWindow.h *********/
  37249. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37250. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37251. /** A window that displays a message and has buttons for the user to react to it.
  37252. For simple dialog boxes with just a couple of buttons on them, there are
  37253. some static methods for running these.
  37254. For more complex dialogs, an AlertWindow can be created, then it can have some
  37255. buttons and components added to it, and its runModalLoop() method is then used to
  37256. show it. The value returned by runModalLoop() shows which button the
  37257. user pressed to dismiss the box.
  37258. @see ThreadWithProgressWindow
  37259. */
  37260. class JUCE_API AlertWindow : public TopLevelWindow,
  37261. private ButtonListener
  37262. {
  37263. public:
  37264. /** The type of icon to show in the dialog box. */
  37265. enum AlertIconType
  37266. {
  37267. NoIcon, /**< No icon will be shown on the dialog box. */
  37268. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37269. user to answer a question. */
  37270. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37271. warning about something and shouldn't be ignored. */
  37272. InfoIcon /**< An icon that indicates that the dialog box is just
  37273. giving the user some information, which doesn't require
  37274. a response from them. */
  37275. };
  37276. /** Creates an AlertWindow.
  37277. @param title the headline to show at the top of the dialog box
  37278. @param message a longer, more descriptive message to show underneath the
  37279. headline
  37280. @param iconType the type of icon to display
  37281. */
  37282. AlertWindow (const String& title,
  37283. const String& message,
  37284. AlertIconType iconType);
  37285. /** Destroys the AlertWindow */
  37286. ~AlertWindow();
  37287. /** Returns the type of alert icon that was specified when the window
  37288. was created. */
  37289. AlertIconType getAlertType() const throw() { return alertIconType; }
  37290. /** Changes the dialog box's message.
  37291. This will also resize the window to fit the new message if required.
  37292. */
  37293. void setMessage (const String& message);
  37294. /** Adds a button to the window.
  37295. @param name the text to show on the button
  37296. @param returnValue the value that should be returned from runModalLoop()
  37297. if this is the button that the user presses.
  37298. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37299. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37300. */
  37301. void addButton (const String& name,
  37302. const int returnValue,
  37303. const KeyPress& shortcutKey1 = KeyPress(),
  37304. const KeyPress& shortcutKey2 = KeyPress());
  37305. /** Returns the number of buttons that the window currently has. */
  37306. int getNumButtons() const;
  37307. /** Adds a textbox to the window for entering strings.
  37308. @param name an internal name for the text-box. This is the name to pass to
  37309. the getTextEditorContents() method to find out what the
  37310. user typed-in.
  37311. @param initialContents a string to show in the text box when it's first shown
  37312. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37313. text-box to label it.
  37314. @param isPasswordBox if true, the text editor will display asterisks instead of
  37315. the actual text
  37316. @see getTextEditorContents
  37317. */
  37318. void addTextEditor (const String& name,
  37319. const String& initialContents,
  37320. const String& onScreenLabel = String::empty,
  37321. const bool isPasswordBox = false);
  37322. /** Returns the contents of a named textbox.
  37323. After showing an AlertWindow that contains a text editor, this can be
  37324. used to find out what the user has typed into it.
  37325. @param nameOfTextEditor the name of the text box that you're interested in
  37326. @see addTextEditor
  37327. */
  37328. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37329. /** Adds a drop-down list of choices to the box.
  37330. After the box has been shown, the getComboBoxComponent() method can
  37331. be used to find out which item the user picked.
  37332. @param name the label to use for the drop-down list
  37333. @param items the list of items to show in it
  37334. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37335. combo-box to label it.
  37336. @see getComboBoxComponent
  37337. */
  37338. void addComboBox (const String& name,
  37339. const StringArray& items,
  37340. const String& onScreenLabel = String::empty);
  37341. /** Returns a drop-down list that was added to the AlertWindow.
  37342. @param nameOfList the name that was passed into the addComboBox() method
  37343. when creating the drop-down
  37344. @returns the ComboBox component, or 0 if none was found for the given name.
  37345. */
  37346. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37347. /** Adds a block of text.
  37348. This is handy for adding a multi-line note next to a textbox or combo-box,
  37349. to provide more details about what's going on.
  37350. */
  37351. void addTextBlock (const String& text);
  37352. /** Adds a progress-bar to the window.
  37353. @param progressValue a variable that will be repeatedly checked while the
  37354. dialog box is visible, to see how far the process has
  37355. got. The value should be in the range 0 to 1.0
  37356. */
  37357. void addProgressBarComponent (double& progressValue);
  37358. /** Adds a user-defined component to the dialog box.
  37359. @param component the component to add - its size should be set up correctly
  37360. before it is passed in. The caller is responsible for deleting
  37361. the component later on - the AlertWindow won't delete it.
  37362. */
  37363. void addCustomComponent (Component* const component);
  37364. /** Returns the number of custom components in the dialog box.
  37365. @see getCustomComponent, addCustomComponent
  37366. */
  37367. int getNumCustomComponents() const;
  37368. /** Returns one of the custom components in the dialog box.
  37369. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37370. will return 0
  37371. @see getNumCustomComponents, addCustomComponent
  37372. */
  37373. Component* getCustomComponent (const int index) const;
  37374. /** Removes one of the custom components in the dialog box.
  37375. Note that this won't delete it, it just removes the component from the window
  37376. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37377. will return 0
  37378. @returns the component that was removed (or zero)
  37379. @see getNumCustomComponents, addCustomComponent
  37380. */
  37381. Component* removeCustomComponent (const int index);
  37382. /** Returns true if the window contains any components other than just buttons.*/
  37383. bool containsAnyExtraComponents() const;
  37384. // easy-to-use message box functions:
  37385. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37386. The box is shown modally, and the method returns after the user
  37387. has clicked the button (or pressed the escape or return keys).
  37388. @param iconType the type of icon to show
  37389. @param title the headline to show at the top of the box
  37390. @param message a longer, more descriptive message to show underneath the
  37391. headline
  37392. @param buttonText the text to show in the button - if this string is empty, the
  37393. default string "ok" (or a localised version) will be used.
  37394. */
  37395. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37396. const String& title,
  37397. const String& message,
  37398. const String& buttonText = String::empty);
  37399. /** Shows a dialog box with two buttons.
  37400. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37401. to trigger the first button, and the escape key for the second button.
  37402. @param iconType the type of icon to show
  37403. @param title the headline to show at the top of the box
  37404. @param message a longer, more descriptive message to show underneath the
  37405. headline
  37406. @param button1Text the text to show in the first button - if this string is
  37407. empty, the default string "ok" (or a localised version of it)
  37408. will be used.
  37409. @param button2Text the text to show in the second button - if this string is
  37410. empty, the default string "cancel" (or a localised version of it)
  37411. will be used.
  37412. @returns true if button 1 was clicked, false if it was button 2
  37413. */
  37414. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37415. const String& title,
  37416. const String& message,
  37417. const String& button1Text = String::empty,
  37418. const String& button2Text = String::empty);
  37419. /** Shows a dialog box with three buttons.
  37420. Ideal for yes/no/cancel boxes.
  37421. The escape key can be used to trigger the third button.
  37422. @param iconType the type of icon to show
  37423. @param title the headline to show at the top of the box
  37424. @param message a longer, more descriptive message to show underneath the
  37425. headline
  37426. @param button1Text the text to show in the first button - if an empty string, then
  37427. "yes" will be used (or a localised version of it)
  37428. @param button2Text the text to show in the first button - if an empty string, then
  37429. "no" will be used (or a localised version of it)
  37430. @param button3Text the text to show in the first button - if an empty string, then
  37431. "cancel" will be used (or a localised version of it)
  37432. @returns one of the following values:
  37433. - 0 if the third button was pressed (normally used for 'cancel')
  37434. - 1 if the first button was pressed (normally used for 'yes')
  37435. - 2 if the middle button was pressed (normally used for 'no')
  37436. */
  37437. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  37438. const String& title,
  37439. const String& message,
  37440. const String& button1Text = String::empty,
  37441. const String& button2Text = String::empty,
  37442. const String& button3Text = String::empty);
  37443. /** Shows an operating-system native dialog box.
  37444. @param title the title to use at the top
  37445. @param bodyText the longer message to show
  37446. @param isOkCancel if true, this will show an ok/cancel box, if false,
  37447. it'll show a box with just an ok button
  37448. @returns true if the ok button was pressed, false if they pressed cancel.
  37449. */
  37450. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  37451. const String& bodyText,
  37452. bool isOkCancel);
  37453. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  37454. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37455. methods.
  37456. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37457. */
  37458. enum ColourIds
  37459. {
  37460. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  37461. textColourId = 0x1001810, /**< The colour for the text. */
  37462. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  37463. };
  37464. juce_UseDebuggingNewOperator
  37465. protected:
  37466. /** @internal */
  37467. void paint (Graphics& g);
  37468. /** @internal */
  37469. void mouseDown (const MouseEvent& e);
  37470. /** @internal */
  37471. void mouseDrag (const MouseEvent& e);
  37472. /** @internal */
  37473. bool keyPressed (const KeyPress& key);
  37474. /** @internal */
  37475. void buttonClicked (Button* button);
  37476. /** @internal */
  37477. void lookAndFeelChanged();
  37478. private:
  37479. String text;
  37480. TextLayout textLayout;
  37481. AlertIconType alertIconType;
  37482. ComponentBoundsConstrainer constrainer;
  37483. ComponentDragger dragger;
  37484. Rectangle textArea;
  37485. VoidArray buttons, textBoxes, comboBoxes;
  37486. VoidArray progressBars, customComps, textBlocks, allComps;
  37487. StringArray textboxNames, comboBoxNames;
  37488. Font font;
  37489. void updateLayout (const bool onlyIncreaseSize);
  37490. // disable copy constructor
  37491. AlertWindow (const AlertWindow&);
  37492. const AlertWindow& operator= (const AlertWindow&);
  37493. };
  37494. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  37495. /********* End of inlined file: juce_AlertWindow.h *********/
  37496. #endif
  37497. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  37498. #endif
  37499. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37500. /********* Start of inlined file: juce_DialogWindow.h *********/
  37501. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37502. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  37503. /**
  37504. A dialog-box style window.
  37505. This class is a convenient way of creating a DocumentWindow with a close button
  37506. that can be triggered by pressing the escape key.
  37507. Any of the methods available to a DocumentWindow or ResizableWindow are also
  37508. available to this, so it can be made resizable, have a menu bar, etc.
  37509. To add items to the box, see the ResizableWindow::setContentComponent() method.
  37510. Don't add components directly to this class - always put them in a content component!
  37511. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  37512. the user clicking the close button - for more info, see the DocumentWindow
  37513. help.
  37514. @see DocumentWindow, ResizableWindow
  37515. */
  37516. class JUCE_API DialogWindow : public DocumentWindow
  37517. {
  37518. public:
  37519. /** Creates a DialogWindow.
  37520. @param name the name to give the component - this is also
  37521. the title shown at the top of the window. To change
  37522. this later, use setName()
  37523. @param backgroundColour the colour to use for filling the window's background.
  37524. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37525. close button to be triggered
  37526. @param addToDesktop if true, the window will be automatically added to the
  37527. desktop; if false, you can use it as a child component
  37528. */
  37529. DialogWindow (const String& name,
  37530. const Colour& backgroundColour,
  37531. const bool escapeKeyTriggersCloseButton,
  37532. const bool addToDesktop = true);
  37533. /** Destructor.
  37534. If a content component has been set with setContentComponent(), it
  37535. will be deleted.
  37536. */
  37537. ~DialogWindow();
  37538. /** Easy way of quickly showing a dialog box containing a given component.
  37539. This will open and display a DialogWindow containing a given component, returning
  37540. when the user clicks its close button.
  37541. It returns the value that was returned by the dialog box's runModalLoop() call.
  37542. To close the dialog programatically, you should call exitModalState (returnValue) on
  37543. the DialogWindow that is created. To find a pointer to this window from your
  37544. contentComponent, you can do something like this:
  37545. @code
  37546. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  37547. if (dw != 0)
  37548. dw->exitModalState (1234);
  37549. @endcode
  37550. @param dialogTitle the dialog box's title
  37551. @param contentComponent the content component for the dialog box. Make sure
  37552. that this has been set to the size you want it to
  37553. be before calling this method. The component won't
  37554. be deleted by this call, so you can re-use it or delete
  37555. it afterwards
  37556. @param componentToCentreAround if this is non-zero, it indicates a component that
  37557. you'd like to show this dialog box in front of. See the
  37558. DocumentWindow::centreAroundComponent() method for more
  37559. info on this parameter
  37560. @param backgroundColour a colour to use for the dialog box's background colour
  37561. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37562. close button to be triggered
  37563. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  37564. a corner resizer
  37565. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  37566. to use a border or corner resizer component. See ResizableWindow::setResizable()
  37567. */
  37568. static int showModalDialog (const String& dialogTitle,
  37569. Component* contentComponent,
  37570. Component* componentToCentreAround,
  37571. const Colour& backgroundColour,
  37572. const bool escapeKeyTriggersCloseButton,
  37573. const bool shouldBeResizable = false,
  37574. const bool useBottomRightCornerResizer = false);
  37575. juce_UseDebuggingNewOperator
  37576. protected:
  37577. /** @internal */
  37578. void resized();
  37579. private:
  37580. bool escapeKeyTriggersCloseButton;
  37581. DialogWindow (const DialogWindow&);
  37582. const DialogWindow& operator= (const DialogWindow&);
  37583. };
  37584. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  37585. /********* End of inlined file: juce_DialogWindow.h *********/
  37586. #endif
  37587. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37588. #endif
  37589. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37590. #endif
  37591. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37592. /********* Start of inlined file: juce_SplashScreen.h *********/
  37593. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37594. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  37595. /** A component for showing a splash screen while your app starts up.
  37596. This will automatically position itself, and delete itself when the app has
  37597. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  37598. this).
  37599. To use it, just create one of these in your JUCEApplication::initialise() method,
  37600. call its show() method and let the object delete itself later.
  37601. E.g. @code
  37602. void MyApp::initialise (const String& commandLine)
  37603. {
  37604. SplashScreen* splash = new SplashScreen();
  37605. splash->show (T("welcome to my app"),
  37606. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  37607. 4000, false);
  37608. .. no need to delete the splash screen - it'll do that itself.
  37609. }
  37610. @endcode
  37611. */
  37612. class JUCE_API SplashScreen : public Component,
  37613. public Timer,
  37614. private DeletedAtShutdown
  37615. {
  37616. public:
  37617. /** Creates a SplashScreen object.
  37618. After creating one of these (or your subclass of it), call one of the show()
  37619. methods to display it.
  37620. */
  37621. SplashScreen();
  37622. /** Destructor. */
  37623. ~SplashScreen();
  37624. /** Creates a SplashScreen object that will display an image.
  37625. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37626. screen. This method will also dispatch any pending messages to make sure that when
  37627. it returns, the splash screen has been completely drawn, and your initialisation
  37628. code can carry on.
  37629. @param title the name to give the component
  37630. @param backgroundImage an image to draw on the component. The component's size
  37631. will be set to the size of this image, and if the image is
  37632. semi-transparent, the component will be made semi-transparent
  37633. too. This image will be deleted (or released from the ImageCache
  37634. if that's how it was created) by the splash screen object when
  37635. it is itself deleted.
  37636. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37637. should stay visible for. If the initialisation takes longer than
  37638. this time, the splash screen will wait for it to finish before
  37639. disappearing, but if initialisation is very quick, this lets
  37640. you make sure that people get a good look at your splash.
  37641. @param useDropShadow if true, the window will have a drop shadow
  37642. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37643. the mouse (anywhere)
  37644. */
  37645. void show (const String& title,
  37646. Image* const backgroundImage,
  37647. const int minimumTimeToDisplayFor,
  37648. const bool useDropShadow,
  37649. const bool removeOnMouseClick = true);
  37650. /** Creates a SplashScreen object with a specified size.
  37651. For a custom splash screen, you can use this method to display it at a certain size
  37652. and then override the paint() method yourself to do whatever's necessary.
  37653. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37654. screen. This method will also dispatch any pending messages to make sure that when
  37655. it returns, the splash screen has been completely drawn, and your initialisation
  37656. code can carry on.
  37657. @param title the name to give the component
  37658. @param width the width to use
  37659. @param height the height to use
  37660. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37661. should stay visible for. If the initialisation takes longer than
  37662. this time, the splash screen will wait for it to finish before
  37663. disappearing, but if initialisation is very quick, this lets
  37664. you make sure that people get a good look at your splash.
  37665. @param useDropShadow if true, the window will have a drop shadow
  37666. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37667. the mouse (anywhere)
  37668. */
  37669. void show (const String& title,
  37670. const int width,
  37671. const int height,
  37672. const int minimumTimeToDisplayFor,
  37673. const bool useDropShadow,
  37674. const bool removeOnMouseClick = true);
  37675. /** @internal */
  37676. void paint (Graphics& g);
  37677. /** @internal */
  37678. void timerCallback();
  37679. juce_UseDebuggingNewOperator
  37680. private:
  37681. Image* backgroundImage;
  37682. Time earliestTimeToDelete;
  37683. int originalClickCounter;
  37684. bool isImageInCache;
  37685. SplashScreen (const SplashScreen&);
  37686. const SplashScreen& operator= (const SplashScreen&);
  37687. };
  37688. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  37689. /********* End of inlined file: juce_SplashScreen.h *********/
  37690. #endif
  37691. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37692. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  37693. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37694. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37695. /**
  37696. A thread that automatically pops up a modal dialog box with a progress bar
  37697. and cancel button while it's busy running.
  37698. These are handy for performing some sort of task while giving the user feedback
  37699. about how long there is to go, etc.
  37700. E.g. @code
  37701. class MyTask : public ThreadWithProgressWindow
  37702. {
  37703. public:
  37704. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  37705. {
  37706. }
  37707. ~MyTask()
  37708. {
  37709. }
  37710. void run()
  37711. {
  37712. for (int i = 0; i < thingsToDo; ++i)
  37713. {
  37714. // must check this as often as possible, because this is
  37715. // how we know if the user's pressed 'cancel'
  37716. if (threadShouldExit())
  37717. break;
  37718. // this will update the progress bar on the dialog box
  37719. setProgress (i / (double) thingsToDo);
  37720. // ... do the business here...
  37721. }
  37722. }
  37723. };
  37724. void doTheTask()
  37725. {
  37726. MyTask m;
  37727. if (m.runThread())
  37728. {
  37729. // thread finished normally..
  37730. }
  37731. else
  37732. {
  37733. // user pressed the cancel button..
  37734. }
  37735. }
  37736. @endcode
  37737. @see Thread, AlertWindow
  37738. */
  37739. class JUCE_API ThreadWithProgressWindow : public Thread,
  37740. private Timer
  37741. {
  37742. public:
  37743. /** Creates the thread.
  37744. Initially, the dialog box won't be visible, it'll only appear when the
  37745. runThread() method is called.
  37746. @param windowTitle the title to go at the top of the dialog box
  37747. @param hasProgressBar whether the dialog box should have a progress bar (see
  37748. setProgress() )
  37749. @param hasCancelButton whether the dialog box should have a cancel button
  37750. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  37751. the thread to stop before killing it forcibly (see
  37752. Thread::stopThread() )
  37753. @param cancelButtonText the text that should be shown in the cancel button
  37754. (if it has one)
  37755. */
  37756. ThreadWithProgressWindow (const String& windowTitle,
  37757. const bool hasProgressBar,
  37758. const bool hasCancelButton,
  37759. const int timeOutMsWhenCancelling = 10000,
  37760. const String& cancelButtonText = JUCE_T("Cancel"));
  37761. /** Destructor. */
  37762. ~ThreadWithProgressWindow();
  37763. /** Starts the thread and waits for it to finish.
  37764. This will start the thread, make the dialog box appear, and wait until either
  37765. the thread finishes normally, or until the cancel button is pressed.
  37766. Before returning, the dialog box will be hidden.
  37767. @param threadPriority the priority to use when starting the thread - see
  37768. Thread::startThread() for values
  37769. @returns true if the thread finished normally; false if the user pressed cancel
  37770. */
  37771. bool runThread (const int threadPriority = 5);
  37772. /** The thread should call this periodically to update the position of the progress bar.
  37773. @param newProgress the progress, from 0.0 to 1.0
  37774. @see setStatusMessage
  37775. */
  37776. void setProgress (const double newProgress);
  37777. /** The thread can call this to change the message that's displayed in the dialog box.
  37778. */
  37779. void setStatusMessage (const String& newStatusMessage);
  37780. juce_UseDebuggingNewOperator
  37781. private:
  37782. void timerCallback();
  37783. double progress;
  37784. AlertWindow alertWindow;
  37785. String message;
  37786. CriticalSection messageLock;
  37787. const int timeOutMsWhenCancelling;
  37788. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  37789. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  37790. };
  37791. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37792. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  37793. #endif
  37794. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  37795. #endif
  37796. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37797. #endif
  37798. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37799. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  37800. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37801. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37802. #if JUCE_WIN32 || DOXYGEN
  37803. /**
  37804. A Windows-specific class that can create and embed an ActiveX control inside
  37805. itself.
  37806. To use it, create one of these, put it in place and make sure it's visible in a
  37807. window, then use createControl() to instantiate an ActiveX control. The control
  37808. will then be moved and resized to follow the movements of this component.
  37809. Of course, since the control is a heavyweight window, it'll obliterate any
  37810. juce components that may overlap this component, but that's life.
  37811. */
  37812. class JUCE_API ActiveXControlComponent : public Component
  37813. {
  37814. public:
  37815. /** Create an initially-empty container. */
  37816. ActiveXControlComponent();
  37817. /** Destructor. */
  37818. ~ActiveXControlComponent();
  37819. /** Tries to create an ActiveX control and embed it in this peer.
  37820. The peer controlIID is a pointer to an IID structure - it's treated
  37821. as a void* because when including the Juce headers, you might not always
  37822. have included windows.h first, in which case IID wouldn't be defined.
  37823. e.g. @code
  37824. const IID myIID = __uuidof (QTControl);
  37825. myControlComp->createControl (&myIID);
  37826. @endcode
  37827. */
  37828. bool createControl (const void* controlIID);
  37829. /** Deletes the ActiveX control, if one has been created.
  37830. */
  37831. void deleteControl();
  37832. /** Returns true if a control is currently in use. */
  37833. bool isControlOpen() const throw() { return control != 0; }
  37834. /** Does a QueryInterface call on the embedded control object.
  37835. This allows you to cast the control to whatever type of COM object you need.
  37836. The iid parameter is a pointer to an IID structure - it's treated
  37837. as a void* because when including the Juce headers, you might not always
  37838. have included windows.h first, in which case IID wouldn't be defined, but
  37839. you should just pass a pointer to an IID.
  37840. e.g. @code
  37841. const IID iid = __uuidof (IOleWindow);
  37842. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  37843. if (oleWindow != 0)
  37844. {
  37845. HWND hwnd;
  37846. oleWindow->GetWindow (&hwnd);
  37847. ...
  37848. oleWindow->Release();
  37849. }
  37850. @endcode
  37851. */
  37852. void* queryInterface (const void* iid) const;
  37853. /** Set this to false to stop mouse events being allowed through to the control.
  37854. */
  37855. void setMouseEventsAllowed (const bool eventsCanReachControl);
  37856. /** Returns true if mouse events are allowed to get through to the control.
  37857. */
  37858. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  37859. /** @internal */
  37860. void paint (Graphics& g);
  37861. /** @internal */
  37862. void* originalWndProc;
  37863. juce_UseDebuggingNewOperator
  37864. private:
  37865. friend class ActiveXControlData;
  37866. void* control;
  37867. bool mouseEventsAllowed;
  37868. ActiveXControlComponent (const ActiveXControlComponent&);
  37869. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  37870. void setControlBounds (const Rectangle& bounds) const;
  37871. void setControlVisible (const bool b) const;
  37872. };
  37873. #endif
  37874. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37875. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  37876. #endif
  37877. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37878. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  37879. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37880. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37881. class MidiInputSelectorComponentListBox;
  37882. /**
  37883. A component containing controls to let the user change the audio settings of
  37884. an AudioDeviceManager object.
  37885. Very easy to use - just create one of these and show it to the user.
  37886. @see AudioDeviceManager
  37887. */
  37888. class JUCE_API AudioDeviceSelectorComponent : public Component,
  37889. public ComboBoxListener,
  37890. public ButtonListener,
  37891. public ChangeListener
  37892. {
  37893. public:
  37894. /** Creates the component.
  37895. If your app needs only output channels, you might ask for a maximum of 0 input
  37896. channels, and the component won't display any options for choosing the input
  37897. channels. And likewise if you're doing an input-only app.
  37898. @param deviceManager the device manager that this component should control
  37899. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  37900. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  37901. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  37902. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  37903. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  37904. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  37905. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  37906. treated as a set of separate mono channels.
  37907. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  37908. are shown, with an "advanced" button that shows the rest of them
  37909. */
  37910. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  37911. const int minAudioInputChannels,
  37912. const int maxAudioInputChannels,
  37913. const int minAudioOutputChannels,
  37914. const int maxAudioOutputChannels,
  37915. const bool showMidiInputOptions,
  37916. const bool showMidiOutputSelector,
  37917. const bool showChannelsAsStereoPairs,
  37918. const bool hideAdvancedOptionsWithButton);
  37919. /** Destructor */
  37920. ~AudioDeviceSelectorComponent();
  37921. /** @internal */
  37922. void resized();
  37923. /** @internal */
  37924. void comboBoxChanged (ComboBox*);
  37925. /** @internal */
  37926. void buttonClicked (Button*);
  37927. /** @internal */
  37928. void changeListenerCallback (void*);
  37929. juce_UseDebuggingNewOperator
  37930. private:
  37931. AudioDeviceManager& deviceManager;
  37932. ComboBox* deviceTypeDropDown;
  37933. Label* deviceTypeDropDownLabel;
  37934. Component* audioDeviceSettingsComp;
  37935. String audioDeviceSettingsCompType;
  37936. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  37937. const bool showChannelsAsStereoPairs;
  37938. const bool hideAdvancedOptionsWithButton;
  37939. MidiInputSelectorComponentListBox* midiInputsList;
  37940. Label* midiInputsLabel;
  37941. ComboBox* midiOutputSelector;
  37942. Label* midiOutputLabel;
  37943. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  37944. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  37945. };
  37946. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37947. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  37948. #endif
  37949. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  37950. /********* Start of inlined file: juce_BubbleComponent.h *********/
  37951. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  37952. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  37953. /**
  37954. A component for showing a message or other graphics inside a speech-bubble-shaped
  37955. outline, pointing at a location on the screen.
  37956. This is a base class that just draws and positions the bubble shape, but leaves
  37957. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  37958. that draws a text message.
  37959. To use it, create your subclass, then either add it to a parent component or
  37960. put it on the desktop with addToDesktop (0), use setPosition() to
  37961. resize and position it, then make it visible.
  37962. @see BubbleMessageComponent
  37963. */
  37964. class JUCE_API BubbleComponent : public Component
  37965. {
  37966. protected:
  37967. /** Creates a BubbleComponent.
  37968. Your subclass will need to implement the getContentSize() and paintContent()
  37969. methods to draw the bubble's contents.
  37970. */
  37971. BubbleComponent();
  37972. public:
  37973. /** Destructor. */
  37974. ~BubbleComponent();
  37975. /** A list of permitted placements for the bubble, relative to the co-ordinates
  37976. at which it should be pointing.
  37977. @see setAllowedPlacement
  37978. */
  37979. enum BubblePlacement
  37980. {
  37981. above = 1,
  37982. below = 2,
  37983. left = 4,
  37984. right = 8
  37985. };
  37986. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  37987. point at which it's pointing.
  37988. By default when setPosition() is called, the bubble will place itself either
  37989. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  37990. the values in BubblePlacement to restrict this choice.
  37991. E.g. if you only want your bubble to appear above or below the target area,
  37992. use setAllowedPlacement (above | below);
  37993. @see BubblePlacement
  37994. */
  37995. void setAllowedPlacement (const int newPlacement);
  37996. /** Moves and resizes the bubble to point at a given component.
  37997. This will resize the bubble to fit its content, then find a position for it
  37998. so that it's next to, but doesn't overlap the given component.
  37999. It'll put itself either above, below, or to the side of the component depending
  38000. on where there's the most space, honouring any restrictions that were set
  38001. with setAllowedPlacement().
  38002. */
  38003. void setPosition (Component* componentToPointTo);
  38004. /** Moves and resizes the bubble to point at a given point.
  38005. This will resize the bubble to fit its content, then position it
  38006. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  38007. are relative to either the bubble component's parent component if it has one, or
  38008. they are screen co-ordinates if not.
  38009. It'll put itself either above, below, or to the side of this point, depending
  38010. on where there's the most space, honouring any restrictions that were set
  38011. with setAllowedPlacement().
  38012. */
  38013. void setPosition (const int arrowTipX,
  38014. const int arrowTipY);
  38015. /** Moves and resizes the bubble to point at a given rectangle.
  38016. This will resize the bubble to fit its content, then find a position for it
  38017. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  38018. co-ordinates are relative to either the bubble component's parent component
  38019. if it has one, or they are screen co-ordinates if not.
  38020. It'll put itself either above, below, or to the side of the component depending
  38021. on where there's the most space, honouring any restrictions that were set
  38022. with setAllowedPlacement().
  38023. */
  38024. void setPosition (const Rectangle& rectangleToPointTo);
  38025. protected:
  38026. /** Subclasses should override this to return the size of the content they
  38027. want to draw inside the bubble.
  38028. */
  38029. virtual void getContentSize (int& width, int& height) = 0;
  38030. /** Subclasses should override this to draw their bubble's contents.
  38031. The graphics object's clip region and the dimensions passed in here are
  38032. set up to paint just the rectangle inside the bubble.
  38033. */
  38034. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38035. public:
  38036. /** @internal */
  38037. void paint (Graphics& g);
  38038. juce_UseDebuggingNewOperator
  38039. private:
  38040. Rectangle content;
  38041. int side, allowablePlacements;
  38042. float arrowTipX, arrowTipY;
  38043. DropShadowEffect shadow;
  38044. BubbleComponent (const BubbleComponent&);
  38045. const BubbleComponent& operator= (const BubbleComponent&);
  38046. };
  38047. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38048. /********* End of inlined file: juce_BubbleComponent.h *********/
  38049. #endif
  38050. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38051. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38052. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38053. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38054. /**
  38055. A speech-bubble component that displays a short message.
  38056. This can be used to show a message with the tail of the speech bubble
  38057. pointing to a particular component or location on the screen.
  38058. @see BubbleComponent
  38059. */
  38060. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38061. private Timer
  38062. {
  38063. public:
  38064. /** Creates a bubble component.
  38065. After creating one a BubbleComponent, do the following:
  38066. - add it to an appropriate parent component, or put it on the
  38067. desktop with Component::addToDesktop (0).
  38068. - use the showAt() method to show a message.
  38069. - it will make itself invisible after it times-out (and can optionally
  38070. also delete itself), or you can reuse it somewhere else by calling
  38071. showAt() again.
  38072. */
  38073. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38074. /** Destructor. */
  38075. ~BubbleMessageComponent();
  38076. /** Shows a message bubble at a particular position.
  38077. This shows the bubble with its stem pointing to the given location
  38078. (co-ordinates being relative to its parent component).
  38079. For details about exactly how it decides where to position itself, see
  38080. BubbleComponent::updatePosition().
  38081. @param x the x co-ordinate of end of the bubble's tail
  38082. @param y the y co-ordinate of end of the bubble's tail
  38083. @param message the text to display
  38084. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38085. from its parent compnent. If this is 0 or less, it
  38086. will stay there until manually removed.
  38087. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38088. mouse button is pressed (anywhere on the screen)
  38089. @param deleteSelfAfterUse if true, then the component will delete itself after
  38090. it becomes invisible
  38091. */
  38092. void showAt (int x, int y,
  38093. const String& message,
  38094. const int numMillisecondsBeforeRemoving,
  38095. const bool removeWhenMouseClicked = true,
  38096. const bool deleteSelfAfterUse = false);
  38097. /** Shows a message bubble next to a particular component.
  38098. This shows the bubble with its stem pointing at the given component.
  38099. For details about exactly how it decides where to position itself, see
  38100. BubbleComponent::updatePosition().
  38101. @param component the component that you want to point at
  38102. @param message the text to display
  38103. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38104. from its parent compnent. If this is 0 or less, it
  38105. will stay there until manually removed.
  38106. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38107. mouse button is pressed (anywhere on the screen)
  38108. @param deleteSelfAfterUse if true, then the component will delete itself after
  38109. it becomes invisible
  38110. */
  38111. void showAt (Component* const component,
  38112. const String& message,
  38113. const int numMillisecondsBeforeRemoving,
  38114. const bool removeWhenMouseClicked = true,
  38115. const bool deleteSelfAfterUse = false);
  38116. /** @internal */
  38117. void getContentSize (int& w, int& h);
  38118. /** @internal */
  38119. void paintContent (Graphics& g, int w, int h);
  38120. /** @internal */
  38121. void timerCallback();
  38122. juce_UseDebuggingNewOperator
  38123. private:
  38124. int fadeOutLength, mouseClickCounter;
  38125. TextLayout textLayout;
  38126. int64 expiryTime;
  38127. bool deleteAfterUse;
  38128. void init (const int numMillisecondsBeforeRemoving,
  38129. const bool removeWhenMouseClicked,
  38130. const bool deleteSelfAfterUse);
  38131. BubbleMessageComponent (const BubbleMessageComponent&);
  38132. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38133. };
  38134. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38135. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38136. #endif
  38137. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38138. /********* Start of inlined file: juce_ColourSelector.h *********/
  38139. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38140. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38141. /**
  38142. A component that lets the user choose a colour.
  38143. This shows RGB sliders and a colourspace that the user can pick colours from.
  38144. This class is also a ChangeBroadcaster, so listeners can register to be told
  38145. when the colour changes.
  38146. */
  38147. class JUCE_API ColourSelector : public Component,
  38148. public ChangeBroadcaster,
  38149. protected SliderListener
  38150. {
  38151. public:
  38152. /** Options for the type of selector to show. These are passed into the constructor. */
  38153. enum ColourSelectorOptions
  38154. {
  38155. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38156. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38157. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38158. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38159. };
  38160. /** Creates a ColourSelector object.
  38161. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38162. which of the selector's features should be visible.
  38163. The edgeGap value specifies the amount of space to leave around the edge.
  38164. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38165. colourspace and hue selector components.
  38166. */
  38167. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38168. const int edgeGap = 4,
  38169. const int gapAroundColourSpaceComponent = 7);
  38170. /** Destructor. */
  38171. ~ColourSelector();
  38172. /** Returns the colour that the user has currently selected.
  38173. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38174. register to be told when the colour changes.
  38175. @see setCurrentColour
  38176. */
  38177. const Colour getCurrentColour() const;
  38178. /** Changes the colour that is currently being shown.
  38179. */
  38180. void setCurrentColour (const Colour& newColour);
  38181. /** Tells the selector how many preset colour swatches you want to have on the component.
  38182. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38183. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38184. their values.
  38185. */
  38186. virtual int getNumSwatches() const;
  38187. /** Called by the selector to find out the colour of one of the swatches.
  38188. Your subclass should return the colour of the swatch with the given index.
  38189. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38190. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38191. their values.
  38192. */
  38193. virtual const Colour getSwatchColour (const int index) const;
  38194. /** Called by the selector when the user puts a new colour into one of the swatches.
  38195. Your subclass should change the colour of the swatch with the given index.
  38196. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38197. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38198. their values.
  38199. */
  38200. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38201. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38202. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38203. methods.
  38204. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38205. */
  38206. enum ColourIds
  38207. {
  38208. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38209. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38210. };
  38211. juce_UseDebuggingNewOperator
  38212. private:
  38213. friend class ColourSpaceView;
  38214. friend class HueSelectorComp;
  38215. Colour colour;
  38216. float h, s, v;
  38217. Slider* sliders[4];
  38218. Component* colourSpace;
  38219. Component* hueSelector;
  38220. VoidArray swatchComponents;
  38221. const int flags;
  38222. int topSpace, edgeGap;
  38223. void setHue (float newH);
  38224. void setSV (float newS, float newV);
  38225. void updateHSV();
  38226. void update();
  38227. void sliderValueChanged (Slider*);
  38228. void paint (Graphics& g);
  38229. void resized();
  38230. ColourSelector (const ColourSelector&);
  38231. const ColourSelector& operator= (const ColourSelector&);
  38232. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38233. // have changed - if you get an error here, update your code to use the new constructor instead..
  38234. // (xxx - note to self: remember to remove this at some point in the future)
  38235. ColourSelector (const bool);
  38236. };
  38237. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38238. /********* End of inlined file: juce_ColourSelector.h *********/
  38239. #endif
  38240. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  38241. #endif
  38242. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38243. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  38244. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38245. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38246. /**
  38247. A component that contains another component, and can magnify or shrink it.
  38248. This component will continually update its size so that it fits the zoomed
  38249. version of the content component that you put inside it, so don't try to
  38250. change the size of this component directly - instead change that of the
  38251. content component.
  38252. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  38253. to remap mouse events correctly. This means that the content component won't
  38254. appear to be a direct child of this component, and instead will think its
  38255. on the desktop.
  38256. */
  38257. class JUCE_API MagnifierComponent : public Component
  38258. {
  38259. public:
  38260. /** Creates a MagnifierComponent.
  38261. This component will continually update its size so that it fits the zoomed
  38262. version of the content component that you put inside it, so don't try to
  38263. change the size of this component directly - instead change that of the
  38264. content component.
  38265. @param contentComponent the component to add as the magnified one
  38266. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  38267. be deleted when this component is deleted. If false,
  38268. it's the caller's responsibility to delete it later.
  38269. */
  38270. MagnifierComponent (Component* const contentComponent,
  38271. const bool deleteContentCompWhenNoLongerNeeded);
  38272. /** Destructor. */
  38273. ~MagnifierComponent();
  38274. /** Returns the current content component. */
  38275. Component* getContentComponent() const throw() { return content; }
  38276. /** Changes the zoom level.
  38277. The scale factor must be greater than zero. Values less than 1 will shrink the
  38278. image; values greater than 1 will multiply its size by this amount.
  38279. When this is called, this component will change its size to fit the full extent
  38280. of the newly zoomed content.
  38281. */
  38282. void setScaleFactor (double newScaleFactor);
  38283. /** Returns the current zoom factor. */
  38284. double getScaleFactor() const throw() { return scaleFactor; }
  38285. juce_UseDebuggingNewOperator
  38286. /** @internal */
  38287. void childBoundsChanged (Component*);
  38288. private:
  38289. Component* content;
  38290. Component* holderComp;
  38291. double scaleFactor;
  38292. ComponentPeer* peer;
  38293. bool deleteContent;
  38294. void paint (Graphics& g);
  38295. void mouseDown (const MouseEvent& e);
  38296. void mouseUp (const MouseEvent& e);
  38297. void mouseDrag (const MouseEvent& e);
  38298. void mouseMove (const MouseEvent& e);
  38299. void mouseEnter (const MouseEvent& e);
  38300. void mouseExit (const MouseEvent& e);
  38301. void mouseWheelMove (const MouseEvent& e, float, float);
  38302. int scaleInt (const int n) const throw();
  38303. MagnifierComponent (const MagnifierComponent&);
  38304. const MagnifierComponent& operator= (const MagnifierComponent&);
  38305. };
  38306. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38307. /********* End of inlined file: juce_MagnifierComponent.h *********/
  38308. #endif
  38309. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38310. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  38311. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38312. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38313. /**
  38314. A component that displays a piano keyboard, whose notes can be clicked on.
  38315. This component will mimic a physical midi keyboard, showing the current state of
  38316. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  38317. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  38318. Another feature is that the computer keyboard can also be used to play notes. By
  38319. default it maps the top two rows of a standard querty keyboard to the notes, but
  38320. these can be remapped if needed. It will only respond to keypresses when it has
  38321. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  38322. The component is also a ChangeBroadcaster, so if you want to be informed when the
  38323. keyboard is scrolled, you can register a ChangeListener for callbacks.
  38324. @see MidiKeyboardState
  38325. */
  38326. class JUCE_API MidiKeyboardComponent : public Component,
  38327. public MidiKeyboardStateListener,
  38328. public ChangeBroadcaster,
  38329. private Timer,
  38330. private AsyncUpdater
  38331. {
  38332. public:
  38333. /** The direction of the keyboard.
  38334. @see setOrientation
  38335. */
  38336. enum Orientation
  38337. {
  38338. horizontalKeyboard,
  38339. verticalKeyboardFacingLeft,
  38340. verticalKeyboardFacingRight,
  38341. };
  38342. /** Creates a MidiKeyboardComponent.
  38343. @param state the midi keyboard model that this component will represent
  38344. @param orientation whether the keyboard is horizonal or vertical
  38345. */
  38346. MidiKeyboardComponent (MidiKeyboardState& state,
  38347. const Orientation orientation);
  38348. /** Destructor. */
  38349. ~MidiKeyboardComponent();
  38350. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  38351. on the component.
  38352. Values are 0 to 1.0, where 1.0 is the heaviest.
  38353. @see setMidiChannel
  38354. */
  38355. void setVelocity (const float velocity);
  38356. /** Changes the midi channel number that will be used for events triggered by clicking
  38357. on the component.
  38358. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  38359. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  38360. Although this is the channel used for outgoing events, the component can display
  38361. incoming events from more than one channel - see setMidiChannelsToDisplay()
  38362. @see setVelocity
  38363. */
  38364. void setMidiChannel (const int midiChannelNumber);
  38365. /** Returns the midi channel that the keyboard is using for midi messages.
  38366. @see setMidiChannel
  38367. */
  38368. int getMidiChannel() const throw() { return midiChannel; }
  38369. /** Sets a mask to indicate which incoming midi channels should be represented by
  38370. key movements.
  38371. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  38372. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  38373. in this mask, the on-screen keys will also go down.
  38374. By default, this mask is set to 0xffff (all channels displayed).
  38375. @see setMidiChannel
  38376. */
  38377. void setMidiChannelsToDisplay (const int midiChannelMask);
  38378. /** Returns the current set of midi channels represented by the component.
  38379. This is the value that was set with setMidiChannelsToDisplay().
  38380. */
  38381. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  38382. /** Changes the width used to draw the white keys. */
  38383. void setKeyWidth (const float widthInPixels);
  38384. /** Returns the width that was set by setKeyWidth(). */
  38385. float getKeyWidth() const throw() { return keyWidth; }
  38386. /** Changes the keyboard's current direction. */
  38387. void setOrientation (const Orientation newOrientation);
  38388. /** Returns the keyboard's current direction. */
  38389. const Orientation getOrientation() const throw() { return orientation; }
  38390. /** Sets the range of midi notes that the keyboard will be limited to.
  38391. By default the range is 0 to 127 (inclusive), but you can limit this if you
  38392. only want a restricted set of the keys to be shown.
  38393. Note that the values here are inclusive and must be between 0 and 127.
  38394. */
  38395. void setAvailableRange (const int lowestNote,
  38396. const int highestNote);
  38397. /** Returns the first note in the available range.
  38398. @see setAvailableRange
  38399. */
  38400. int getRangeStart() const throw() { return rangeStart; }
  38401. /** Returns the last note in the available range.
  38402. @see setAvailableRange
  38403. */
  38404. int getRangeEnd() const throw() { return rangeEnd; }
  38405. /** If the keyboard extends beyond the size of the component, this will scroll
  38406. it to show the given key at the start.
  38407. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  38408. base class to send a callback to any ChangeListeners that have been registered.
  38409. */
  38410. void setLowestVisibleKey (int noteNumber);
  38411. /** Returns the number of the first key shown in the component.
  38412. @see setLowestVisibleKey
  38413. */
  38414. int getLowestVisibleKey() const throw() { return firstKey; }
  38415. /** If set to true, then scroll buttons will appear at either end of the keyboard
  38416. if there are too many notes to fit them all in the component at once.
  38417. */
  38418. void setScrollButtonsVisible (const bool canScroll);
  38419. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38420. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38421. methods.
  38422. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38423. */
  38424. enum ColourIds
  38425. {
  38426. whiteNoteColourId = 0x1005000,
  38427. blackNoteColourId = 0x1005001,
  38428. keySeparatorLineColourId = 0x1005002,
  38429. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  38430. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  38431. textLabelColourId = 0x1005005,
  38432. upDownButtonBackgroundColourId = 0x1005006,
  38433. upDownButtonArrowColourId = 0x1005007
  38434. };
  38435. /** Returns the position within the component of the left-hand edge of a key.
  38436. Depending on the keyboard's orientation, this may be a horizontal or vertical
  38437. distance, in either direction.
  38438. */
  38439. int getKeyStartPosition (const int midiNoteNumber) const;
  38440. /** Deletes all key-mappings.
  38441. @see setKeyPressForNote
  38442. */
  38443. void clearKeyMappings();
  38444. /** Maps a key-press to a given note.
  38445. @param key the key that should trigger the note
  38446. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  38447. be. The actual midi note that gets played will be
  38448. this value + (12 * the current base octave). To change
  38449. the base octave, see setKeyPressBaseOctave()
  38450. */
  38451. void setKeyPressForNote (const KeyPress& key,
  38452. const int midiNoteOffsetFromC);
  38453. /** Removes any key-mappings for a given note.
  38454. For a description of what the note number means, see setKeyPressForNote().
  38455. */
  38456. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  38457. /** Changes the base note above which key-press-triggered notes are played.
  38458. The set of key-mappings that trigger notes can be moved up and down to cover
  38459. the entire scale using this method.
  38460. The value passed in is an octave number between 0 and 10 (inclusive), and
  38461. indicates which C is the base note to which the key-mapped notes are
  38462. relative.
  38463. */
  38464. void setKeyPressBaseOctave (const int newOctaveNumber);
  38465. /** This sets the octave number which is shown as the octave number for middle C.
  38466. This affects only the default implementation of getWhiteNoteText(), which
  38467. passes this octave number to MidiMessage::getMidiNoteName() in order to
  38468. get the note text. See MidiMessage::getMidiNoteName() for more info about
  38469. the parameter.
  38470. By default this value is set to 3.
  38471. @see getOctaveForMiddleC
  38472. */
  38473. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  38474. /** This returns the value set by setOctaveForMiddleC().
  38475. @see setOctaveForMiddleC
  38476. */
  38477. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  38478. /** @internal */
  38479. void paint (Graphics& g);
  38480. /** @internal */
  38481. void resized();
  38482. /** @internal */
  38483. void mouseMove (const MouseEvent& e);
  38484. /** @internal */
  38485. void mouseDrag (const MouseEvent& e);
  38486. /** @internal */
  38487. void mouseDown (const MouseEvent& e);
  38488. /** @internal */
  38489. void mouseUp (const MouseEvent& e);
  38490. /** @internal */
  38491. void mouseEnter (const MouseEvent& e);
  38492. /** @internal */
  38493. void mouseExit (const MouseEvent& e);
  38494. /** @internal */
  38495. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38496. /** @internal */
  38497. void timerCallback();
  38498. /** @internal */
  38499. bool keyStateChanged();
  38500. /** @internal */
  38501. void focusLost (FocusChangeType cause);
  38502. /** @internal */
  38503. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  38504. /** @internal */
  38505. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  38506. /** @internal */
  38507. void handleAsyncUpdate();
  38508. /** @internal */
  38509. void colourChanged();
  38510. juce_UseDebuggingNewOperator
  38511. protected:
  38512. friend class MidiKeyboardUpDownButton;
  38513. /** Draws a white note in the given rectangle.
  38514. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38515. currently pressed down.
  38516. When doing this, be sure to note the keyboard's orientation.
  38517. */
  38518. virtual void drawWhiteNote (int midiNoteNumber,
  38519. Graphics& g,
  38520. int x, int y, int w, int h,
  38521. bool isDown, bool isOver,
  38522. const Colour& lineColour,
  38523. const Colour& textColour);
  38524. /** Draws a black note in the given rectangle.
  38525. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38526. currently pressed down.
  38527. When doing this, be sure to note the keyboard's orientation.
  38528. */
  38529. virtual void drawBlackNote (int midiNoteNumber,
  38530. Graphics& g,
  38531. int x, int y, int w, int h,
  38532. bool isDown, bool isOver,
  38533. const Colour& noteFillColour);
  38534. /** Allows text to be drawn on the white notes.
  38535. By default this is used to label the C in each octave, but could be used for other things.
  38536. @see setOctaveForMiddleC
  38537. */
  38538. virtual const String getWhiteNoteText (const int midiNoteNumber);
  38539. /** Draws the up and down buttons that change the base note. */
  38540. virtual void drawUpDownButton (Graphics& g, int w, int h,
  38541. const bool isMouseOver,
  38542. const bool isButtonPressed,
  38543. const bool movesOctavesUp);
  38544. /** Callback when the mouse is clicked on a key.
  38545. You could use this to do things like handle right-clicks on keys, etc.
  38546. Return true if you want the click to trigger the note, or false if you
  38547. want to handle it yourself and not have the note played.
  38548. @see mouseDraggedToKey
  38549. */
  38550. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  38551. /** Callback when the mouse is dragged from one key onto another.
  38552. @see mouseDownOnKey
  38553. */
  38554. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  38555. /** Calculates the positon of a given midi-note.
  38556. This can be overridden to create layouts with custom key-widths.
  38557. @param midiNoteNumber the note to find
  38558. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  38559. @param x the x position of the left-hand edge of the key (this method
  38560. always works in terms of a horizontal keyboard)
  38561. @param w the width of the key
  38562. */
  38563. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  38564. int& x, int& w) const;
  38565. private:
  38566. MidiKeyboardState& state;
  38567. int xOffset, blackNoteLength;
  38568. float keyWidth;
  38569. Orientation orientation;
  38570. int midiChannel, midiInChannelMask;
  38571. float velocity;
  38572. int noteUnderMouse, mouseDownNote;
  38573. BitArray keysPressed, keysCurrentlyDrawnDown;
  38574. int rangeStart, rangeEnd, firstKey;
  38575. bool canScroll, mouseDragging;
  38576. Button* scrollDown;
  38577. Button* scrollUp;
  38578. Array <KeyPress> keyPresses;
  38579. Array <int> keyPressNotes;
  38580. int keyMappingOctave;
  38581. int octaveNumForMiddleC;
  38582. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  38583. int xyToNote (int x, int y);
  38584. int remappedXYToNote (int x, int y) const;
  38585. void resetAnyKeysInUse();
  38586. void updateNoteUnderMouse (int x, int y);
  38587. void repaintNote (const int midiNoteNumber);
  38588. MidiKeyboardComponent (const MidiKeyboardComponent&);
  38589. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  38590. };
  38591. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38592. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  38593. #endif
  38594. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38595. /********* Start of inlined file: juce_NSViewComponent.h *********/
  38596. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38597. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38598. #if ! DOXYGEN
  38599. class NSViewComponentInternal;
  38600. #endif
  38601. #if JUCE_MAC || DOXYGEN
  38602. /**
  38603. A Mac-specific class that can create and embed an NSView inside itself.
  38604. To use it, create one of these, put it in place and make sure it's visible in a
  38605. window, then use setView() to assign an NSView to it. The view will then be
  38606. moved and resized to follow the movements of this component.
  38607. Of course, since the view is a native object, it'll obliterate any
  38608. juce components that may overlap this component, but that's life.
  38609. */
  38610. class JUCE_API NSViewComponent : public Component
  38611. {
  38612. public:
  38613. /** Create an initially-empty container. */
  38614. NSViewComponent();
  38615. /** Destructor. */
  38616. ~NSViewComponent();
  38617. /** Assigns an NSView to this peer.
  38618. The view will be retained and released by this component for as long as
  38619. it is needed. To remove the current view, just call setView (0).
  38620. Note: a void* is used here to avoid including the cocoa headers as
  38621. part of the juce.h, but the method expects an NSView*.
  38622. */
  38623. void setView (void* nsView);
  38624. /** Returns the current NSView.
  38625. Note: a void* is returned here to avoid including the cocoa headers as
  38626. a requirement of juce.h, so you should just cast the object to an NSView*.
  38627. */
  38628. void* getView() const;
  38629. /** @internal */
  38630. void paint (Graphics& g);
  38631. juce_UseDebuggingNewOperator
  38632. private:
  38633. friend class NSViewComponentInternal;
  38634. NSViewComponentInternal* info;
  38635. NSViewComponent (const NSViewComponent&);
  38636. const NSViewComponent& operator= (const NSViewComponent&);
  38637. };
  38638. #endif
  38639. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38640. /********* End of inlined file: juce_NSViewComponent.h *********/
  38641. #endif
  38642. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38643. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  38644. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38645. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38646. // this is used to disable OpenGL, and is defined in juce_Config.h
  38647. #if JUCE_OPENGL || DOXYGEN
  38648. class OpenGLComponentWatcher;
  38649. /**
  38650. Represents the various properties of an OpenGL bitmap format.
  38651. @see OpenGLComponent::setPixelFormat
  38652. */
  38653. struct OpenGLPixelFormat
  38654. {
  38655. /** Creates an OpenGLPixelFormat.
  38656. The default constructor just initialises the object as a simple 8-bit
  38657. RGBA format.
  38658. */
  38659. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  38660. const int alphaBits = 8,
  38661. const int depthBufferBits = 16,
  38662. const int stencilBufferBits = 0) throw();
  38663. int redBits; /**< The number of bits per pixel to use for the red channel. */
  38664. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  38665. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  38666. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  38667. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  38668. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  38669. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  38670. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  38671. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  38672. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  38673. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  38674. /** Returns a list of all the pixel formats that can be used in this system.
  38675. A reference component is needed in case there are multiple screens with different
  38676. capabilities - in which case, the one that the component is on will be used.
  38677. */
  38678. static void getAvailablePixelFormats (Component* component,
  38679. OwnedArray <OpenGLPixelFormat>& results);
  38680. bool operator== (const OpenGLPixelFormat&) const throw();
  38681. juce_UseDebuggingNewOperator
  38682. };
  38683. /**
  38684. A base class for types of OpenGL context.
  38685. An OpenGLComponent will supply its own context for drawing in its window.
  38686. */
  38687. class OpenGLContext
  38688. {
  38689. public:
  38690. /** Destructor. */
  38691. virtual ~OpenGLContext();
  38692. /** Makes this context the currently active one. */
  38693. virtual bool makeActive() const throw() = 0;
  38694. /** If this context is currently active, it is disactivated. */
  38695. virtual bool makeInactive() const throw() = 0;
  38696. /** Returns true if this context is currently active. */
  38697. virtual bool isActive() const throw() = 0;
  38698. /** Swaps the buffers (if the context can do this). */
  38699. virtual void swapBuffers() = 0;
  38700. /** Sets whether the context checks the vertical sync before swapping.
  38701. The value is the number of frames to allow between buffer-swapping. This is
  38702. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  38703. and greater numbers indicate that it should swap less often.
  38704. Returns true if it sets the value successfully.
  38705. */
  38706. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  38707. /** Returns the current swap-sync interval.
  38708. See setSwapInterval() for info about the value returned.
  38709. */
  38710. virtual int getSwapInterval() const = 0;
  38711. /** Returns the pixel format being used by this context. */
  38712. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  38713. /** For windowed contexts, this moves the context within the bounds of
  38714. its parent window.
  38715. */
  38716. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  38717. /** For windowed contexts, this triggers a repaint of the window.
  38718. (Not relevent on all platforms).
  38719. */
  38720. virtual void repaint() = 0;
  38721. /** Returns an OS-dependent handle to the raw GL context.
  38722. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  38723. a GLXContext.
  38724. */
  38725. virtual void* getRawContext() const throw() = 0;
  38726. /** This tries to create a context that can be used for drawing into the
  38727. area occupied by the specified component.
  38728. Note that you probably shouldn't use this method directly unless you know what
  38729. you're doing - the OpenGLComponent calls this and manages the context for you.
  38730. */
  38731. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  38732. const OpenGLPixelFormat& pixelFormat,
  38733. const OpenGLContext* const contextToShareWith);
  38734. /** Returns the context that's currently in active use by the calling thread.
  38735. Returns 0 if there isn't an active context.
  38736. */
  38737. static OpenGLContext* getCurrentContext();
  38738. juce_UseDebuggingNewOperator
  38739. protected:
  38740. OpenGLContext() throw();
  38741. };
  38742. /**
  38743. A component that contains an OpenGL canvas.
  38744. Override this, add it to whatever component you want to, and use the renderOpenGL()
  38745. method to draw its contents.
  38746. */
  38747. class JUCE_API OpenGLComponent : public Component
  38748. {
  38749. public:
  38750. /** Creates an OpenGLComponent.
  38751. */
  38752. OpenGLComponent();
  38753. /** Destructor. */
  38754. ~OpenGLComponent();
  38755. /** Changes the pixel format used by this component.
  38756. @see OpenGLPixelFormat::getAvailablePixelFormats()
  38757. */
  38758. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  38759. /** Returns the pixel format that this component is currently using. */
  38760. const OpenGLPixelFormat getPixelFormat() const;
  38761. /** Specifies an OpenGL context which should be shared with the one that this
  38762. component is using.
  38763. This is an OpenGL feature that lets two contexts share their texture data.
  38764. Note that this pointer is stored by the component, and when the component
  38765. needs to recreate its internal context for some reason, the same context
  38766. will be used again to share lists. So if you pass a context in here,
  38767. don't delete the context while this component is still using it! You can
  38768. call shareWith (0) to stop this component from sharing with it.
  38769. */
  38770. void shareWith (OpenGLContext* contextToShareListsWith);
  38771. /** Returns the context that this component is sharing with.
  38772. @see shareWith
  38773. */
  38774. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  38775. /** Flips the openGL buffers over. */
  38776. void swapBuffers();
  38777. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  38778. When this is called, makeCurrentContextActive() will already have been called
  38779. for you, so you just need to draw.
  38780. */
  38781. virtual void renderOpenGL() = 0;
  38782. /** This method is called when the component creates a new OpenGL context.
  38783. A new context may be created when the component is first used, or when it
  38784. is moved to a different window, or when the window is hidden and re-shown,
  38785. etc.
  38786. You can use this callback as an opportunity to set up things like textures
  38787. that your context needs.
  38788. New contexts are created on-demand by the makeCurrentContextActive() method - so
  38789. if the context is deleted, e.g. by changing the pixel format or window, no context
  38790. will be created until the next call to makeCurrentContextActive(), which will
  38791. synchronously create one and call this method. This means that if you're using
  38792. a non-GUI thread for rendering, you can make sure this method is be called by
  38793. your renderer thread.
  38794. When this callback happens, the context will already have been made current
  38795. using the makeCurrentContextActive() method, so there's no need to call it
  38796. again in your code.
  38797. */
  38798. virtual void newOpenGLContextCreated() = 0;
  38799. /** Returns the context that will draw into this component.
  38800. This may return 0 if the component is currently invisible or hasn't currently
  38801. got a context. The context object can be deleted and a new one created during
  38802. the lifetime of this component, and there may be times when it doesn't have one.
  38803. @see newOpenGLContextCreated()
  38804. */
  38805. OpenGLContext* getCurrentContext() const throw() { return context; }
  38806. /** Makes this component the current openGL context.
  38807. You might want to use this in things like your resize() method, before calling
  38808. GL commands.
  38809. If this returns false, then the context isn't active, so you should avoid
  38810. making any calls.
  38811. This call may actually create a context if one isn't currently initialised. If
  38812. it does this, it will also synchronously call the newOpenGLContextCreated()
  38813. method to let you initialise it as necessary.
  38814. @see OpenGLContext::makeActive
  38815. */
  38816. bool makeCurrentContextActive();
  38817. /** Stops the current component being the active OpenGL context.
  38818. This is the opposite of makeCurrentContextActive()
  38819. @see OpenGLContext::makeInactive
  38820. */
  38821. void makeCurrentContextInactive();
  38822. /** Returns true if this component is the active openGL context for the
  38823. current thread.
  38824. @see OpenGLContext::isActive
  38825. */
  38826. bool isActiveContext() const throw();
  38827. /** Calls the rendering callback, and swaps the buffers afterwards.
  38828. This is called automatically by paint() when the component needs to be rendered.
  38829. It can be overridden if you need to decouple the rendering from the paint callback
  38830. and render with a custom thread.
  38831. Returns true if the operation succeeded.
  38832. */
  38833. virtual bool renderAndSwapBuffers();
  38834. /** This returns a critical section that can be used to lock the current context.
  38835. Because the context that is used by this component can change, e.g. when the
  38836. component is shown or hidden, then if you're rendering to it on a background
  38837. thread, this allows you to lock the context for the duration of your rendering
  38838. routine.
  38839. */
  38840. CriticalSection& getContextLock() throw() { return contextLock; }
  38841. /** @internal */
  38842. void paint (Graphics& g);
  38843. /** Returns the native handle of an embedded heavyweight window, if there is one.
  38844. E.g. On windows, this will return the HWND of the sub-window containing
  38845. the opengl context, on the mac it'll be the NSOpenGLView.
  38846. */
  38847. void* getNativeWindowHandle() const;
  38848. juce_UseDebuggingNewOperator
  38849. private:
  38850. friend class OpenGLComponentWatcher;
  38851. OpenGLComponentWatcher* componentWatcher;
  38852. OpenGLContext* context;
  38853. OpenGLContext* contextToShareListsWith;
  38854. CriticalSection contextLock;
  38855. OpenGLPixelFormat preferredPixelFormat;
  38856. bool needToUpdateViewport;
  38857. void deleteContext();
  38858. void updateContextPosition();
  38859. void internalRepaint (int x, int y, int w, int h);
  38860. OpenGLComponent (const OpenGLComponent&);
  38861. const OpenGLComponent& operator= (const OpenGLComponent&);
  38862. };
  38863. #endif
  38864. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38865. /********* End of inlined file: juce_OpenGLComponent.h *********/
  38866. #endif
  38867. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38868. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  38869. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38870. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38871. /**
  38872. A component with a set of buttons at the top for changing between pages of
  38873. preferences.
  38874. This is just a handy way of writing a Mac-style preferences panel where you
  38875. have a row of buttons along the top for the different preference categories,
  38876. each button having an icon above its name. Clicking these will show an
  38877. appropriate prefs page below it.
  38878. You can either put one of these inside your own component, or just use the
  38879. showInDialogBox() method to show it in a window and run it modally.
  38880. To use it, just add a set of named pages with the addSettingsPage() method,
  38881. and implement the createComponentForPage() method to create suitable components
  38882. for each of these pages.
  38883. */
  38884. class JUCE_API PreferencesPanel : public Component,
  38885. private ButtonListener
  38886. {
  38887. public:
  38888. /** Creates an empty panel.
  38889. Use addSettingsPage() to add some pages to it in your constructor.
  38890. */
  38891. PreferencesPanel();
  38892. /** Destructor. */
  38893. ~PreferencesPanel();
  38894. /** Creates a page using a set of drawables to define the page's icon.
  38895. Note that the other version of this method is much easier if you're using
  38896. an image instead of a custom drawable.
  38897. @param pageTitle the name of this preferences page - you'll need to
  38898. make sure your createComponentForPage() method creates
  38899. a suitable component when it is passed this name
  38900. @param normalIcon the drawable to display in the page's button normally
  38901. @param overIcon the drawable to display in the page's button when the mouse is over
  38902. @param downIcon the drawable to display in the page's button when the button is down
  38903. @see DrawableButton
  38904. */
  38905. void addSettingsPage (const String& pageTitle,
  38906. const Drawable* normalIcon,
  38907. const Drawable* overIcon,
  38908. const Drawable* downIcon);
  38909. /** Creates a page using a set of drawables to define the page's icon.
  38910. The other version of this method gives you more control over the icon, but this
  38911. one is much easier if you're just loading it from a file.
  38912. @param pageTitle the name of this preferences page - you'll need to
  38913. make sure your createComponentForPage() method creates
  38914. a suitable component when it is passed this name
  38915. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  38916. For this to look good, you'll probably want to use a nice
  38917. transparent png file.
  38918. @param imageDataSize the size of the image data, in bytes
  38919. */
  38920. void addSettingsPage (const String& pageTitle,
  38921. const char* imageData,
  38922. const int imageDataSize);
  38923. /** Utility method to display this panel in a DialogWindow.
  38924. Calling this will create a DialogWindow containing this panel with the
  38925. given size and title, and will run it modally, returning when the user
  38926. closes the dialog box.
  38927. */
  38928. void showInDialogBox (const String& dialogtitle,
  38929. int dialogWidth,
  38930. int dialogHeight,
  38931. const Colour& backgroundColour = Colours::white);
  38932. /** Subclasses must override this to return a component for each preferences page.
  38933. The subclass should return a pointer to a new component representing the named
  38934. page, which the panel will then display.
  38935. The panel will delete the component later when the user goes to another page
  38936. or deletes the panel.
  38937. */
  38938. virtual Component* createComponentForPage (const String& pageName) = 0;
  38939. /** Changes the current page being displayed. */
  38940. void setCurrentPage (const String& pageName);
  38941. /** @internal */
  38942. void resized();
  38943. /** @internal */
  38944. void paint (Graphics& g);
  38945. /** @internal */
  38946. void buttonClicked (Button* button);
  38947. juce_UseDebuggingNewOperator
  38948. private:
  38949. String currentPageName;
  38950. Component* currentPage;
  38951. int buttonSize;
  38952. PreferencesPanel (const PreferencesPanel&);
  38953. const PreferencesPanel& operator= (const PreferencesPanel&);
  38954. };
  38955. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38956. /********* End of inlined file: juce_PreferencesPanel.h *********/
  38957. #endif
  38958. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  38959. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  38960. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  38961. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  38962. // this is used to disable QuickTime, and is defined in juce_Config.h
  38963. #if JUCE_QUICKTIME || DOXYGEN
  38964. #if JUCE_WIN32
  38965. typedef ActiveXControlComponent QTCompBaseClass;
  38966. #else
  38967. typedef NSViewComponent QTCompBaseClass;
  38968. #endif
  38969. /**
  38970. A window that can play back a QuickTime movie.
  38971. */
  38972. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  38973. {
  38974. public:
  38975. /** Creates a QuickTimeMovieComponent, initially blank.
  38976. Use the loadMovie() method to load a movie once you've added the
  38977. component to a window, (or put it on the desktop as a heavyweight window).
  38978. Loading a movie when the component isn't visible can cause problems, as
  38979. QuickTime needs a window handle to initialise properly.
  38980. */
  38981. QuickTimeMovieComponent();
  38982. /** Destructor. */
  38983. ~QuickTimeMovieComponent();
  38984. /** Returns true if QT is installed and working on this machine.
  38985. */
  38986. static bool isQuickTimeAvailable() throw();
  38987. /** Tries to load a QuickTime movie into the player.
  38988. It's best to call this function once you've added the component to a window,
  38989. (or put it on the desktop as a heavyweight window). Loading a movie when the
  38990. component isn't visible can cause problems, because QuickTime needs a window
  38991. handle to do its stuff.
  38992. @param movieFile the .mov file to open
  38993. @param isControllerVisible whether to show a controller bar at the bottom
  38994. @returns true if the movie opens successfully
  38995. */
  38996. bool loadMovie (const File& movieFile,
  38997. const bool isControllerVisible);
  38998. bool loadMovie (InputStream* movieStream,
  38999. const bool isControllerVisible);
  39000. /** Closes the movie, if one is open. */
  39001. void closeMovie();
  39002. /** Returns the movie file that is currently open.
  39003. If there isn't one, this returns File::nonexistent
  39004. */
  39005. const File getCurrentMovieFile() const;
  39006. /** Returns true if there's currently a movie open. */
  39007. bool isMovieOpen() const;
  39008. /** Returns the length of the movie, in seconds. */
  39009. double getMovieDuration() const;
  39010. /** Returns the movie's natural size, in pixels.
  39011. You can use this to resize the component to show the movie at its preferred
  39012. scale.
  39013. If no movie is loaded, the size returned will be 0 x 0.
  39014. */
  39015. void getMovieNormalSize (int& width, int& height) const;
  39016. /** This will position the component within a given area, keeping its aspect
  39017. ratio correct according to the movie's normal size.
  39018. The component will be made as large as it can go within the space, and will
  39019. be aligned according to the justification value if this means there are gaps at
  39020. the top or sides.
  39021. */
  39022. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  39023. const RectanglePlacement& placement);
  39024. /** Starts the movie playing. */
  39025. void play();
  39026. /** Stops the movie playing. */
  39027. void stop();
  39028. /** Returns true if the movie is currently playing. */
  39029. bool isPlaying() const;
  39030. /** Moves the movie's position back to the start. */
  39031. void goToStart();
  39032. /** Sets the movie's position to a given time. */
  39033. void setPosition (const double seconds);
  39034. /** Returns the current play position of the movie. */
  39035. double getPosition() const;
  39036. /** Changes the movie playback rate.
  39037. A value of 1 is normal speed, greater values play it proportionately faster,
  39038. smaller values play it slower.
  39039. */
  39040. void setSpeed (const float newSpeed);
  39041. /** Changes the movie's playback volume.
  39042. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39043. */
  39044. void setMovieVolume (const float newVolume);
  39045. /** Returns the movie's playback volume.
  39046. @returns the volume in the range 0 (silent) to 1.0 (full)
  39047. */
  39048. float getMovieVolume() const;
  39049. /** Tells the movie whether it should loop. */
  39050. void setLooping (const bool shouldLoop);
  39051. /** Returns true if the movie is currently looping.
  39052. @see setLooping
  39053. */
  39054. bool isLooping() const;
  39055. /** True if the native QuickTime controller bar is shown in the window.
  39056. @see loadMovie
  39057. */
  39058. bool isControllerVisible() const;
  39059. /** @internal */
  39060. void paint (Graphics& g);
  39061. juce_UseDebuggingNewOperator
  39062. private:
  39063. File movieFile;
  39064. bool movieLoaded, controllerVisible, looping;
  39065. #if JUCE_WIN32
  39066. /** @internal */
  39067. void parentHierarchyChanged();
  39068. /** @internal */
  39069. void visibilityChanged();
  39070. void createControlIfNeeded();
  39071. bool isControlCreated() const;
  39072. void* internal;
  39073. #else
  39074. void* movie;
  39075. #endif
  39076. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39077. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39078. };
  39079. #endif
  39080. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39081. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39082. #endif
  39083. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39084. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  39085. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39086. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39087. #if JUCE_WIN32 || JUCE_LINUX
  39088. /**
  39089. On Windows only, this component sits in the taskbar tray as a small icon.
  39090. To use it, just create one of these components, but don't attempt to make it
  39091. visible, add it to a parent, or put it on the desktop.
  39092. You can then call setIconImage() to create an icon for it in the taskbar.
  39093. To change the icon's tooltip, you can use setIconTooltip().
  39094. To respond to mouse-events, you can override the normal mouseDown(),
  39095. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  39096. position will not be valid, you can use this to respond to clicks. Traditionally
  39097. you'd use a left-click to show your application's window, and a right-click
  39098. to show a pop-up menu.
  39099. */
  39100. class JUCE_API SystemTrayIconComponent : public Component
  39101. {
  39102. public:
  39103. SystemTrayIconComponent();
  39104. /** Destructor. */
  39105. ~SystemTrayIconComponent();
  39106. /** Changes the image shown in the taskbar.
  39107. */
  39108. void setIconImage (const Image& newImage);
  39109. /** Changes the tooltip that Windows shows above the icon. */
  39110. void setIconTooltip (const String& tooltip);
  39111. #if JUCE_LINUX
  39112. /** @internal */
  39113. void paint (Graphics& g);
  39114. #endif
  39115. juce_UseDebuggingNewOperator
  39116. private:
  39117. SystemTrayIconComponent (const SystemTrayIconComponent&);
  39118. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  39119. };
  39120. #endif
  39121. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39122. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  39123. #endif
  39124. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39125. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  39126. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39127. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39128. #if JUCE_WEB_BROWSER
  39129. class WebBrowserComponentInternal;
  39130. /**
  39131. A component that displays an embedded web browser.
  39132. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  39133. Windows, probably IE.
  39134. */
  39135. class WebBrowserComponent : public Component
  39136. {
  39137. public:
  39138. /** Creates a WebBrowserComponent.
  39139. Once it's created and visible, send the browser to a URL using goToURL().
  39140. */
  39141. WebBrowserComponent();
  39142. /** Destructor. */
  39143. ~WebBrowserComponent();
  39144. /** Sends the browser to a particular URL.
  39145. @param url the URL to go to.
  39146. @param headers an optional set of parameters to put in the HTTP header. If
  39147. you supply this, it should be a set of string in the form
  39148. "HeaderKey: HeaderValue"
  39149. @param postData an optional block of data that will be attached to the HTTP
  39150. POST request
  39151. */
  39152. void goToURL (const String& url,
  39153. const StringArray* headers = 0,
  39154. const MemoryBlock* postData = 0);
  39155. /** Stops the current page loading.
  39156. */
  39157. void stop();
  39158. /** Sends the browser back one page.
  39159. */
  39160. void goBack();
  39161. /** Sends the browser forward one page.
  39162. */
  39163. void goForward();
  39164. /** This callback is called when the browser is about to navigate
  39165. to a new location.
  39166. You can override this method to perform some action when the user
  39167. tries to go to a particular URL. To allow the operation to carry on,
  39168. return true, or return false to stop the navigation happening.
  39169. */
  39170. virtual bool pageAboutToLoad (const String& newURL);
  39171. /** @internal */
  39172. void paint (Graphics& g);
  39173. /** @internal */
  39174. void resized();
  39175. /** @internal */
  39176. void parentHierarchyChanged();
  39177. /** @internal */
  39178. void visibilityChanged();
  39179. juce_UseDebuggingNewOperator
  39180. private:
  39181. WebBrowserComponentInternal* browser;
  39182. bool blankPageShown;
  39183. String lastURL;
  39184. StringArray lastHeaders;
  39185. MemoryBlock lastPostData;
  39186. void reloadLastURL();
  39187. void checkWindowAssociation();
  39188. WebBrowserComponent (const WebBrowserComponent&);
  39189. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  39190. };
  39191. #endif
  39192. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39193. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  39194. #endif
  39195. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39196. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39197. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39198. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39199. class ToggleButton;
  39200. class TextButton;
  39201. class AlertWindow;
  39202. class TextLayout;
  39203. class ScrollBar;
  39204. class BubbleComponent;
  39205. class ComboBox;
  39206. class Button;
  39207. class FilenameComponent;
  39208. class DocumentWindow;
  39209. class ResizableWindow;
  39210. class GroupComponent;
  39211. class MenuBarComponent;
  39212. class DropShadower;
  39213. class GlyphArrangement;
  39214. class PropertyComponent;
  39215. class TableHeaderComponent;
  39216. class Toolbar;
  39217. class ToolbarItemComponent;
  39218. class PopupMenu;
  39219. class ProgressBar;
  39220. class FileBrowserComponent;
  39221. class DirectoryContentsDisplayComponent;
  39222. class FilePreviewComponent;
  39223. /**
  39224. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39225. can be used to apply different 'skins' to the application.
  39226. */
  39227. class JUCE_API LookAndFeel
  39228. {
  39229. public:
  39230. /** Creates the default JUCE look and feel. */
  39231. LookAndFeel();
  39232. /** Destructor. */
  39233. virtual ~LookAndFeel();
  39234. /** Returns the current default look-and-feel for a component to use when it
  39235. hasn't got one explicitly set.
  39236. @see setDefaultLookAndFeel
  39237. */
  39238. static LookAndFeel& getDefaultLookAndFeel() throw();
  39239. /** Changes the default look-and-feel.
  39240. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39241. set to 0, it will revert to using the default one. The
  39242. object passed-in must be deleted by the caller when
  39243. it's no longer needed.
  39244. @see getDefaultLookAndFeel
  39245. */
  39246. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39247. /** Looks for a colour that has been registered with the given colour ID number.
  39248. If a colour has been set for this ID number using setColour(), then it is
  39249. returned. If none has been set, it will just return Colours::black.
  39250. The colour IDs for various purposes are stored as enums in the components that
  39251. they are relevent to - for an example, see Slider::ColourIds,
  39252. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39253. If you're looking up a colour for use in drawing a component, it's usually
  39254. best not to call this directly, but to use the Component::findColour() method
  39255. instead. That will first check whether a suitable colour has been registered
  39256. directly with the component, and will fall-back on calling the component's
  39257. LookAndFeel's findColour() method if none is found.
  39258. @see setColour, Component::findColour, Component::setColour
  39259. */
  39260. const Colour findColour (const int colourId) const throw();
  39261. /** Registers a colour to be used for a particular purpose.
  39262. For more details, see the comments for findColour().
  39263. @see findColour, Component::findColour, Component::setColour
  39264. */
  39265. void setColour (const int colourId, const Colour& colour) throw();
  39266. /** Draws the lozenge-shaped background for a standard button. */
  39267. virtual void drawButtonBackground (Graphics& g,
  39268. Button& button,
  39269. const Colour& backgroundColour,
  39270. bool isMouseOverButton,
  39271. bool isButtonDown);
  39272. /** Draws the text for a TextButton. */
  39273. virtual void drawButtonText (Graphics& g,
  39274. TextButton& button,
  39275. bool isMouseOverButton,
  39276. bool isButtonDown);
  39277. /** Draws the contents of a standard ToggleButton. */
  39278. virtual void drawToggleButton (Graphics& g,
  39279. ToggleButton& button,
  39280. bool isMouseOverButton,
  39281. bool isButtonDown);
  39282. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39283. virtual void drawTickBox (Graphics& g,
  39284. Component& component,
  39285. int x, int y, int w, int h,
  39286. const bool ticked,
  39287. const bool isEnabled,
  39288. const bool isMouseOverButton,
  39289. const bool isButtonDown);
  39290. /** Draws the contents of a message box.
  39291. */
  39292. virtual void drawAlertBox (Graphics& g,
  39293. AlertWindow& alert,
  39294. const Rectangle& textArea,
  39295. TextLayout& textLayout);
  39296. virtual int getAlertBoxWindowFlags();
  39297. virtual int getAlertWindowButtonHeight();
  39298. virtual const Font getAlertWindowFont();
  39299. /** Draws a progress bar.
  39300. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39301. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39302. isn't known). It can use the current time as a basis for playing an animation.
  39303. (Used by progress bars in AlertWindow).
  39304. */
  39305. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39306. int width, int height,
  39307. double progress, const String& textToShow);
  39308. /** Draws one of the buttons on a scrollbar.
  39309. @param g the context to draw into
  39310. @param scrollbar the bar itself
  39311. @param width the width of the button
  39312. @param height the height of the button
  39313. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39314. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39315. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39316. @param isButtonDown whether the mouse button's held down
  39317. */
  39318. virtual void drawScrollbarButton (Graphics& g,
  39319. ScrollBar& scrollbar,
  39320. int width, int height,
  39321. int buttonDirection,
  39322. bool isScrollbarVertical,
  39323. bool isMouseOverButton,
  39324. bool isButtonDown);
  39325. /** Draws the thumb area of a scrollbar.
  39326. @param g the context to draw into
  39327. @param scrollbar the bar itself
  39328. @param x the x position of the left edge of the thumb area to draw in
  39329. @param y the y position of the top edge of the thumb area to draw in
  39330. @param width the width of the thumb area to draw in
  39331. @param height the height of the thumb area to draw in
  39332. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39333. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39334. thumb, or its x position for horizontal bars
  39335. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39336. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39337. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39338. currently dragging the thumb
  39339. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39340. */
  39341. virtual void drawScrollbar (Graphics& g,
  39342. ScrollBar& scrollbar,
  39343. int x, int y,
  39344. int width, int height,
  39345. bool isScrollbarVertical,
  39346. int thumbStartPosition,
  39347. int thumbSize,
  39348. bool isMouseOver,
  39349. bool isMouseDown);
  39350. /** Returns the component effect to use for a scrollbar */
  39351. virtual ImageEffectFilter* getScrollbarEffect();
  39352. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39353. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39354. /** Returns the default thickness to use for a scrollbar. */
  39355. virtual int getDefaultScrollbarWidth();
  39356. /** Returns the length in pixels to use for a scrollbar button. */
  39357. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39358. /** Returns a tick shape for use in yes/no boxes, etc. */
  39359. virtual const Path getTickShape (const float height);
  39360. /** Returns a cross shape for use in yes/no boxes, etc. */
  39361. virtual const Path getCrossShape (const float height);
  39362. /** Draws the + or - box in a treeview. */
  39363. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus);
  39364. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39365. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39366. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39367. virtual Image* getDefaultFolderImage();
  39368. virtual Image* getDefaultDocumentFileImage();
  39369. virtual void createFileChooserHeaderText (const String& title,
  39370. const String& instructions,
  39371. GlyphArrangement& destArrangement,
  39372. int width);
  39373. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39374. const String& filename, Image* icon,
  39375. const String& fileSizeDescription,
  39376. const String& fileTimeDescription,
  39377. const bool isDirectory,
  39378. const bool isItemSelected,
  39379. const int itemIndex);
  39380. virtual Button* createFileBrowserGoUpButton();
  39381. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39382. DirectoryContentsDisplayComponent* fileListComponent,
  39383. FilePreviewComponent* previewComp,
  39384. ComboBox* currentPathBox,
  39385. TextEditor* filenameBox,
  39386. Button* goUpButton);
  39387. virtual void drawBubble (Graphics& g,
  39388. float tipX, float tipY,
  39389. float boxX, float boxY, float boxW, float boxH);
  39390. /** Fills the background of a popup menu component. */
  39391. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39392. /** Draws one of the items in a popup menu. */
  39393. virtual void drawPopupMenuItem (Graphics& g,
  39394. int width, int height,
  39395. const bool isSeparator,
  39396. const bool isActive,
  39397. const bool isHighlighted,
  39398. const bool isTicked,
  39399. const bool hasSubMenu,
  39400. const String& text,
  39401. const String& shortcutKeyText,
  39402. Image* image,
  39403. const Colour* const textColour);
  39404. /** Returns the size and style of font to use in popup menus. */
  39405. virtual const Font getPopupMenuFont();
  39406. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  39407. int width, int height,
  39408. bool isScrollUpArrow);
  39409. /** Finds the best size for an item in a popup menu. */
  39410. virtual void getIdealPopupMenuItemSize (const String& text,
  39411. const bool isSeparator,
  39412. int standardMenuItemHeight,
  39413. int& idealWidth,
  39414. int& idealHeight);
  39415. virtual int getMenuWindowFlags();
  39416. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39417. bool isMouseOverBar,
  39418. MenuBarComponent& menuBar);
  39419. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39420. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39421. virtual void drawMenuBarItem (Graphics& g,
  39422. int width, int height,
  39423. int itemIndex,
  39424. const String& itemText,
  39425. bool isMouseOverItem,
  39426. bool isMenuOpen,
  39427. bool isMouseOverBar,
  39428. MenuBarComponent& menuBar);
  39429. virtual void drawComboBox (Graphics& g, int width, int height,
  39430. const bool isButtonDown,
  39431. int buttonX, int buttonY,
  39432. int buttonW, int buttonH,
  39433. ComboBox& box);
  39434. virtual const Font getComboBoxFont (ComboBox& box);
  39435. virtual Label* createComboBoxTextBox (ComboBox& box);
  39436. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  39437. virtual void drawLabel (Graphics& g, Label& label);
  39438. virtual void drawLinearSlider (Graphics& g,
  39439. int x, int y,
  39440. int width, int height,
  39441. float sliderPos,
  39442. float minSliderPos,
  39443. float maxSliderPos,
  39444. const Slider::SliderStyle style,
  39445. Slider& slider);
  39446. virtual void drawLinearSliderBackground (Graphics& g,
  39447. int x, int y,
  39448. int width, int height,
  39449. float sliderPos,
  39450. float minSliderPos,
  39451. float maxSliderPos,
  39452. const Slider::SliderStyle style,
  39453. Slider& slider);
  39454. virtual void drawLinearSliderThumb (Graphics& g,
  39455. int x, int y,
  39456. int width, int height,
  39457. float sliderPos,
  39458. float minSliderPos,
  39459. float maxSliderPos,
  39460. const Slider::SliderStyle style,
  39461. Slider& slider);
  39462. virtual int getSliderThumbRadius (Slider& slider);
  39463. virtual void drawRotarySlider (Graphics& g,
  39464. int x, int y,
  39465. int width, int height,
  39466. float sliderPosProportional,
  39467. const float rotaryStartAngle,
  39468. const float rotaryEndAngle,
  39469. Slider& slider);
  39470. virtual Button* createSliderButton (const bool isIncrement);
  39471. virtual Label* createSliderTextBox (Slider& slider);
  39472. virtual ImageEffectFilter* getSliderEffect();
  39473. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  39474. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  39475. virtual Button* createFilenameComponentBrowseButton (const String& text);
  39476. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  39477. ComboBox* filenameBox, Button* browseButton);
  39478. virtual void drawCornerResizer (Graphics& g,
  39479. int w, int h,
  39480. bool isMouseOver,
  39481. bool isMouseDragging);
  39482. virtual void drawResizableFrame (Graphics& g,
  39483. int w, int h,
  39484. const BorderSize& borders);
  39485. virtual void drawResizableWindowBorder (Graphics& g,
  39486. int w, int h,
  39487. const BorderSize& border,
  39488. ResizableWindow& window);
  39489. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  39490. Graphics& g, int w, int h,
  39491. int titleSpaceX, int titleSpaceW,
  39492. const Image* icon,
  39493. bool drawTitleTextOnLeft);
  39494. virtual Button* createDocumentWindowButton (int buttonType);
  39495. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39496. int titleBarX, int titleBarY,
  39497. int titleBarW, int titleBarH,
  39498. Button* minimiseButton,
  39499. Button* maximiseButton,
  39500. Button* closeButton,
  39501. bool positionTitleBarButtonsOnLeft);
  39502. virtual int getDefaultMenuBarHeight();
  39503. virtual DropShadower* createDropShadowerForComponent (Component* component);
  39504. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  39505. int w, int h,
  39506. bool isVerticalBar,
  39507. bool isMouseOver,
  39508. bool isMouseDragging);
  39509. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  39510. const String& text,
  39511. const Justification& position,
  39512. GroupComponent& group);
  39513. virtual void createTabButtonShape (Path& p,
  39514. int width, int height,
  39515. int tabIndex,
  39516. const String& text,
  39517. Button& button,
  39518. TabbedButtonBar::Orientation orientation,
  39519. const bool isMouseOver,
  39520. const bool isMouseDown,
  39521. const bool isFrontTab);
  39522. virtual void fillTabButtonShape (Graphics& g,
  39523. const Path& path,
  39524. const Colour& preferredBackgroundColour,
  39525. int tabIndex,
  39526. const String& text,
  39527. Button& button,
  39528. TabbedButtonBar::Orientation orientation,
  39529. const bool isMouseOver,
  39530. const bool isMouseDown,
  39531. const bool isFrontTab);
  39532. virtual void drawTabButtonText (Graphics& g,
  39533. int x, int y, int w, int h,
  39534. const Colour& preferredBackgroundColour,
  39535. int tabIndex,
  39536. const String& text,
  39537. Button& button,
  39538. TabbedButtonBar::Orientation orientation,
  39539. const bool isMouseOver,
  39540. const bool isMouseDown,
  39541. const bool isFrontTab);
  39542. virtual int getTabButtonOverlap (int tabDepth);
  39543. virtual int getTabButtonSpaceAroundImage();
  39544. virtual int getTabButtonBestWidth (int tabIndex,
  39545. const String& text,
  39546. int tabDepth,
  39547. Button& button);
  39548. virtual void drawTabButton (Graphics& g,
  39549. int w, int h,
  39550. const Colour& preferredColour,
  39551. int tabIndex,
  39552. const String& text,
  39553. Button& button,
  39554. TabbedButtonBar::Orientation orientation,
  39555. const bool isMouseOver,
  39556. const bool isMouseDown,
  39557. const bool isFrontTab);
  39558. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  39559. int w, int h,
  39560. TabbedButtonBar& tabBar,
  39561. TabbedButtonBar::Orientation orientation);
  39562. virtual Button* createTabBarExtrasButton();
  39563. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  39564. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  39565. int width, int height,
  39566. bool isMouseOver, bool isMouseDown,
  39567. int columnFlags);
  39568. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  39569. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  39570. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  39571. bool isMouseOver, bool isMouseDown,
  39572. ToolbarItemComponent& component);
  39573. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  39574. const String& text, ToolbarItemComponent& component);
  39575. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  39576. bool isOpen, int width, int height);
  39577. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  39578. PropertyComponent& component);
  39579. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  39580. PropertyComponent& component);
  39581. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  39582. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  39583. /**
  39584. */
  39585. virtual void playAlertSound();
  39586. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  39587. static void drawGlassSphere (Graphics& g,
  39588. const float x, const float y,
  39589. const float diameter,
  39590. const Colour& colour,
  39591. const float outlineThickness) throw();
  39592. static void drawGlassPointer (Graphics& g,
  39593. const float x, const float y,
  39594. const float diameter,
  39595. const Colour& colour, const float outlineThickness,
  39596. const int direction) throw();
  39597. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  39598. static void drawGlassLozenge (Graphics& g,
  39599. const float x, const float y,
  39600. const float width, const float height,
  39601. const Colour& colour,
  39602. const float outlineThickness,
  39603. const float cornerSize,
  39604. const bool flatOnLeft, const bool flatOnRight,
  39605. const bool flatOnTop, const bool flatOnBottom) throw();
  39606. juce_UseDebuggingNewOperator
  39607. protected:
  39608. // xxx the following methods are only here to cause a compiler error, because they've been
  39609. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  39610. // error if you try to build a subclass with the old versions.
  39611. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  39612. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  39613. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  39614. virtual void getTabButtonBestWidth (int, const String&, int) {}
  39615. private:
  39616. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  39617. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  39618. Array <int> colourIds;
  39619. Array <Colour> colours;
  39620. void drawShinyButtonShape (Graphics& g,
  39621. float x, float y, float w, float h, float maxCornerSize,
  39622. const Colour& baseColour,
  39623. const float strokeWidth,
  39624. const bool flatOnLeft,
  39625. const bool flatOnRight,
  39626. const bool flatOnTop,
  39627. const bool flatOnBottom) throw();
  39628. LookAndFeel (const LookAndFeel&);
  39629. const LookAndFeel& operator= (const LookAndFeel&);
  39630. };
  39631. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  39632. /********* End of inlined file: juce_LookAndFeel.h *********/
  39633. #endif
  39634. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39635. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39636. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39637. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39638. /**
  39639. The original Juce look-and-feel.
  39640. */
  39641. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  39642. {
  39643. public:
  39644. /** Creates the default JUCE look and feel. */
  39645. OldSchoolLookAndFeel();
  39646. /** Destructor. */
  39647. virtual ~OldSchoolLookAndFeel();
  39648. /** Draws the lozenge-shaped background for a standard button. */
  39649. virtual void drawButtonBackground (Graphics& g,
  39650. Button& button,
  39651. const Colour& backgroundColour,
  39652. bool isMouseOverButton,
  39653. bool isButtonDown);
  39654. /** Draws the contents of a standard ToggleButton. */
  39655. virtual void drawToggleButton (Graphics& g,
  39656. ToggleButton& button,
  39657. bool isMouseOverButton,
  39658. bool isButtonDown);
  39659. virtual void drawTickBox (Graphics& g,
  39660. Component& component,
  39661. int x, int y, int w, int h,
  39662. const bool ticked,
  39663. const bool isEnabled,
  39664. const bool isMouseOverButton,
  39665. const bool isButtonDown);
  39666. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39667. int width, int height,
  39668. double progress, const String& textToShow);
  39669. virtual void drawScrollbarButton (Graphics& g,
  39670. ScrollBar& scrollbar,
  39671. int width, int height,
  39672. int buttonDirection,
  39673. bool isScrollbarVertical,
  39674. bool isMouseOverButton,
  39675. bool isButtonDown);
  39676. virtual void drawScrollbar (Graphics& g,
  39677. ScrollBar& scrollbar,
  39678. int x, int y,
  39679. int width, int height,
  39680. bool isScrollbarVertical,
  39681. int thumbStartPosition,
  39682. int thumbSize,
  39683. bool isMouseOver,
  39684. bool isMouseDown);
  39685. virtual ImageEffectFilter* getScrollbarEffect();
  39686. virtual void drawTextEditorOutline (Graphics& g,
  39687. int width, int height,
  39688. TextEditor& textEditor);
  39689. /** Fills the background of a popup menu component. */
  39690. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39691. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39692. bool isMouseOverBar,
  39693. MenuBarComponent& menuBar);
  39694. virtual void drawComboBox (Graphics& g, int width, int height,
  39695. const bool isButtonDown,
  39696. int buttonX, int buttonY,
  39697. int buttonW, int buttonH,
  39698. ComboBox& box);
  39699. virtual const Font getComboBoxFont (ComboBox& box);
  39700. virtual void drawLinearSlider (Graphics& g,
  39701. int x, int y,
  39702. int width, int height,
  39703. float sliderPos,
  39704. float minSliderPos,
  39705. float maxSliderPos,
  39706. const Slider::SliderStyle style,
  39707. Slider& slider);
  39708. virtual int getSliderThumbRadius (Slider& slider);
  39709. virtual Button* createSliderButton (const bool isIncrement);
  39710. virtual ImageEffectFilter* getSliderEffect();
  39711. virtual void drawCornerResizer (Graphics& g,
  39712. int w, int h,
  39713. bool isMouseOver,
  39714. bool isMouseDragging);
  39715. virtual Button* createDocumentWindowButton (int buttonType);
  39716. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39717. int titleBarX, int titleBarY,
  39718. int titleBarW, int titleBarH,
  39719. Button* minimiseButton,
  39720. Button* maximiseButton,
  39721. Button* closeButton,
  39722. bool positionTitleBarButtonsOnLeft);
  39723. juce_UseDebuggingNewOperator
  39724. private:
  39725. DropShadowEffect scrollbarShadow;
  39726. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  39727. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  39728. };
  39729. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39730. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39731. #endif
  39732. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39733. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  39734. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39735. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39736. /**
  39737. A class to take care of the logic involved with the loading/saving of some kind
  39738. of document.
  39739. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  39740. functions you need for documents that get saved to a file, so this class attempts
  39741. to abstract most of the boring stuff.
  39742. Your subclass should just implement all the pure virtual methods, and you can
  39743. then use the higher-level public methods to do the load/save dialogs, to warn the user
  39744. about overwriting files, etc.
  39745. The document object keeps track of whether it has changed since it was last saved or
  39746. loaded, so when you change something, call its changed() method. This will set a
  39747. flag so it knows it needs saving, and will also broadcast a change message using the
  39748. ChangeBroadcaster base class.
  39749. @see ChangeBroadcaster
  39750. */
  39751. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  39752. {
  39753. public:
  39754. /** Creates a FileBasedDocument.
  39755. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  39756. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  39757. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  39758. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  39759. */
  39760. FileBasedDocument (const String& fileExtension,
  39761. const String& fileWildCard,
  39762. const String& openFileDialogTitle,
  39763. const String& saveFileDialogTitle);
  39764. /** Destructor. */
  39765. virtual ~FileBasedDocument();
  39766. /** Returns true if the changed() method has been called since the file was
  39767. last saved or loaded.
  39768. @see resetChangedFlag, changed
  39769. */
  39770. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  39771. /** Called to indicate that the document has changed and needs saving.
  39772. This method will also trigger a change message to be sent out using the
  39773. ChangeBroadcaster base class.
  39774. After calling the method, the hasChangedSinceSaved() method will return true, until
  39775. it is reset either by saving to a file or using the resetChangedFlag() method.
  39776. @see hasChangedSinceSaved, resetChangedFlag
  39777. */
  39778. virtual void changed();
  39779. /** Sets the state of the 'changed' flag.
  39780. The 'changed' flag is set to true when the changed() method is called - use this method
  39781. to reset it or to set it without also broadcasting a change message.
  39782. @see changed, hasChangedSinceSaved
  39783. */
  39784. void setChangedFlag (const bool hasChanged);
  39785. /** Tries to open a file.
  39786. If the file opens correctly, the document's file (see the getFile() method) is set
  39787. to this new one; if it fails, the document's file is left unchanged, and optionally
  39788. a message box is shown telling the user there was an error.
  39789. @returns true if the new file loaded successfully
  39790. @see loadDocument, loadFromUserSpecifiedFile
  39791. */
  39792. bool loadFrom (const File& fileToLoadFrom,
  39793. const bool showMessageOnFailure);
  39794. /** Asks the user for a file and tries to load it.
  39795. This will pop up a dialog box using the title, file extension and
  39796. wildcard specified in the document's constructor, and asks the user
  39797. for a file. If they pick one, the loadFrom() method is used to
  39798. try to load it, optionally showing a message if it fails.
  39799. @returns true if a file was loaded; false if the user cancelled or if they
  39800. picked a file which failed to load correctly
  39801. @see loadFrom
  39802. */
  39803. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  39804. /** A set of possible outcomes of one of the save() methods
  39805. */
  39806. enum SaveResult
  39807. {
  39808. savedOk = 0, /**< indicates that a file was saved successfully. */
  39809. userCancelledSave, /**< indicates that the user aborted the save operation. */
  39810. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  39811. };
  39812. /** Tries to save the document to the last file it was saved or loaded from.
  39813. This will always try to write to the file, even if the document isn't flagged as
  39814. having changed.
  39815. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  39816. true, it will prompt the user to pick a file, as if
  39817. saveAsInteractive() was called.
  39818. @param showMessageOnFailure if true it will show a warning message when if the
  39819. save operation fails
  39820. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  39821. */
  39822. SaveResult save (const bool askUserForFileIfNotSpecified,
  39823. const bool showMessageOnFailure);
  39824. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  39825. it if they say yes.
  39826. If you've got a document open and want to close it (e.g. to quit the app), this is the
  39827. method to call.
  39828. If the document doesn't need saving it'll return the value savedOk so
  39829. you can go ahead and delete the document.
  39830. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  39831. return savedOk, so again, you can safely delete the document.
  39832. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  39833. close-document operation.
  39834. And if they click "save changes", it'll try to save and either return savedOk, or
  39835. failedToWriteToFile if there was a problem.
  39836. @see save, saveAs, saveAsInteractive
  39837. */
  39838. SaveResult saveIfNeededAndUserAgrees();
  39839. /** Tries to save the document to a specified file.
  39840. If this succeeds, it'll also change the document's internal file (as returned by
  39841. the getFile() method). If it fails, the file will be left unchanged.
  39842. @param newFile the file to try to write to
  39843. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39844. the user first if they want to overwrite it
  39845. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  39846. use the saveAsInteractive() method to ask the user for a
  39847. filename
  39848. @param showMessageOnFailure if true and the write operation fails, it'll show
  39849. a message box to warn the user
  39850. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  39851. */
  39852. SaveResult saveAs (const File& newFile,
  39853. const bool warnAboutOverwritingExistingFiles,
  39854. const bool askUserForFileIfNotSpecified,
  39855. const bool showMessageOnFailure);
  39856. /** Prompts the user for a filename and tries to save to it.
  39857. This will pop up a dialog box using the title, file extension and
  39858. wildcard specified in the document's constructor, and asks the user
  39859. for a file. If they pick one, the saveAs() method is used to try to save
  39860. to this file.
  39861. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39862. the user first if they want to overwrite it
  39863. @see saveIfNeededAndUserAgrees, save, saveAs
  39864. */
  39865. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  39866. /** Returns the file that this document was last successfully saved or loaded from.
  39867. When the document object is created, this will be set to File::nonexistent.
  39868. It is changed when one of the load or save methods is used, or when setFile()
  39869. is used to explicitly set it.
  39870. */
  39871. const File getFile() const throw() { return documentFile; }
  39872. /** Sets the file that this document thinks it was loaded from.
  39873. This won't actually load anything - it just changes the file stored internally.
  39874. @see getFile
  39875. */
  39876. void setFile (const File& newFile);
  39877. protected:
  39878. /** Overload this to return the title of the document.
  39879. This is used in message boxes, filenames and file choosers, so it should be
  39880. something sensible.
  39881. */
  39882. virtual const String getDocumentTitle() = 0;
  39883. /** This method should try to load your document from the given file.
  39884. If it fails, it should return an error message. If it succeeds, it should return
  39885. an empty string.
  39886. */
  39887. virtual const String loadDocument (const File& file) = 0;
  39888. /** This method should try to write your document to the given file.
  39889. If it fails, it should return an error message. If it succeeds, it should return
  39890. an empty string.
  39891. */
  39892. virtual const String saveDocument (const File& file) = 0;
  39893. /** This is used for dialog boxes to make them open at the last folder you
  39894. were using.
  39895. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39896. the last document that was used - you might want to store this value
  39897. in a static variable, or even in your application's properties. It should
  39898. be a global setting rather than a property of this object.
  39899. This method works very well in conjunction with a RecentlyOpenedFilesList
  39900. object to manage your recent-files list.
  39901. As a default value, it's ok to return File::nonexistent, and the document
  39902. object will use a sensible one instead.
  39903. @see RecentlyOpenedFilesList
  39904. */
  39905. virtual const File getLastDocumentOpened() = 0;
  39906. /** This is used for dialog boxes to make them open at the last folder you
  39907. were using.
  39908. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39909. the last document that was used - you might want to store this value
  39910. in a static variable, or even in your application's properties. It should
  39911. be a global setting rather than a property of this object.
  39912. This method works very well in conjunction with a RecentlyOpenedFilesList
  39913. object to manage your recent-files list.
  39914. @see RecentlyOpenedFilesList
  39915. */
  39916. virtual void setLastDocumentOpened (const File& file) = 0;
  39917. public:
  39918. juce_UseDebuggingNewOperator
  39919. private:
  39920. File documentFile;
  39921. bool changedSinceSave;
  39922. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  39923. FileBasedDocument (const FileBasedDocument&);
  39924. const FileBasedDocument& operator= (const FileBasedDocument&);
  39925. };
  39926. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39927. /********* End of inlined file: juce_FileBasedDocument.h *********/
  39928. #endif
  39929. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39930. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  39931. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39932. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  39933. /**
  39934. Manages a set of files for use as a list of recently-opened documents.
  39935. This is a handy class for holding your list of recently-opened documents, with
  39936. helpful methods for things like purging any non-existent files, automatically
  39937. adding them to a menu, and making persistence easy.
  39938. @see File, FileBasedDocument
  39939. */
  39940. class JUCE_API RecentlyOpenedFilesList
  39941. {
  39942. public:
  39943. /** Creates an empty list.
  39944. */
  39945. RecentlyOpenedFilesList();
  39946. /** Destructor. */
  39947. ~RecentlyOpenedFilesList();
  39948. /** Sets a limit for the number of files that will be stored in the list.
  39949. When addFile() is called, then if there is no more space in the list, the
  39950. least-recently added file will be dropped.
  39951. @see getMaxNumberOfItems
  39952. */
  39953. void setMaxNumberOfItems (const int newMaxNumber);
  39954. /** Returns the number of items that this list will store.
  39955. @see setMaxNumberOfItems
  39956. */
  39957. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  39958. /** Returns the number of files in the list.
  39959. The most recently added file is always at index 0.
  39960. */
  39961. int getNumFiles() const;
  39962. /** Returns one of the files in the list.
  39963. The most recently added file is always at index 0.
  39964. */
  39965. const File getFile (const int index) const;
  39966. /** Returns an array of all the absolute pathnames in the list.
  39967. */
  39968. const StringArray& getAllFilenames() const throw() { return files; }
  39969. /** Clears all the files from the list. */
  39970. void clear();
  39971. /** Adds a file to the list.
  39972. The file will be added at index 0. If this file is already in the list, it will
  39973. be moved up to index 0, but a file can only appear once in the list.
  39974. If the list already contains the maximum number of items that is permitted, the
  39975. least-recently added file will be dropped from the end.
  39976. */
  39977. void addFile (const File& file);
  39978. /** Checks each of the files in the list, removing any that don't exist.
  39979. You might want to call this after reloading a list of files, or before putting them
  39980. on a menu.
  39981. */
  39982. void removeNonExistentFiles();
  39983. /** Adds entries to a menu, representing each of the files in the list.
  39984. This is handy for creating an "open recent file..." menu in your app. The
  39985. menu items are numbered consecutively starting with the baseItemId value,
  39986. and can either be added as complete pathnames, or just the last part of the
  39987. filename.
  39988. If dontAddNonExistentFiles is true, then each file will be checked and only those
  39989. that exist will be added.
  39990. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  39991. pointers to file objects. Any files that appear in this list will not be added to the
  39992. menu - the reason for this is that you might have a number of files already open, so
  39993. might not want these to be shown in the menu.
  39994. It returns the number of items that were added.
  39995. */
  39996. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  39997. const int baseItemId,
  39998. const bool showFullPaths,
  39999. const bool dontAddNonExistentFiles,
  40000. const File** filesToAvoid = 0);
  40001. /** Returns a string that encapsulates all the files in the list.
  40002. The string that is returned can later be passed into restoreFromString() in
  40003. order to recreate the list. This is handy for persisting your list, e.g. in
  40004. a PropertiesFile object.
  40005. @see restoreFromString
  40006. */
  40007. const String toString() const;
  40008. /** Restores the list from a previously stringified version of the list.
  40009. Pass in a stringified version created with toString() in order to persist/restore
  40010. your list.
  40011. @see toString
  40012. */
  40013. void restoreFromString (const String& stringifiedVersion);
  40014. juce_UseDebuggingNewOperator
  40015. private:
  40016. StringArray files;
  40017. int maxNumberOfItems;
  40018. };
  40019. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40020. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40021. #endif
  40022. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40023. #endif
  40024. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  40025. #endif
  40026. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40027. #endif
  40028. #endif
  40029. /********* End of inlined file: juce_app_includes.h *********/
  40030. #endif
  40031. #if JUCE_MSVC
  40032. #pragma warning (pop)
  40033. #pragma pack (pop)
  40034. #endif
  40035. #if JUCE_MAC
  40036. #pragma align=reset
  40037. #endif
  40038. END_JUCE_NAMESPACE
  40039. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40040. #ifdef JUCE_NAMESPACE
  40041. // this will obviously save a lot of typing, but can be disabled by
  40042. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40043. using namespace JUCE_NAMESPACE;
  40044. /* On the Mac, these symbols are defined in the Mac libraries, so
  40045. these macros make it easier to reference them without writing out
  40046. the namespace every time.
  40047. If you run into difficulties where these macros interfere with the contents
  40048. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40049. the comments in that file for more information.
  40050. */
  40051. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40052. #define Component JUCE_NAMESPACE::Component
  40053. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40054. #define Point JUCE_NAMESPACE::Point
  40055. #define Button JUCE_NAMESPACE::Button
  40056. #endif
  40057. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40058. it easier to use the juce version explicitly.
  40059. If you run into difficulties where this macro interferes with other 3rd party header
  40060. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40061. file for more information.
  40062. */
  40063. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40064. #define Rectangle JUCE_NAMESPACE::Rectangle
  40065. #endif
  40066. #endif
  40067. #endif
  40068. /* Easy autolinking to the right JUCE libraries under win32.
  40069. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40070. including this header file.
  40071. */
  40072. #if JUCE_MSVC
  40073. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40074. /** If you want your application to link to Juce as a DLL instead of
  40075. a static library (on win32), just define the JUCE_DLL macro before
  40076. including juce.h
  40077. */
  40078. #ifdef JUCE_DLL
  40079. #ifdef JUCE_DEBUG
  40080. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40081. #else
  40082. #define AUTOLINKEDLIB "JUCE.lib"
  40083. #endif
  40084. #else
  40085. #ifdef JUCE_DEBUG
  40086. #ifdef _WIN64
  40087. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40088. #else
  40089. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40090. #endif
  40091. #else
  40092. #ifdef _WIN64
  40093. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40094. #else
  40095. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40096. #endif
  40097. #endif
  40098. #endif
  40099. #pragma comment(lib, AUTOLINKEDLIB)
  40100. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40101. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40102. #endif
  40103. // Auto-link the other win32 libs that are needed by library calls..
  40104. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40105. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40106. // Auto-links to various win32 libs that are needed by library calls..
  40107. #pragma comment(lib, "kernel32.lib")
  40108. #pragma comment(lib, "user32.lib")
  40109. #pragma comment(lib, "shell32.lib")
  40110. #pragma comment(lib, "gdi32.lib")
  40111. #pragma comment(lib, "vfw32.lib")
  40112. #pragma comment(lib, "comdlg32.lib")
  40113. #pragma comment(lib, "winmm.lib")
  40114. #pragma comment(lib, "wininet.lib")
  40115. #pragma comment(lib, "ole32.lib")
  40116. #pragma comment(lib, "advapi32.lib")
  40117. #pragma comment(lib, "ws2_32.lib")
  40118. #pragma comment(lib, "comsupp.lib")
  40119. #if JUCE_OPENGL
  40120. #pragma comment(lib, "OpenGL32.Lib")
  40121. #pragma comment(lib, "GlU32.Lib")
  40122. #endif
  40123. #if JUCE_QUICKTIME
  40124. #pragma comment (lib, "QTMLClient.lib")
  40125. #endif
  40126. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40127. #endif
  40128. #endif
  40129. #endif
  40130. /*
  40131. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40132. AppSubClass is the name of a class derived from JUCEApplication.
  40133. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40134. */
  40135. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40136. #define START_JUCE_APPLICATION(AppClass) \
  40137. int main (int argc, char* argv[]) \
  40138. { \
  40139. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40140. }
  40141. #elif JUCE_WIN32
  40142. #ifdef _CONSOLE
  40143. #define START_JUCE_APPLICATION(AppClass) \
  40144. int main (int, char* argv[]) \
  40145. { \
  40146. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40147. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40148. }
  40149. #elif ! defined (_AFXDLL)
  40150. #ifdef _WINDOWS_
  40151. #define START_JUCE_APPLICATION(AppClass) \
  40152. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40153. { \
  40154. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40155. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40156. }
  40157. #else
  40158. #define START_JUCE_APPLICATION(AppClass) \
  40159. int __stdcall WinMain (int, int, const char*, int) \
  40160. { \
  40161. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40162. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40163. }
  40164. #endif
  40165. #endif
  40166. #endif
  40167. #endif // __JUCE_JUCEHEADER__
  40168. /********* End of inlined file: juce.h *********/
  40169. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__